commit e9f2ae8721b550e41d4e1142e81c78a56fc914df
parent 93f71808f7400fc4bf34e9973586feb1dee59b43
Author: triesap <tyson@radroots.org>
Date: Tue, 6 Oct 2026 23:07:06 +0000
storage: add immutable artifact and target-receipt transaction primitives (HCP-050)
- Bind verified signed artifacts to exact captured author, kind and hash.
- Preserve frozen intent while capturing typed artifact and receipt transitions.
- Commit full-wire revision CAS under transactional public storage quotas.
- Verify idempotence, abort rollback and unknown-completion readback.
Diffstat:
6 files changed, 1478 insertions(+), 0 deletions(-)
diff --git a/web/src/lib/persistence/artifact-records.ts b/web/src/lib/persistence/artifact-records.ts
@@ -0,0 +1,263 @@
+import { canonicalPublicKey } from '../contracts/public-key.ts';
+import { canonicalLocalId } from '../private-handles.ts';
+import {
+ exactLocalFields,
+ type PublicOperationRecord,
+ type PreferenceOperationRecord,
+ type PublicTargetReceipt
+} from '../contracts/local-records.ts';
+import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';
+import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
+import {
+ verifyEnvelope,
+ verifiedEnvelopeSnapshot
+} from '../nostr/verified-envelope.ts';
+import {
+ decodePublicRecord,
+ publicRecordSnapshot,
+ publicRecordWire,
+ type PublicRecordHandle
+} from './records.ts';
+
+declare const artifactBrand: unique symbol;
+declare const transitionBrand: unique symbol;
+export type CapturedArtifact = Readonly<{ [artifactBrand]: true }>;
+export type PublicOperationTransition = Readonly<{ [transitionBrand]: true }>;
+export type ArtifactFailure =
+ 'invalid_artifact' | 'invalid_record' | 'conflict' | 'revision_exhausted';
+type Result<T> =
+ | Readonly<{ ok: true; value: T }>
+ | Readonly<{ ok: false; reason: ArtifactFailure }>;
+type Artifact = Readonly<{
+ author: string;
+ kind: 30402 | 5 | 10050 | 1059;
+ hash: string;
+ wire: string;
+}>;
+type Operation = PublicOperationRecord | PreferenceOperationRecord;
+type Transition = Readonly<{
+ owner: string;
+ id: string;
+ family: Operation['family'];
+ kind: 30402 | 5 | 10050;
+ expectedRevision: number;
+ revision: number;
+ baseWire: string;
+ nextWire: string;
+}>;
+const artifacts = new WeakMap<CapturedArtifact, Artifact>();
+const transitions = new WeakMap<PublicOperationTransition, Transition>();
+function failed(reason: ArtifactFailure): Result<never> {
+ return { ok: false, reason };
+}
+// SDK-verified exact envelope binding only. A1059 token proves an outer
+// signature/hash, not nested Message authenticity, routing or durable storage.
+// Private typed repositories own those later checks. No plaintext14/13 token.
+export function bindCapturedArtifact(
+ rawWire: unknown,
+ expectedAuthor: unknown,
+ expectedKind: unknown,
+ expectedHash: unknown
+): Result<CapturedArtifact> {
+ const author = canonicalPublicKey(expectedAuthor);
+ if (
+ !author ||
+ (expectedKind !== 30402 &&
+ expectedKind !== 5 &&
+ expectedKind !== 10050 &&
+ expectedKind !== 1059) ||
+ typeof expectedHash !== 'string' ||
+ !/^[0-9a-f]{64}$/.test(expectedHash) ||
+ typeof rawWire !== 'string'
+ )
+ return failed('invalid_artifact');
+ const proof = verifyEnvelope(rawWire);
+ if (!proof.ok) return failed('invalid_artifact');
+ const event = verifiedEnvelopeSnapshot(proof.value);
+ if (
+ !event ||
+ !exactLocalFields(event, [
+ 'id',
+ 'pubkey',
+ 'kind',
+ 'created_at',
+ 'tags',
+ 'content',
+ 'sig'
+ ]) ||
+ event.pubkey !== author ||
+ event.kind !== expectedKind ||
+ event.id !== expectedHash
+ )
+ return failed('invalid_artifact');
+ const token = Object.freeze({}) as CapturedArtifact;
+ artifacts.set(token, {
+ author,
+ kind: expectedKind,
+ hash: expectedHash,
+ wire: rawWire
+ });
+ return { ok: true, value: token };
+}
+export function capturedArtifactSnapshot(
+ handle: CapturedArtifact
+): Artifact | undefined {
+ const saved = artifacts.get(handle);
+ return saved ? { ...saved } : undefined;
+}
+function baseOf(
+ handle: PublicRecordHandle,
+ owner: unknown,
+ id: unknown
+): Readonly<{ row: Operation; wire: string }> | undefined {
+ const row = publicRecordSnapshot(handle, owner, id),
+ wire = publicRecordWire(handle, owner, id);
+ return row && row.family !== 'public_draft' && wire
+ ? { row, wire }
+ : undefined;
+}
+function retain(
+ base: Readonly<{ row: Operation; wire: string }>,
+ next: Operation
+): Result<PublicOperationTransition> {
+ const nextWire = JSON.stringify(next);
+ const decoded = decodePublicRecord(nextWire, base.row.owner, base.row.id);
+ if (!decoded.ok) return failed('invalid_record');
+ const token = Object.freeze({}) as PublicOperationTransition;
+ transitions.set(token, {
+ owner: base.row.owner,
+ id: base.row.id,
+ family: base.row.family,
+ kind: base.row.capture.kind,
+ expectedRevision: base.row.revision,
+ revision: next.revision,
+ baseWire: base.wire,
+ nextWire
+ });
+ return { ok: true, value: token };
+}
+export function preparePublicArtifactTransition(
+ record: PublicRecordHandle,
+ owner: unknown,
+ id: unknown,
+ artifact: CapturedArtifact
+): Result<PublicOperationTransition> {
+ const base = baseOf(record, owner, id),
+ signed = artifacts.get(artifact);
+ if (!base) return failed('invalid_record');
+ if (
+ !signed ||
+ signed.author !== base.row.owner ||
+ signed.kind !== base.row.capture.kind ||
+ signed.hash !== base.row.capture.hash
+ )
+ return failed('invalid_artifact');
+ if (base.row.artifact !== null)
+ return base.row.artifact.wire === signed.wire
+ ? retain(base, base.row)
+ : failed('conflict');
+ if (base.row.revision === Number.MAX_SAFE_INTEGER)
+ return failed('revision_exhausted');
+ return retain(base, {
+ ...base.row,
+ revision: base.row.revision + 1,
+ artifact: { eventId: signed.hash, wire: signed.wire }
+ });
+}
+function sameFact(a: PublicTargetReceipt, b: PublicTargetReceipt): boolean {
+ return (
+ a.actionId === b.actionId &&
+ a.origin === b.origin &&
+ a.role === b.role &&
+ a.attempt === b.attempt &&
+ a.eventId === b.eventId &&
+ a.status === b.status &&
+ a.observedAtMilliseconds === b.observedAtMilliseconds
+ );
+}
+// Only canonical primitive wire is acquired; defensive record decoding validates
+// every receipt field, target, role, event and exact readback signature. Distinct
+// status/time observations remain distinct. No EventStore seen metadata is used.
+export function preparePublicReceiptTransition(
+ record: PublicRecordHandle,
+ owner: unknown,
+ id: unknown,
+ receiptWire: unknown
+): Result<PublicOperationTransition> {
+ const base = baseOf(record, owner, id);
+ if (
+ !base ||
+ !base.row.artifact ||
+ typeof receiptWire !== 'string' ||
+ !boundedUtf8(receiptWire, LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes)
+ )
+ return failed('invalid_record');
+ try {
+ const fact: unknown = JSON.parse(receiptWire);
+ if (
+ JSON.stringify(fact) !== receiptWire ||
+ !exactLocalFields(fact, [
+ 'actionId',
+ 'origin',
+ 'role',
+ 'attempt',
+ 'eventId',
+ 'status',
+ 'observedAtMilliseconds',
+ 'readbackWire'
+ ])
+ )
+ return failed('invalid_record');
+ // Validate the proposed fact through the existing complete typed codec before
+ // comparing keys; the parsed object contains only detached JSON data.
+ const checked = decodePublicRecord(
+ JSON.stringify({ ...base.row, receipts: [fact] }),
+ base.row.owner,
+ base.row.id
+ );
+ if (!checked.ok) return failed('invalid_record');
+ const admitted = publicRecordSnapshot(
+ checked.value,
+ base.row.owner,
+ base.row.id
+ );
+ if (!admitted || admitted.family === 'public_draft')
+ return failed('invalid_record');
+ const nextFact = admitted.receipts[0];
+ const existing = base.row.receipts.find((row) => sameFact(row, nextFact));
+ if (existing)
+ return JSON.stringify(existing) === JSON.stringify(nextFact)
+ ? retain(base, base.row)
+ : failed('conflict');
+ if (base.row.revision === Number.MAX_SAFE_INTEGER)
+ return failed('revision_exhausted');
+ return retain(base, {
+ ...base.row,
+ revision: base.row.revision + 1,
+ receipts: [...base.row.receipts, nextFact]
+ });
+ } catch {
+ return failed('invalid_record');
+ }
+}
+// Internal repository input: a detached snapshot of a genuine frozen command,
+// never a signing/network capability. Scope and full-wire CAS remain in IDB.
+export function publicTransitionSnapshot(
+ handle: PublicOperationTransition,
+ owner: unknown,
+ id: unknown
+): Transition | undefined {
+ const saved = transitions.get(handle);
+ return saved &&
+ saved.owner === canonicalPublicKey(owner) &&
+ saved.id === canonicalLocalId(id)
+ ? { ...saved }
+ : undefined;
+}
+// Metadata-only scope admission avoids accepting caller-owned record objects.
+export function publicTransitionIdentity(
+ handle: PublicOperationTransition
+): Readonly<{ owner: string; id: string }> | undefined {
+ const saved = transitions.get(handle);
+ return saved ? { owner: saved.owner, id: saved.id } : undefined;
+}
diff --git a/web/src/lib/persistence/operation-transactions.ts b/web/src/lib/persistence/operation-transactions.ts
@@ -0,0 +1,11 @@
+// Pure storage mechanics shared by typed operation repositories. This module
+// acquires no database, signer, relay, raw-event publisher or account authority.
+// Matching the original base is an observation, not proof of global absence.
+export function decideFrozenTransition(
+ currentWire: unknown,
+ baseWire: string,
+ nextWire: string
+): 'committed' | 'base_observed' | 'conflict' {
+ if (currentWire === nextWire) return 'committed';
+ return currentWire === baseWire ? 'base_observed' : 'conflict';
+}
diff --git a/web/src/lib/persistence/quota.ts b/web/src/lib/persistence/quota.ts
@@ -22,6 +22,13 @@ import {
type PublicInventoryRow
} from './local-inventory.ts';
+import {
+ publicTransitionIdentity,
+ publicTransitionSnapshot,
+ type PublicOperationTransition
+} from './artifact-records.ts';
+import { decideFrozenTransition } from './operation-transactions.ts';
+
declare const repositoryBrand: unique symbol;
declare const inventoryBrand: unique symbol;
declare const cleanupBrand: unique symbol;
@@ -393,3 +400,87 @@ export function commitPublicCleanup(
return { ok: true, value: Array.from(cleanup.selected) };
});
}
+
+// No signer/network await exists inside this transaction. It consumes only a
+// genuine immutable typed transition captured before storage acquisition.
+export function commitPublicOperationTransition(
+ repository: PublicQuotaRepository,
+ handle: PublicOperationTransition
+): Promise<PublicQuotaResult<Readonly<{ id: string; revision: number }>>> {
+ const scope = scopeOf(repository);
+ if (!scope) return Promise.resolve(failed('invalid_scope'));
+ const identity = publicTransitionIdentity(handle);
+ const command =
+ identity && publicTransitionSnapshot(handle, scope.owner, identity.id);
+ if (!command) return Promise.resolve(failed('invalid_record'));
+ const store: Store =
+ command.family === 'public_operation'
+ ? 'public_operations'
+ : 'preference_operations';
+ return transaction(scope, 'readwrite', (rows, active, refuse) => {
+ const previous = rows.find(
+ (row) => row.store === store && row.record.id === command.id
+ );
+ const decision = decideFrozenTransition(
+ previous?.wire,
+ command.baseWire,
+ command.nextWire
+ );
+ if (decision === 'conflict') {
+ refuse('conflict');
+ return;
+ }
+ if (decision === 'committed')
+ return {
+ ok: true,
+ value: { id: command.id, revision: command.revision }
+ };
+ const operations = rows.filter(
+ (row) => row.record.family !== 'public_draft'
+ );
+ const bytes =
+ operations.reduce((sum, row) => sum + row.bytes, 0) -
+ (previous?.bytes ?? 0) +
+ new TextEncoder().encode(command.nextWire).length;
+ if (bytes > LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes) {
+ refuse('capacity');
+ return;
+ }
+ active
+ .objectStore(store)
+ .put({ owner: scope.owner, id: command.id, wire: command.nextWire });
+ return { ok: true, value: { id: command.id, revision: command.revision } };
+ });
+}
+export async function observePublicOperationTransition(
+ repository: PublicQuotaRepository,
+ handle: PublicOperationTransition
+): Promise<
+ | Readonly<{ state: 'committed'; id: string; revision: number }>
+ | Readonly<{ state: 'base_observed' | 'conflict' | 'unavailable' }>
+> {
+ const scope = scopeOf(repository),
+ identity = publicTransitionIdentity(handle);
+ const command =
+ scope &&
+ identity &&
+ publicTransitionSnapshot(handle, scope.owner, identity.id);
+ if (!scope || !command) return { state: 'unavailable' };
+ const store: Store =
+ command.family === 'public_operation'
+ ? 'public_operations'
+ : 'preference_operations';
+ const read = await transaction(scope, 'readonly', (rows) => ({
+ ok: true,
+ value: decideFrozenTransition(
+ rows.find((row) => row.store === store && row.record.id === command.id)
+ ?.wire,
+ command.baseWire,
+ command.nextWire
+ )
+ }));
+ if (!read.ok || !scopeOf(repository)) return { state: 'unavailable' };
+ return read.value === 'committed'
+ ? { state: 'committed', id: command.id, revision: command.revision }
+ : { state: read.value };
+}
diff --git a/web/tests/e2e/operation-transactions.spec.ts b/web/tests/e2e/operation-transactions.spec.ts
@@ -0,0 +1,644 @@
+import { expect, test, type Page } from '@playwright/test';
+import { build } from 'vite';
+import { fileURLToPath } from 'node:url';
+import { createHash, randomUUID } from 'node:crypto';
+import { finalizeEvent, getEventHash } from 'applesauce-core/helpers';
+import { createStaticHarness } from '../integration/harness/static.ts';
+import type * as Database from '../../src/lib/persistence/database.ts';
+import type * as Records from '../../src/lib/persistence/records.ts';
+import type * as Quota from '../../src/lib/persistence/quota.ts';
+import type * as Artifacts from '../../src/lib/persistence/artifact-records.ts';
+import type {
+ PublicOperationRecord,
+ PublicTargetReceipt
+} from '../../src/lib/contracts/local-records.ts';
+declare global {
+ interface Window {
+ hcp050: typeof Database & typeof Records & typeof Quota & typeof Artifacts;
+ hcp050Database: Database.BrowserDatabase;
+ hcp050Quota: Quota.PublicQuotaRepository;
+ hcp050Transition: Artifacts.PublicOperationTransition;
+ }
+}
+let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string;
+test.beforeAll(async () => {
+ server = await createStaticHarness();
+ const source = (name: string) =>
+ fileURLToPath(
+ new URL('../../src/lib/persistence/' + name, import.meta.url)
+ );
+ const result = await build({
+ configFile: false,
+ logLevel: 'silent',
+ plugins: [
+ {
+ name: 'hcp050-test-entry',
+ resolveId(id) {
+ if (id === 'virtual:hcp050') return '\0hcp050';
+ },
+ load(id) {
+ if (id === '\0hcp050')
+ return [
+ 'database.ts',
+ 'records.ts',
+ 'quota.ts',
+ 'artifact-records.ts'
+ ]
+ .map((n) => `export * from ${JSON.stringify(source(n))};`)
+ .join('');
+ }
+ }
+ ],
+ build: {
+ write: false,
+ minify: false,
+ rolldownOptions: { input: 'virtual:hcp050' },
+ lib: { entry: 'virtual:hcp050', name: 'hcp050', formats: ['iife'] }
+ }
+ });
+ const output = Array.isArray(result) ? result[0] : result;
+ if (!('output' in output)) throw new Error('missing bundle');
+ const chunks = output.output.filter((item) => item.type === 'chunk');
+ expect(chunks).toHaveLength(1);
+ bundle = chunks[0].code;
+ console.log(
+ JSON.stringify({
+ fixture: 'HCP050_ACTUAL_MODULES_REAL_IDB',
+ bundleSha256: createHash('sha256').update(bundle).digest('hex'),
+ exposure: 'test-only virtual entry'
+ })
+ );
+});
+test.afterAll(async () => server.close());
+function fixture(content = 'public operation transition fixture') {
+ const key = crypto.getRandomValues(new Uint8Array(32));
+ try {
+ const event = finalizeEvent(
+ {
+ kind: 30402,
+ created_at: 100,
+ tags: [
+ ['d', 'transition'],
+ ['published_at', '100']
+ ],
+ content
+ },
+ key
+ );
+ const id = randomUUID();
+ const template = {
+ pubkey: event.pubkey,
+ kind: 30402,
+ created_at: 100,
+ tags: event.tags,
+ content
+ };
+ const row: PublicOperationRecord = {
+ schema: 1,
+ family: 'public_operation',
+ owner: event.pubkey,
+ id,
+ revision: 0,
+ source: { type: 'draft', id, revision: 0 },
+ capture: {
+ kind: 30402,
+ wire: JSON.stringify(template),
+ hash: getEventHash(template),
+ targets: ['wss://one.example.org'],
+ policyFingerprint: 'a'.repeat(64)
+ },
+ artifact: null,
+ receipts: []
+ };
+ return { row, wire: JSON.stringify(event) };
+ } finally {
+ key.fill(0);
+ }
+}
+async function load(page: Page, owner: string) {
+ await page.goto(server.url + '/search');
+ await page.addScriptTag({ content: bundle });
+ await page.evaluate(async (owner) => {
+ const api = window.hcp050;
+ const opened = await api.openBrowserDatabase();
+ if (opened.state !== 'ready') throw new Error(opened.reason);
+ const repo = api.createPublicQuotaRepository(opened.owner, owner);
+ if (!repo) throw new Error('missing quota');
+ window.hcp050Database = opened.owner;
+ window.hcp050Quota = repo;
+ }, owner);
+}
+async function admit(page: Page, row: PublicOperationRecord) {
+ return page.evaluate(async (row) => {
+ const api = window.hcp050;
+ const record = api.decodePublicRecord(
+ JSON.stringify(row),
+ row.owner,
+ row.id
+ );
+ if (!record.ok) throw new Error(record.reason);
+ return api.admitPublicOperation(window.hcp050Quota, row.id, record.value);
+ }, row);
+}
+async function prepare(page: Page, f: ReturnType<typeof fixture>) {
+ return page.evaluate((f) => {
+ const api = window.hcp050;
+ const record = api.decodePublicRecord(
+ JSON.stringify(f.row),
+ f.row.owner,
+ f.row.id
+ );
+ if (!record.ok) throw new Error(record.reason);
+ const artifact = api.bindCapturedArtifact(
+ f.wire,
+ f.row.owner,
+ 30402,
+ f.row.capture.hash
+ );
+ if (!artifact.ok) throw new Error(artifact.reason);
+ const transition = api.preparePublicArtifactTransition(
+ record.value,
+ f.row.owner,
+ f.row.id,
+ artifact.value
+ );
+ if (!transition.ok) throw new Error(transition.reason);
+ window.hcp050Transition = transition.value;
+ return api.publicTransitionSnapshot(
+ transition.value,
+ f.row.owner,
+ f.row.id
+ );
+ }, f);
+}
+async function commit(page: Page) {
+ return page.evaluate(() =>
+ window.hcp050.commitPublicOperationTransition(
+ window.hcp050Quota,
+ window.hcp050Transition
+ )
+ );
+}
+async function observe(page: Page) {
+ return page.evaluate(() =>
+ window.hcp050.observePublicOperationTransition(
+ window.hcp050Quota,
+ window.hcp050Transition
+ )
+ );
+}
+function receipt(row: PublicOperationRecord): PublicTargetReceipt {
+ return {
+ actionId: randomUUID(),
+ origin: row.capture.targets[0],
+ role: 'publication',
+ attempt: 1,
+ eventId: row.capture.hash,
+ status: 'accepted',
+ observedAtMilliseconds: 1000,
+ readbackWire: null
+ };
+}
+async function prepareReceipt(
+ page: Page,
+ row: PublicOperationRecord,
+ fact: PublicTargetReceipt
+) {
+ await page.evaluate(
+ ({ row, fact }) => {
+ const api = window.hcp050;
+ const base = api.decodePublicRecord(
+ JSON.stringify(row),
+ row.owner,
+ row.id
+ );
+ if (!base.ok) throw new Error(base.reason);
+ const next = api.preparePublicReceiptTransition(
+ base.value,
+ row.owner,
+ row.id,
+ JSON.stringify(fact)
+ );
+ if (!next.ok) throw new Error(next.reason);
+ window.hcp050Transition = next.value;
+ },
+ { row, fact }
+ );
+}
+test('signed artifact commits exactly once and original full-wire observation distinguishes base and committed', async ({
+ page
+}) => {
+ const f = fixture();
+ await load(page, f.row.owner);
+ expect((await admit(page, f.row)).ok).toBe(true);
+ const capture = await prepare(page, f);
+ expect(await observe(page)).toEqual({ state: 'base_observed' });
+ expect(await commit(page)).toEqual({
+ ok: true,
+ value: { id: f.row.id, revision: 1 }
+ });
+ expect(await commit(page)).toEqual({
+ ok: true,
+ value: { id: f.row.id, revision: 1 }
+ });
+ expect(await observe(page)).toEqual({
+ state: 'committed',
+ id: f.row.id,
+ revision: 1
+ });
+ expect(capture?.baseWire).toBe(JSON.stringify(f.row));
+});
+test('two genuine tabs race distinct receipts at one revision; stale request conflicts and winning exact replay is idempotent', async ({
+ page,
+ context
+}) => {
+ const f = fixture();
+ await load(page, f.row.owner);
+ await admit(page, f.row);
+ const capture = await prepare(page, f);
+ await commit(page);
+ const row = JSON.parse(capture?.nextWire ?? 'null') as PublicOperationRecord;
+ const other = await context.newPage();
+ await load(other, row.owner);
+ await prepareReceipt(page, row, receipt(row));
+ await prepareReceipt(other, row, receipt(row));
+ const results = await Promise.all([commit(page), commit(other)]);
+ expect(results.filter((r) => r.ok)).toHaveLength(1);
+ expect(results.filter((r) => !r.ok)).toEqual([
+ { ok: false, reason: 'conflict' }
+ ]);
+ const winner = results[0].ok ? page : other,
+ loser = results[0].ok ? other : page;
+ expect((await commit(winner)).ok).toBe(true);
+ expect(await observe(loser)).toEqual({ state: 'conflict' });
+ await other.close();
+});
+test('changed capture or targets cannot replace the already captured operation', async ({
+ page
+}) => {
+ const f = fixture();
+ await load(page, f.row.owner);
+ await admit(page, f.row);
+ const changed = {
+ row: {
+ ...f.row,
+ capture: { ...f.row.capture, targets: ['wss://other.example.org'] }
+ },
+ wire: f.wire
+ };
+ await prepare(page, changed);
+ expect(await commit(page)).toEqual({ ok: false, reason: 'conflict' });
+ expect(await observe(page)).toEqual({ state: 'conflict' });
+});
+test('native put request success followed by abort is never a durable artifact acknowledgment', async ({
+ page
+}) => {
+ const f = fixture();
+ await load(page, f.row.owner);
+ await admit(page, f.row);
+ await prepare(page, f);
+ const result = await page.evaluate(async () => {
+ const descriptor = Object.getOwnPropertyDescriptor(
+ IDBObjectStore.prototype,
+ 'put'
+ );
+ if (!descriptor || typeof descriptor.value !== 'function')
+ throw new Error('missing put');
+ const original = descriptor.value as IDBObjectStore['put'];
+ let successes = 0;
+ Object.defineProperty(IDBObjectStore.prototype, 'put', {
+ ...descriptor,
+ value: function (
+ this: IDBObjectStore,
+ ...args: Parameters<IDBObjectStore['put']>
+ ) {
+ const request = Reflect.apply(original, this, args) as IDBRequest;
+ const transaction = this.transaction;
+ request.addEventListener(
+ 'success',
+ () => {
+ successes++;
+ transaction.abort();
+ },
+ { once: true }
+ );
+ return request;
+ }
+ });
+ try {
+ return {
+ result: await window.hcp050.commitPublicOperationTransition(
+ window.hcp050Quota,
+ window.hcp050Transition
+ ),
+ successes
+ };
+ } finally {
+ Object.defineProperty(IDBObjectStore.prototype, 'put', descriptor);
+ }
+ });
+ expect(result).toEqual({
+ result: { ok: false, reason: 'aborted' },
+ successes: 1
+ });
+ expect(await observe(page)).toEqual({ state: 'base_observed' });
+});
+test('unknown completion reconciles original expected payload after real native commit without another write', async ({
+ page
+}) => {
+ const f = fixture();
+ await load(page, f.row.owner);
+ await admit(page, f.row);
+ await prepare(page, f);
+ const result = await page.evaluate(async () => {
+ const put = Object.getOwnPropertyDescriptor(
+ IDBObjectStore.prototype,
+ 'put'
+ ),
+ abort = Object.getOwnPropertyDescriptor(
+ IDBTransaction.prototype,
+ 'abort'
+ );
+ if (!put || !abort || typeof put.value !== 'function')
+ throw new Error('missing methods');
+ const original = put.value as IDBObjectStore['put'];
+ let requests = 0;
+ Object.defineProperty(IDBObjectStore.prototype, 'put', {
+ ...put,
+ value: function (
+ this: IDBObjectStore,
+ ...args: Parameters<IDBObjectStore['put']>
+ ) {
+ Reflect.apply(original, this, args);
+ requests++;
+ throw new Error('controlled delivery loss after native request queued');
+ }
+ });
+ Object.defineProperty(IDBTransaction.prototype, 'abort', {
+ ...abort,
+ value() {
+ throw new Error('controlled unavailable abort channel');
+ }
+ });
+ try {
+ return {
+ result: await window.hcp050.commitPublicOperationTransition(
+ window.hcp050Quota,
+ window.hcp050Transition
+ ),
+ requests
+ };
+ } finally {
+ Object.defineProperty(IDBObjectStore.prototype, 'put', put);
+ Object.defineProperty(IDBTransaction.prototype, 'abort', abort);
+ }
+ });
+ expect(result).toEqual({
+ result: { ok: false, reason: 'unknown_completion' },
+ requests: 1
+ });
+ expect(await observe(page)).toEqual({
+ state: 'committed',
+ id: f.row.id,
+ revision: 1
+ });
+});
+test('artifact replacement rechecks aggregate8MiB and preserves every original row on refusal', async ({
+ page
+}) => {
+ const f = fixture('p'.repeat(120000));
+ await load(page, f.row.owner);
+ const size = Buffer.byteLength(JSON.stringify(f.row));
+ const count = Math.floor(8388608 / size);
+ const rows: PublicOperationRecord[] = Array.from({ length: count }, () => ({
+ ...f.row,
+ id: randomUUID()
+ }));
+ rows[0] = f.row;
+ await page.evaluate(async (rows) => {
+ const api = window.hcp050;
+ for (const row of rows) {
+ const decoded = api.decodePublicRecord(
+ JSON.stringify(row),
+ row.owner,
+ row.id
+ );
+ if (!decoded.ok) throw new Error(decoded.reason);
+ }
+ const transaction = api.browserDatabaseTransaction(
+ window.hcp050Database,
+ ['public_operations'],
+ 'readwrite'
+ );
+ for (const row of rows)
+ transaction
+ .objectStore('public_operations')
+ .put({ owner: row.owner, id: row.id, wire: JSON.stringify(row) });
+ await new Promise<void>((resolve, reject) => {
+ transaction.addEventListener('complete', () => resolve());
+ transaction.addEventListener('abort', () =>
+ reject(new Error('seed aborted'))
+ );
+ });
+ }, rows);
+ await prepare(page, f);
+ expect(await commit(page)).toEqual({ ok: false, reason: 'capacity' });
+ expect(await observe(page)).toEqual({ state: 'base_observed' });
+ const inventory = await page.evaluate(async () => {
+ const api = window.hcp050;
+ const result = await api.inspectPublicStorage(window.hcp050Quota);
+ if (!result.ok) throw new Error(result.reason);
+ return api.publicInventorySnapshot(window.hcp050Quota, result.value);
+ });
+ expect(inventory?.rows).toHaveLength(count);
+});
+test('unknown stored row aborts artifact transition and owner lifetime closes admission', async ({
+ page
+}) => {
+ const f = fixture();
+ await load(page, f.row.owner);
+ await admit(page, f.row);
+ await prepare(page, f);
+ await page.evaluate(async (row) => {
+ const transaction = window.hcp050.browserDatabaseTransaction(
+ window.hcp050Database,
+ ['preference_operations'],
+ 'readwrite'
+ );
+ transaction.objectStore('preference_operations').put({
+ owner: row.owner,
+ id: '3d030bf5-901d-45e1-8251-41cbdf805e96',
+ wire: 'unknown schema'
+ });
+ await new Promise<void>((resolve, reject) => {
+ transaction.addEventListener('complete', () => resolve());
+ transaction.addEventListener('abort', () =>
+ reject(new Error('seed aborted'))
+ );
+ });
+ }, f.row);
+ expect(await commit(page)).toEqual({ ok: false, reason: 'corrupt_record' });
+ expect(await observe(page)).toEqual({ state: 'unavailable' });
+ await page.evaluate(() =>
+ window.hcp050.closeBrowserDatabase(window.hcp050Database)
+ );
+ expect(await commit(page)).toEqual({ ok: false, reason: 'invalid_scope' });
+});
+
+test('genuine preference artifact and receipt CAS preserves source, consent, target role and public aggregate store', async ({
+ page
+}) => {
+ const key = crypto.getRandomValues(new Uint8Array(32));
+ let event: ReturnType<typeof finalizeEvent>;
+ try {
+ event = finalizeEvent(
+ {
+ kind: 10050,
+ created_at: 100,
+ tags: [['relay', 'wss://inbox.example.org']],
+ content: ''
+ },
+ key
+ );
+ } finally {
+ key.fill(0);
+ }
+ const id = randomUUID();
+ const template = {
+ pubkey: event.pubkey,
+ kind: 10050,
+ created_at: 100,
+ tags: event.tags,
+ content: event.content
+ };
+ const row = {
+ schema: 1 as const,
+ family: 'preference_operation' as const,
+ owner: event.pubkey,
+ id,
+ revision: 0,
+ source: { type: 'inbox_head' as const, wire: null },
+ consent: 'explicit_review' as const,
+ capture: {
+ kind: 10050 as const,
+ wire: JSON.stringify(template),
+ hash: getEventHash(template),
+ targets: ['wss://one.example.org'],
+ policyFingerprint: 'a'.repeat(64)
+ },
+ artifact: null,
+ receipts: []
+ };
+ await load(page, row.owner);
+ const result = await page.evaluate(
+ async ({ row, wire, actionId }) => {
+ const api = window.hcp050;
+ const record = api.decodePublicRecord(
+ JSON.stringify(row),
+ row.owner,
+ row.id
+ );
+ if (!record.ok) throw new Error(record.reason);
+ const admitted = await api.admitPublicOperation(
+ window.hcp050Quota,
+ row.id,
+ record.value
+ );
+ if (!admitted.ok) throw new Error(admitted.reason);
+ const artifact = api.bindCapturedArtifact(
+ wire,
+ row.owner,
+ 10050,
+ row.capture.hash
+ );
+ if (!artifact.ok) throw new Error(artifact.reason);
+ const prepared = api.preparePublicArtifactTransition(
+ record.value,
+ row.owner,
+ row.id,
+ artifact.value
+ );
+ if (!prepared.ok) throw new Error(prepared.reason);
+ const committed = await api.commitPublicOperationTransition(
+ window.hcp050Quota,
+ prepared.value
+ );
+ if (!committed.ok) throw new Error(committed.reason);
+ const capture = api.publicTransitionSnapshot(
+ prepared.value,
+ row.owner,
+ row.id
+ );
+ const signed = api.decodePublicRecord(
+ capture?.nextWire,
+ row.owner,
+ row.id
+ );
+ if (!signed.ok) throw new Error(signed.reason);
+ const fact = {
+ actionId,
+ origin: row.capture.targets[0],
+ role: 'preference',
+ attempt: 1,
+ eventId: row.capture.hash,
+ status: 'accepted',
+ observedAtMilliseconds: 1000,
+ readbackWire: wire
+ };
+ const receipt = api.preparePublicReceiptTransition(
+ signed.value,
+ row.owner,
+ row.id,
+ JSON.stringify(fact)
+ );
+ if (!receipt.ok) throw new Error(receipt.reason);
+ const receiptCommit = await api.commitPublicOperationTransition(
+ window.hcp050Quota,
+ receipt.value
+ );
+ if (!receiptCommit.ok) throw new Error(receiptCommit.reason);
+ const observed = await api.observePublicOperationTransition(
+ window.hcp050Quota,
+ receipt.value
+ );
+ const state = api.publicTransitionSnapshot(
+ receipt.value,
+ row.owner,
+ row.id
+ );
+ const final = api.decodePublicRecord(state?.nextWire, row.owner, row.id);
+ if (!final.ok) throw new Error(final.reason);
+ const duplicate = api.preparePublicReceiptTransition(
+ final.value,
+ row.owner,
+ row.id,
+ JSON.stringify(fact)
+ );
+ if (!duplicate.ok) throw new Error(duplicate.reason);
+ return {
+ committed,
+ receiptCommit,
+ observed,
+ duplicate: await api.commitPublicOperationTransition(
+ window.hcp050Quota,
+ duplicate.value
+ ),
+ record: api.publicRecordSnapshot(final.value, row.owner, row.id)
+ };
+ },
+ { row, wire: JSON.stringify(event), actionId: randomUUID() }
+ );
+ expect(result.committed).toEqual({ ok: true, value: { id, revision: 1 } });
+ expect(result.receiptCommit).toEqual({
+ ok: true,
+ value: { id, revision: 2 }
+ });
+ expect(result.observed).toEqual({ state: 'committed', id, revision: 2 });
+ expect(result.duplicate).toEqual({ ok: true, value: { id, revision: 2 } });
+ expect(result.record).toMatchObject({
+ ...row,
+ revision: 2,
+ artifact: { eventId: event.id, wire: JSON.stringify(event) },
+ receipts: [{ role: 'preference', readbackWire: JSON.stringify(event) }]
+ });
+});
diff --git a/web/tests/integration/operation-transactions.test.ts b/web/tests/integration/operation-transactions.test.ts
@@ -0,0 +1,27 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ createPublicQuotaRepository,
+ commitPublicOperationTransition,
+ observePublicOperationTransition,
+ type PublicQuotaRepository
+} from '../../src/lib/persistence/quota.ts';
+import type { PublicOperationTransition } from '../../src/lib/persistence/artifact-records.ts';
+await test('SSR import and fabricated transition capabilities cannot open public or private storage', async () => {
+ const owner =
+ '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798';
+ assert.equal(
+ createPublicQuotaRepository({ kind: 'browser_database' }, owner),
+ undefined
+ );
+ const repository = {} as PublicQuotaRepository,
+ transition = {} as PublicOperationTransition;
+ assert.deepEqual(
+ await commitPublicOperationTransition(repository, transition),
+ { ok: false, reason: 'invalid_scope' }
+ );
+ assert.deepEqual(
+ await observePublicOperationTransition(repository, transition),
+ { state: 'unavailable' }
+ );
+});
diff --git a/web/tests/unit/artifact-records.test.ts b/web/tests/unit/artifact-records.test.ts
@@ -0,0 +1,442 @@
+import { expect, it } from 'vitest';
+import { finalizeEvent, getEventHash } from 'applesauce-core/helpers';
+import {
+ decodePublicRecord,
+ publicRecordSnapshot
+} from '../../src/lib/persistence/records.ts';
+import type {
+ PublicOperationRecord,
+ PreferenceOperationRecord,
+ PublicTargetReceipt
+} from '../../src/lib/contracts/local-records.ts';
+import {
+ bindCapturedArtifact,
+ capturedArtifactSnapshot,
+ preparePublicArtifactTransition,
+ preparePublicReceiptTransition,
+ publicTransitionSnapshot,
+ type CapturedArtifact,
+ type PublicOperationTransition
+} from '../../src/lib/persistence/artifact-records.ts';
+import { decideFrozenTransition } from '../../src/lib/persistence/operation-transactions.ts';
+const id = '3d030bf5-901d-45e1-8251-41cbdf805e96';
+const actionId = 'b1d6d23d-79f3-4779-9b03-e289712cc73f';
+function fixture(kind: 30402 | 10050 | 1059 = 30402) {
+ const key = crypto.getRandomValues(new Uint8Array(32));
+ try {
+ const event = finalizeEvent(
+ {
+ kind,
+ created_at: 100,
+ tags:
+ kind === 30402
+ ? [
+ ['d', 'transition'],
+ ['published_at', '100']
+ ]
+ : [],
+ content:
+ kind === 1059 ? 'controlled ciphertext fixture' : 'public fixture'
+ },
+ key
+ );
+ const template = {
+ pubkey: event.pubkey,
+ kind: kind === 1059 ? 30402 : kind,
+ created_at: event.created_at,
+ tags: event.tags,
+ content: event.content
+ };
+ const capture = {
+ kind: kind === 10050 ? (10050 as const) : (30402 as const),
+ wire: JSON.stringify(template),
+ hash: getEventHash(template),
+ targets: ['wss://one.example.org'],
+ policyFingerprint: 'a'.repeat(64)
+ };
+ const row: PublicOperationRecord | PreferenceOperationRecord =
+ kind === 10050
+ ? {
+ schema: 1,
+ family: 'preference_operation',
+ owner: event.pubkey,
+ id,
+ revision: 0,
+ source: { type: 'inbox_head', wire: null },
+ consent: 'explicit_review',
+ capture: { ...capture, kind: 10050 },
+ artifact: null,
+ receipts: []
+ }
+ : {
+ schema: 1,
+ family: 'public_operation',
+ owner: event.pubkey,
+ id,
+ revision: 0,
+ source: { type: 'draft', id, revision: 0 },
+ capture: { ...capture, kind: 30402 },
+ artifact: null,
+ receipts: []
+ };
+ return { row, event, wire: JSON.stringify(event) };
+ } finally {
+ key.fill(0);
+ }
+}
+function handle(row: PublicOperationRecord | PreferenceOperationRecord) {
+ const decoded = decodePublicRecord(JSON.stringify(row), row.owner, row.id);
+ if (!decoded.ok) throw new Error(decoded.reason);
+ return decoded.value;
+}
+function artifact(f: ReturnType<typeof fixture>) {
+ const result = bindCapturedArtifact(
+ f.wire,
+ f.row.owner,
+ f.event.kind,
+ f.event.id
+ );
+ if (!result.ok) throw new Error(result.reason);
+ return result.value;
+}
+function signedRow(f: ReturnType<typeof fixture>) {
+ return {
+ ...f.row,
+ revision: 1,
+ artifact: { eventId: f.event.id, wire: f.wire }
+ };
+}
+function receipt(f: ReturnType<typeof fixture>): PublicTargetReceipt {
+ return {
+ actionId,
+ origin: 'wss://one.example.org',
+ role:
+ f.row.family === 'preference_operation' ? 'preference' : 'publication',
+ attempt: 1,
+ eventId: f.event.id,
+ status: 'accepted',
+ observedAtMilliseconds: 1000,
+ readbackWire: null
+ };
+}
+it('SDK signature binding rejects changed author, kind, hash and forged wire', () => {
+ const f = fixture();
+ expect(bindCapturedArtifact(f.wire, f.row.owner, 30402, f.event.id).ok).toBe(
+ true
+ );
+ for (const args of [
+ [
+ f.wire,
+ 'c6047f9441ed7d6d3045406e95c07cd85c778e4bcef3ca7abac09b95c709ee5',
+ 30402,
+ f.event.id
+ ],
+ [f.wire, f.row.owner, 10050, f.event.id],
+ [f.wire, f.row.owner, 30402, 'b'.repeat(64)],
+ [
+ JSON.stringify({ ...f.event, sig: '0'.repeat(128) }),
+ f.row.owner,
+ 30402,
+ f.event.id
+ ]
+ ] as const)
+ expect(bindCapturedArtifact(args[0], args[1], args[2], args[3]).ok).toBe(
+ false
+ );
+});
+it('outer1059 binding is only a mechanical capability and cannot enter public record transitions', () => {
+ const f = fixture(1059);
+ expect(bindCapturedArtifact(f.wire, f.row.owner, 1059, f.event.id).ok).toBe(
+ true
+ );
+ expect(
+ preparePublicArtifactTransition(handle(f.row), f.row.owner, id, artifact(f))
+ .ok
+ ).toBe(false);
+ expect(bindCapturedArtifact(f.wire, f.row.owner, 14, f.event.id).ok).toBe(
+ false
+ );
+});
+it('artifact transition binds original full wire and advances one revision with immutable capture', () => {
+ const f = fixture();
+ const base = handle(f.row);
+ const result = preparePublicArtifactTransition(
+ base,
+ f.row.owner,
+ id,
+ artifact(f)
+ );
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const state = publicTransitionSnapshot(result.value, f.row.owner, id);
+ expect(state?.baseWire).toBe(JSON.stringify(f.row));
+ expect(state?.revision).toBe(1);
+ const decoded = decodePublicRecord(state?.nextWire, f.row.owner, id);
+ expect(decoded.ok).toBe(true);
+ if (!decoded.ok) return;
+ const next = publicRecordSnapshot(decoded.value, f.row.owner, id);
+ expect(next).toMatchObject({
+ ...f.row,
+ revision: 1,
+ artifact: { eventId: f.event.id, wire: f.wire }
+ });
+});
+it('same exact already-bound artifact is idempotent but different signed wire conflicts', () => {
+ const f = fixture();
+ const row = signedRow(f);
+ const same = preparePublicArtifactTransition(
+ handle(row),
+ row.owner,
+ id,
+ artifact(f)
+ );
+ expect(same.ok).toBe(true);
+ if (!same.ok) return;
+ expect(publicTransitionSnapshot(same.value, row.owner, id)?.nextWire).toBe(
+ JSON.stringify(row)
+ );
+ const formatted = bindCapturedArtifact(
+ JSON.stringify(f.event, null, 2),
+ row.owner,
+ 30402,
+ f.event.id
+ );
+ expect(formatted.ok).toBe(true);
+ if (!formatted.ok) return;
+ expect(
+ preparePublicArtifactTransition(handle(row), row.owner, id, formatted.value)
+ ).toEqual({ ok: false, reason: 'conflict' });
+});
+it('forged capabilities, wrong scope and maximum revision fail before transitions', () => {
+ const f = fixture();
+ expect(
+ preparePublicArtifactTransition(
+ handle(f.row),
+ f.row.owner,
+ id,
+ {} as CapturedArtifact
+ ).ok
+ ).toBe(false);
+ expect(
+ publicTransitionSnapshot({} as PublicOperationTransition, f.row.owner, id)
+ ).toBeUndefined();
+ expect(
+ preparePublicArtifactTransition(
+ handle({ ...f.row, revision: Number.MAX_SAFE_INTEGER }),
+ f.row.owner,
+ id,
+ artifact(f)
+ ).ok
+ ).toBe(false);
+ expect(
+ preparePublicArtifactTransition(
+ handle(f.row),
+ 'b'.repeat(64),
+ id,
+ artifact(f)
+ ).ok
+ ).toBe(false);
+});
+it('preference artifact remains typed, consent and source unchanged', () => {
+ const f = fixture(10050);
+ const result = preparePublicArtifactTransition(
+ handle(f.row),
+ f.row.owner,
+ id,
+ artifact(f)
+ );
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const state = publicTransitionSnapshot(result.value, f.row.owner, id);
+ expect(JSON.parse(state?.nextWire ?? 'null')).toMatchObject({
+ family: 'preference_operation',
+ consent: 'explicit_review',
+ source: { type: 'inbox_head', wire: null },
+ capture: f.row.capture
+ });
+});
+it('receipt append preserves separate observations and exact duplicate has no revision growth', () => {
+ const f = fixture();
+ const row = signedRow(f);
+ const fact = receipt(f);
+ const first = preparePublicReceiptTransition(
+ handle(row),
+ row.owner,
+ id,
+ JSON.stringify(fact)
+ );
+ expect(first.ok).toBe(true);
+ if (!first.ok) return;
+ const state = publicTransitionSnapshot(first.value, row.owner, id);
+ const next = JSON.parse(state?.nextWire ?? 'null') as PublicOperationRecord;
+ expect(next.receipts).toEqual([fact]);
+ expect(next.revision).toBe(2);
+ const duplicate = preparePublicReceiptTransition(
+ handle(next),
+ row.owner,
+ id,
+ JSON.stringify(fact)
+ );
+ expect(duplicate.ok).toBe(true);
+ if (!duplicate.ok) return;
+ expect(
+ publicTransitionSnapshot(duplicate.value, row.owner, id)?.nextWire
+ ).toBe(JSON.stringify(next));
+ const timed = preparePublicReceiptTransition(
+ handle(next),
+ row.owner,
+ id,
+ JSON.stringify({
+ ...fact,
+ status: 'timed_out',
+ observedAtMilliseconds: 999
+ })
+ );
+ expect(timed.ok).toBe(true);
+ if (!timed.ok) return;
+ expect(
+ (
+ JSON.parse(
+ publicTransitionSnapshot(timed.value, row.owner, id)?.nextWire ?? 'null'
+ ) as PublicOperationRecord
+ ).receipts
+ ).toHaveLength(2);
+});
+it('same fact identity with changed readback conflicts; wrong role/target/event or unsigned record rejects', () => {
+ const f = fixture();
+ const fact = receipt(f);
+ const row = { ...signedRow(f), receipts: [fact] };
+ expect(
+ preparePublicReceiptTransition(
+ handle(row),
+ row.owner,
+ id,
+ JSON.stringify({ ...fact, readbackWire: f.wire })
+ )
+ ).toEqual({ ok: false, reason: 'conflict' });
+ for (const changed of [
+ { ...fact, role: 'preference' },
+ { ...fact, origin: 'wss://other.example.org' },
+ { ...fact, eventId: 'b'.repeat(64) },
+ { ...fact, body: 'forbidden' }
+ ])
+ expect(
+ preparePublicReceiptTransition(
+ handle(signedRow(f)),
+ row.owner,
+ id,
+ JSON.stringify(changed)
+ ).ok
+ ).toBe(false);
+ expect(
+ preparePublicReceiptTransition(
+ handle(f.row),
+ row.owner,
+ id,
+ JSON.stringify(fact)
+ ).ok
+ ).toBe(false);
+});
+it('returned snapshots are detached and cannot retarget an existing transition', () => {
+ const f = fixture();
+ const token = artifact(f);
+ const snapshot = capturedArtifactSnapshot(token);
+ expect(snapshot?.wire).toBe(f.wire);
+ if (snapshot) (snapshot as { wire: string }).wire = 'changed';
+ expect(capturedArtifactSnapshot(token)?.wire).toBe(f.wire);
+ const result = preparePublicArtifactTransition(
+ handle(f.row),
+ f.row.owner,
+ id,
+ token
+ );
+ if (!result.ok) throw new Error(result.reason);
+ const view = publicTransitionSnapshot(result.value, f.row.owner, id);
+ if (view) (view as { nextWire: string }).nextWire = 'changed';
+ expect(
+ publicTransitionSnapshot(result.value, f.row.owner, id)?.nextWire
+ ).not.toBe('changed');
+});
+it('full original and expected payload comparison distinguishes committed, base and conflict', () => {
+ expect(decideFrozenTransition('next', 'base', 'next')).toBe('committed');
+ expect(decideFrozenTransition('base', 'base', 'next')).toBe('base_observed');
+ expect(decideFrozenTransition('different', 'base', 'next')).toBe('conflict');
+ expect(decideFrozenTransition(undefined, 'base', 'next')).toBe('conflict');
+});
+
+it('actual signed kind5 binds its immutable own-author source and rejects cross-kind binding', () => {
+ const key = crypto.getRandomValues(new Uint8Array(32));
+ try {
+ const base = finalizeEvent(
+ {
+ kind: 30402,
+ created_at: 99,
+ tags: [
+ ['d', 'withdraw'],
+ ['published_at', '99']
+ ],
+ content: 'public source'
+ },
+ key
+ );
+ const event = finalizeEvent(
+ { kind: 5, created_at: 100, tags: [['e', base.id]], content: 'withdraw' },
+ key
+ );
+ const template = {
+ pubkey: event.pubkey,
+ kind: 5,
+ created_at: 100,
+ tags: event.tags,
+ content: event.content
+ };
+ const row: PublicOperationRecord = {
+ schema: 1,
+ family: 'public_operation',
+ owner: event.pubkey,
+ id,
+ revision: 0,
+ source: { type: 'public_head', wire: JSON.stringify(base) },
+ capture: {
+ kind: 5,
+ wire: JSON.stringify(template),
+ hash: getEventHash(template),
+ targets: ['wss://one.example.org'],
+ policyFingerprint: 'a'.repeat(64)
+ },
+ artifact: null,
+ receipts: []
+ };
+ const bound = bindCapturedArtifact(
+ JSON.stringify(event),
+ row.owner,
+ 5,
+ event.id
+ );
+ expect(bound.ok).toBe(true);
+ if (!bound.ok) return;
+ const result = preparePublicArtifactTransition(
+ handle(row),
+ row.owner,
+ id,
+ bound.value
+ );
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(
+ JSON.parse(
+ publicTransitionSnapshot(result.value, row.owner, id)?.nextWire ??
+ 'null'
+ )
+ ).toMatchObject({
+ capture: row.capture,
+ source: row.source,
+ artifact: { eventId: event.id, wire: JSON.stringify(event) }
+ });
+ expect(
+ bindCapturedArtifact(JSON.stringify(event), row.owner, 30402, event.id).ok
+ ).toBe(false);
+ } finally {
+ key.fill(0);
+ }
+});