@real-life/trust-protocol 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +79 -34
  3. package/dist/adapters/vti-mediator.d.ts +18 -5
  4. package/dist/adapters/vti-mediator.d.ts.map +1 -1
  5. package/dist/adapters/vti-mediator.js +143 -17
  6. package/dist/adapters/vti-mediator.js.map +1 -1
  7. package/dist/codec.d.ts +2 -9
  8. package/dist/codec.d.ts.map +1 -1
  9. package/dist/codec.js +61 -96
  10. package/dist/codec.js.map +1 -1
  11. package/dist/engine.d.ts +62 -1
  12. package/dist/engine.d.ts.map +1 -1
  13. package/dist/engine.js +289 -15
  14. package/dist/engine.js.map +1 -1
  15. package/dist/holder-api.d.ts +15 -1
  16. package/dist/holder-api.d.ts.map +1 -1
  17. package/dist/holder-api.js +28 -3
  18. package/dist/holder-api.js.map +1 -1
  19. package/dist/{holder-state-v2.d.ts → holder-state-v3.d.ts} +210 -207
  20. package/dist/holder-state-v3.d.ts.map +1 -0
  21. package/dist/holder-state-v3.js +2 -0
  22. package/dist/holder-state-v3.js.map +1 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/internal.d.ts +1 -2
  27. package/dist/internal.d.ts.map +1 -1
  28. package/dist/internal.js.map +1 -1
  29. package/dist/results.d.ts +5 -1
  30. package/dist/results.d.ts.map +1 -1
  31. package/dist/results.js.map +1 -1
  32. package/dist/state.d.ts +22 -9
  33. package/dist/state.d.ts.map +1 -1
  34. package/dist/state.js.map +1 -1
  35. package/package.json +4 -6
  36. package/schemas/{holder-state-v2.schema.json → holder-state-v3.schema.json} +50 -5
  37. package/dist/holder-state-v1.d.ts +0 -801
  38. package/dist/holder-state-v1.d.ts.map +0 -1
  39. package/dist/holder-state-v1.js +0 -2
  40. package/dist/holder-state-v1.js.map +0 -1
  41. package/dist/holder-state-v2.d.ts.map +0 -1
  42. package/dist/holder-state-v2.js +0 -2
  43. package/dist/holder-state-v2.js.map +0 -1
  44. package/schemas/holder-state-v1.schema.json +0 -3880
