app

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

inbox-access-check.spec.ts (82183B)


      1 import { test, expect, type Page } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { once } from 'node:events';
      4 import { fileURLToPath } from 'node:url';
      5 import { WebSocketServer, type WebSocket } from 'ws';
      6 import { createStaticHarness } from '../integration/harness/static.ts';
      7 import type * as Fixture from './harness/inbox-access-check.ts';
      8 import type { PrivateAccessProbe } from '../../src/lib/persistence/private-records.ts';
      9 function probeRow(wire: string) {
     10   return JSON.parse(wire) as PrivateAccessProbe;
     11 }
     12 declare global {
     13   interface Window {
     14     hcCheck: typeof Fixture;
     15     hcCheckFixture: Awaited<ReturnType<typeof Fixture.makeCheckFixture>>;
     16     hcCheckPending: ReturnType<typeof Fixture.runInboxAccessCheck>;
     17     hcCheckCloseCalls: number;
     18     hcHostedCheck: Awaited<ReturnType<typeof Fixture.openHostedCheck>>;
     19     hcCheckRelease?: () => Promise<void>;
     20     hcCheckLockReady?: Promise<void>;
     21     hcCheckAuthPending?: Promise<string>;
     22     hcCheckRestore?: () => void;
     23     hcCheckOther?: Awaited<
     24       ReturnType<Window['hcCheckFixture']['alternateActors']>
     25     >;
     26     hcCheckCloseMode?: 'hold' | 'fail';
     27     hcCheckHeldClose?: (() => void)[];
     28   }
     29 }
     30 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     31   sockets: WebSocketServer,
     32   endpoint: string,
     33   bundle: string,
     34   head = '';
     35 let holdRead = false;
     36 let wireFault:
     37   'normal' | 'refused' | 'wrong_ack' | 'disconnect' | 'missing' | 'wrong_read' =
     38   'normal';
     39 let holdArchive = false;
     40 let releaseArchive: (() => void) | undefined;
     41 let challenge = false;
     42 let authMode: 'accept' | 'refuse' | 'hold' = 'accept';
     43 let releaseAuth: (() => void) | undefined;
     44 const physical = new Set<WebSocket>(),
     45   physicalOrigins = new WeakMap<WebSocket, string>(),
     46   archived = new Map<string, unknown>();
     47 const frames: { origin: string; type: string; id?: string }[] = [];
     48 const origins = [
     49   'wss://inbox.example.org',
     50   'wss://peer.example.org',
     51   'wss://archive.example.org'
     52 ];
     53 test.beforeAll(async () => {
     54   server = await createStaticHarness();
     55   sockets = new WebSocketServer({
     56     host: '127.0.0.1',
     57     port: 0,
     58     maxPayload: 65536
     59   });
     60   await once(sockets, 'listening');
     61   const address = sockets.address();
     62   if (!address || typeof address === 'string')
     63     throw Error('actual loopback endpoint');
     64   endpoint = 'ws://127.0.0.1:' + address.port;
     65   sockets.on('connection', (socket, request) => {
     66     physical.add(socket);
     67     socket.on('close', () => physical.delete(socket));
     68     const origin = new URL(request.url!, 'http://127.0.0.1').searchParams.get(
     69       'origin'
     70     )!;
     71     physicalOrigins.set(socket, origin);
     72     if (challenge && origin === 'wss://inbox.example.org')
     73       socket.send(JSON.stringify(['AUTH', 's5c-actual-source-challenge']));
     74     socket.on('message', (bytes) => {
     75       const raw = Buffer.isBuffer(bytes)
     76         ? bytes
     77         : Array.isArray(bytes)
     78           ? Buffer.concat(bytes)
     79           : Buffer.from(bytes);
     80       const frame = JSON.parse(raw.toString()) as unknown[];
     81       if (frames.length >= 10000)
     82         throw Error('bounded source fixture frame log');
     83       if (frame[0] === 'REQ') {
     84         const filter = frame[2] as { kinds?: number[]; ids?: string[] };
     85         frames.push({ origin, type: 'REQ', id: filter.ids?.[0] });
     86         if (filter.kinds?.includes(10050) && head)
     87           socket.send(JSON.stringify(['EVENT', frame[1], JSON.parse(head)]));
     88         if (filter.kinds?.includes(1059) && filter.ids) {
     89           if (holdRead) return;
     90           const event = archived.get(JSON.stringify([origin, filter.ids[0]]));
     91           if (event && wireFault !== 'missing')
     92             socket.send(
     93               JSON.stringify([
     94                 'EVENT',
     95                 frame[1],
     96                 wireFault === 'wrong_read'
     97                   ? { ...event, id: 'f'.repeat(64) }
     98                   : event
     99               ])
    100             );
    101         }
    102         if (filter.kinds?.includes(1059) && !filter.ids) {
    103           for (const [key, event] of archived) {
    104             if ((JSON.parse(key) as [string, string])[0] === origin)
    105               socket.send(JSON.stringify(['EVENT', frame[1], event]));
    106           }
    107         }
    108         socket.send(JSON.stringify(['EOSE', frame[1]]));
    109       } else if (frame[0] === 'AUTH') {
    110         const event = frame[1] as { id: string };
    111         frames.push({ origin, type: 'AUTH', id: event.id });
    112         const acknowledge = () =>
    113           socket.send(
    114             JSON.stringify([
    115               'OK',
    116               event.id,
    117               authMode !== 'refuse',
    118               'controlled actual auth response'
    119             ])
    120           );
    121         if (authMode === 'hold') releaseAuth = acknowledge;
    122         else acknowledge();
    123       } else if (frame[0] === 'EVENT') {
    124         const event = frame[1] as { id: string };
    125         frames.push({ origin, type: 'EVENT', id: event.id });
    126         archived.set(JSON.stringify([origin, event.id]), event);
    127         const acknowledge = () => {
    128           if (wireFault === 'disconnect') {
    129             socket.close();
    130             return;
    131           }
    132           socket.send(
    133             JSON.stringify([
    134               'OK',
    135               wireFault === 'wrong_ack' ? 'f'.repeat(64) : event.id,
    136               wireFault !== 'refused',
    137               'controlled actual named acceptance'
    138             ])
    139           );
    140           if (wireFault === 'wrong_ack') socket.close();
    141         };
    142         if (holdArchive) releaseArchive = acknowledge;
    143         else acknowledge();
    144       }
    145     });
    146   });
    147   const result = await build({
    148     configFile: false,
    149     logLevel: 'silent',
    150     build: {
    151       write: false,
    152       minify: false,
    153       lib: {
    154         entry: fileURLToPath(
    155           new URL('./harness/inbox-access-check.ts', import.meta.url)
    156         ),
    157         name: 'hcCheck',
    158         formats: ['iife']
    159       }
    160     }
    161   });
    162   const output = Array.isArray(result) ? result[0] : result;
    163   if (!('output' in output)) throw Error('actual compiled check harness');
    164   const chunks = output.output.filter((item) => item.type === 'chunk');
    165   expect(chunks).toHaveLength(1);
    166   bundle = chunks[0].code;
    167 });
    168 test.afterAll(async () => {
    169   for (const socket of sockets.clients) socket.terminate();
    170   await new Promise<void>((resolve) => sockets.close(() => resolve()));
    171   await server.close();
    172 });
    173 test.beforeEach(async ({ page }, testInfo) => {
    174   await expect.poll(() => physical.size).toBe(0);
    175   head = '';
    176   archived.clear();
    177   frames.length = 0;
    178   holdRead = false;
    179   wireFault = 'normal';
    180   holdArchive = false;
    181   releaseArchive = undefined;
    182   challenge = false;
    183   authMode = 'accept';
    184   releaseAuth = undefined;
    185   await page.addInitScript(
    186     ({ endpoint, origins }) => {
    187       const Native = window.WebSocket;
    188       window.hcCheckCloseCalls = 0;
    189       const close = Object.getOwnPropertyDescriptor(Native.prototype, 'close')!
    190         .value as WebSocket['close'];
    191       window.WebSocket = class extends Native {
    192         constructor(url: string | URL, protocols?: string | string[]) {
    193           const origin = new URL(String(url)).origin;
    194           if (!['wss://discovery.example.org', ...origins].includes(origin))
    195             throw Error('unapproved fixture origin');
    196           super(endpoint + '/?origin=' + encodeURIComponent(origin), protocols);
    197         }
    198         close(...args: Parameters<WebSocket['close']>) {
    199           window.hcCheckCloseCalls++;
    200           if (window.hcCheckCloseMode === 'fail')
    201             throw Error('actual controlled physical close refusal');
    202           if (window.hcCheckCloseMode === 'hold') {
    203             (window.hcCheckHeldClose ??= []).push(() =>
    204               close.apply(this, args)
    205             );
    206             return;
    207           }
    208           return close.apply(this, args);
    209         }
    210       };
    211     },
    212     { endpoint, origins }
    213   );
    214   await page.goto(server.url + '/search');
    215   await page.addScriptTag({ content: bundle });
    216   head = await page.evaluate(
    217     async ({ origins, authRequired }) => {
    218       window.hcCheckFixture =
    219         await window.hcCheck.makeCheckFixture(authRequired);
    220       return window.hcCheckFixture.host.preferenceWire(origins);
    221     },
    222     { origins, authRequired: testInfo.title.includes('required AUTH') }
    223   );
    224   await page.evaluate(() => window.hcCheckFixture.open());
    225 });
    226 test.afterEach(async ({ page }) => {
    227   if (page.isClosed()) return;
    228   const closed = await page.evaluate(async () => {
    229     await window.hcCheckRelease?.();
    230     window.hcCheckRelease = undefined;
    231     window.hcCheckRestore?.();
    232     window.hcCheckRestore = undefined;
    233     window.hcCheckCloseMode = undefined;
    234     for (const release of window.hcCheckHeldClose ?? []) release();
    235     window.hcCheckHeldClose = [];
    236     try {
    237       window.hcCheckFixture.close();
    238       return true;
    239     } catch (error) {
    240       if (
    241         error instanceof Error &&
    242         [
    243           'inbox_access_check_cleanup_required',
    244           'private_inbox_cleanup_required',
    245           'private_history_cleanup_required',
    246           'private_auth_cleanup_required',
    247           'private_pool_close_pending',
    248           'private_pool_close_failed'
    249         ].includes(error.message)
    250       )
    251         return false;
    252       throw error;
    253     }
    254   });
    255   if (!closed) {
    256     await expect
    257       .poll(
    258         () =>
    259           [...physical].filter(
    260             (socket) =>
    261               physicalOrigins.get(socket) !== 'wss://discovery.example.org'
    262           ).length
    263       )
    264       .toBe(0);
    265     await page.evaluate(() => window.hcCheckFixture.close());
    266   }
    267 });
    268 test('cold original check shows source disclosure with no preparation or provider work before review', async ({
    269   page
    270 }) => {
    271   const result = await page.evaluate(async () => {
    272     const f = window.hcCheckFixture,
    273       before = f.host.counts(),
    274       rowsBefore = await f.host.stored();
    275     const disclosure = f.select();
    276     const invalid = await f.run('not_reviewed');
    277     return {
    278       before,
    279       after: f.host.counts(),
    280       rowsBefore: rowsBefore.length,
    281       rowsAfter: (await f.host.stored()).length,
    282       disclosure,
    283       invalid: invalid.status,
    284       state: f.snapshot()
    285     };
    286   });
    287   expect(result.rowsBefore).toBe(0);
    288   expect(result.rowsAfter).toBe(0);
    289   expect(result.after).toEqual(result.before);
    290   expect(result.invalid).toBe('invalid');
    291   expect(JSON.stringify(result.disclosure)).toMatch(/note to self|self.note/i);
    292   expect(JSON.stringify(result.disclosure)).toMatch(
    293     /remote retention|relay.*retain/i
    294   );
    295   expect(JSON.stringify(result.disclosure)).toMatch(/receive|decrypt/i);
    296   expect(result.state?.sourceOnly).toBe(true);
    297   expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(0);
    298 });
    299 test('cold original coordinator performs actual journal archive read nonce and source qualification', async ({
    300   page
    301 }) => {
    302   const result = await page.evaluate(async () => {
    303     const f = window.hcCheckFixture;
    304     f.select();
    305     const before = f.host.counts(),
    306       result = await f.run();
    307     return {
    308       status: result.status,
    309       before,
    310       after: f.host.counts(),
    311       snapshot: f.snapshot(),
    312       rows: await f.host.stored(),
    313       qualification:
    314         f.qualification() &&
    315         window.hcCheck.inboxAccessQualificationSnapshot(f.qualification()!)
    316     };
    317   });
    318   expect(result.status).toBe('qualified');
    319   expect(result.rows).toHaveLength(1);
    320   const row = JSON.parse(result.rows[0].wire) as {
    321     family: string;
    322     self: { eventId: string };
    323     receipts: { role: string; status: string }[];
    324   };
    325   expect(row.family).toBe('private_access_probe');
    326   expect(
    327     row.receipts.filter(
    328       (fact) => fact.role === 'access_archive' && fact.status === 'accepted'
    329     )
    330   ).toHaveLength(3);
    331   expect(row.receipts.some((fact) => fact.status === 'nonce_verified')).toBe(
    332     true
    333   );
    334   expect(
    335     frames.filter((frame) => frame.type === 'EVENT').map((frame) => frame.id)
    336   ).toEqual([row.self.eventId, row.self.eventId, row.self.eventId]);
    337   expect(
    338     new Set(
    339       frames
    340         .filter((frame) => frame.type === 'EVENT')
    341         .map((frame) => frame.origin)
    342     ).size
    343   ).toBe(3);
    344   expect(result.qualification?.sourceOnly).toBe(true);
    345   expect(result.after.signs - result.before.signs).toBe(1);
    346 });
    347 test('copied review never authorizes work and a consumed review cannot replay', async ({
    348   page
    349 }) => {
    350   const result = await page.evaluate(async () => {
    351     const f = window.hcCheckFixture;
    352     f.select();
    353     const before = f.host.counts(),
    354       copied = await window.hcCheck.runInboxAccessCheck(
    355         { ...f.review()! },
    356         'reviewed_inbox_access_check'
    357       );
    358     const afterCopy = f.host.counts(),
    359       actual = await f.run(),
    360       replay = await f.run();
    361     return {
    362       before,
    363       afterCopy,
    364       copied: copied.status,
    365       actual: actual.status,
    366       replay: replay.status
    367     };
    368   });
    369   expect(result.copied).toBe('invalid');
    370   expect(result.afterCopy).toEqual(result.before);
    371   expect(result.actual).toBe('qualified');
    372   expect(result.replay).toBe('invalid');
    373 });
    374 test('fresh explicit successful check review reuses genuine current qualification without new effects', async ({
    375   page
    376 }) => {
    377   const result = await page.evaluate(async () => {
    378     const f = window.hcCheckFixture;
    379     f.select();
    380     const first = await f.run(),
    381       qualification = f.qualification(),
    382       before = f.host.counts();
    383     f.select();
    384     const second = await f.run();
    385     return {
    386       first: first.status,
    387       second: second.status,
    388       same: qualification === f.qualification(),
    389       before,
    390       after: f.host.counts(),
    391       rows: (await f.host.stored()).length
    392     };
    393   });
    394   expect(result.first).toBe('qualified');
    395   expect(result.second).toBe('qualified');
    396   expect(result.same).toBe(true);
    397   expect(result.after).toEqual(result.before);
    398   expect(result.rows).toBe(1);
    399   expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(3);
    400 });
    401 
    402 test('source review regression: another requested read origin cannot inherit cached qualification', async ({
    403   page
    404 }) => {
    405   const result = await page.evaluate(async () => {
    406     const f = window.hcCheckFixture;
    407     f.select();
    408     const first = await f.run(),
    409       before = f.host.counts();
    410     const changed = f.select('original', 'wss://archive.example.org');
    411     return { first: first.status, changed, before, after: f.host.counts() };
    412   });
    413   expect(result.first).toBe('qualified');
    414   expect(result.changed).toBeUndefined();
    415   expect(result.after).toEqual(result.before);
    416 });
    417 
    418 test('source review regression: bare coordinator cannot bypass reviewed cleanup selection', async ({
    419   page
    420 }) => {
    421   const result = await page.evaluate(async () => {
    422     const f = window.hcCheckFixture,
    423       api = window.hcCheck;
    424     f.select();
    425     const first = await f.run(),
    426       before = f.host.counts();
    427     const cleanup = await api.cleanupInboxAccessCheck(
    428       f.check()! as unknown as Parameters<
    429         typeof api.cleanupInboxAccessCheck
    430       >[0],
    431       'reviewed_delete_local_inbox_probe'
    432     );
    433     return {
    434       first: first.status,
    435       cleanup: cleanup.status,
    436       rows: (await f.host.stored()).length,
    437       before,
    438       after: f.host.counts()
    439     };
    440   });
    441   expect(result.first).toBe('qualified');
    442   expect(result.cleanup).toBe('invalid');
    443   expect(result.rows).toBe(1);
    444   expect(result.after).toEqual(result.before);
    445 });
    446 
    447 test('source review regression: bare coordinator cannot bypass reviewed reconciliation selection', async ({
    448   page
    449 }) => {
    450   const result = await page.evaluate(async () => {
    451     const f = window.hcCheckFixture,
    452       api = window.hcCheck,
    453       before = f.host.counts();
    454     const reconciled = await api.reconcileInboxAccessCheck(
    455       f.check()! as unknown as Parameters<
    456         typeof api.reconcileInboxAccessCheck
    457       >[0],
    458       'reviewed_inbox_access_check_reconciliation'
    459     );
    460     return {
    461       status: reconciled.status,
    462       before,
    463       after: f.host.counts(),
    464       rows: (await f.host.stored()).length
    465     };
    466   });
    467   expect(result.status).toBe('invalid');
    468   expect(result.rows).toBe(0);
    469   expect(result.after).toEqual(result.before);
    470 });
    471 
    472 test('source review regression: actual head loss closes the owned retained transport scope', async ({
    473   page
    474 }) => {
    475   holdRead = true;
    476   await page.evaluate(() => {
    477     const f = window.hcCheckFixture;
    478     f.select();
    479     window.hcCheckPending = f.run();
    480   });
    481   await expect
    482     .poll(() => frames.some((frame) => frame.type === 'REQ' && !!frame.id))
    483     .toBe(true);
    484   const result = await page.evaluate(async () => {
    485     const f = window.hcCheckFixture,
    486       before = window.hcCheckCloseCalls;
    487     f.actors().churnHead();
    488     const snapshot = f.snapshot(),
    489       after = window.hcCheckCloseCalls;
    490     const completed = await window.hcCheckPending;
    491     return {
    492       before,
    493       after,
    494       snapshot,
    495       status: completed.status,
    496       qualified: !!f.qualification()
    497     };
    498   });
    499   expect(result.status).toBe('stopped');
    500   expect(result.qualified).toBe(false);
    501   expect(result.snapshot?.state).toBe('stopped');
    502   expect(result.after).toBeGreaterThan(result.before);
    503   await expect
    504     .poll(
    505       () =>
    506         [...physical].filter(
    507           (socket) =>
    508             physicalOrigins.get(socket) !== 'wss://discovery.example.org'
    509         ).length
    510     )
    511     .toBe(0);
    512 });
    513 
    514 test('source review regression: explicit retry after actual nonce owner contention makes a later genuine read', async ({
    515   page
    516 }) => {
    517   const result = await page.evaluate(async () => {
    518     const f = window.hcCheckFixture,
    519       held = window.hcCheck.holdCheckNonceOwnerLock();
    520     try {
    521       f.select();
    522       const first = await f.run(),
    523         command = f.snapshot()?.command;
    524       await held.release();
    525       const before = f.host.counts();
    526       f.select();
    527       const second = await f.run();
    528       return {
    529         first: first.status,
    530         second: second.status,
    531         command,
    532         afterCommand: f.snapshot()?.command,
    533         hits: held.hits(),
    534         before,
    535         after: f.host.counts(),
    536         rows: (await f.host.stored()).length
    537       };
    538     } finally {
    539       await held.release();
    540       held.restore();
    541     }
    542   });
    543   expect(result.hits).toBe(1);
    544   expect(result.first).toBe('busy');
    545   expect(result.second).toBe('qualified');
    546   expect(result.afterCommand).toBe(result.command);
    547   expect(result.rows).toBe(1);
    548   expect(result.after.signs).toBe(result.before.signs);
    549   expect(result.after.encrypts).toBe(result.before.encrypts);
    550   expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(3);
    551   expect(
    552     frames.filter((frame) => frame.type === 'REQ' && !!frame.id)
    553   ).toHaveLength(2);
    554 });
    555 
    556 async function seedRecovery(page: Page, freshSession = false) {
    557   const original = await page.evaluate(async () => {
    558     const f = window.hcCheckFixture;
    559     f.select();
    560     const completed = await f.run(),
    561       command = f.snapshot()?.command,
    562       row = (await f.host.stored()).find(
    563         (row) => row.id === command && row.owner === f.host.owner
    564       );
    565     if (completed.status !== 'qualified' || !row)
    566       throw Error('actual coordinator seed failed');
    567     if (!command) throw Error('actual coordinator command missing');
    568     f.stop();
    569     return { command, row };
    570   });
    571   await expect
    572     .poll(
    573       () =>
    574         [...physical].filter(
    575           (socket) =>
    576             physicalOrigins.get(socket) !== 'wss://discovery.example.org'
    577         ).length
    578     )
    579     .toBe(0);
    580   await page.evaluate(async (freshSession) => {
    581     const f = window.hcCheckFixture;
    582     if (!f.retryCleanup()) throw Error('actual ended scope cleanup incomplete');
    583     await f.replaceCheck(freshSession);
    584   }, freshSession);
    585   return original;
    586 }
    587 
    588 for (const freshSession of [false, true]) {
    589   test(`persisted recovery through ${freshSession ? 'fresh session' : 'replacement controller'} uses exact original artifact without new signing or encryption`, async ({
    590     page
    591   }) => {
    592     const original = await seedRecovery(page, freshSession);
    593     const result = await page.evaluate(async ({ command }) => {
    594       const f = window.hcCheckFixture,
    595         before = f.host.counts();
    596       const disclosure = f.select(
    597         'recover',
    598         'wss://inbox.example.org',
    599         command
    600       );
    601       const result = await f.run();
    602       return {
    603         disclosure,
    604         status: result.status,
    605         before,
    606         after: f.host.counts(),
    607         row: (await f.host.stored())[0],
    608         snapshot: f.snapshot(),
    609         qualified: !!f.qualification()
    610       };
    611     }, original);
    612     expect(result.disclosure?.kind).toBe('check');
    613     if (!result.disclosure || !('mode' in result.disclosure))
    614       throw Error('actual check review metadata missing');
    615     expect(result.disclosure.mode).toBe('recover');
    616     expect(result.status).toBe('qualified');
    617     expect(result.qualified).toBe(true);
    618     expect(result.snapshot?.command).toBe(original.command);
    619     const before = probeRow(original.row.wire),
    620       after = probeRow(result.row.wire);
    621     expect(after.self).toEqual(before.self);
    622     expect(after.rumorHash).toBe(before.rumorHash);
    623     expect(after.id).toBe(before.id);
    624     expect(result.after.signs).toBe(result.before.signs);
    625     expect(result.after.encrypts).toBe(result.before.encrypts);
    626     expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(6);
    627     expect(
    628       new Set(
    629         frames
    630           .filter((frame) => frame.type === 'EVENT')
    631           .map((frame) => frame.id)
    632       ).size
    633     ).toBe(1);
    634   });
    635 }
    636 
    637 test('persisted recovery explicit retry after actual nonce owner contention spends a later real read under the same command', async ({
    638   page
    639 }) => {
    640   const original = await seedRecovery(page, true);
    641   const result = await page.evaluate(async ({ command }) => {
    642     const f = window.hcCheckFixture,
    643       held = window.hcCheck.holdCheckNonceOwnerLock();
    644     try {
    645       f.select('recover', 'wss://inbox.example.org', command);
    646       const first = await f.run();
    647       await held.release();
    648       const before = f.host.counts();
    649       f.select('recover', 'wss://inbox.example.org', command);
    650       const second = await f.run();
    651       return {
    652         first: first.status,
    653         second: second.status,
    654         hits: held.hits(),
    655         before,
    656         after: f.host.counts(),
    657         command: f.snapshot()?.command,
    658         row: (await f.host.stored())[0]
    659       };
    660     } finally {
    661       await held.release();
    662       held.restore();
    663     }
    664   }, original);
    665   expect(result.hits).toBe(1);
    666   expect(result.first).toBe('busy');
    667   expect(result.second).toBe('qualified');
    668   expect(result.command).toBe(original.command);
    669   expect(probeRow(result.row.wire).self).toEqual(
    670     probeRow(original.row.wire).self
    671   );
    672   expect(result.after.signs).toBe(result.before.signs);
    673   expect(result.after.encrypts).toBe(result.before.encrypts);
    674   expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(6);
    675   expect(
    676     frames.filter((frame) => frame.type === 'REQ' && !!frame.id)
    677   ).toHaveLength(3);
    678 });
    679 
    680 for (const lane of ['original', 'recover'] as const) {
    681   test(`${lane} optional cleanup requires its own genuine one-use review and yields independently covered removed qualification`, async ({
    682     page
    683   }) => {
    684     const seed =
    685       lane === 'recover' ? await seedRecovery(page, true) : undefined;
    686     const result = await page.evaluate(
    687       async ({ lane, command }) => {
    688         const f = window.hcCheckFixture,
    689           api = window.hcCheck;
    690         f.select(lane, 'wss://inbox.example.org', command);
    691         const checked = await f.run(),
    692           before = f.host.counts();
    693         const disclosure = f.selectCleanup(),
    694           review = f.review()!;
    695         const copied = await api.cleanupInboxAccessCheck(
    696           { ...review },
    697           'reviewed_delete_local_inbox_probe'
    698         );
    699         const wrongKind = await api.runInboxAccessCheck(
    700           review,
    701           'reviewed_inbox_access_check'
    702         );
    703         const wrongSentinel = await f.cleanup('not_reviewed');
    704         const rowsBefore = (await f.host.stored()).length;
    705         const removed = await f.cleanup(),
    706           replay = await f.cleanup();
    707         return {
    708           checked: checked.status,
    709           disclosure,
    710           copied: copied.status,
    711           wrongKind: wrongKind.status,
    712           wrongSentinel: wrongSentinel.status,
    713           rowsBefore,
    714           removed: removed.status,
    715           replay: replay.status,
    716           rowsAfter: (await f.host.stored()).length,
    717           qualified: !!f.qualification(),
    718           qualification:
    719             f.qualification() &&
    720             api.inboxAccessQualificationSnapshot(f.qualification()!),
    721           before,
    722           after: f.host.counts()
    723         };
    724       },
    725       { lane, command: seed?.command }
    726     );
    727     expect(result.checked).toBe('qualified');
    728     expect(result.disclosure?.kind).toBe('cleanup');
    729     expect(result.copied).toBe('invalid');
    730     expect(result.wrongKind).toBe('invalid');
    731     expect(result.wrongSentinel).toBe('invalid');
    732     expect(result.rowsBefore).toBe(1);
    733     expect(result.removed).toBe('removed');
    734     expect(result.replay).toBe('invalid');
    735     expect(result.rowsAfter).toBe(0);
    736     expect(result.qualified).toBe(true);
    737     expect(result.qualification?.sourceOnly).toBe(true);
    738     expect(result.after.signs).toBe(result.before.signs);
    739     expect(result.after.encrypts).toBe(result.before.encrypts);
    740     expect(result.after.decrypts).toBe(result.before.decrypts);
    741   });
    742 }
    743 
    744 test('genuine coordinator capture rejects copied policy, operator, C7, identity, session and repository before effects', async ({
    745   page
    746 }) => {
    747   const result = await page.evaluate(async () => {
    748     const f = window.hcCheckFixture,
    749       api = window.hcCheck,
    750       a = f.actors(),
    751       before = f.host.counts(),
    752       rows = await f.host.stored();
    753     type Args = Parameters<typeof api.createInboxAccessCheck>;
    754     const actual: Args = [
    755       f.repository,
    756       a.identity,
    757       a.session,
    758       f.host.policy,
    759       a.access,
    760       f.host.qualification
    761     ];
    762     const copied = actual.map((_, index) => {
    763       const args = actual.slice() as Args;
    764       args[index] = { ...args[index] };
    765       return !!api.createInboxAccessCheck(...args);
    766     });
    767     const policy = api.createInboxAccessCheck(
    768       f.repository,
    769       a.identity,
    770       a.session,
    771       f.host.copiedPolicy(),
    772       a.access,
    773       f.host.qualification
    774     );
    775     const unsupported = api.createInboxAccessCheck(
    776       f.repository,
    777       a.identity,
    778       a.session,
    779       f.host.policy,
    780       a.access,
    781       f.host.operator(true)
    782     );
    783     const unconfigured = api.createInboxAccessCheck(
    784       f.repository,
    785       a.identity,
    786       a.session,
    787       f.host.policy,
    788       a.access,
    789       f.host.operator(false, true)
    790     );
    791     const foreignRepository = api.createInboxAccessCheck(
    792       f.host.foreignRepository(),
    793       a.identity,
    794       a.session,
    795       f.host.policy,
    796       a.access,
    797       f.host.qualification
    798     );
    799     const otherOperator = api.createInboxAccessCheck(
    800       f.repository,
    801       a.identity,
    802       a.session,
    803       f.host.policy,
    804       a.access,
    805       f.host.operator()
    806     );
    807     return {
    808       copied,
    809       policy: !!policy,
    810       unsupported: !!unsupported,
    811       unconfigured: !!unconfigured,
    812       foreignRepository: !!foreignRepository,
    813       otherOperator: !!otherOperator,
    814       same: api.createInboxAccessCheck(...actual) === f.check(),
    815       before,
    816       after: f.host.counts(),
    817       rows,
    818       afterRows: await f.host.stored()
    819     };
    820   });
    821   expect(result.copied).toEqual([false, false, false, false, false, false]);
    822   expect(result.policy).toBe(false);
    823   expect(result.unsupported).toBe(false);
    824   expect(result.unconfigured).toBe(false);
    825   expect(result.foreignRepository).toBe(false);
    826   expect(result.otherOperator).toBe(false);
    827   expect(result.same).toBe(true);
    828   expect(result.after).toEqual(result.before);
    829   expect(result.afterRows).toEqual(result.rows);
    830   expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(0);
    831 });
    832 
    833 test('unsupported and malformed review targets and recovery ids remain inert before a valid selection', async ({
    834   page
    835 }) => {
    836   const result = await page.evaluate(async () => {
    837     const f = window.hcCheckFixture,
    838       before = f.host.counts();
    839     const rejected = [
    840       f.select('other'),
    841       f.select('original', 'wss://unapproved.example.org'),
    842       f.select('recover', 'wss://inbox.example.org'),
    843       f.select('recover', 'wss://inbox.example.org', 'not-a-command'),
    844       f.select('original', 'wss://inbox.example.org', crypto.randomUUID())
    845     ];
    846     const original = f.select(),
    847       stale = f.review()!;
    848     f.select('original', 'wss://peer.example.org');
    849     const replaced = await window.hcCheck.runInboxAccessCheck(
    850       stale,
    851       'reviewed_inbox_access_check'
    852     );
    853     return {
    854       rejected: rejected.map(Boolean),
    855       original: !!original,
    856       replaced: replaced.status,
    857       before,
    858       after: f.host.counts(),
    859       rows: (await f.host.stored()).length
    860     };
    861   });
    862   expect(result.rejected).toEqual([false, false, false, false, false]);
    863   expect(result.original).toBe(true);
    864   expect(result.replaced).toBe('invalid');
    865   expect(result.after).toEqual(result.before);
    866   expect(result.rows).toBe(0);
    867   expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(0);
    868 });
    869 
    870 for (const lane of ['original', 'recover'] as const) {
    871   for (const contention of ['lock', 'SDK'] as const) {
    872     for (const holds of [1, 2] as const) {
    873       test(`${lane} nonce ${contention} contention ${holds === 1 ? 'retries with later real read' : 'exhausts the combined bound without renewal'}`, async ({
    874         page
    875       }) => {
    876         const seed =
    877           lane === 'recover' ? await seedRecovery(page, true) : undefined;
    878         const result = await page.evaluate(
    879           async ({ lane, command, contention, holds }) => {
    880             const f = window.hcCheckFixture,
    881               api = window.hcCheck;
    882             const held =
    883               contention === 'lock'
    884                 ? api.holdCheckNonceOwnerLock(holds)
    885                 : api.holdCheckNonceSdk(f.actors().session, holds);
    886             const outcomes: string[] = [];
    887             try {
    888               const before = f.host.counts();
    889               for (let n = 0; n < holds + 1; n++) {
    890                 f.select(lane, 'wss://inbox.example.org', command);
    891                 outcomes.push((await f.run()).status);
    892                 await held.release();
    893               }
    894               const row = (await f.host.stored())[0];
    895               return {
    896                 outcomes,
    897                 hits: held.hits(),
    898                 before,
    899                 after: f.host.counts(),
    900                 command: f.snapshot()?.command,
    901                 row,
    902                 qualified: !!f.qualification()
    903               };
    904             } finally {
    905               await held.release();
    906               held.restore();
    907             }
    908           },
    909           { lane, command: seed?.command, contention, holds }
    910         );
    911         expect(result.hits).toBe(holds);
    912         expect(result.outcomes.slice(0, holds)).toEqual(
    913           Array(holds).fill('busy')
    914         );
    915         expect(result.outcomes.at(-1)).toBe(
    916           holds === 1
    917             ? 'qualified'
    918             : lane === 'original'
    919               ? 'stopped'
    920               : 'unavailable'
    921         );
    922         expect(result.qualified).toBe(holds === 1);
    923         const row = JSON.parse(result.row.wire) as {
    924           id: string;
    925           self: { eventId: string };
    926           receipts: {
    927             actionId: string;
    928             eventId: string;
    929             origin: string;
    930             role: string;
    931             status: string;
    932             attempt: number;
    933           }[];
    934         };
    935         const read = row.receipts
    936           .filter(
    937             (fact) =>
    938               fact.role === 'access_readback' && fact.status === 'readback'
    939           )
    940           .at(-1)!;
    941         const action = row.receipts.filter(
    942           (fact) => fact.actionId === read.actionId
    943         );
    944         expect(new Set(action.map((fact) => fact.eventId))).toEqual(
    945           new Set([row.self.eventId])
    946         );
    947         expect(
    948           action
    949             .filter(
    950               (fact) =>
    951                 fact.origin === 'wss://inbox.example.org' &&
    952                 fact.status !== 'nonce_verified'
    953             )
    954             .map((fact) => [fact.role, fact.attempt])
    955         ).toEqual([
    956           ['access_archive', 1],
    957           ['access_readback', 2],
    958           ['access_readback', 3]
    959         ]);
    960         expect(
    961           action
    962             .filter((fact) => fact.status === 'nonce_verified')
    963             .map((fact) => fact.attempt)
    964         ).toEqual(holds === 1 ? [3] : []);
    965         expect(result.command).toBe(row.id);
    966         if (seed) expect(row.self).toEqual(probeRow(seed.row.wire).self);
    967         expect(result.after.signs - result.before.signs).toBe(
    968           lane === 'original' ? 1 : 0
    969         );
    970         expect(result.after.encrypts - result.before.encrypts).toBe(
    971           lane === 'original' ? 1 : 0
    972         );
    973         expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(
    974           lane === 'original' ? 3 : 6
    975         );
    976         expect(
    977           frames.filter((frame) => frame.type === 'REQ' && !!frame.id)
    978         ).toHaveLength(lane === 'original' ? 2 : 3);
    979       });
    980     }
    981   }
    982 }
    983 
    984 test('actual child page reload recovers and qualifies original stored ciphertext in two fresh source realms', async ({
    985   page
    986 }) => {
    987   const setup = await page.evaluate(async () => {
    988     const f = window.hcCheckFixture,
    989       api = window.hcCheck;
    990     f.select();
    991     if ((await f.run()).status !== 'qualified')
    992       throw Error('actual original coordinator qualification');
    993     const row = (await f.host.stored())[0];
    994     const result = {
    995       owner: f.host.owner,
    996       command: f.snapshot()!.command!,
    997       policyWire: JSON.stringify(api.readRelayPolicy(f.host.policy)),
    998       operatorWire: api.inboxOperatorQualificationWire(
    999         f.host.qualification,
   1000         f.host.policy
   1001       )!,
   1002       row
   1003     };
   1004     f.stop();
   1005     return result;
   1006   });
   1007   await expect
   1008     .poll(
   1009       () =>
   1010         [...physical].filter(
   1011           (socket) =>
   1012             physicalOrigins.get(socket) !== 'wss://discovery.example.org'
   1013         ).length
   1014     )
   1015     .toBe(0);
   1016   expect(await page.evaluate(() => window.hcCheckFixture.retryCleanup())).toBe(
   1017     true
   1018   );
   1019   await page.evaluate((url) => {
   1020     const iframe = document.createElement('iframe');
   1021     iframe.id = 'coordinator-reload';
   1022     iframe.src = url;
   1023     document.body.append(iframe);
   1024   }, server.url + '/search');
   1025   const frame = await (
   1026     await page.locator('#coordinator-reload').elementHandle()
   1027   ).contentFrame();
   1028   if (!frame) throw Error('actual child source realm missing');
   1029   await frame.waitForLoadState();
   1030   try {
   1031     for (let cycle = 0; cycle < 2; cycle++) {
   1032       if (cycle) await frame.goto(server.url + '/search');
   1033       await frame.addScriptTag({ content: bundle });
   1034       await frame.evaluate(async (setup) => {
   1035         window.hcHostedCheck = await window.hcCheck.openHostedCheck(setup);
   1036       }, setup);
   1037       const before = await page.evaluate(() =>
   1038         window.hcCheckFixture.host.counts()
   1039       );
   1040       const result = await frame.evaluate(async (setup) => {
   1041         const api = window.hcCheck,
   1042           { check } = window.hcHostedCheck;
   1043         const selected = api.reviewInboxAccessCheck(
   1044           check,
   1045           'recover',
   1046           'wss://inbox.example.org',
   1047           setup.command
   1048         );
   1049         if (!selected) throw Error('actual hosted recovery review missing');
   1050         const result = await api.runInboxAccessCheck(
   1051           selected,
   1052           'reviewed_inbox_access_check'
   1053         );
   1054         const output = {
   1055           status: result.status,
   1056           command: api.inboxAccessCheckSnapshot(check)?.command,
   1057           qualified: !!api.inboxAccessCheckQualification(check)
   1058         };
   1059         api.stopInboxAccessCheck(check);
   1060         return output;
   1061       }, setup);
   1062       expect(result).toEqual({
   1063         status: 'qualified',
   1064         command: setup.command,
   1065         qualified: true
   1066       });
   1067       await expect
   1068         .poll(
   1069           () =>
   1070             [...physical].filter(
   1071               (socket) =>
   1072                 physicalOrigins.get(socket) !== 'wss://discovery.example.org'
   1073             ).length
   1074         )
   1075         .toBe(0);
   1076       await frame.evaluate(() => {
   1077         const { check, context } = window.hcHostedCheck;
   1078         if (!window.hcCheck.stopInboxAccessCheck(check))
   1079           throw Error('actual hosted physical cleanup incomplete');
   1080         context.close();
   1081       });
   1082       const after = await page.evaluate(() =>
   1083         window.hcCheckFixture.host.counts()
   1084       );
   1085       expect(after.signs).toBe(before.signs);
   1086       expect(after.encrypts).toBe(before.encrypts);
   1087       const row = await page.evaluate(
   1088         async () => (await window.hcCheckFixture.host.stored())[0]
   1089       );
   1090       expect(probeRow(row.wire).self).toEqual(probeRow(setup.row.wire).self);
   1091       expect(probeRow(row.wire).rumorHash).toBe(
   1092         probeRow(setup.row.wire).rumorHash
   1093       );
   1094     }
   1095   } finally {
   1096     await frame.evaluate(() => {
   1097       if (window.hcHostedCheck) {
   1098         window.hcCheck.stopInboxAccessCheck(window.hcHostedCheck.check);
   1099         window.hcHostedCheck.context.close();
   1100       }
   1101     });
   1102     await page
   1103       .locator('#coordinator-reload')
   1104       .evaluate((element) => element.remove());
   1105   }
   1106   expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(9);
   1107   expect(
   1108     new Set(
   1109       frames.filter((frame) => frame.type === 'EVENT').map((frame) => frame.id)
   1110     ).size
   1111   ).toBe(1);
   1112 });
   1113 
   1114 for (const lane of ['original', 'recover'] as const) {
   1115   for (const fault of [
   1116     'refused',
   1117     'wrong_ack',
   1118     'disconnect',
   1119     'missing',
   1120     'wrong_read'
   1121   ] as const) {
   1122     test(`${lane} actual ${fault} wire outcome cannot qualify or fabricate successful readback`, async ({
   1123       page
   1124     }) => {
   1125       const seed =
   1126         lane === 'recover' ? await seedRecovery(page, true) : undefined;
   1127       const priorEvents = frames.filter(
   1128         (frame) => frame.type === 'EVENT'
   1129       ).length;
   1130       wireFault = fault;
   1131       const result = await page.evaluate(
   1132         async ({ lane, command }) => {
   1133           const f = window.hcCheckFixture;
   1134           f.select(lane, 'wss://inbox.example.org', command);
   1135           const completed = await f.run();
   1136           return {
   1137             status: completed.status,
   1138             qualification: !!f.qualification(),
   1139             snapshot: f.snapshot(),
   1140             rows: await f.host.stored()
   1141           };
   1142         },
   1143         { lane, command: seed?.command }
   1144       );
   1145       expect(result.status).not.toBe('qualified');
   1146       expect(result.qualification).toBe(false);
   1147       expect(result.rows).toHaveLength(1);
   1148       const row = JSON.parse(result.rows[0].wire) as {
   1149         self: { eventId: string };
   1150         receipts: { status: string; actionId: string }[];
   1151       };
   1152       const added = row.receipts.slice(
   1153         seed ? probeRow(seed.row.wire).receipts.length : 0
   1154       );
   1155       expect(added.some((fact) => fact.status === 'nonce_verified')).toBe(
   1156         false
   1157       );
   1158       if (fault === 'missing' || fault === 'wrong_read') {
   1159         expect(added.filter((fact) => fact.status === 'accepted')).toHaveLength(
   1160           3
   1161         );
   1162         expect(added.some((fact) => fact.status === 'readback')).toBe(false);
   1163       } else {
   1164         expect(added.some((fact) => fact.status === 'accepted')).toBe(false);
   1165         expect(
   1166           frames.filter((frame) => frame.type === 'EVENT').length - priorEvents
   1167         ).toBe(1);
   1168       }
   1169       if (seed) expect(row.self).toEqual(probeRow(seed.row.wire).self);
   1170     });
   1171   }
   1172   for (const fault of ['stop', 'head', 'session'] as const) {
   1173     for (const callback of ['key', 'cipher'] as const) {
   1174       test(`${lane} actual ${callback} callback ${fault} loss cannot continue effects or issue qualification`, async ({
   1175         page
   1176       }) => {
   1177         const seed =
   1178           lane === 'recover' ? await seedRecovery(page, true) : undefined;
   1179         const priorEvents = frames.filter(
   1180           (frame) => frame.type === 'EVENT'
   1181         ).length;
   1182         const result = await page.evaluate(
   1183           async ({ lane, command, fault, callback }) => {
   1184             const f = window.hcCheckFixture,
   1185               api = window.hcCheck;
   1186             let hits = 0;
   1187             const lose = () => {
   1188               if (hits++) return;
   1189               if (fault === 'stop') f.stop();
   1190               else if (fault === 'head') f.actors().churnHead();
   1191               else api.closePrivateSession(f.actors().session);
   1192             };
   1193             const restore =
   1194               callback === 'key'
   1195                 ? f.host.keyCallback(1, lose)
   1196                 : f.host.cipherGetter(lose);
   1197             try {
   1198               f.select(lane, 'wss://inbox.example.org', command);
   1199               const result = await f.run();
   1200               return {
   1201                 status: result.status,
   1202                 hits,
   1203                 qualified: !!f.qualification(),
   1204                 snapshot: f.snapshot(),
   1205                 rows: await f.host.stored()
   1206               };
   1207             } finally {
   1208               restore();
   1209             }
   1210           },
   1211           { lane, command: seed?.command, fault, callback }
   1212         );
   1213         expect(result.hits).toBeGreaterThan(0);
   1214         expect(result.status).not.toBe('qualified');
   1215         expect(result.qualified).toBe(false);
   1216         expect(result.snapshot?.state).toBe('stopped');
   1217         expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(
   1218           priorEvents
   1219         );
   1220         if (seed) expect(result.rows).toEqual([seed.row]);
   1221       });
   1222     }
   1223   }
   1224   for (const closeMode of ['hold', 'fail'] as const) {
   1225     test(`${lane} actual ${closeMode} physical close retains cleanup requirement until explicit retry`, async ({
   1226       page
   1227     }) => {
   1228       const seed =
   1229         lane === 'recover' ? await seedRecovery(page, true) : undefined;
   1230       const result = await page.evaluate(
   1231         async ({ lane, command, closeMode }) => {
   1232           const f = window.hcCheckFixture;
   1233           f.select(lane, 'wss://inbox.example.org', command);
   1234           const checked = await f.run();
   1235           window.hcCheckCloseMode = closeMode;
   1236           const stopped = f.stop(),
   1237             snapshot = f.snapshot(),
   1238             closes = window.hcCheckCloseCalls;
   1239           const selection = f.select(lane, 'wss://inbox.example.org', command);
   1240           const observed = f.snapshot();
   1241           return {
   1242             checked: checked.status,
   1243             stopped,
   1244             snapshot,
   1245             selection,
   1246             observed,
   1247             closes,
   1248             afterCloses: window.hcCheckCloseCalls,
   1249             qualified: !!f.qualification(),
   1250             held: window.hcCheckHeldClose?.length ?? 0
   1251           };
   1252         },
   1253         { lane, command: seed?.command, closeMode }
   1254       );
   1255       expect(result.checked).toBe('qualified');
   1256       expect(result.stopped).toBe(false);
   1257       expect(result.snapshot?.cleanupRequired).toBe(true);
   1258       expect(result.observed?.cleanupRequired).toBe(true);
   1259       expect(result.selection).toBeUndefined();
   1260       expect(result.afterCloses).toBe(result.closes);
   1261       expect(result.qualified).toBe(false);
   1262       if (closeMode === 'hold') expect(result.held).toBeGreaterThan(0);
   1263       await page.evaluate(() => {
   1264         window.hcCheckCloseMode = undefined;
   1265         for (const release of window.hcCheckHeldClose ?? []) release();
   1266         window.hcCheckHeldClose = [];
   1267         window.hcCheckFixture.retryCleanup();
   1268       });
   1269       await expect
   1270         .poll(
   1271           () =>
   1272             [...physical].filter(
   1273               (socket) =>
   1274                 physicalOrigins.get(socket) !== 'wss://discovery.example.org'
   1275             ).length
   1276         )
   1277         .toBe(0);
   1278       expect(
   1279         await page.evaluate(() => window.hcCheckFixture.retryCleanup())
   1280       ).toBe(true);
   1281     });
   1282   }
   1283 }
   1284 
   1285 test('authentic pending archive survives Stop and requires a distinct reviewed historical reconciliation without new effects', async ({
   1286   page
   1287 }) => {
   1288   holdArchive = true;
   1289   await page.evaluate(() => {
   1290     const f = window.hcCheckFixture;
   1291     f.select();
   1292     window.hcCheckPending = f.run();
   1293   });
   1294   await expect.poll(() => !!releaseArchive).toBe(true);
   1295   await page.evaluate(() => {
   1296     // Publication correctly owns the real lock through its network result.
   1297     // Queue the competing holder, then release the actual ACK so it acquires
   1298     // before append's separate ifAvailable request; never wait out the relay.
   1299     window.hcCheckLockReady = window.hcCheck
   1300       .holdCheckOwnerLock(window.hcCheckFixture.host.owner)
   1301       .then((release) => {
   1302         window.hcCheckRelease = release;
   1303       });
   1304   });
   1305   holdArchive = false;
   1306   releaseArchive!();
   1307   const pending = await page.evaluate(async () => {
   1308     await window.hcCheckLockReady;
   1309     const f = window.hcCheckFixture,
   1310       completed = await window.hcCheckPending;
   1311     const snapshot = f.snapshot();
   1312     f.stop();
   1313     await window.hcCheckRelease!();
   1314     window.hcCheckRelease = undefined;
   1315     return { status: completed.status, snapshot };
   1316   });
   1317   expect(pending.status).toBe('busy');
   1318   expect(pending.snapshot?.pendingSettlement).toBe(true);
   1319   const reconciled = await page.evaluate(async () => {
   1320     const f = window.hcCheckFixture,
   1321       api = window.hcCheck,
   1322       before = f.host.counts();
   1323     const disclosure = f.selectReconciliation(),
   1324       selected = f.review()!;
   1325     const copied = await api.reconcileInboxAccessCheck(
   1326       { ...selected },
   1327       'reviewed_inbox_access_check_reconciliation'
   1328     );
   1329     const wrongKind = await api.cleanupInboxAccessCheck(
   1330       selected,
   1331       'reviewed_delete_local_inbox_probe'
   1332     );
   1333     const result = await f.reconcile(),
   1334       replay = await f.reconcile();
   1335     return {
   1336       disclosure,
   1337       copied: copied.status,
   1338       wrongKind: wrongKind.status,
   1339       status: result.status,
   1340       replay: replay.status,
   1341       before,
   1342       after: f.host.counts(),
   1343       snapshot: f.snapshot(),
   1344       qualified: !!f.qualification(),
   1345       rows: await f.host.stored()
   1346     };
   1347   });
   1348   expect(reconciled.disclosure?.kind).toBe('reconcile');
   1349   expect(reconciled.copied).toBe('invalid');
   1350   expect(reconciled.wrongKind).toBe('invalid');
   1351   expect(['saved', 'existing', 'reconciled']).toContain(reconciled.status);
   1352   expect(reconciled.replay).toBe('invalid');
   1353   expect(reconciled.after).toEqual(reconciled.before);
   1354   expect(reconciled.snapshot?.pendingSettlement).toBe(false);
   1355   expect(reconciled.qualified).toBe(false);
   1356   expect(reconciled.snapshot?.state).toBe('stopped');
   1357   expect(
   1358     probeRow(reconciled.rows[0].wire).receipts.filter(
   1359       (fact: { status: string }) => fact.status === 'accepted'
   1360     )
   1361   ).toHaveLength(1);
   1362   expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(1);
   1363 });
   1364 
   1365 async function beginActualAuth(page: Page, mode: 'accept' | 'refuse' | 'hold') {
   1366   challenge = true;
   1367   authMode = mode;
   1368   const before = frames.filter((frame) => frame.type === 'AUTH').length;
   1369   // On a cold socket this API initially observes stopped until actual open;
   1370   // the following real challenge observation is required before responding.
   1371   expect(['waiting', 'challenge', 'stopped']).toContain(
   1372     await page.evaluate(() =>
   1373       window.hcCheck.authenticateInboxAccess(
   1374         window.hcCheckFixture.actors().access,
   1375         'wss://inbox.example.org',
   1376         'reviewed_inbox_connection_auth'
   1377       )
   1378     )
   1379   );
   1380   await expect
   1381     .poll(() =>
   1382       page.evaluate(
   1383         () =>
   1384           window.hcCheck
   1385             .inboxAccessControllerSourceSnapshot(
   1386               window.hcCheckFixture.actors().access
   1387             )
   1388             ?.auth.find((row) => row.origin === 'wss://inbox.example.org')
   1389             ?.state
   1390       )
   1391     )
   1392     .toBe('challenge');
   1393   await page.evaluate(() => {
   1394     window.hcCheckAuthPending = window.hcCheck.respondInboxAccessAuthentication(
   1395       window.hcCheckFixture.actors().access,
   1396       'wss://inbox.example.org',
   1397       'reviewed_inbox_auth_response'
   1398     );
   1399   });
   1400   await expect
   1401     .poll(() => frames.filter((frame) => frame.type === 'AUTH').length)
   1402     .toBe(before + 1);
   1403   if (mode !== 'hold')
   1404     expect(await page.evaluate(() => window.hcCheckAuthPending)).toBe(
   1405       mode === 'accept' ? 'accepted' : 'refused'
   1406     );
   1407 }
   1408 
   1409 test('required AUTH pending response refuses coordinator work without a second SDK job or diagnostic effect', async ({
   1410   page
   1411 }) => {
   1412   await beginActualAuth(page, 'hold');
   1413   try {
   1414     const result = await page.evaluate(async () => {
   1415       const f = window.hcCheckFixture,
   1416         before = f.host.counts();
   1417       f.select();
   1418       const result = await f.run();
   1419       return {
   1420         status: result.status,
   1421         before,
   1422         after: f.host.counts(),
   1423         rows: await f.host.stored(),
   1424         qualified: !!f.qualification()
   1425       };
   1426     });
   1427     expect(result.status).not.toBe('qualified');
   1428     expect(result.qualified).toBe(false);
   1429     expect(result.after).toEqual(result.before);
   1430     expect(result.rows).toHaveLength(0);
   1431     expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(0);
   1432     expect(frames.filter((frame) => frame.type === 'AUTH')).toHaveLength(1);
   1433   } finally {
   1434     releaseAuth!();
   1435     await page.evaluate(() => window.hcCheckAuthPending);
   1436   }
   1437 });
   1438 
   1439 for (const lane of ['original', 'recover'] as const) {
   1440   for (const auth of ['accept', 'refuse', 'hold'] as const) {
   1441     test(`${lane} required AUTH ${auth} uses genuine C7 response and preserves source-only presentation`, async ({
   1442       page
   1443     }) => {
   1444       let seed: Awaited<ReturnType<typeof seedRecovery>> | undefined;
   1445       if (lane === 'recover') {
   1446         await beginActualAuth(page, 'accept');
   1447         seed = await seedRecovery(page, true);
   1448       }
   1449       await beginActualAuth(page, auth);
   1450       const inert = await page.evaluate(() => ({
   1451         qualified: !!window.hcCheckFixture.qualification(),
   1452         readiness: window.hcCheck.inboxAccessControllerSnapshot(
   1453           window.hcCheckFixture.actors().access
   1454         )?.readiness
   1455       }));
   1456       expect(inert).toEqual({ qualified: false, readiness: 'unavailable' });
   1457       if (auth === 'hold') {
   1458         expect(
   1459           await page.evaluate(
   1460             () =>
   1461               window.hcCheck
   1462                 .inboxAccessControllerSourceSnapshot(
   1463                   window.hcCheckFixture.actors().access
   1464                 )
   1465                 ?.auth.find((row) => row.origin === 'wss://inbox.example.org')
   1466                 ?.state
   1467           )
   1468         ).toBe('signing');
   1469         expect(releaseAuth).toBeDefined();
   1470         releaseAuth!();
   1471         expect(await page.evaluate(() => window.hcCheckAuthPending)).toBe(
   1472           'accepted'
   1473         );
   1474       }
   1475       const result = await page.evaluate(
   1476         async ({ lane, command }) => {
   1477           const f = window.hcCheckFixture;
   1478           f.select(lane, 'wss://inbox.example.org', command);
   1479           const result = await f.run();
   1480           return {
   1481             status: result.status,
   1482             qualified: !!f.qualification(),
   1483             readiness: window.hcCheck.inboxAccessControllerSnapshot(
   1484               f.actors().access
   1485             )?.readiness,
   1486             sourceOnly: f.snapshot()?.sourceOnly
   1487           };
   1488         },
   1489         { lane, command: seed?.command }
   1490       );
   1491       expect(result.readiness).toBe('unavailable');
   1492       expect(result.sourceOnly).toBe(true);
   1493       if (auth === 'refuse') {
   1494         expect(result.status).not.toBe('qualified');
   1495         expect(result.qualified).toBe(false);
   1496       } else {
   1497         expect(result.status).toBe('qualified');
   1498         expect(result.qualified).toBe(true);
   1499         const before = await page.evaluate(() =>
   1500           window.hcCheckFixture.host.counts()
   1501         );
   1502         for (const socket of physical)
   1503           if (physicalOrigins.get(socket) === 'wss://inbox.example.org')
   1504             socket.send(JSON.stringify(['AUTH', 's5c-genuine-new-challenge']));
   1505         await expect
   1506           .poll(() =>
   1507             page.evaluate(
   1508               () =>
   1509                 window.hcCheck
   1510                   .inboxAccessControllerSourceSnapshot(
   1511                     window.hcCheckFixture.actors().access
   1512                   )
   1513                   ?.auth.find((row) => row.origin === 'wss://inbox.example.org')
   1514                   ?.state
   1515             )
   1516           )
   1517           .toBe('challenge');
   1518         expect(
   1519           await page.evaluate(() => !!window.hcCheckFixture.qualification())
   1520         ).toBe(false);
   1521         expect(
   1522           await page.evaluate(() => window.hcCheckFixture.host.counts())
   1523         ).toEqual(before);
   1524       }
   1525     });
   1526   }
   1527 }
   1528 
   1529 for (const lane of ['original', 'recover'] as const) {
   1530   for (const mode of ['missing', 'corrupt', 'alias', 'foreign'] as const) {
   1531     test(`${lane} actual nonce-stage ${mode} native journal observation preserves source qualification rules`, async ({
   1532       page
   1533     }) => {
   1534       const seed =
   1535         lane === 'recover' ? await seedRecovery(page, true) : undefined;
   1536       const result = await page.evaluate(
   1537         async ({ lane, command, mode }) => {
   1538           const f = window.hcCheckFixture,
   1539             api = window.hcCheck;
   1540           const hook = api.atCheckNonce(async () => {
   1541             const row = (await f.host.stored()).find(
   1542               (row) =>
   1543                 row.owner === f.host.owner && row.id === f.snapshot()?.command
   1544             );
   1545             if (!row)
   1546               throw Error(
   1547                 'actual selected native journal missing before mutation'
   1548               );
   1549             await api.changeCheckNativeRow(row, mode);
   1550           });
   1551           try {
   1552             f.select(lane, 'wss://inbox.example.org', command);
   1553             const result = await f.run();
   1554             return {
   1555               status: result.status,
   1556               hits: hook.hits(),
   1557               qualified: !!f.qualification(),
   1558               rows: await f.host.stored()
   1559             };
   1560           } finally {
   1561             hook.restore();
   1562           }
   1563         },
   1564         { lane, command: seed?.command, mode }
   1565       );
   1566       expect(result.hits).toBe(1);
   1567       if (mode === 'foreign') {
   1568         expect(result.status).toBe('qualified');
   1569         expect(result.qualified).toBe(true);
   1570         expect(result.rows).toHaveLength(2);
   1571         expect(new Set(result.rows.map((row) => row.owner)).size).toBe(2);
   1572       } else {
   1573         expect(result.status).not.toBe('qualified');
   1574         expect(result.qualified).toBe(false);
   1575       }
   1576     });
   1577   }
   1578   test(`${lane} actual native admission abort cannot become qualification`, async ({
   1579     page
   1580   }) => {
   1581     const seed =
   1582       lane === 'recover' ? await seedRecovery(page, true) : undefined;
   1583     const result = await page.evaluate(
   1584       async ({ lane, command }) => {
   1585         const f = window.hcCheckFixture,
   1586           fault = f.installCommitFault('aborted');
   1587         try {
   1588           f.select(lane, 'wss://inbox.example.org', command);
   1589           const result = await f.run();
   1590           const rows = await f.host.stored();
   1591           return {
   1592             status: result.status,
   1593             counts: fault.counts(),
   1594             qualified: !!f.qualification(),
   1595             rows
   1596           };
   1597         } finally {
   1598           fault.restore();
   1599         }
   1600       },
   1601       { lane, command: seed?.command }
   1602     );
   1603     expect(result.counts.aborted).toBe(1);
   1604     expect(result.status).not.toBe('qualified');
   1605     expect(result.qualified).toBe(false);
   1606     if (lane === 'recover') {
   1607       const reconciled = await page.evaluate(async () => {
   1608         const f = window.hcCheckFixture;
   1609         if (!f.snapshot()?.pendingSettlement) return 'no_pending';
   1610         if (!f.selectReconciliation())
   1611           throw Error('actual aborted attempt review missing');
   1612         return (await f.reconcile()).status;
   1613       });
   1614       expect(['saved', 'existing', 'reconciled']).toContain(reconciled);
   1615     }
   1616     if (seed) expect(result.rows).toEqual([seed.row]);
   1617     else {
   1618       expect(result.rows).toHaveLength(0);
   1619       expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(0);
   1620     }
   1621   });
   1622   test(`${lane} actual reviewed cleanup abort preserves the journal and permanently invalidates the old journal qualification`, async ({
   1623     page
   1624   }) => {
   1625     const seed =
   1626       lane === 'recover' ? await seedRecovery(page, true) : undefined;
   1627     const result = await page.evaluate(
   1628       async ({ lane, command }) => {
   1629         const f = window.hcCheckFixture,
   1630           api = window.hcCheck;
   1631         f.select(lane, 'wss://inbox.example.org', command);
   1632         const checked = await f.run(),
   1633           old = f.qualification()!,
   1634           before = await f.host.stored(),
   1635           fault = api.abortCheckCleanup();
   1636         try {
   1637           f.selectCleanup();
   1638           const removed = await f.cleanup();
   1639           const after = await f.host.stored();
   1640           return {
   1641             checked: checked.status,
   1642             status: removed.status,
   1643             aborts: fault.aborts(),
   1644             before,
   1645             after,
   1646             qualified: !!f.qualification(),
   1647             oldSnapshot: api.inboxAccessQualificationSnapshot(old),
   1648             afterSnapshot: api.inboxAccessQualificationSnapshot(old)
   1649           };
   1650         } finally {
   1651           fault.restore();
   1652         }
   1653       },
   1654       { lane, command: seed?.command }
   1655     );
   1656     expect(result.checked).toBe('qualified');
   1657     expect(result.aborts).toBe(1);
   1658     expect(result.status).not.toBe('removed');
   1659     expect(result.after).toEqual(result.before);
   1660     expect(result.qualified).toBe(false);
   1661     expect(result.oldSnapshot).toBeUndefined();
   1662     expect(result.afterSnapshot).toBeUndefined();
   1663   });
   1664   for (const cleanup of [false, true]) {
   1665     test(`${lane} actual own InboxSync ${cleanup ? 'after reviewed cleanup retains then rejects the self message' : 'excludes the live genuine diagnostic journal'} without losing qualification`, async ({
   1666       page
   1667     }) => {
   1668       const seed =
   1669         lane === 'recover' ? await seedRecovery(page, true) : undefined;
   1670       const started = await page.evaluate(
   1671         async ({ lane, command, cleanup }) => {
   1672           const f = window.hcCheckFixture;
   1673           f.select(lane, 'wss://inbox.example.org', command);
   1674           if ((await f.run()).status !== 'qualified')
   1675             throw Error('actual coordinator qualification required');
   1676           if (cleanup) {
   1677             f.selectCleanup();
   1678             if ((await f.cleanup()).status !== 'removed')
   1679               throw Error('actual optional removal required');
   1680           }
   1681           return f.startOwnInbox();
   1682         },
   1683         { lane, command: seed?.command, cleanup }
   1684       );
   1685       expect(started).toBe(true);
   1686       await expect
   1687         .poll(() =>
   1688           page.evaluate(() => {
   1689             const s = window.hcCheckFixture.syncSnapshot();
   1690             return (
   1691               !!s && s.pending === 0 && (s.excludedProbes > 0 || s.retained > 0)
   1692             );
   1693           })
   1694         )
   1695         .toBe(true);
   1696       const result = await page.evaluate(async (cleanup) => {
   1697         const f = window.hcCheckFixture,
   1698           before = f.host.counts();
   1699         const decrypted = cleanup ? await f.decryptReceived() : undefined;
   1700         return {
   1701           snapshot: f.syncSnapshot(),
   1702           qualified: !!f.qualification(),
   1703           decrypted,
   1704           before,
   1705           after: f.host.counts(),
   1706           rows: (await f.host.stored()).length
   1707         };
   1708       }, cleanup);
   1709       expect(result.qualified).toBe(true);
   1710       if (cleanup) {
   1711         expect(result.snapshot?.retained).toBe(1);
   1712         expect(result.snapshot?.excludedProbes).toBe(0);
   1713         expect(result.decrypted?.rooms).toBe(0);
   1714         expect(result.decrypted?.snapshot.invalid).toBe(1);
   1715         expect(result.after.decrypts - result.before.decrypts).toBe(2);
   1716         expect(result.rows).toBe(0);
   1717       } else {
   1718         expect(result.snapshot?.retained).toBe(0);
   1719         expect(result.snapshot?.excludedProbes).toBeGreaterThan(0);
   1720         expect(result.after).toEqual(result.before);
   1721         expect(result.rows).toBe(1);
   1722       }
   1723     });
   1724   }
   1725 }
   1726 
   1727 for (const lane of ['original', 'recover'] as const) {
   1728   for (const mode of [
   1729     'wrong_key',
   1730     'refuse_decrypt',
   1731     'wrong_decrypt'
   1732   ] as const) {
   1733     test(`${lane} actual nonce provider ${mode} cannot qualify or silently repeat rejected crypto`, async ({
   1734       page
   1735     }) => {
   1736       const seed =
   1737         lane === 'recover' ? await seedRecovery(page, true) : undefined;
   1738       const result = await page.evaluate(
   1739         async ({ lane, command, mode }) => {
   1740           const f = window.hcCheckFixture,
   1741             hook = window.hcCheck.atCheckNonce(async () => {
   1742               f.host.mode(mode);
   1743               await Promise.resolve();
   1744             });
   1745           try {
   1746             f.select(lane, 'wss://inbox.example.org', command);
   1747             const first = await f.run(),
   1748               before = f.host.counts();
   1749             f.host.mode('normal');
   1750             const selection = f.select(
   1751               lane,
   1752               'wss://inbox.example.org',
   1753               command
   1754             );
   1755             const second = selection ? await f.run() : undefined;
   1756             return {
   1757               first: first.status,
   1758               second: second?.status,
   1759               hits: hook.hits(),
   1760               before,
   1761               after: f.host.counts(),
   1762               rows: await f.host.stored(),
   1763               qualified: !!f.qualification()
   1764             };
   1765           } finally {
   1766             hook.restore();
   1767             f.host.mode('normal');
   1768           }
   1769         },
   1770         { lane, command: seed?.command, mode }
   1771       );
   1772       expect(result.hits).toBe(1);
   1773       expect(result.first).not.toBe('qualified');
   1774       expect(result.second).not.toBe('qualified');
   1775       expect(result.qualified).toBe(false);
   1776       expect(result.after).toEqual(result.before);
   1777       const oldFacts = seed ? probeRow(seed.row.wire).receipts.length : 0;
   1778       expect(
   1779         probeRow(result.rows[0].wire)
   1780           .receipts.slice(oldFacts)
   1781           .some((fact) => fact.status === 'nonce_verified')
   1782       ).toBe(false);
   1783     });
   1784   }
   1785   for (const loss of ['stop', 'head', 'session'] as const) {
   1786     test(`${lane} actual held nonce decrypt ${loss} loss retains the admitted promise until real settlement`, async ({
   1787       page
   1788     }) => {
   1789       const seed =
   1790         lane === 'recover' ? await seedRecovery(page, true) : undefined;
   1791       await page.evaluate(
   1792         ({ lane, command }) => {
   1793           const f = window.hcCheckFixture;
   1794           window.hcCheckRestore = window.hcCheck.atCheckNonce(async () => {
   1795             f.host.mode('hold_decrypt');
   1796             await Promise.resolve();
   1797           }).restore;
   1798           f.select(lane, 'wss://inbox.example.org', command);
   1799           window.hcCheckPending = f.run();
   1800         },
   1801         { lane, command: seed?.command }
   1802       );
   1803       await expect
   1804         .poll(() => page.evaluate(() => window.hcCheckFixture.host.waiting()))
   1805         .toBe('decrypt');
   1806       const during = await page.evaluate((loss) => {
   1807         const f = window.hcCheckFixture;
   1808         if (loss === 'stop') f.stop();
   1809         else if (loss === 'head') f.actors().churnHead();
   1810         else window.hcCheck.closePrivateSession(f.actors().session);
   1811         const result = {
   1812           snapshot: f.snapshot(),
   1813           qualified: !!f.qualification(),
   1814           counts: f.host.counts(),
   1815           waiting: f.host.waiting()
   1816         };
   1817         f.host.settle();
   1818         return result;
   1819       }, loss);
   1820       expect(during.snapshot?.state).toBe('stopped');
   1821       expect(during.snapshot?.busy).toBe(true);
   1822       expect(during.qualified).toBe(false);
   1823       expect(during.waiting).toBe('decrypt');
   1824       const after = await page.evaluate(async () => {
   1825         const f = window.hcCheckFixture,
   1826           result = await window.hcCheckPending;
   1827         f.host.mode('normal');
   1828         return {
   1829           status: result.status,
   1830           snapshot: f.snapshot(),
   1831           counts: f.host.counts(),
   1832           qualified: !!f.qualification(),
   1833           rows: await f.host.stored()
   1834         };
   1835       });
   1836       expect(after.status).toBe('stopped');
   1837       expect(after.snapshot?.busy).toBe(false);
   1838       expect(after.qualified).toBe(false);
   1839       expect(after.counts).toEqual(during.counts);
   1840       const oldFacts = seed ? probeRow(seed.row.wire).receipts.length : 0;
   1841       expect(
   1842         probeRow(after.rows[0].wire)
   1843           .receipts.slice(oldFacts)
   1844           .some((fact) => fact.status === 'nonce_verified')
   1845       ).toBe(false);
   1846     });
   1847   }
   1848   test(`${lane} real held first key admits no reentry and Stop protects unfinished journal without a replacement artifact`, async ({
   1849     page
   1850   }) => {
   1851     const seed =
   1852       lane === 'recover' ? await seedRecovery(page, true) : undefined;
   1853     const priorEvents = frames.filter((frame) => frame.type === 'EVENT').length;
   1854     await page.evaluate(
   1855       ({ lane, command }) => {
   1856         const f = window.hcCheckFixture;
   1857         f.host.mode('hold_key');
   1858         f.select(lane, 'wss://inbox.example.org', command);
   1859         window.hcCheckPending = f.run();
   1860       },
   1861       { lane, command: seed?.command }
   1862     );
   1863     await expect
   1864       .poll(() => page.evaluate(() => window.hcCheckFixture.host.waiting()))
   1865       .toBe('key');
   1866     const during = await page.evaluate(
   1867       async ({ lane, command }) => {
   1868         const f = window.hcCheckFixture,
   1869           api = window.hcCheck,
   1870           before = f.host.counts(),
   1871           consumed = f.review()!;
   1872         const reentry = await api.runInboxAccessCheck(
   1873           consumed,
   1874           'reviewed_inbox_access_check'
   1875         );
   1876         const selection = f.select(lane, 'wss://inbox.example.org', command);
   1877         f.stop();
   1878         const snapshot = f.snapshot(),
   1879           counts = f.host.counts();
   1880         f.host.settle();
   1881         return { before, counts, reentry: reentry.status, selection, snapshot };
   1882       },
   1883       { lane, command: seed?.command }
   1884     );
   1885     expect(during.reentry).toBe('invalid');
   1886     expect(during.selection).toBeUndefined();
   1887     expect(during.counts).toEqual(during.before);
   1888     expect(during.snapshot?.state).toBe('stopped');
   1889     expect(during.snapshot?.busy).toBe(true);
   1890     const after = await page.evaluate(async () => {
   1891       const f = window.hcCheckFixture,
   1892         result = await window.hcCheckPending;
   1893       f.host.mode('normal');
   1894       return {
   1895         status: result.status,
   1896         counts: f.host.counts(),
   1897         rows: await f.host.stored(),
   1898         qualified: !!f.qualification()
   1899       };
   1900     });
   1901     expect(after.status).toBe('stopped');
   1902     expect(after.qualified).toBe(false);
   1903     expect(after.counts).toEqual(during.counts);
   1904     expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(
   1905       priorEvents
   1906     );
   1907     if (seed) expect(after.rows).toEqual([seed.row]);
   1908     else expect(probeRow(after.rows[0].wire).self).toBeNull();
   1909   });
   1910 }
   1911 
   1912 async function seedOrdinaryRow(page: Page, foreign = false) {
   1913   return page.evaluate(async (foreign) => {
   1914     const f = window.hcCheckFixture;
   1915     const owner = foreign ? window.hcCheck.otherCheckOwner() : f.host.owner;
   1916     const id = crypto.randomUUID(),
   1917       peer = window.hcCheck.otherCheckOwner();
   1918     if (owner === peer || (foreign && owner === f.host.owner))
   1919       throw Error('actual distinct public fixture owners required');
   1920     const wire = JSON.stringify({
   1921       schema: 1,
   1922       family: 'private_send_reservation',
   1923       owner,
   1924       id,
   1925       revision: 0,
   1926       peer,
   1927       rumorHash: 'a'.repeat(64),
   1928       createdAt: Math.floor(Date.now() / 1000)
   1929     });
   1930     if (!window.hcCheck.decodePrivateRecord(wire, owner, id).ok)
   1931       throw Error('actual canonical schema1 ordinary reservation fixture');
   1932     const row = { owner, id, wire };
   1933     await f.host.inject([row]);
   1934     return row;
   1935   }, foreign);
   1936 }
   1937 
   1938 for (const selected of ['absent', 'ordinary', 'foreign'] as const) {
   1939   test(`cold recovery rejects an actual ${selected} stored selection without fallback construction or mutation`, async ({
   1940     page
   1941   }) => {
   1942     const row =
   1943       selected === 'absent'
   1944         ? undefined
   1945         : await seedOrdinaryRow(page, selected === 'foreign');
   1946     const result = await page.evaluate(async (id) => {
   1947       const f = window.hcCheckFixture,
   1948         before = f.host.counts(),
   1949         beforeRows = await f.host.stored();
   1950       const command = id ?? crypto.randomUUID();
   1951       f.select('recover', 'wss://inbox.example.org', command);
   1952       const completed = await f.run();
   1953       return {
   1954         status: completed.status,
   1955         before,
   1956         after: f.host.counts(),
   1957         beforeRows,
   1958         afterRows: await f.host.stored(),
   1959         qualified: !!f.qualification(),
   1960         command: f.snapshot()?.command,
   1961         selected: command
   1962       };
   1963     }, row?.id);
   1964     expect(result.status).not.toBe('qualified');
   1965     expect(result.qualified).toBe(false);
   1966     expect(result.after).toEqual(result.before);
   1967     expect(result.afterRows).toEqual(result.beforeRows);
   1968     expect(result.command).toBe(result.selected);
   1969     expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(0);
   1970   });
   1971 }
   1972 
   1973 for (const lane of ['original', 'recover'] as const) {
   1974   for (const cleanup of [false, true]) {
   1975     test(`${lane} ${cleanup ? 'reviewed optional cleanup' : 'qualification'} preserves exact preexisting schema1 ordinary reservation bytes`, async ({
   1976       page
   1977     }) => {
   1978       const row = await seedOrdinaryRow(page);
   1979       const seed =
   1980         lane === 'recover' ? await seedRecovery(page, true) : undefined;
   1981       const result = await page.evaluate(
   1982         async ({ lane, command, cleanup, id }) => {
   1983           const f = window.hcCheckFixture;
   1984           f.select(lane, 'wss://inbox.example.org', command);
   1985           const completed = await f.run();
   1986           let removed: string | undefined;
   1987           if (cleanup) {
   1988             f.selectCleanup();
   1989             removed = (await f.cleanup()).status;
   1990           }
   1991           const rows = await f.host.stored();
   1992           return {
   1993             status: completed.status,
   1994             removed,
   1995             ordinary: rows.find((row) => row.id === id),
   1996             rows: rows.length,
   1997             qualified: !!f.qualification()
   1998           };
   1999         },
   2000         { lane, command: seed?.command, cleanup, id: row.id }
   2001       );
   2002       expect(result.status).toBe('qualified');
   2003       if (cleanup) expect(result.removed).toBe('removed');
   2004       expect(result.qualified).toBe(true);
   2005       expect(result.ordinary).toEqual(row);
   2006       expect(result.rows).toBe(cleanup ? 1 : 2);
   2007     });
   2008   }
   2009 }
   2010 
   2011 test('mismatched genuine same-owner identity private-session and C7 tuples cannot authorize effects or close either scope', async ({
   2012   page
   2013 }) => {
   2014   const result = await page.evaluate(async () => {
   2015     const f = window.hcCheckFixture,
   2016       api = window.hcCheck,
   2017       original = f.actors(),
   2018       other = await f.alternateActors();
   2019     const before = f.host.counts(),
   2020       closes = window.hcCheckCloseCalls;
   2021     try {
   2022       const attempts = [
   2023         api.createInboxAccessCheck(
   2024           f.repository,
   2025           other.identity,
   2026           original.session,
   2027           f.host.policy,
   2028           original.access,
   2029           f.host.qualification
   2030         ),
   2031         api.createInboxAccessCheck(
   2032           f.repository,
   2033           original.identity,
   2034           other.session,
   2035           f.host.policy,
   2036           other.access,
   2037           f.host.qualification
   2038         ),
   2039         api.createInboxAccessCheck(
   2040           f.repository,
   2041           other.identity,
   2042           original.session,
   2043           f.host.policy,
   2044           other.access,
   2045           f.host.qualification
   2046         ),
   2047         api.createInboxAccessCheck(
   2048           f.repository,
   2049           original.identity,
   2050           other.session,
   2051           f.host.policy,
   2052           original.access,
   2053           f.host.qualification
   2054         )
   2055       ];
   2056       return {
   2057         attempts: attempts.map(Boolean),
   2058         before,
   2059         after: f.host.counts(),
   2060         closes,
   2061         afterCloses: window.hcCheckCloseCalls,
   2062         original: api.inboxAccessControllerSourceSnapshot(original.access),
   2063         other: api.inboxAccessControllerSourceSnapshot(other.access),
   2064         same:
   2065           api.createInboxAccessCheck(
   2066             f.repository,
   2067             original.identity,
   2068             original.session,
   2069             f.host.policy,
   2070             original.access,
   2071             f.host.qualification
   2072           ) === f.check(),
   2073         rows: await f.host.stored()
   2074       };
   2075     } finally {
   2076       other.close();
   2077     }
   2078   });
   2079   expect(result.attempts).toEqual([false, false, false, false]);
   2080   expect(result.after).toEqual(result.before);
   2081   expect(result.afterCloses).toBe(result.closes);
   2082   expect(result.original?.state).not.toBe('stopped');
   2083   expect(result.other?.state).not.toBe('stopped');
   2084   expect(result.same).toBe(true);
   2085   expect(result.rows).toHaveLength(0);
   2086   expect(
   2087     frames.filter((frame) => ['EVENT', 'AUTH'].includes(frame.type))
   2088   ).toHaveLength(0);
   2089 });
   2090 
   2091 test('coordinator Stop preserves a genuine alternate actor failed AUTH cleanup for its own explicit retry', async ({
   2092   page
   2093 }) => {
   2094   await page.evaluate(async () => {
   2095     const f = window.hcCheckFixture;
   2096     window.hcCheckOther = await f.alternateActors();
   2097     await window.hcCheck.authenticateInboxAccess(
   2098       window.hcCheckOther.access,
   2099       'wss://inbox.example.org',
   2100       'reviewed_inbox_connection_auth'
   2101     );
   2102   });
   2103   await expect
   2104     .poll(() =>
   2105       page.evaluate(
   2106         () =>
   2107           window.hcCheck
   2108             .inboxAccessControllerSourceSnapshot(window.hcCheckOther!.access)
   2109             ?.auth.find((row) => row.origin === 'wss://inbox.example.org')
   2110             ?.state
   2111       )
   2112     )
   2113     .toBe('waiting');
   2114   try {
   2115     const result = await page.evaluate(() => {
   2116       const f = window.hcCheckFixture,
   2117         api = window.hcCheck,
   2118         other = window.hcCheckOther!;
   2119       window.hcCheckCloseMode = 'fail';
   2120       const foreignClosed = api.closeInboxAccessController(other.access),
   2121         closes = window.hcCheckCloseCalls;
   2122       const bad = api.createInboxAccessCheck(
   2123         f.repository,
   2124         f.actors().identity,
   2125         other.session,
   2126         f.host.policy,
   2127         other.access,
   2128         f.host.qualification
   2129       );
   2130       const ownStopped = f.stop();
   2131       return {
   2132         foreignClosed,
   2133         bad: !!bad,
   2134         closes,
   2135         afterCloses: window.hcCheckCloseCalls,
   2136         ownStopped,
   2137         foreignSnapshot: api.inboxAccessControllerSourceSnapshot(other.access)
   2138       };
   2139     });
   2140     expect(result.foreignClosed).toBe(false);
   2141     expect(result.bad).toBe(false);
   2142     expect(result.ownStopped).toBe(true);
   2143     expect(result.afterCloses).toBe(result.closes);
   2144     expect(result.foreignSnapshot?.cleanupRequired).toBe(true);
   2145     expect(
   2146       [...physical].some(
   2147         (socket) =>
   2148           physicalOrigins.get(socket) !== 'wss://discovery.example.org'
   2149       )
   2150     ).toBe(true);
   2151   } finally {
   2152     await page.evaluate(() => {
   2153       window.hcCheckCloseMode = undefined;
   2154       window.hcCheckOther!.close();
   2155     });
   2156     await expect
   2157       .poll(
   2158         () =>
   2159           [...physical].filter(
   2160             (socket) =>
   2161               physicalOrigins.get(socket) !== 'wss://discovery.example.org'
   2162           ).length
   2163       )
   2164       .toBe(0);
   2165     expect(await page.evaluate(() => window.hcCheckOther!.close())).toBe(true);
   2166   }
   2167 });
   2168 
   2169 for (const lane of ['original', 'recover'] as const) {
   2170   for (const phase of ['append', 'nonce', 'qualification'] as const) {
   2171     for (const loss of ['head', 'session', 'C7'] as const) {
   2172       test(`${lane} actual native ${phase} callback ${loss} loss revokes before subsequent effects and preserves admitted bookkeeping`, async ({
   2173         page
   2174       }) => {
   2175         const seed =
   2176           lane === 'recover' ? await seedRecovery(page, true) : undefined;
   2177         const result = await page.evaluate(
   2178           async ({ lane, command, phase, loss }) => {
   2179             const f = window.hcCheckFixture,
   2180               api = window.hcCheck;
   2181             let atLoss: ReturnType<typeof f.snapshot> | undefined,
   2182               counts: ReturnType<typeof f.host.counts> | undefined;
   2183             const hook = api.checkNativeLoss(phase, () => {
   2184               if (loss === 'head') f.actors().churnHead();
   2185               else if (loss === 'session')
   2186                 api.closePrivateSession(f.actors().session);
   2187               else api.closeInboxAccessController(f.actors().access);
   2188               atLoss = f.snapshot();
   2189               counts = f.host.counts();
   2190             });
   2191             try {
   2192               f.select(lane, 'wss://inbox.example.org', command);
   2193               const completed = await f.run(),
   2194                 rows = await f.host.stored();
   2195               return {
   2196                 hits: hook.hits(),
   2197                 status: completed.status,
   2198                 atLoss,
   2199                 counts,
   2200                 after: f.host.counts(),
   2201                 qualified: !!f.qualification(),
   2202                 snapshot: f.snapshot(),
   2203                 rows
   2204               };
   2205             } finally {
   2206               hook.restore();
   2207             }
   2208           },
   2209           { lane, command: seed?.command, phase, loss }
   2210         );
   2211         expect(result.hits).toBe(1);
   2212         expect(result.atLoss?.state).toBe('stopped');
   2213         expect(result.atLoss?.busy).toBe(true);
   2214         expect(result.status).toBe('stopped');
   2215         expect(result.qualified).toBe(false);
   2216         expect(result.snapshot?.state).toBe('stopped');
   2217         expect(result.after).toEqual(result.counts);
   2218         expect(result.rows).toHaveLength(1);
   2219         const row = probeRow(result.rows[0].wire),
   2220           oldCount = seed ? probeRow(seed.row.wire).receipts.length : 0;
   2221         expect(
   2222           row.receipts
   2223             .slice(oldCount)
   2224             .filter((fact) => fact.status === 'accepted')
   2225         ).toHaveLength(phase === 'append' ? 1 : 3);
   2226         if (seed) expect(row.self).toEqual(probeRow(seed.row.wire).self);
   2227         expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(
   2228           (seed ? 3 : 0) + (phase === 'append' ? 1 : 3)
   2229         );
   2230       });
   2231     }
   2232   }
   2233 }
   2234 
   2235 for (const mode of ['readback', 'uncertain_readback'] as const) {
   2236   test(`actual durable R0 ${mode} uncertainty protects one original reservation and explicit Retry creates no replacement identity`, async ({
   2237     page
   2238   }) => {
   2239     const result = await page.evaluate(async (mode) => {
   2240       const f = window.hcCheckFixture,
   2241         api = window.hcCheck,
   2242         hook = api.failCheckPreparationNative('R0', mode);
   2243       const uuid = crypto.randomUUID.bind(crypto);
   2244       let uuids = 0;
   2245       crypto.randomUUID = () => {
   2246         uuids++;
   2247         return uuid();
   2248       };
   2249       try {
   2250         f.select();
   2251         const first = await f.run(),
   2252           firstRows = await f.host.stored(),
   2253           counts = hook.counts(),
   2254           firstUuids = uuids,
   2255           before = f.host.counts();
   2256         hook.restore();
   2257         f.select();
   2258         const second = await f.run(),
   2259           rows = await f.host.stored();
   2260         return {
   2261           first: first.status,
   2262           second: second.status,
   2263           counts,
   2264           firstRows,
   2265           rows,
   2266           firstUuids,
   2267           uuids,
   2268           before,
   2269           after: f.host.counts(),
   2270           qualified: !!f.qualification(),
   2271           candidate: hook.candidate()
   2272         };
   2273       } finally {
   2274         hook.restore();
   2275         crypto.randomUUID = uuid;
   2276       }
   2277     }, mode);
   2278     expect(result.counts.puts).toBe(1);
   2279     expect(result.counts.completes).toBe(1);
   2280     expect(result.counts.readbackAborts).toBe(mode === 'readback' ? 1 : 0);
   2281     if (mode === 'uncertain_readback')
   2282       expect(result.counts.abortRefusals).toBeGreaterThan(0);
   2283     expect(result.first).not.toBe('qualified');
   2284     expect(result.second).not.toBe('qualified');
   2285     expect(result.firstRows).toHaveLength(1);
   2286     expect(result.rows).toEqual(result.firstRows);
   2287     expect(result.rows[0]).toEqual(result.candidate);
   2288     expect(result.uuids).toBe(result.firstUuids);
   2289     expect(result.after).toEqual(result.before);
   2290     expect(result.qualified).toBe(false);
   2291     expect(probeRow(result.rows[0].wire).self).toBeNull();
   2292     expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(0);
   2293   });
   2294 }
   2295 
   2296 for (const mode of ['abort', 'readback', 'uncertain_readback'] as const) {
   2297   test(`actual R1 ${mode} uncertainty sends no EVENT before genuine ACK and explicit Retry reuses exact original wrap and command`, async ({
   2298     page
   2299   }) => {
   2300     const first = await page.evaluate(async (mode) => {
   2301       const f = window.hcCheckFixture,
   2302         hook = window.hcCheck.failCheckPreparationNative('R1', mode);
   2303       try {
   2304         f.select();
   2305         const completed = await f.run(),
   2306           rows = await f.host.stored();
   2307         return {
   2308           status: completed.status,
   2309           counts: hook.counts(),
   2310           candidate: hook.candidate(),
   2311           command: f.snapshot()?.command,
   2312           before: f.host.counts(),
   2313           rows,
   2314           qualified: !!f.qualification()
   2315         };
   2316       } finally {
   2317         hook.restore();
   2318       }
   2319     }, mode);
   2320     expect(first.status).not.toBe('qualified');
   2321     expect(first.qualified).toBe(false);
   2322     expect(first.counts.puts).toBe(1);
   2323     expect(first.rows).toHaveLength(1);
   2324     expect(first.command).toBe(first.candidate?.id);
   2325     expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(0);
   2326     if (mode === 'abort') {
   2327       expect(first.counts.aborts).toBe(1);
   2328       expect(probeRow(first.rows[0].wire).self).toBeNull();
   2329     } else {
   2330       expect(first.counts.completes).toBe(1);
   2331       expect(first.counts.readbackAborts).toBe(1);
   2332       expect(first.rows[0]).toEqual(first.candidate);
   2333     }
   2334     if (mode === 'uncertain_readback')
   2335       expect(first.counts.abortRefusals).toBeGreaterThan(0);
   2336     const second = await page.evaluate(async () => {
   2337       const f = window.hcCheckFixture;
   2338       f.select();
   2339       const completed = await f.run();
   2340       return {
   2341         status: completed.status,
   2342         after: f.host.counts(),
   2343         command: f.snapshot()?.command,
   2344         rows: await f.host.stored(),
   2345         qualified: !!f.qualification()
   2346       };
   2347     });
   2348     expect(second.status).toBe('qualified');
   2349     expect(second.qualified).toBe(true);
   2350     expect(second.command).toBe(first.command);
   2351     expect(second.after.signs).toBe(first.before.signs);
   2352     expect(second.after.encrypts).toBe(first.before.encrypts);
   2353     expect(probeRow(second.rows[0].wire).self).toEqual(
   2354       probeRow(first.candidate!.wire).self
   2355     );
   2356     expect(frames.filter((frame) => frame.type === 'EVENT')).toHaveLength(3);
   2357     expect(
   2358       new Set(
   2359         frames
   2360           .filter((frame) => frame.type === 'EVENT')
   2361           .map((frame) => frame.id)
   2362       )
   2363     ).toEqual(new Set([probeRow(first.candidate!.wire).self!.eventId]));
   2364   });
   2365 }