@@ -1 +1 @@
1
- {"version":3,"file":"vti-mediator.js","sourceRoot":"","sources":["../../src/adapters/vti-mediator.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,4EAA4E;AAC5E,EAAE;AACF,4EAA4E;AAC5E,8DAA8D;AAC9D,wEAAwE;AACxE,wEAAwE;AACxE,wEAAwE;AACxE,yEAAyE;AACzE,EAAE;AACF,qEAAqE;AACrE,kDAAkD;AAClD,0DAA0D;AAC1D,EAAE;AACF,2EAA2E;AAC3E,uEAAuE;AACvE,0EAA0E;AAC1E,oEAAoE;AACpE,oEAAoE;AACpE,8BAA8B;AAC9B,EAAE;AACF,kCAAkC;AAClC,6DAA6D;AAC7D,oEAAoE;AACpE,mDAAmD;AACnD,qEAAqE;AACrE,mEAAmE;AACnE,8DAA8D;AAC9D,uDAAuD;AACvD,gEAAgE;AAChE,oCAAoC;AAEpC,OAAO,EAAE,GAAG,EAAE,MAAM,YAAY,CAAA;AAChC,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AAClC,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAA;AAMhF,uEAAuE;AACvE,qEAAqE;AACrE,MAAM,CAAC,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC;IACpC,eAAe,EAAE,EAAE,GAAG,SAAS;IAC/B,eAAe,EAAE,MAAM;IACvB,eAAe,EAAE,EAAE;IACnB,eAAe,EAAE,SAAS;IAC1B,aAAa,EAAE,UAAU;IACzB,iBAAiB,EAAE,EAAE,GAAG,UAAU;CAC1B,CAAC,CAAA;AAMX,MAAM,OAAO,SAAU,SAAQ,KAAK;IAClC,IAAI,CAAe;IACnB,YAAa,IAAmB,EAAE,OAAgB;QAChD,KAAK,CAAC,OAAO,IA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;QAChE,+DAA+D;QAC/D,6DAA6D;QAC7D,gDAAgD;QAChD,KAAK,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YAC3C,IAAI,GAAG,GAAG,EAAE,IAAI,QAAQ,CAAC,iBAAiB,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC5E,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;gBAC9B,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;YAClC,CAAC;QACH,CAAC;QACD,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAA;QAC3B,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAA;IACvB,CAAC;IAED;;;;mBAIe;IACf,KAAK,KAAY,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA,CAAC,CAAC;IAEtC,IAAI,MAAM,KAAe,OAAO,IAAI,CAAC,OAAO,CAAA,CAAC,CAAC;CAC/C;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,KAAK,EAAE,KAAiB,EAAmB,EAAE,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,CAAC,CAAA","sourcesContent":["// RLTP transport adapter: VTI mediator — published as\n// @real-life/trust-protocol/adapters/vti-mediator (lib Stage 2, note §4.6).\n//\n// Its reports reach the holder as the ports' DeliveryReport: submitOutbound\n// files an Outbound under its document digest and returns the\n// SubmissionRef (submission id ↔ digest); report(id) maps the adapter's\n// SubmissionState onto DeliveryReport (deliveryReportOf), which the app\n// hands to holder.report(). An adapter's `delivered` is its claim about\n// transport; the holder's receive core verifies the delivery-ack itself.\n//\n// Profile: spec/adapter-vti-mediator.md v0.23 (twenty-third casting;\n// round journals under design/adapter-review*). A\n// transport adapter contract — NOT a carrier at the port.\n//\n// Beyond the profile (lib 0.5.0): conclude(collection, now, {keep}) leaves\n// the items whose disposition is transient unconcluded and offers them\n// again (Delivery 0.82 RLTP-DEL-5810, 5820: failed(rate-limited) is never\n// concluded); `concludable(result)` says which receive outcomes are\n// terminal. The profile's §4 concludes a collection whole; its next\n// casting is to take this up.\n//\n// Structural rules (reviews 3+4):\n// · No port operation ever awaits the mediator — including\n// register: keylist synchronization is a recorded intent with a\n// tracked background task, retried by advance.\n// · No report is invented, and absence is ABSENT: before the first\n// honest report exists, status() returns null (§6.1 grants the\n// window; representing it as a queryable fourth value was\n// review-4 B2). has() distinguishes an unknown id.\n// · A retired instance mutates nothing and refuses everything\n// except reading its ack state.\n\nimport { jcs } from '../core.js'\nimport { sha } from '../crypto.js'\nimport { carrierPrincipal, carrierScopedIdentity } from '../carrier-identity.js'\nimport type { CarrierPrincipal, CarrierScopedIdentity } from '../carrier-identity.js'\nimport type { DeliveryReport, Outbound, ReceiverRefusalCode, SubmissionRef } from '../ports.js'\nimport type { ReceiveResult } from '../results.js'\nexport type { ReceiverRefusalCode } from '../ports.js'\n\n// ── Declared constants (profile §2) — promises of THIS casting ──────\n// frozen: the declared promises cannot be changed at run time either\nexport const DECLARED = Object.freeze({\n giveUpHorizonMs: 72 * 3_600_000,\n statusHorizonMs: 60_000,\n queueFloorCount: 64,\n queueFloorBytes: 1_048_576,\n maxQueueBytes: 16_777_216,\n duplicateWindowMs: 30 * 86_400_000,\n} as const)\n\n// ── The injected wire ────────────────────────────────────────────────\nexport type WireErrorKind =\n | 'unreachable' | 'refused-retriable' | 'refused-admission' | 'oversize'\n\nexport class WireError extends Error {\n kind: WireErrorKind\n constructor (kind: WireErrorKind, message?: string) {\n super(message ?? kind)\n this.kind = kind\n }\n}\n\nexport interface MediatorWire {\n authChallenge (did: string): Promise<{ challenge: string, sessionId: string }>\n authenticate (answer: { did: string, challenge: string, sessionId: string }): Promise<TokenSet>\n // A transient failure MUST be a WireError 'unreachable' or\n // 'refused-retriable' (the tokens are kept); any other error means the\n // mediator refused the refresh token (the adapter re-runs the handshake).\n refresh (refreshToken: string): Promise<TokenSet>\n keylistUpdate (accessToken: string, rkids: string[]): Promise<void>\n deposit (accessToken: string, bytes: Uint8Array, egressDid: string): Promise<void>\n ackReceived (accessToken: string, queueIds: string[]): Promise<void>\n onDeliver (cb: (bytes: Uint8Array) => Promise<void>): void\n /** Optional truthful connectivity signal; absent means unknown. */\n offline? (): boolean\n}\n\nexport interface TokenSet {\n accessToken: string\n accessExpiresAt: number\n refreshToken: string\n refreshExpiresAt: number\n}\n\n// ── Sender states (§6.1 — the closed sets, nothing else) ────────────\n// ReceiverRefusalCode is the ports' (one closed set, one place)\nconst RECEIVER_REFUSAL_CODES: ReadonlySet<ReceiverRefusalCode> = new Set<ReceiverRefusalCode>([\n 'malformedRequest', 'unsupportedType', 'proofRequired',\n 'proofInvalid', 'wrongRecipient', 'identityMismatch',\n])\n\nexport type SubmissionState =\n | { state: 'awaiting-transport', reason: 'offline' | 'transport-unreachable' | 'carrier-refused-retriable' }\n | { state: 'accepted' }\n | { state: 'delivered', late: boolean }\n | { state: 'failed', reason: 'unroutable' | 'oversize' | 'expired-by-adapter-policy' }\n | { state: 'failed', reason: 'rejected-by-receiver', code: ReceiverRefusalCode }\n\n/** The ports' DeliveryReport for a document `digest` in adapter state `st`\n * (Delivery §6.1): one-to-one, `late` and the refusal code carried over. */\nexport function deliveryReportOf (digest: string, st: SubmissionState): DeliveryReport {\n switch (st.state) {\n case 'awaiting-transport': return { digest, status: 'awaiting-transport', reason: st.reason }\n case 'accepted': return { digest, status: 'accepted' }\n case 'delivered': return { digest, status: 'delivered', late: st.late }\n case 'failed': return st.reason === 'rejected-by-receiver'\n ? { digest, status: 'failed', reason: 'rejected-by-receiver', code: st.code }\n : { digest, status: 'failed', reason: st.reason }\n }\n}\n\n/** Whether a receive outcome is terminal and its item may be concluded\n * (Delivery 5a.8): every disposition but `failed(rate-limited)`, the one\n * failure that is transient (RLTP-DEL-5820). An InfraError of the\n * holder's store is transient as well (RLTP-DEL-5810): an item whose\n * receive threw is kept, too. */\nexport function concludable (r: ReceiveResult): boolean {\n return !(r.disposition === 'failed' && r.reason === 'rate-limited')\n}\n\n/** The adapter's own copy of a wire's token set: the wire keeps no handle on it. */\nconst tokenCopy = (t: TokenSet): TokenSet => ({ accessToken: t.accessToken, accessExpiresAt: t.accessExpiresAt, refreshToken: t.refreshToken, refreshExpiresAt: t.refreshExpiresAt })\n\nexport interface CollectedItem { bytes: Uint8Array, queueId: string }\nexport interface Collection { id: string, items: CollectedItem[] }\n\n/** Ack state for the host to persist (profile §4). Invariant: every\n * pending id names a concluded entry; violations are refused at\n * construction (fail-closed). */\nexport interface AckState {\n concluded: Array<{ queueId: string, concludedAt: number }>\n pending: string[]\n}\n\ninterface Submission {\n /** the document digest, for submissions filed by submitOutbound */\n digest?: string\n bytes: Uint8Array\n submittedAt: number\n attemptStartedAt: number | null\n lastKind: WireErrorKind | null\n st: SubmissionState | null // null = no honest report exists yet\n}\n\nconst hex = (b: Uint8Array): string =>\n Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')\n\n// construction capability: only create() holds it\nconst KEY = Symbol('MediatorCarrierAdapter.create')\n\n// ── The adapter ──────────────────────────────────────────────────────\nexport class MediatorCarrierAdapter {\n // JS-hard identity fields: TS `readonly` is a compile-time promise\n // only, and §8 claims runtime unforgeability — so the values live\n // in true privates behind getters (R8-B1)\n #principal: string\n #connectionDid: string\n #egressDid: string\n get principal (): string { return this.#principal }\n get connectionDid (): string { return this.#connectionDid }\n get egressDid (): string { return this.#egressDid }\n #wire: MediatorWire\n #tokens: TokenSet | null = null\n #clock = Number.NEGATIVE_INFINITY\n #closed = false\n\n #subs = new Map<string, Submission>()\n #inflight = new Set<Promise<void>>()\n #nextId = 1\n\n #desiredRkids: string[] | null = null\n #keylistSynced = false\n #keylistSyncing = false\n\n #inbox: CollectedItem[] = []\n #inboxBytes = 0\n #inboxDigests = new Set<string>()\n #outstanding = new Map<string, Map<string, CollectedItem>>()\n #outstandingBytes = 0\n #concluded = new Map<string, number>()\n #pendingAcks = new Set<string>()\n #flightAcks = new Set<string>() // ids inside the in-flight flush snapshot\n #flushing = false\n #nextColId = 1\n\n #transitions: Array<{ id: string, to: 'delivered' }> = []\n\n /** The only way to build an adapter: the trio is DERIVED here from\n * one root, one carrier, one nonce — so principal, connection DID\n * and egress identity cannot come from different relationships\n * (R7-B2: the coupling is enforced by construction, not by\n * inspecting caller-supplied identities). */\n static async create (\n rootIkm: Uint8Array, carrier: string, nonce: Uint8Array,\n wire: MediatorWire, restored?: AckState, restoredAt?: number,\n ): Promise<MediatorCarrierAdapter> {\n // ONE tuple, snapshotted at entry: a caller mutating its buffers\n // between the three awaited derivations must not be able to mix\n // identities from two tuples (R8-B2)\n const ikm = new Uint8Array(rootIkm)\n const n = new Uint8Array(nonce)\n const principal = await carrierPrincipal(ikm, carrier, n)\n const connection = await carrierScopedIdentity(ikm, carrier, n, 'connection')\n const egress = await carrierScopedIdentity(ikm, carrier, n, 'egress')\n return new MediatorCarrierAdapter(KEY, principal, connection, egress, wire, restored, restoredAt)\n }\n\n constructor (\n key: symbol,\n principal: CarrierPrincipal,\n connection: CarrierScopedIdentity,\n egress: CarrierScopedIdentity,\n wire: MediatorWire,\n restored?: AckState,\n restoredAt?: number,\n ) {\n if (key !== KEY) {\n throw new Error('use MediatorCarrierAdapter.create — the identity trio must be derived, not supplied (5a.10)')\n }\n if (connection.scope !== 'connection' || egress.scope !== 'egress') {\n throw new Error('scoped identities passed in the wrong roles')\n }\n const three = new Set([principal.principal, connection.did, egress.did])\n if (three.size !== 3) {\n throw new Error('principal, connection DID and egress identity must be pairwise distinct (5a.10)')\n }\n this.#principal = principal.principal\n this.#connectionDid = connection.did\n this.#egressDid = egress.did\n this.#wire = wire\n if (restored) {\n // The restore instant anchors the duplicate-window: an expired,\n // debt-free entry is dropped HERE, not at the first advance —\n // otherwise a redelivery arriving before any port call would be\n // absorbed beyond the declared window (review-4 B4).\n if (typeof restoredAt !== 'number' || !Number.isFinite(restoredAt)) {\n throw new Error('restoring ack state requires a finite restoredAt instant')\n }\n this.#now(restoredAt)\n const pending = new Set(restored.pending)\n const known = new Set(restored.concluded.map((c) => c.queueId))\n for (const id of pending) {\n if (!known.has(id)) {\n throw new Error('ack snapshot violates its invariant: pending intent without a concluded entry')\n }\n }\n for (const { queueId, concludedAt } of restored.concluded) {\n if (!Number.isFinite(concludedAt) || concludedAt > restoredAt) {\n // a conclusion \"from the future\" would stretch the window\n // past its declared span (R5-B4) — fail closed\n throw new Error('ack snapshot: conclusion instant is non-finite or after restoredAt')\n }\n // the window beats everything (round-14 B): an expired entry\n // falls at the restore instant, owed or not — a phantom debt\n // from an ack that landed just before a close can never\n // outlive the window and delete a fresh copy (R14-B2)\n if (restoredAt - concludedAt >= DECLARED.duplicateWindowMs) continue\n this.#concluded.set(queueId, concludedAt)\n if (pending.has(queueId)) this.#pendingAcks.add(queueId)\n }\n }\n this.#wire.onDeliver(async (raw) => {\n if (this.#closed) return\n // a plain copy of its own: a Node Buffer's slice() would share memory\n const bytes = new Uint8Array(raw)\n const queueId = hex(await sha(bytes))\n if (this.#closed) return\n // Absorption is WINDOW-checked at the moment it happens\n // (R11-B1), and the window beats everything (round-14 B):\n // beyond it, entry AND any leftover intent fall, and the frame\n // is a new item — so no acknowledgement, owed or phantom, can\n // ever delete the only fresh copy.\n const concludedAt = this.#concluded.get(queueId)\n if (concludedAt !== undefined) {\n if (this.#flightAcks.has(queueId) ||\n this.#clock - concludedAt < DECLARED.duplicateWindowMs) {\n // inside the window — or deferred: an id inside an\n // in-flight flush keeps absorbing until that flush ends,\n // because its irrecallable ack may still land (R15-B1)\n this.#pendingAcks.add(queueId)\n return\n }\n this.#concluded.delete(queueId)\n this.#pendingAcks.delete(queueId)\n }\n if (this.#inboxDigests.has(queueId)) return\n for (const col of this.#outstanding.values()) if (col.has(queueId)) return\n const held = this.#inboxBytes + this.#outstandingBytes\n const underFloor = this.#inbox.length < DECLARED.queueFloorCount &&\n held + bytes.length <= DECLARED.queueFloorBytes\n const underCap = held + bytes.length <= DECLARED.maxQueueBytes\n if (!underFloor && !underCap) return\n this.#inbox.push({ bytes, queueId })\n this.#inboxBytes += bytes.length\n this.#inboxDigests.add(queueId)\n })\n }\n\n #now (raw: number): number {\n if (!Number.isFinite(raw)) throw new Error('non-finite time')\n if (raw > this.#clock) this.#clock = raw\n return this.#clock\n }\n\n #open (): void { if (this.#closed) throw new Error('retired (5a.10 lifecycle)') }\n\n #track (p: Promise<void>): void {\n const t = p.catch(() => {})\n this.#inflight.add(t)\n void t.finally(() => this.#inflight.delete(t))\n }\n\n // ── auth: silent carrier policy ─────────────────────────────────\n // Single-flight: concurrent callers share one handshake — the ATM\n // challenge/response is a session, and two interleaved sessions\n // under one connection DID would answer each other's challenges.\n #authing: Promise<string> | null = null\n\n #ensureAuth (now: number): Promise<string> {\n if (this.#tokens && now < this.#tokens.accessExpiresAt) return Promise.resolve(this.#tokens.accessToken)\n if (this.#authing) return this.#authing\n const run = (async (): Promise<string> => {\n if (this.#tokens && now < this.#tokens.refreshExpiresAt) {\n try {\n const refreshed = await this.#wire.refresh(this.#tokens.refreshToken)\n if (this.#closed) throw new Error('retired') // as on the handshake path (R6-B1)\n this.#tokens = tokenCopy(refreshed)\n return this.#tokens.accessToken\n } catch (e) {\n if (this.#closed) throw e\n // a transient failure (mediator unreachable, retriable refusal)\n // says nothing about the token: keep it for the next attempt (#9)\n if (e instanceof WireError && (e.kind === 'unreachable' || e.kind === 'refused-retriable')) throw e\n // a refused refresh (revoked before its expiry) is never replayed:\n // drop the tokens and take the challenge handshake below\n this.#tokens = null\n }\n }\n const { challenge, sessionId } = await this.#wire.authChallenge(this.#connectionDid)\n if (this.#closed) throw new Error('retired') // nothing new starts, not even the answer (R6-B1)\n this.#tokens = tokenCopy(await this.#wire.authenticate({ did: this.#connectionDid, challenge, sessionId }))\n return this.#tokens.accessToken\n })()\n this.#authing = run.finally(() => { this.#authing = null })\n return this.#authing\n }\n\n // ── transport registration (profile §3 — NOT §5a.3) ─────────────\n /** Records the desired keylist and returns; synchronization runs\n * as a tracked background task and advance retries it until it\n * lands (review-4 B1). */\n register (rkids: string[], rawNow: number): void {\n this.#open()\n const now = this.#now(rawNow)\n this.#desiredRkids = [...rkids]\n this.#keylistSynced = false\n this.#startKeylistSync(now)\n }\n\n get keylistSynced (): boolean {\n this.#open()\n return this.#keylistSynced\n }\n\n #startKeylistSync (now: number): void {\n if (this.#keylistSyncing || this.#keylistSynced || this.#desiredRkids === null) return\n this.#keylistSyncing = true\n const wanted = [...this.#desiredRkids]\n this.#track((async () => {\n try {\n const token = await this.#ensureAuth(now)\n if (this.#closed) return\n await this.#wire.keylistUpdate(token, [...wanted]) // the wire's own list: `wanted` is compared below\n // land only if the desire has not moved meanwhile\n if (!this.#closed && this.#desiredRkids !== null &&\n wanted.join(' ') === this.#desiredRkids.join(' ')) {\n this.#keylistSynced = true\n }\n } catch {\n // intent survives; advance retries\n } finally {\n this.#keylistSyncing = false\n }\n })())\n }\n\n // ── sender side ─────────────────────────────────────────────────\n /** Returns the submission id synchronously. Before the first\n * honest report exists, status() returns null — §6.1's own\n * pre-report window, represented as absence, not as a value. */\n submit (envelopeBytes: Uint8Array, rawNow: number): string {\n this.#open()\n const now = this.#now(rawNow)\n const id = 's' + this.#nextId++\n const knownOffline = this.#wire.offline?.() === true\n const sub: Submission = {\n // a plain copy of its own (a Node Buffer's slice() shares memory)\n bytes: new Uint8Array(envelopeBytes),\n submittedAt: now,\n attemptStartedAt: null,\n lastKind: null,\n st: null,\n }\n this.#subs.set(id, sub)\n if (!knownOffline) this.#startAttempt(sub, now)\n return id\n }\n\n /** Files an Outbound (its envelope as JCS bytes) and returns the\n * SubmissionRef the holder's reports are keyed by: submission id ↔\n * document digest (note §4.3). */\n submitOutbound (outbound: Pick<Outbound, 'digest' | 'envelope'>, rawNow: number): SubmissionRef {\n this.#open()\n if (typeof outbound?.digest !== 'string' || outbound.digest === '') throw new Error('an outbound needs its document digest')\n const submissionId = this.submit(new TextEncoder().encode(jcs(outbound.envelope)), rawNow)\n this.#subs.get(submissionId)!.digest = outbound.digest\n return { submissionId, digest: outbound.digest }\n }\n\n /** The current state as the ports' DeliveryReport for holder.report(),\n * or null while no honest report exists (and for an unknown id). A\n * submission filed without a digest (submit) has no report form. */\n report (id: string): DeliveryReport | null {\n const st = this.status(id)\n if (st === null) return null\n const digest = this.#subs.get(id)!.digest\n if (digest === undefined) throw new Error('submitted without a document digest: use submitOutbound')\n return deliveryReportOf(digest, st)\n }\n\n has (id: string): boolean {\n this.#open()\n return this.#subs.has(id)\n }\n\n #startAttempt (sub: Submission, now: number): void {\n if (sub.attemptStartedAt !== null) return\n sub.attemptStartedAt = now\n this.#track(this.#trySend(sub, now).finally(() => { sub.attemptStartedAt = null }))\n }\n\n async #trySend (sub: Submission, now: number): Promise<void> {\n if (sub.st !== null && sub.st.state !== 'awaiting-transport') return\n let next: SubmissionState\n try {\n const token = await this.#ensureAuth(now)\n if (this.#closed) return // retirement between auth and deposit: nothing new starts (R5-B2)\n // each attempt hands the wire a copy: what it does with it never reaches the next\n await this.#wire.deposit(token, new Uint8Array(sub.bytes), this.#egressDid)\n sub.lastKind = null\n next = { state: 'accepted' }\n } catch (e) {\n const kind: WireErrorKind = e instanceof WireError ? e.kind : 'unreachable'\n sub.lastKind = kind\n next = kind === 'oversize'\n ? { state: 'failed', reason: 'oversize' }\n : {\n state: 'awaiting-transport',\n reason: kind === 'unreachable' ? 'transport-unreachable' : 'carrier-refused-retriable',\n }\n }\n if (this.#closed) return\n // An interim report (including a horizon-corrected one) never\n // outranks the attempt's real outcome; only a TERMINAL state —\n // a give-up, a refusal, a delivery — stands (R5-B1). Without\n // this, an accepted deposit would stay reported unreachable and\n // be sent a second time.\n if (sub.st === null || sub.st.state === 'awaiting-transport') sub.st = next\n }\n\n /** Host teardown aid, NOT a port operation (profile §6): awaits\n * the in-flight background tasks so a host can drain before\n * persisting ackState. On a hanging wire it waits as long as the\n * wire does — a host bounds it externally (Promise.race) exactly\n * because this library holds no clock of its own. */\n async settle (): Promise<void> {\n while (this.#inflight.size > 0) await Promise.all([...this.#inflight])\n }\n\n /** The §6.1 report, or null while none exists yet (has()\n * distinguishes an unknown id). status is a PORT: after close it\n * refuses like every other port operation (R5-B3).\n *\n * The pre-transport report is an HONEST SNAPSHOT, derived at the\n * moment of observation by one precedence order (Option B of the\n * round-14 halt) — never a stored patchwork:\n * (a) the wire knows itself offline → offline\n * (b) an attempt is overdue → transport-unreachable\n * (c) the last completed attempt's kind → its report\n * (d) otherwise → no report yet (null)\n * Terminal states and `accepted` are stored and stand. */\n status (id: string): SubmissionState | null {\n this.#open()\n const sub = this.#subs.get(id)\n if (!sub) return null\n if (sub.st !== null && sub.st.state !== 'awaiting-transport') return { ...sub.st }\n if (this.#wire.offline?.() === true) {\n return { state: 'awaiting-transport', reason: 'offline' }\n }\n if (sub.attemptStartedAt !== null &&\n this.#clock - sub.attemptStartedAt >= DECLARED.statusHorizonMs) {\n return { state: 'awaiting-transport', reason: 'transport-unreachable' }\n }\n return sub.st === null ? null : { ...sub.st }\n }\n\n acknowledged (id: string): void {\n if (this.#closed) return\n const sub = this.#subs.get(id)\n if (!sub) return\n if (sub.st?.state === 'delivered') return // idempotent: a duplicate ack never rewrites `late` (R9-M4)\n const late = sub.st?.state === 'failed'\n sub.st = { state: 'delivered', late }\n if (late) this.#transitions.push({ id, to: 'delivered' })\n }\n\n /** Refusals act on live submissions only (§6.1 knows exactly one\n * late correction — the valid ack). The code set is closed and\n * TERMINAL: retryable counterpart conditions (unavailable,\n * internalError) are transport outcomes, never receiver verdicts\n * — they have no entry here, and an unknown code is refused\n * fail-closed rather than minted into a verdict (R6-B2). */\n receiverRefused (id: string, code: ReceiverRefusalCode): void {\n if (this.#closed) return\n if (!RECEIVER_REFUSAL_CODES.has(code)) {\n throw new Error('not a terminal receiver refusal code — retryable conditions are transport outcomes')\n }\n const sub = this.#subs.get(id)\n if (!sub) return\n // A VALIDATED refusal is itself the proof of receipt — the\n // mediator can have accepted and forwarded while our deposit\n // promise is still unresolved, so the report-less phase is a\n // legitimate moment for it (R9-B2, reversing the R8-B3\n // overcorrection). Only terminal states stand against it.\n if (sub.st !== null && sub.st.state !== 'awaiting-transport' && sub.st.state !== 'accepted') return\n sub.st = { state: 'failed', reason: 'rejected-by-receiver', code }\n }\n\n drainTransitions (): Array<{ id: string, to: 'delivered' }> {\n this.#open()\n return this.#transitions.splice(0)\n }\n\n // ── receiver side ───────────────────────────────────────────────\n collect (rawNow: number): Collection {\n this.#open()\n this.#now(rawNow)\n if (this.#inbox.length === 0) return { id: 'c-empty', items: [] }\n const items = this.#inbox.splice(0)\n this.#outstandingBytes += this.#inboxBytes\n this.#inboxBytes = 0\n this.#inboxDigests.clear()\n const id = 'c' + this.#nextColId++\n this.#outstanding.set(id, new Map(items.map((i) => [i.queueId, i])))\n // the caller gets its own copies: the outstanding entries stay intact,\n // whatever it does with the bytes, for a conclusion that keeps them\n return { id, items: items.map((i) => ({ ...i, bytes: new Uint8Array(i.bytes) })) }\n }\n\n /** Concludes a collection (profile §4, Delivery 5a.8): its items'\n * digests become ack intent. `keep` names the items whose disposition\n * is transient (Delivery RLTP-DEL-5810, 5820: `failed(rate-limited)`,\n * or a transaction that could not commit, see `concludable`): they are\n * not concluded and not acknowledged, they go back to the buffer and the\n * next collect offers them again, and the mediator keeps its copy. */\n conclude (collection: { id: string }, rawNow: number, opts: { keep?: readonly string[] } = {}): void {\n this.#open()\n const now = this.#now(rawNow)\n const col = this.#outstanding.get(collection.id)\n if (!col) return\n this.#outstanding.delete(collection.id)\n const keep = new Set(opts.keep ?? [])\n for (const item of col.values()) {\n this.#outstandingBytes -= item.bytes.length\n if (keep.has(item.queueId)) {\n // transient: back to the buffer, offered again, never acknowledged\n this.#inbox.push(item)\n this.#inboxBytes += item.bytes.length\n this.#inboxDigests.add(item.queueId)\n continue\n }\n this.#concluded.set(item.queueId, now)\n this.#pendingAcks.add(item.queueId)\n }\n this.#startFlush(now)\n }\n\n ackState (): AckState {\n return {\n concluded: [...this.#concluded].map(([queueId, concludedAt]) => ({ queueId, concludedAt })),\n pending: [...this.#pendingAcks],\n }\n }\n\n #startFlush (now: number): void {\n if (this.#flushing || this.#pendingAcks.size === 0) return\n this.#flushing = true\n const snapshot = new Set(this.#pendingAcks)\n this.#track(this.#flushAcks(now, [...snapshot]).finally(() => {\n this.#flushing = false\n // lost-wake-up guard (review-4 M6): intents that arrived while\n // this flush ran get their own flush now — but only newcomers,\n // so a failing wire waits for the next advance instead of\n // spinning\n if (!this.#closed) {\n for (const id of this.#pendingAcks) {\n if (!snapshot.has(id)) { this.#startFlush(this.#clock); break }\n }\n }\n }))\n }\n\n async #flushAcks (now: number, ids: string[]): Promise<void> {\n try {\n const token = await this.#ensureAuth(now)\n if (this.#closed) return\n // Only NOW does anything become irrecallable (R16-B1): the\n // stay of expiry begins at the wire call itself, never at the\n // snapshot — a hanging auth extends no window. And \"live\" is\n // WINDOW-live (R17-B1): an entry whose window already closed —\n // even if no prune has swept it yet — is never sent.\n const live = ids.filter((id) => {\n const at = this.#concluded.get(id)\n return at !== undefined && this.#clock - at < DECLARED.duplicateWindowMs\n })\n if (live.length === 0) return\n for (const id of live) this.#flightAcks.add(id)\n try {\n // the wire gets its own list: what it does with it never reaches the bookkeeping below\n await this.#wire.ackReceived(token, [...live])\n if (!this.#closed) for (const id of live) this.#pendingAcks.delete(id)\n } finally {\n for (const id of live) this.#flightAcks.delete(id)\n // deferred window sweep: entries whose window closed while\n // the ack flew fall now — intent, entry and absorption\n // together (R15-B1). Never on a retired instance: after\n // close, ackState() is the host's final-persist surface and\n // a late-returning wire mutates nothing (R17-B2).\n if (!this.#closed) {\n for (const id of live) {\n const at = this.#concluded.get(id)\n if (at !== undefined && this.#clock - at >= DECLARED.duplicateWindowMs) {\n this.#concluded.delete(id)\n this.#pendingAcks.delete(id)\n }\n }\n }\n }\n } catch {\n // intent survives; the next advance starts a fresh flush\n }\n }\n\n // ── the adapter clock — never awaits the mediator ───────────────\n advance (rawNow: number): void {\n this.#open()\n const now = this.#now(rawNow)\n for (const sub of this.#subs.values()) {\n const live = sub.st === null || sub.st.state === 'awaiting-transport' || sub.st.state === 'accepted'\n if (!live) continue\n if (now - sub.submittedAt >= DECLARED.giveUpHorizonMs) {\n // unroutable only when the LAST COMPLETED attempt was an\n // admission refusal and no attempt is in flight whose outcome\n // is unknown (review-4 B3)\n // the give-up verdict applies the SAME precedence as every\n // observation (R17-B3): a wire that knows itself offline at\n // the horizon outranks any stored refusal class — unroutable\n // needs a completed admission refusal, no unknown outcome in\n // flight, AND no offline signal standing over it\n sub.st = {\n state: 'failed',\n reason: sub.lastKind === 'refused-admission' && sub.attemptStartedAt === null &&\n this.#wire.offline?.() !== true\n ? 'unroutable'\n : 'expired-by-adapter-policy',\n }\n continue\n }\n if (sub.st !== null && sub.st.state === 'accepted') continue\n // reports are DERIVED at observation (see status()); the clock\n // only decides here whether to start an attempt — and never\n // against a wire that knows itself offline\n if (this.#wire.offline?.() === true) continue\n if (sub.attemptStartedAt === null) this.#startAttempt(sub, now)\n }\n // THE WINDOW BEATS EVERYTHING (Option B of the round-14 halt):\n // an ack intent is retried until the window closes; then intent\n // and absorption fall together. There is no ageless debt whose\n // truth the adapter would have to know — the receiver's §6.2\n // absorption owns everything beyond the window.\n for (const [digest, at] of this.#concluded) {\n if (now - at >= DECLARED.duplicateWindowMs && !this.#flightAcks.has(digest)) {\n this.#concluded.delete(digest)\n this.#pendingAcks.delete(digest)\n }\n }\n this.#startKeylistSync(now)\n this.#startFlush(now)\n }\n\n /** §5a.10 lifecycle boundary: after close, every state port is\n * inert — port operations refuse, inbound reports (acknowledged,\n * receiverRefused) are no-ops, late wire resolutions mutate\n * nothing. Only ackState() stays readable for the host's final\n * persist. */\n close (): void { this.#closed = true }\n\n get closed (): boolean { return this.#closed }\n}\n\nexport const queueIdOf = async (bytes: Uint8Array): Promise<string> => hex(await sha(bytes))\n"]}
1
+ {"version":3,"file":"vti-mediator.js","sourceRoot":"","sources":["../../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CAAC,UAAU,EAAE,CAAC;YAC3C,IAAI,GAAG,GAAG,EAAE,IAAI,QAAQ,CAAC,iBAAiB,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC5E,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;gBAC9B,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;YAClC,CAAC;QACH,CAAC;QACD,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAA;QAC3B,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAA;IACvB,CAAC;IAED;;;;mBAIe;IACf,KAAK,KAAY,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA,CAAC,CAAC;IAEtC,IAAI,MAAM,KAAe,OAAO,IAAI,CAAC,OAAO,CAAA,CAAC,CAAC;CAC/C;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,KAAK,EAAE,KAAiB,EAAmB,EAAE,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,CAAC,CAAA","sourcesContent":["// RLTP transport adapter: VTI mediator — published as\n// @real-life/trust-protocol/adapters/vti-mediator (lib Stage 2, note §4.6).\n//\n// It takes the holder's documents from the holder's custody (Delivery 0.83\n// RLTP-DEL-6120 to 6135, lib 0.6.0): reconcile(view, gate, now) files every\n// entry of holder.pendingTransport(when) not yet filed, and withdraws every\n// filed submission still before the trias whose digest the view no longer\n// names — a missing entry means stop, never keep sending. Before every\n// deposit it asks gate.mayHandOver(entry, now) (the holder): false\n// withdraws the submission, an error skips the attempt. It keeps no\n// custody of its own: its copies are volatile and bound to the holder's\n// opening: bound to the holder of its first reconcile, it refuses another,\n// so after holder.close() nothing it holds goes out, and the next opening\n// gets a new adapter (restored from ackState like any other). Its give-up horizon counts\n// from the entry's first submission (`since`), never from when it took the\n// entry over (RLTP-DEL-6130). Its reports reach the holder as the ports'\n// DeliveryReport: report(id) maps the adapter's SubmissionState onto\n// DeliveryReport (deliveryReportOf), keyed by the document digest, which\n// the app hands to holder.report(). An adapter's `delivered` is its claim\n// about transport; the holder's receive core verifies the delivery-ack\n// itself.\n//\n// Profile: spec/adapter-vti-mediator.md v0.23 (twenty-third casting;\n// round journals under design/adapter-review*). A\n// transport adapter contract — NOT a carrier at the port.\n//\n// Beyond the profile (lib 0.5.0): conclude(collection, now, {keep}) leaves\n// the items whose disposition is transient unconcluded and offers them\n// again (Delivery 0.82 RLTP-DEL-5810, 5820: failed(rate-limited) is never\n// concluded); `concludable(result)` says which receive outcomes are\n// terminal. The profile's §4 concludes a collection whole; its next\n// casting is to take this up.\n//\n// Structural rules (reviews 3+4):\n// · No port operation ever awaits the mediator — including\n// register: keylist synchronization is a recorded intent with a\n// tracked background task, retried by advance.\n// · No report is invented, and absence is ABSENT: before the first\n// honest report exists, status() returns null (§6.1 grants the\n// window; representing it as a queryable fourth value was\n// review-4 B2). has() distinguishes an unknown id.\n// · A retired instance mutates nothing and refuses everything\n// except reading its ack state.\n\nimport { jcs } from '../core.js'\nimport { sha } from '../crypto.js'\nimport { carrierPrincipal, carrierScopedIdentity } from '../carrier-identity.js'\nimport type { CarrierPrincipal, CarrierScopedIdentity } from '../carrier-identity.js'\nimport type { DeliveryReport, ReceiverRefusalCode, SubmissionRef } from '../ports.js'\nimport type { TransportEntry, TransportView } from '../engine.js'\nimport type { ReceiveResult } from '../results.js'\nexport type { ReceiverRefusalCode } from '../ports.js'\n\n// ── Declared constants (profile §2) — promises of THIS casting ──────\n// frozen: the declared promises cannot be changed at run time either\nexport const DECLARED = Object.freeze({\n giveUpHorizonMs: 72 * 3_600_000,\n statusHorizonMs: 60_000,\n queueFloorCount: 64,\n queueFloorBytes: 1_048_576,\n maxQueueBytes: 16_777_216,\n duplicateWindowMs: 30 * 86_400_000,\n} as const)\n\n// ── The injected wire ────────────────────────────────────────────────\nexport type WireErrorKind =\n | 'unreachable' | 'refused-retriable' | 'refused-admission' | 'oversize'\n\nexport class WireError extends Error {\n kind: WireErrorKind\n constructor (kind: WireErrorKind, message?: string) {\n super(message ?? kind)\n this.kind = kind\n }\n}\n\nexport interface MediatorWire {\n authChallenge (did: string): Promise<{ challenge: string, sessionId: string }>\n authenticate (answer: { did: string, challenge: string, sessionId: string }): Promise<TokenSet>\n // A transient failure MUST be a WireError 'unreachable' or\n // 'refused-retriable' (the tokens are kept); any other error means the\n // mediator refused the refresh token (the adapter re-runs the handshake).\n refresh (refreshToken: string): Promise<TokenSet>\n keylistUpdate (accessToken: string, rkids: string[]): Promise<void>\n deposit (accessToken: string, bytes: Uint8Array, egressDid: string): Promise<void>\n ackReceived (accessToken: string, queueIds: string[]): Promise<void>\n onDeliver (cb: (bytes: Uint8Array) => Promise<void>): void\n /** Optional truthful connectivity signal; absent means unknown. */\n offline? (): boolean\n}\n\nexport interface TokenSet {\n accessToken: string\n accessExpiresAt: number\n refreshToken: string\n refreshExpiresAt: number\n}\n\n// ── Sender states (§6.1 — the closed sets, nothing else) ────────────\n// ReceiverRefusalCode is the ports' (one closed set, one place)\nconst RECEIVER_REFUSAL_CODES: ReadonlySet<ReceiverRefusalCode> = new Set<ReceiverRefusalCode>([\n 'malformedRequest', 'unsupportedType', 'proofRequired',\n 'proofInvalid', 'wrongRecipient', 'identityMismatch',\n])\n\nexport type SubmissionState =\n | { state: 'awaiting-transport', reason: 'offline' | 'transport-unreachable' | 'carrier-refused-retriable' }\n | { state: 'accepted' }\n | { state: 'delivered', late: boolean }\n | { state: 'failed', reason: 'unroutable' | 'oversize' | 'expired-by-adapter-policy' }\n | { state: 'failed', reason: 'rejected-by-receiver', code: ReceiverRefusalCode }\n\n/** The ports' DeliveryReport for a document `digest` in adapter state `st`\n * (Delivery §6.1): one-to-one, `late` and the refusal code carried over. */\nexport function deliveryReportOf (digest: string, st: SubmissionState): DeliveryReport {\n switch (st.state) {\n case 'awaiting-transport': return { digest, status: 'awaiting-transport', reason: st.reason }\n case 'accepted': return { digest, status: 'accepted' }\n case 'delivered': return { digest, status: 'delivered', late: st.late }\n case 'failed': return st.reason === 'rejected-by-receiver'\n ? { digest, status: 'failed', reason: 'rejected-by-receiver', code: st.code }\n : { digest, status: 'failed', reason: st.reason }\n }\n}\n\n/** Whether a receive outcome is terminal and its item may be concluded\n * (Delivery 5a.8): every disposition but `failed(rate-limited)`, the one\n * failure that is transient (RLTP-DEL-5820). An InfraError of the\n * holder's store is transient as well (RLTP-DEL-5810): an item whose\n * receive threw is kept, too. */\nexport function concludable (r: ReceiveResult): boolean {\n return !(r.disposition === 'failed' && r.reason === 'rate-limited')\n}\n\n/** The adapter's own copy of a wire's token set: the wire keeps no handle on it. */\nconst tokenCopy = (t: TokenSet): TokenSet => ({ accessToken: t.accessToken, accessExpiresAt: t.accessExpiresAt, refreshToken: t.refreshToken, refreshExpiresAt: t.refreshExpiresAt })\n\nexport interface CollectedItem { bytes: Uint8Array, queueId: string }\nexport interface Collection { id: string, items: CollectedItem[] }\n\n/** Ack state for the host to persist (profile §4). Invariant: every\n * pending id names a concluded entry; violations are refused at\n * construction (fail-closed). */\nexport interface AckState {\n concluded: Array<{ queueId: string, concludedAt: number }>\n pending: string[]\n}\n\n/** The holder's side of a hand-over (lib 0.6.0): the holder itself.\n * handOver checks the entry and calls `start` inside the holder's queue;\n * `start` re-checks the adapter's own state, starts the deposit\n * synchronously and says whether it did. `closed` is read in `start`. */\nexport interface TransportGate {\n handOver (entry: TransportEntry, when: number, start: () => boolean): Promise<boolean>\n readonly closed?: boolean\n}\n\ninterface Submission {\n id: string\n /** the document digest, for submissions filed by reconcile */\n digest?: string\n /** the holder's entry and its gate, for submissions filed by reconcile */\n entry?: TransportEntry\n gate?: TransportGate\n bytes: Uint8Array\n submittedAt: number\n attemptStartedAt: number | null\n lastKind: WireErrorKind | null\n st: SubmissionState | null // null = no honest report exists yet\n}\n\nconst hex = (b: Uint8Array): string =>\n Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')\n\n// construction capability: only create() holds it\nconst KEY = Symbol('MediatorCarrierAdapter.create')\n\n// ── The adapter ──────────────────────────────────────────────────────\nexport class MediatorCarrierAdapter {\n // JS-hard identity fields: TS `readonly` is a compile-time promise\n // only, and §8 claims runtime unforgeability — so the values live\n // in true privates behind getters (R8-B1)\n #principal: string\n #connectionDid: string\n #egressDid: string\n get principal (): string { return this.#principal }\n get connectionDid (): string { return this.#connectionDid }\n get egressDid (): string { return this.#egressDid }\n #wire: MediatorWire\n #tokens: TokenSet | null = null\n #clock = Number.NEGATIVE_INFINITY\n #closed = false\n /** the opening this adapter serves, bound at its first reconcile */\n #gate: TransportGate | null = null\n\n #subs = new Map<string, Submission>()\n #inflight = new Set<Promise<void>>()\n #nextId = 1\n\n #desiredRkids: string[] | null = null\n #keylistSynced = false\n #keylistSyncing = false\n\n #inbox: CollectedItem[] = []\n #inboxBytes = 0\n #inboxDigests = new Set<string>()\n #outstanding = new Map<string, Map<string, CollectedItem>>()\n #outstandingBytes = 0\n #concluded = new Map<string, number>()\n #pendingAcks = new Set<string>()\n #flightAcks = new Set<string>() // ids inside the in-flight flush snapshot\n #flushing = false\n #nextColId = 1\n\n #transitions: Array<{ id: string, to: 'delivered' }> = []\n\n /** The only way to build an adapter: the trio is DERIVED here from\n * one root, one carrier, one nonce — so principal, connection DID\n * and egress identity cannot come from different relationships\n * (R7-B2: the coupling is enforced by construction, not by\n * inspecting caller-supplied identities). */\n static async create (\n rootIkm: Uint8Array, carrier: string, nonce: Uint8Array,\n wire: MediatorWire, restored?: AckState, restoredAt?: number,\n ): Promise<MediatorCarrierAdapter> {\n // ONE tuple, snapshotted at entry: a caller mutating its buffers\n // between the three awaited derivations must not be able to mix\n // identities from two tuples (R8-B2)\n const ikm = new Uint8Array(rootIkm)\n const n = new Uint8Array(nonce)\n const principal = await carrierPrincipal(ikm, carrier, n)\n const connection = await carrierScopedIdentity(ikm, carrier, n, 'connection')\n const egress = await carrierScopedIdentity(ikm, carrier, n, 'egress')\n return new MediatorCarrierAdapter(KEY, principal, connection, egress, wire, restored, restoredAt)\n }\n\n constructor (\n key: symbol,\n principal: CarrierPrincipal,\n connection: CarrierScopedIdentity,\n egress: CarrierScopedIdentity,\n wire: MediatorWire,\n restored?: AckState,\n restoredAt?: number,\n ) {\n if (key !== KEY) {\n throw new Error('use MediatorCarrierAdapter.create — the identity trio must be derived, not supplied (5a.10)')\n }\n if (connection.scope !== 'connection' || egress.scope !== 'egress') {\n throw new Error('scoped identities passed in the wrong roles')\n }\n const three = new Set([principal.principal, connection.did, egress.did])\n if (three.size !== 3) {\n throw new Error('principal, connection DID and egress identity must be pairwise distinct (5a.10)')\n }\n this.#principal = principal.principal\n this.#connectionDid = connection.did\n this.#egressDid = egress.did\n this.#wire = wire\n if (restored) {\n // The restore instant anchors the duplicate-window: an expired,\n // debt-free entry is dropped HERE, not at the first advance —\n // otherwise a redelivery arriving before any port call would be\n // absorbed beyond the declared window (review-4 B4).\n if (typeof restoredAt !== 'number' || !Number.isFinite(restoredAt)) {\n throw new Error('restoring ack state requires a finite restoredAt instant')\n }\n this.#now(restoredAt)\n const pending = new Set(restored.pending)\n const known = new Set(restored.concluded.map((c) => c.queueId))\n for (const id of pending) {\n if (!known.has(id)) {\n throw new Error('ack snapshot violates its invariant: pending intent without a concluded entry')\n }\n }\n for (const { queueId, concludedAt } of restored.concluded) {\n if (!Number.isFinite(concludedAt) || concludedAt > restoredAt) {\n // a conclusion \"from the future\" would stretch the window\n // past its declared span (R5-B4) — fail closed\n throw new Error('ack snapshot: conclusion instant is non-finite or after restoredAt')\n }\n // the window beats everything (round-14 B): an expired entry\n // falls at the restore instant, owed or not — a phantom debt\n // from an ack that landed just before a close can never\n // outlive the window and delete a fresh copy (R14-B2)\n if (restoredAt - concludedAt >= DECLARED.duplicateWindowMs) continue\n this.#concluded.set(queueId, concludedAt)\n if (pending.has(queueId)) this.#pendingAcks.add(queueId)\n }\n }\n this.#wire.onDeliver(async (raw) => {\n if (this.#closed) return\n // a plain copy of its own: a Node Buffer's slice() would share memory\n const bytes = new Uint8Array(raw)\n const queueId = hex(await sha(bytes))\n if (this.#closed) return\n // Absorption is WINDOW-checked at the moment it happens\n // (R11-B1), and the window beats everything (round-14 B):\n // beyond it, entry AND any leftover intent fall, and the frame\n // is a new item — so no acknowledgement, owed or phantom, can\n // ever delete the only fresh copy.\n const concludedAt = this.#concluded.get(queueId)\n if (concludedAt !== undefined) {\n if (this.#flightAcks.has(queueId) ||\n this.#clock - concludedAt < DECLARED.duplicateWindowMs) {\n // inside the window — or deferred: an id inside an\n // in-flight flush keeps absorbing until that flush ends,\n // because its irrecallable ack may still land (R15-B1)\n this.#pendingAcks.add(queueId)\n return\n }\n this.#concluded.delete(queueId)\n this.#pendingAcks.delete(queueId)\n }\n if (this.#inboxDigests.has(queueId)) return\n for (const col of this.#outstanding.values()) if (col.has(queueId)) return\n const held = this.#inboxBytes + this.#outstandingBytes\n const underFloor = this.#inbox.length < DECLARED.queueFloorCount &&\n held + bytes.length <= DECLARED.queueFloorBytes\n const underCap = held + bytes.length <= DECLARED.maxQueueBytes\n if (!underFloor && !underCap) return\n this.#inbox.push({ bytes, queueId })\n this.#inboxBytes += bytes.length\n this.#inboxDigests.add(queueId)\n })\n }\n\n #now (raw: number): number {\n if (!Number.isFinite(raw)) throw new Error('non-finite time')\n if (raw > this.#clock) this.#clock = raw\n return this.#clock\n }\n\n #open (): void { if (this.#closed) throw new Error('retired (5a.10 lifecycle)') }\n\n #track (p: Promise<void>): void {\n const t = p.catch(() => {})\n this.#inflight.add(t)\n void t.finally(() => this.#inflight.delete(t))\n }\n\n // ── auth: silent carrier policy ─────────────────────────────────\n // Single-flight: concurrent callers share one handshake — the ATM\n // challenge/response is a session, and two interleaved sessions\n // under one connection DID would answer each other's challenges.\n #authing: Promise<string> | null = null\n\n #ensureAuth (now: number): Promise<string> {\n if (this.#tokens && now < this.#tokens.accessExpiresAt) return Promise.resolve(this.#tokens.accessToken)\n if (this.#authing) return this.#authing\n const run = (async (): Promise<string> => {\n if (this.#tokens && now < this.#tokens.refreshExpiresAt) {\n try {\n const refreshed = await this.#wire.refresh(this.#tokens.refreshToken)\n if (this.#closed) throw new Error('retired') // as on the handshake path (R6-B1)\n this.#tokens = tokenCopy(refreshed)\n return this.#tokens.accessToken\n } catch (e) {\n if (this.#closed) throw e\n // a transient failure (mediator unreachable, retriable refusal)\n // says nothing about the token: keep it for the next attempt (#9)\n if (e instanceof WireError && (e.kind === 'unreachable' || e.kind === 'refused-retriable')) throw e\n // a refused refresh (revoked before its expiry) is never replayed:\n // drop the tokens and take the challenge handshake below\n this.#tokens = null\n }\n }\n const { challenge, sessionId } = await this.#wire.authChallenge(this.#connectionDid)\n if (this.#closed) throw new Error('retired') // nothing new starts, not even the answer (R6-B1)\n this.#tokens = tokenCopy(await this.#wire.authenticate({ did: this.#connectionDid, challenge, sessionId }))\n return this.#tokens.accessToken\n })()\n this.#authing = run.finally(() => { this.#authing = null })\n return this.#authing\n }\n\n // ── transport registration (profile §3 — NOT §5a.3) ─────────────\n /** Records the desired keylist and returns; synchronization runs\n * as a tracked background task and advance retries it until it\n * lands (review-4 B1). */\n register (rkids: string[], rawNow: number): void {\n this.#open()\n const now = this.#now(rawNow)\n this.#desiredRkids = [...rkids]\n this.#keylistSynced = false\n this.#startKeylistSync(now)\n }\n\n get keylistSynced (): boolean {\n this.#open()\n return this.#keylistSynced\n }\n\n #startKeylistSync (now: number): void {\n if (this.#keylistSyncing || this.#keylistSynced || this.#desiredRkids === null) return\n this.#keylistSyncing = true\n const wanted = [...this.#desiredRkids]\n this.#track((async () => {\n try {\n const token = await this.#ensureAuth(now)\n if (this.#closed) return\n await this.#wire.keylistUpdate(token, [...wanted]) // the wire's own list: `wanted` is compared below\n // land only if the desire has not moved meanwhile\n if (!this.#closed && this.#desiredRkids !== null &&\n wanted.join(' ') === this.#desiredRkids.join(' ')) {\n this.#keylistSynced = true\n }\n } catch {\n // intent survives; advance retries\n } finally {\n this.#keylistSyncing = false\n }\n })())\n }\n\n // ── sender side ─────────────────────────────────────────────────\n /** Returns the submission id synchronously. Before the first\n * honest report exists, status() returns null — §6.1's own\n * pre-report window, represented as absence, not as a value. */\n submit (envelopeBytes: Uint8Array, rawNow: number): string {\n this.#open()\n const now = this.#now(rawNow)\n const id = 's' + this.#nextId++\n const knownOffline = this.#wire.offline?.() === true\n const sub: Submission = {\n id,\n // a plain copy of its own (a Node Buffer's slice() shares memory)\n bytes: new Uint8Array(envelopeBytes),\n submittedAt: now,\n attemptStartedAt: null,\n lastKind: null,\n st: null,\n }\n this.#subs.set(id, sub)\n if (!knownOffline) this.#startAttempt(sub, now)\n return id\n }\n\n /** Takes the holder's custody set (holder.pendingTransport, after a\n * resume of this opening) and the holder as the gate: files every entry\n * not yet filed under its digest (its envelope as JCS bytes; the give-up\n * horizon from entry.since) and returns their SubmissionRefs; withdraws\n * every filed submission still before the trias (no report, or\n * awaiting-transport) whose digest the view does not name. Accepted and\n * terminal submissions stay for their reports. */\n reconcile (view: TransportView, gate: TransportGate, rawNow: number): SubmissionRef[] {\n this.#open()\n if (view?.ok !== true || !Array.isArray(view.entries)) throw new Error('reconcile needs a view of holder.pendingTransport')\n if (typeof gate?.handOver !== 'function') throw new Error('reconcile needs the holder as its gate')\n // one adapter per opening: its copies and the holder's grants belong to\n // that opening, and the next opening gets an adapter of its own\n if (this.#gate === null) this.#gate = gate\n else if (this.#gate !== gate) throw new Error('one adapter per opening: this adapter reconciles with another holder (create a new adapter for the next opening)')\n const now = this.#now(rawNow)\n // a submission's key: the digest, and for a duplicate's answer its\n // grant too — the retries and each answer are hand-overs of their own\n const keyOf = (digest: string, resend: number | undefined): string => resend === undefined ? digest : `${digest}#${resend}`\n const named = new Set(view.entries.map((e) => keyOf(e.digest, e.resend)))\n const filed = new Map<string, Submission>()\n for (const [id, sub] of this.#subs) {\n if (sub.digest === undefined) continue\n const key = keyOf(sub.digest, sub.entry?.resend)\n const before = sub.st === null || sub.st.state === 'awaiting-transport'\n if (before && !named.has(key)) { this.#subs.delete(id); continue }\n filed.set(key, sub)\n }\n const refs: SubmissionRef[] = []\n for (const entry of view.entries) {\n const had = filed.get(keyOf(entry.digest, entry.resend))\n if (had !== undefined) {\n // the newest entry of a live submission is the one its gate checks\n if (had.st === null || had.st.state === 'awaiting-transport') { had.entry = entry; had.gate = gate; continue }\n // an answer the holder still offers is still owed — its hand-over\n // never began, or the holder could not record that it did: a\n // terminal submission of it is filed again (the holder ends it)\n if (entry.resend === undefined) continue\n this.#subs.delete(had.id)\n }\n const id = 's' + this.#nextId++\n const sub: Submission = {\n id, digest: entry.digest, entry, gate,\n bytes: new TextEncoder().encode(jcs(entry.envelope)),\n // a duplicate's ack is a hand-over of its own, from now\n submittedAt: entry.resend !== undefined ? now : Math.min(entry.since, now),\n attemptStartedAt: null, lastKind: null, st: null,\n }\n this.#subs.set(id, sub)\n refs.push({ submissionId: id, digest: entry.digest })\n // taken over past its horizon (counted from the first submission,\n // RLTP-DEL-6130): given up at once, never attempted\n if (now - sub.submittedAt >= DECLARED.giveUpHorizonMs) { sub.st = { state: 'failed', reason: 'expired-by-adapter-policy' }; continue }\n if (this.#wire.offline?.() !== true) this.#startAttempt(sub, now)\n }\n return refs\n }\n\n /** The current state as the ports' DeliveryReport for holder.report(),\n * or null while no honest report exists (and for an unknown id). A\n * submission filed without a digest (submit) has no report form. */\n report (id: string): DeliveryReport | null {\n const st = this.status(id)\n if (st === null) return null\n const digest = this.#subs.get(id)!.digest\n if (digest === undefined) throw new Error('submitted without a document digest: file holder documents through reconcile')\n return deliveryReportOf(digest, st)\n }\n\n has (id: string): boolean {\n this.#open()\n return this.#subs.has(id)\n }\n\n #startAttempt (sub: Submission, now: number): void {\n if (sub.attemptStartedAt !== null) return\n sub.attemptStartedAt = now\n this.#track(this.#trySend(sub, now).finally(() => { sub.attemptStartedAt = null }))\n }\n\n async #trySend (sub: Submission, now: number): Promise<void> {\n if (sub.st !== null && sub.st.state !== 'awaiting-transport') return\n let next: SubmissionState\n try {\n const token = await this.#ensureAuth(now)\n if (this.#closed) return // retirement between auth and deposit: nothing new starts (R5-B2)\n // each attempt hands the wire a copy: what it does with it never reaches the next\n const deposit = (): Promise<void> => {\n try { return this.#wire.deposit(token, new Uint8Array(sub.bytes), this.#egressDid) } catch (e) { return Promise.reject(e) }\n }\n if (sub.gate !== undefined) {\n // the holder decides, and the deposit starts in the same step of its\n // queue (Delivery RLTP-DEL-6125 to 6135); the adapter re-checks its\n // own state there: retired, withdrawn, past the trias, past the\n // entry's deadline or its own horizon → no deposit\n // the deposit's outcome, caught at once: the holder's step may still\n // be committing when the wire answers\n let started: Promise<unknown> | null = null\n let declined = false\n const entry = sub.entry!\n const start = (): boolean => {\n if (this.#closed || this.#subs.get(sub.id) !== sub || sub.gate!.closed === true ||\n (sub.st !== null && sub.st.state !== 'awaiting-transport') || this.#clock >= entry.notAfter ||\n this.#clock - sub.submittedAt >= DECLARED.giveUpHorizonMs) { declined = true; return false }\n started = deposit().then(() => null, (e: unknown) => ({ failed: e }))\n return true\n }\n let ok: boolean | null\n try { ok = await sub.gate.handOver(entry, this.#clock, start) } catch { ok = null }\n if (started === null) {\n // the holder said no: withdrawn; the adapter declined or the\n // holder was unreachable: not this attempt\n if (ok === false && !declined && this.#subs.get(sub.id) === sub) this.#subs.delete(sub.id)\n return\n }\n const outcome = await (started as Promise<unknown>)\n if (outcome !== null) throw (outcome as { failed: unknown }).failed\n } else {\n await deposit()\n }\n sub.lastKind = null\n next = { state: 'accepted' }\n } catch (e) {\n const kind: WireErrorKind = e instanceof WireError ? e.kind : 'unreachable'\n sub.lastKind = kind\n next = kind === 'oversize'\n ? { state: 'failed', reason: 'oversize' }\n : {\n state: 'awaiting-transport',\n reason: kind === 'unreachable' ? 'transport-unreachable' : 'carrier-refused-retriable',\n }\n }\n if (this.#closed) return\n // An interim report (including a horizon-corrected one) never\n // outranks the attempt's real outcome; only a TERMINAL state —\n // a give-up, a refusal, a delivery — stands (R5-B1). Without\n // this, an accepted deposit would stay reported unreachable and\n // be sent a second time.\n if (sub.st === null || sub.st.state === 'awaiting-transport') sub.st = next\n }\n\n /** Host teardown aid, NOT a port operation (profile §6): awaits\n * the in-flight background tasks so a host can drain before\n * persisting ackState. On a hanging wire it waits as long as the\n * wire does — a host bounds it externally (Promise.race) exactly\n * because this library holds no clock of its own. */\n async settle (): Promise<void> {\n while (this.#inflight.size > 0) await Promise.all([...this.#inflight])\n }\n\n /** The §6.1 report, or null while none exists yet (has()\n * distinguishes an unknown id). status is a PORT: after close it\n * refuses like every other port operation (R5-B3).\n *\n * The pre-transport report is an HONEST SNAPSHOT, derived at the\n * moment of observation by one precedence order (Option B of the\n * round-14 halt) — never a stored patchwork:\n * (a) the wire knows itself offline → offline\n * (b) an attempt is overdue → transport-unreachable\n * (c) the last completed attempt's kind → its report\n * (d) otherwise → no report yet (null)\n * Terminal states and `accepted` are stored and stand. */\n status (id: string): SubmissionState | null {\n this.#open()\n const sub = this.#subs.get(id)\n if (!sub) return null\n if (sub.st !== null && sub.st.state !== 'awaiting-transport') return { ...sub.st }\n if (this.#wire.offline?.() === true) {\n return { state: 'awaiting-transport', reason: 'offline' }\n }\n if (sub.attemptStartedAt !== null &&\n this.#clock - sub.attemptStartedAt >= DECLARED.statusHorizonMs) {\n return { state: 'awaiting-transport', reason: 'transport-unreachable' }\n }\n return sub.st === null ? null : { ...sub.st }\n }\n\n acknowledged (id: string): void {\n if (this.#closed) return\n const sub = this.#subs.get(id)\n if (!sub) return\n if (sub.st?.state === 'delivered') return // idempotent: a duplicate ack never rewrites `late` (R9-M4)\n const late = sub.st?.state === 'failed'\n sub.st = { state: 'delivered', late }\n if (late) this.#transitions.push({ id, to: 'delivered' })\n }\n\n /** Refusals act on live submissions only (§6.1 knows exactly one\n * late correction — the valid ack). The code set is closed and\n * TERMINAL: retryable counterpart conditions (unavailable,\n * internalError) are transport outcomes, never receiver verdicts\n * — they have no entry here, and an unknown code is refused\n * fail-closed rather than minted into a verdict (R6-B2). */\n receiverRefused (id: string, code: ReceiverRefusalCode): void {\n if (this.#closed) return\n if (!RECEIVER_REFUSAL_CODES.has(code)) {\n throw new Error('not a terminal receiver refusal code — retryable conditions are transport outcomes')\n }\n const sub = this.#subs.get(id)\n if (!sub) return\n // A VALIDATED refusal is itself the proof of receipt — the\n // mediator can have accepted and forwarded while our deposit\n // promise is still unresolved, so the report-less phase is a\n // legitimate moment for it (R9-B2, reversing the R8-B3\n // overcorrection). Only terminal states stand against it.\n if (sub.st !== null && sub.st.state !== 'awaiting-transport' && sub.st.state !== 'accepted') return\n sub.st = { state: 'failed', reason: 'rejected-by-receiver', code }\n }\n\n drainTransitions (): Array<{ id: string, to: 'delivered' }> {\n this.#open()\n return this.#transitions.splice(0)\n }\n\n // ── receiver side ───────────────────────────────────────────────\n collect (rawNow: number): Collection {\n this.#open()\n this.#now(rawNow)\n if (this.#inbox.length === 0) return { id: 'c-empty', items: [] }\n const items = this.#inbox.splice(0)\n this.#outstandingBytes += this.#inboxBytes\n this.#inboxBytes = 0\n this.#inboxDigests.clear()\n const id = 'c' + this.#nextColId++\n this.#outstanding.set(id, new Map(items.map((i) => [i.queueId, i])))\n // the caller gets its own copies: the outstanding entries stay intact,\n // whatever it does with the bytes, for a conclusion that keeps them\n return { id, items: items.map((i) => ({ ...i, bytes: new Uint8Array(i.bytes) })) }\n }\n\n /** Concludes a collection (profile §4, Delivery 5a.8): its items'\n * digests become ack intent. `keep` names the items whose disposition\n * is transient (Delivery RLTP-DEL-5810, 5820: `failed(rate-limited)`,\n * or a transaction that could not commit, see `concludable`): they are\n * not concluded and not acknowledged, they go back to the buffer and the\n * next collect offers them again, and the mediator keeps its copy. */\n conclude (collection: { id: string }, rawNow: number, opts: { keep?: readonly string[] } = {}): void {\n this.#open()\n const now = this.#now(rawNow)\n const col = this.#outstanding.get(collection.id)\n if (!col) return\n this.#outstanding.delete(collection.id)\n const keep = new Set(opts.keep ?? [])\n for (const item of col.values()) {\n this.#outstandingBytes -= item.bytes.length\n if (keep.has(item.queueId)) {\n // transient: back to the buffer, offered again, never acknowledged\n this.#inbox.push(item)\n this.#inboxBytes += item.bytes.length\n this.#inboxDigests.add(item.queueId)\n continue\n }\n this.#concluded.set(item.queueId, now)\n this.#pendingAcks.add(item.queueId)\n }\n this.#startFlush(now)\n }\n\n ackState (): AckState {\n return {\n concluded: [...this.#concluded].map(([queueId, concludedAt]) => ({ queueId, concludedAt })),\n pending: [...this.#pendingAcks],\n }\n }\n\n #startFlush (now: number): void {\n if (this.#flushing || this.#pendingAcks.size === 0) return\n this.#flushing = true\n const snapshot = new Set(this.#pendingAcks)\n this.#track(this.#flushAcks(now, [...snapshot]).finally(() => {\n this.#flushing = false\n // lost-wake-up guard (review-4 M6): intents that arrived while\n // this flush ran get their own flush now — but only newcomers,\n // so a failing wire waits for the next advance instead of\n // spinning\n if (!this.#closed) {\n for (const id of this.#pendingAcks) {\n if (!snapshot.has(id)) { this.#startFlush(this.#clock); break }\n }\n }\n }))\n }\n\n async #flushAcks (now: number, ids: string[]): Promise<void> {\n try {\n const token = await this.#ensureAuth(now)\n if (this.#closed) return\n // Only NOW does anything become irrecallable (R16-B1): the\n // stay of expiry begins at the wire call itself, never at the\n // snapshot — a hanging auth extends no window. And \"live\" is\n // WINDOW-live (R17-B1): an entry whose window already closed —\n // even if no prune has swept it yet — is never sent.\n const live = ids.filter((id) => {\n const at = this.#concluded.get(id)\n return at !== undefined && this.#clock - at < DECLARED.duplicateWindowMs\n })\n if (live.length === 0) return\n for (const id of live) this.#flightAcks.add(id)\n try {\n // the wire gets its own list: what it does with it never reaches the bookkeeping below\n await this.#wire.ackReceived(token, [...live])\n if (!this.#closed) for (const id of live) this.#pendingAcks.delete(id)\n } finally {\n for (const id of live) this.#flightAcks.delete(id)\n // deferred window sweep: entries whose window closed while\n // the ack flew fall now — intent, entry and absorption\n // together (R15-B1). Never on a retired instance: after\n // close, ackState() is the host's final-persist surface and\n // a late-returning wire mutates nothing (R17-B2).\n if (!this.#closed) {\n for (const id of live) {\n const at = this.#concluded.get(id)\n if (at !== undefined && this.#clock - at >= DECLARED.duplicateWindowMs) {\n this.#concluded.delete(id)\n this.#pendingAcks.delete(id)\n }\n }\n }\n }\n } catch {\n // intent survives; the next advance starts a fresh flush\n }\n }\n\n // ── the adapter clock — never awaits the mediator ───────────────\n advance (rawNow: number): void {\n this.#open()\n const now = this.#now(rawNow)\n for (const sub of this.#subs.values()) {\n const live = sub.st === null || sub.st.state === 'awaiting-transport' || sub.st.state === 'accepted'\n if (!live) continue\n if (now - sub.submittedAt >= DECLARED.giveUpHorizonMs) {\n // unroutable only when the LAST COMPLETED attempt was an\n // admission refusal and no attempt is in flight whose outcome\n // is unknown (review-4 B3)\n // the give-up verdict applies the SAME precedence as every\n // observation (R17-B3): a wire that knows itself offline at\n // the horizon outranks any stored refusal class — unroutable\n // needs a completed admission refusal, no unknown outcome in\n // flight, AND no offline signal standing over it\n sub.st = {\n state: 'failed',\n reason: sub.lastKind === 'refused-admission' && sub.attemptStartedAt === null &&\n this.#wire.offline?.() !== true\n ? 'unroutable'\n : 'expired-by-adapter-policy',\n }\n continue\n }\n if (sub.st !== null && sub.st.state === 'accepted') continue\n // reports are DERIVED at observation (see status()); the clock\n // only decides here whether to start an attempt — and never\n // against a wire that knows itself offline\n if (this.#wire.offline?.() === true) continue\n if (sub.attemptStartedAt === null) this.#startAttempt(sub, now)\n }\n // THE WINDOW BEATS EVERYTHING (Option B of the round-14 halt):\n // an ack intent is retried until the window closes; then intent\n // and absorption fall together. There is no ageless debt whose\n // truth the adapter would have to know — the receiver's §6.2\n // absorption owns everything beyond the window.\n for (const [digest, at] of this.#concluded) {\n if (now - at >= DECLARED.duplicateWindowMs && !this.#flightAcks.has(digest)) {\n this.#concluded.delete(digest)\n this.#pendingAcks.delete(digest)\n }\n }\n this.#startKeylistSync(now)\n this.#startFlush(now)\n }\n\n /** §5a.10 lifecycle boundary: after close, every state port is\n * inert — port operations refuse, inbound reports (acknowledged,\n * receiverRefused) are no-ops, late wire resolutions mutate\n * nothing. Only ackState() stays readable for the host's final\n * persist. */\n close (): void { this.#closed = true }\n\n get closed (): boolean { return this.#closed }\n}\n\nexport const queueIdOf = async (bytes: Uint8Array): Promise<string> => hex(await sha(bytes))\n"]}
package/dist/codec.d.ts CHANGED
@@ -1,17 +1,10 @@
1
1
  import type { Duty, HolderState, KnownDuty } from './state.js';
2
2
  /** The codec this library writes. */
3
- export declare const CODEC = 2;
3
+ export declare const CODEC = 3;
4
4
  /**
5
5
  * Migrations keyed by the codec they read: MIGRATIONS[n] maps a valid
6
6
  * codec-n state to a codec-(n+1) state. Pure, never async, never keys.
7
- *
8
- * 1 → 2 (lib 0.5.0, Message Tasks 0.1, Membership 0.20): the message
9
- * state starts empty (no block, no rate, no record, no inbox) but for the
10
- * ready tuples, read from what the state shows a counterpart's document
11
- * did (readyOf1); every invitation a codec-1 holder received was
12
- * surfaced, so their credential digests seed the permanent record of
13
- * RLTP-MT-3130; the register of declined invitations starts empty (codec 1
14
- * knew no block).
7
+ * None today: codec 3 is the first codec a rolled-out app holds.
15
8
  */
16
9
  export declare const MIGRATIONS: Readonly<Record<number, (state: any) => any>>;
17
10
  /** A codec's structural validator: throws StateCodecError('shape') or returns. */
@@ -1 +1 @@
1
- {"version":3,"file":"codec.d.ts","sourceRoot":"","sources":["../src/codec.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAG9D,qCAAqC;AACrC,eAAO,MAAM,KAAK,IAAI,CAAA;AAkBtB;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,GAAG,CAAC,CAOnE,CAAA;AAEF,kFAAkF;AAClF,MAAM,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAA;AAEnD;iEACiE;AACjE,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAA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AEtD;AAED,sEAAsE;AACtE,wBAAgB,WAAW,CAAE,KAAK,EAAE,WAAW,GAAG,MAAM,CAIvD;AAED,8DAA8D;AAC9D,eAAO,MAAM,SAAS,GAAI,GAAG,WAAW,EAAE,GAAG,WAAW,KAAG,OAA4B,CAAA"}
package/dist/codec.js CHANGED
@@ -11,55 +11,26 @@
11
11
  // versions and the codec are independent; a migration never re-issues
12
12
  // stored documents, outbound or acks.
13
13
  //
14
- // Codec 1 is the format of 0.4.0: its golden fixtures are
15
- // lib/test/fixtures/state-v1*.json (runs of lib 0.4.0, frozen), decoded and
16
- // re-encoded byte-identically and migrated by test/codec-fixture.test.mjs.
17
- // Codec 2 is the format of 0.5.0 (Message Tasks 0.1, Membership 0.20): its
18
- // fixtures are lib/test/fixtures/state-v2*.json (deterministic runs,
19
- // test/fixtures/gen-state-v2.mjs, reproduced in npm test). The rule: codecs
20
- // 1 and 2 are read, 1 migrated to 2; a newer codec is codec-newer; a codec
21
- // without a validator is codec-unknown. Every later codec adds its
22
- // validator, a migration from the one before, and its own fixture with a
23
- // migration test.
14
+ // Codec 3 is the format of 0.6.0 and the only one this library reads
15
+ // (Delivery 0.83: an acknowledgement is sent when a service took it, failed,
16
+ // or its retries ended; it may be held by the adapter meanwhile, and it
17
+ // carries the duplicates' answers). Codecs 1 and 2 (lib 0.4.0, 0.5.0) never
18
+ // held the state of a rolled-out app, so they have neither validator nor
19
+ // migration: a state of either is codec-unknown, a clean cut. Its fixtures
20
+ // are lib/test/fixtures/state-v3*.json (deterministic runs,
21
+ // test/fixtures/gen-state-v3.mjs, reproduced in npm test). The rule: a
22
+ // newer codec is codec-newer, a codec without a validator codec-unknown.
23
+ // A later codec that must read this one adds its validator, a migration
24
+ // from codec 3, and its own fixture with a migration test.
24
25
  import { jcs } from './core.js';
25
26
  /** The codec this library writes. */
26
- export const CODEC = 2;
27
- /** The tuples of a codec-1 state on which a document of the counterpart
28
- * was accepted, as far as the state shows it (Message Tasks 5.1): a probe,
29
- * a star, a group star, a continuity or anchor mapping, or a profile
30
- * received; or the counterparty's step credential of its enactment record. */
31
- function readyOf1(s) {
32
- const out = new Set();
33
- const inRec = new Set(Object.values(s.encounter.records).filter((r) => r.in !== null).map((r) => r.label));
34
- for (const r of Object.values(s.relationships)) {
35
- for (const t of r.tuples) {
36
- if (t.probeIn.hwm !== '0' || t.starIn.hwm !== '0' || t.groupStarIn.hwm !== '0' || t.continuityIn.rev !== '0' ||
37
- t.mappingIn.rev !== '0' || t.profileIn.rev !== '0' || inRec.has(t.ownPairLabel))
38
- out.add(t.ownPairLabel);
39
- }
40
- }
41
- return [...out].sort();
42
- }
27
+ export const CODEC = 3;
43
28
  /**
44
29
  * Migrations keyed by the codec they read: MIGRATIONS[n] maps a valid
45
30
  * codec-n state to a codec-(n+1) state. Pure, never async, never keys.
46
- *
47
- * 1 → 2 (lib 0.5.0, Message Tasks 0.1, Membership 0.20): the message
48
- * state starts empty (no block, no rate, no record, no inbox) but for the
49
- * ready tuples, read from what the state shows a counterpart's document
50
- * did (readyOf1); every invitation a codec-1 holder received was
51
- * surfaced, so their credential digests seed the permanent record of
52
- * RLTP-MT-3130; the register of declined invitations starts empty (codec 1
53
- * knew no block).
31
+ * None today: codec 3 is the first codec a rolled-out app holds.
54
32
  */
55
- export const MIGRATIONS = Object.freeze({
56
- 1: (s) => ({
57
- ...s,
58
- codec: 2,
59
- joining: { ...s.joining, surfaced: Object.keys(s.joining.invites).sort(), declined: [] },
60
- messages: { blocked: [], rates: {}, ready: readyOf1(s), records: {}, inbox: {} },
61
- }),
62
- });
33
+ export const MIGRATIONS = Object.freeze({});
63
34
  /** A stored state the library will not load (or a state it will not write). */
64
35
  export class StateCodecError extends Error {
65
36
  code;
@@ -204,8 +175,8 @@ const contact = obj({
204
175
  settings: obj({ star: setting, groupStar: setting, anchorMapping: setting, sealedGroupStar: setting, profile: setting }),
205
176
  groupSettings: rec(setting),
206
177
  });
207
- /** an outbox step of codec n: codec 2 added the failure reason task-expired */
208
- const outboxStepOf = (codec) => (x, p) => {
178
+ /** an outbox step */
179
+ const outboxStep = (x, p) => {
209
180
  if (!isObj(x))
210
181
  fail(p, 'object expected');
211
182
  const s = x;
@@ -216,30 +187,40 @@ const outboxStepOf = (codec) => (x, p) => {
216
187
  case 'delivered': return obj({ status: str, at: millis, late: bool })(x, p);
217
188
  case 'failed': return s.reason === 'rejected-by-receiver'
218
189
  ? obj({ status: str, at: millis, reason: str, code: lit('malformedRequest', 'unsupportedType', 'proofRequired', 'proofInvalid', 'wrongRecipient', 'identityMismatch') })(x, p)
219
- : obj({ status: str, at: millis, reason: codec < 2 ? lit('unroutable', 'oversize', 'expired-by-adapter-policy') : lit('unroutable', 'oversize', 'expired-by-adapter-policy', 'task-expired') })(x, p);
190
+ : obj({ status: str, at: millis, reason: lit('unroutable', 'oversize', 'expired-by-adapter-policy', 'task-expired') })(x, p);
220
191
  default: fail(`${p}.status`, 'unknown outbox status');
221
192
  }
222
193
  };
223
- /** an outbox item of codec n: codec 2 added expiresAt (the sender lifetime);
194
+ /** an outbox item with its sender lifetime (expiresAt);
224
195
  * the envelope is sealed to the counterpart key, never to the own rkid */
225
- const outboxItemOf = (codec) => {
196
+ const outboxItem = (() => {
226
197
  const shape = obj({
227
- type: str, threadId: str, recipient, envelope, attempt: positive, history: arr(outboxStepOf(codec)),
228
- }, codec < 2 ? { nextAttemptAt: millis } : { nextAttemptAt: millis, expiresAt: millis });
198
+ type: str, threadId: str, recipient, envelope, attempt: positive, history: arr(outboxStep),
199
+ }, { nextAttemptAt: millis, expiresAt: millis });
229
200
  return (x, p) => {
230
201
  shape(x, p);
231
202
  const o = x;
232
203
  if (o.envelope.rkid !== o.recipient.keyAgreement)
233
204
  fail(`${p}.envelope.rkid`, 'must equal recipient.keyAgreement');
234
205
  };
235
- };
206
+ })();
236
207
  const DUE = { dueAt: millis };
237
208
  /** a retained ack: sealed to the counterpart key, like an outbox item */
209
+ /** codec 3: sent exactly when it names why; held only while unsent */
238
210
  const storedAck = (x, p) => {
239
- obj({ digest: str, envelope, threadId: str, recipient, at: millis, attempt: positive, sent: bool }, { nextAttemptAt: millis, sentBy: lit('report', 'horizon') })(x, p);
211
+ obj({ digest: str, envelope, threadId: str, recipient, at: millis, attempt: positive, sent: bool }, {
212
+ nextAttemptAt: millis, sentBy: lit('accepted', 'failed', 'horizon'), held: lit('offline', 'transport-unreachable', 'carrier-refused-retriable'),
213
+ answers: positive, answerDue: lit(true),
214
+ })(x, p);
240
215
  const a = x;
216
+ if (a.answerDue !== undefined && a.answers === undefined)
217
+ fail(`${p}.answers`, 'present with answerDue');
241
218
  if (a.envelope.rkid !== a.recipient.keyAgreement)
242
219
  fail(`${p}.envelope.rkid`, 'must equal recipient.keyAgreement');
220
+ if (a.sent !== (a.sentBy !== undefined))
221
+ fail(`${p}.sentBy`, 'present exactly when sent');
222
+ if (a.sent && a.held !== undefined)
223
+ fail(`${p}.held`, 'only while unsent');
243
224
  };
244
225
  const KNOWN_DUTIES = {
245
226
  'reissue-mapping': { v: 1, shape: obj({ kind: str, v: positive, id: str, contactId: str, relId: str, awaitHead: nullable(str) }, DUE) },
@@ -294,13 +275,12 @@ const EVENT_FIELDS = {
294
275
  'message.sent': [{ contactId: str, mid: str, digest: str }],
295
276
  'message.received': [{ contactId: str, inboxId: str }],
296
277
  };
297
- /** the event types codec 2 added: codec 1 does not know them */
298
- const EVENTS_SINCE_2 = new Set(['contact.blocked', 'message.sent', 'message.received']);
299
- const eventOf = (codec) => (x, p) => {
278
+ /** a journaled event of a type this library emits */
279
+ const event = (x, p) => {
300
280
  if (!isObj(x))
301
281
  fail(p, 'object expected');
302
282
  const t = x.type;
303
- if (typeof t !== 'string' || !Object.hasOwn(EVENT_FIELDS, t) || (codec < 2 && EVENTS_SINCE_2.has(t)))
283
+ if (typeof t !== 'string' || !Object.hasOwn(EVENT_FIELDS, t))
304
284
  fail(`${p}.type`, 'unknown event type');
305
285
  const [req, opt = {}] = EVENT_FIELDS[t];
306
286
  obj({ type: str, eventId: str, commitSeq: dec, ...req }, { actId: str, ...opt })(x, p);
@@ -337,8 +317,27 @@ const introAct = obj({
337
317
  at: millis, ackDelayMs: natural, ownLabel: nullable(str), ack: nullable(anyObj), replyForwarded: bool, vouchersSent: bool,
338
318
  pendingVoucher: nullable(anyObj), voucher: nullable(anyObj), vouched: bool, promptId: nullable(str),
339
319
  }, { peerName: str });
340
- const fields1 = {
341
- codec: lit(1),
320
+ /** a sorted set of strings */
321
+ const sortedSet = (x, p) => {
322
+ set(str)(x, p);
323
+ const a = x;
324
+ for (let i = 1; i < a.length; i++)
325
+ if (!(a[i - 1] < a[i]))
326
+ fail(`${p}[${i}]`, 'a sorted set expected');
327
+ };
328
+ /** an invitation received: attributed to a relationship (contactId and
329
+ * rkid together) or to none (Membership RLTP-MT-3100) */
330
+ const receivedInvite = (x, p) => {
331
+ obj({
332
+ credDigest: str, group: str, name: str, memberLabel: str, invite: anyObj, promptId: str, validUntil: millis,
333
+ status: lit('open', 'accepted', 'declined', 'joined'), at: millis,
334
+ }, { acceptDigest: str, contactId: str, rkid: str })(x, p);
335
+ const i = x;
336
+ if ((i.contactId === undefined) !== (i.rkid === undefined))
337
+ fail(`${p}.rkid`, 'present exactly with contactId');
338
+ };
339
+ const codec3 = obj({
340
+ codec: lit(3),
342
341
  commitSeq: dec,
343
342
  lastWhen: millis,
344
343
  register: obj({
@@ -355,14 +354,14 @@ const fields1 = {
355
354
  groups: keyed(group, 'id'),
356
355
  profile: obj({ body: json, revision: dec }),
357
356
  effects: rec(obj({ ack: nullable(storedAck), expiresAt: millis })),
358
- outbox: rec(outboxItemOf(1)),
357
+ outbox: rec(outboxItem),
359
358
  duties: keyed(duty, 'id'),
360
359
  rotations: keyed(obj({
361
360
  id: str, from: dec, to: dec, step: lit('register', 'log', 'duties'), startedAt: millis,
362
361
  entry: json, overHead: logHead, awaitHead: rec(nullable(str)),
363
362
  }), 'id'),
364
363
  prompts: keyed(obj({ id: str, kind: lit('encounter-confirm', 'group-invite', 'introduction'), openedAt: millis }, { contactId: str, groupId: str, expiresAt: millis }), 'id'),
365
- acts: keyed(obj({ actId: str, inputHash: str, commitSeq: dec, outboundDigests: arr(str), events: arr(eventOf(1)), at: millis }), 'actId'),
364
+ acts: keyed(obj({ actId: str, inputHash: str, commitSeq: dec, outboundDigests: arr(str), events: arr(event), at: millis }), 'actId'),
366
365
  encounter: obj({
367
366
  challenges: keyed(obj({ value: str, tCh: millis, label: str, card: anyObj }), 'value'),
368
367
  records: keyed(enactmentRecord, 'own'),
@@ -373,40 +372,7 @@ const fields1 = {
373
372
  }),
374
373
  joining: obj({
375
374
  preludes: rec(obj({ group: str, inviter: str, contactId: str, rkid: str, memberLabel: str, at: millis })),
376
- invites: keyed(obj({
377
- credDigest: str, group: str, name: str, contactId: str, rkid: str, memberLabel: str, invite: anyObj, promptId: str, validUntil: millis,
378
- status: lit('open', 'accepted', 'declined', 'joined'), at: millis,
379
- }, { acceptDigest: str }), 'credDigest'),
380
- }),
381
- };
382
- const codec1 = obj(fields1);
383
- /** a sorted set of strings */
384
- const sortedSet = (x, p) => {
385
- set(str)(x, p);
386
- const a = x;
387
- for (let i = 1; i < a.length; i++)
388
- if (!(a[i - 1] < a[i]))
389
- fail(`${p}[${i}]`, 'a sorted set expected');
390
- };
391
- /** an invitation received: attributed to a relationship (contactId and
392
- * rkid together) or to none (Membership RLTP-MT-3100) */
393
- const receivedInvite2 = (x, p) => {
394
- obj({
395
- credDigest: str, group: str, name: str, memberLabel: str, invite: anyObj, promptId: str, validUntil: millis,
396
- status: lit('open', 'accepted', 'declined', 'joined'), at: millis,
397
- }, { acceptDigest: str, contactId: str, rkid: str })(x, p);
398
- const i = x;
399
- if ((i.contactId === undefined) !== (i.rkid === undefined))
400
- fail(`${p}.rkid`, 'present exactly with contactId');
401
- };
402
- const codec2 = obj({
403
- ...fields1,
404
- codec: lit(2),
405
- outbox: rec(outboxItemOf(2)),
406
- acts: keyed(obj({ actId: str, inputHash: str, commitSeq: dec, outboundDigests: arr(str), events: arr(eventOf(2)), at: millis }), 'actId'),
407
- joining: obj({
408
- preludes: rec(obj({ group: str, inviter: str, contactId: str, rkid: str, memberLabel: str, at: millis })),
409
- invites: keyed(receivedInvite2, 'credDigest'),
375
+ invites: keyed(receivedInvite, 'credDigest'),
410
376
  surfaced: sortedSet,
411
377
  declined: sortedSet,
412
378
  }),
@@ -420,8 +386,7 @@ const codec2 = obj({
420
386
  });
421
387
  /** Structural validators per codec version; every readable codec has one. */
422
388
  export const VALIDATORS = Object.freeze({
423
- 1: (raw) => codec1(raw, '$'),
424
- 2: (raw) => codec2(raw, '$'),
389
+ 3: (raw) => codec3(raw, '$'),
425
390
  });
426
391
  // ── the codec ──────────────────────────────────────────────────────────
427
392
  /** Canonical JSON text of a JSON-pure value, or not-json. */