@byok-sdk/cloud-dataplane 0.6.0 → 0.7.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.
- package/dist/index.js +161 -17
- package/dist/index.js.map +1 -1
- package/dist/runtime.js +160 -16
- package/dist/runtime.js.map +1 -1
- package/dist/sql/0012_agent_home_contract.sql +41 -0
- package/dist/sql/0013_agent_egress_contract.sql +47 -0
- package/dist/stores/agent-egress.d.ts +14 -0
- package/dist/stores/devices.d.ts +4 -0
- package/dist/stores/index.d.ts +2 -1
- package/dist/stores/task-attempts.d.ts +16 -2
- package/dist/tenant-erasure.d.ts +2 -2
- package/package.json +4 -4
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pool.ts","../src/stores/core/objects.ts","../src/stores/r2-blobs.ts","../src/stores/devices.ts","../src/stores/dedup.ts","../src/stores/nonces.ts","../src/stores/pairing-codes.ts","../src/stores/receipts.ts","../src/stores/proof-receipts.ts","../src/stores/task-attempts.ts","../src/stores/core/mailbox-sequence.ts","../src/stores/core/mailbox.ts","../src/stores/task-cancellations.ts","../src/stores/activity.ts","../src/stores/approval-timeline.ts","../src/stores/device-assertion-replay.ts","../src/stores/index.ts","../src/stores/core/presence.ts","../src/stores/core/board.ts","../src/stores/core/quota.ts","../src/stores/core/skill-pack.ts","../src/stores/core/truth.ts","../src/stores/core/index.ts","../src/truth-committer.ts","../src/migrations-dir.ts","../src/migrate.ts","../src/cleanup.ts","../src/tenant-erasure.ts"],"names":["ByokCoreError","SELECT_COLUMNS","toReceipt","assertCanonicalTimestamp","toTail","ByokCloudError","DEFAULT_LIST_LIMIT","CoreConflictError","toRecord","RECORD_COLUMNS","toBody","bodyColumns","response","OUTBOX_COLUMNS","toMailboxMessage","contentHash","createHash","DEFAULT_BATCH_SIZE","MAX_BATCH_SIZE","tenantId"],"mappings":";;;;;;;;;;;;AAwBA,IAAM,iBAAA,GAAoB,GAAG,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K,WAAA,CAAY,SAAS,GAAA,IAAO,WAAA,CAAY,IAAA,EAAK,KAAM,WAAA,EAAa;AAC9F,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR,8BAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;AAEA,SAAS,kBAAA,CAAmB,KAAA,EAAe,KAAA,EAAe,GAAA,EAAqB;AAC7E,EAAA,IAAI,CAAC,OAAO,aAAA,CAAc,KAAK,KAAK,KAAA,GAAQ,CAAA,IAAK,QAAQ,GAAA,EAAK;AAC5D,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR,8BAAA;AAAA,MACA,CAAA,EAAG,KAAK,CAAA,+BAAA,EAAkC,MAAA,CAAO,GAAG,CAAC,CAAA,EAAA;AAAA,KACvD;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,aAAa,KAAA,EAAoC;AACxD,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,MAAA,IAAU,KAAA,IAAS,OAAO,KAAA,CAAM,IAAA,KAAS,QAAA,GAC3F,KAAA,CAAM,IAAA,GACN,MAAA;AACN;AAEA,SAAS,cAAA,CAAe,QAAgB,KAAA,EAAoC;AAC1E,EAAA,OAAO,IAAI,kBAAA;AAAA,IACT,gCAAA;AAAA,IACA,mCAAmC,MAAM,CAAA,+BAAA,CAAA;AAAA,IACzC,EAAE,KAAA;AAAM,GACV;AACF;AAEA,SAAS,eAAA,CAAgB,QAAgB,KAAA,EAAoC;AAC3E,EAAA,OAAO,KAAA,YAAiB,kBAAA,GACpB,KAAA,GACA,IAAI,kBAAA;AAAA,IACJ,iCAAA;AAAA,IACA,mCAAmC,MAAM,CAAA,mCAAA,CAAA;AAAA,IACzC,EAAE,KAAA;AAAM,GACV;AACJ","file":"index.js","sourcesContent":["/**\n * The `pg` Pool factory.\n *\n * One thing here is load-bearing and easy to get wrong: **int8 parsing**.\n * `pg` decodes `bigint` columns as strings by default, because a 64-bit value\n * does not fit a JS `number`. Every byte-count contract in `@byok-sdk/core` is\n * declared `bigint` (`byteSize`, `releasedBytes`, the whole quota surface), so\n * a default-configured pool would hand the stores strings, and\n * `usage.reservedBytes > limit` would silently become a lexicographic string\n * comparison that answers a different question. Nothing would throw.\n *\n * The parser is injected **into the pool config**, never onto `pg.types`. That\n * registry is process-wide: mutating it would reach into every other `pg`\n * consumer in the host application, including ones that deliberately want\n * strings back. A host composing this SDK next to its own database code must\n * not have its decoding changed by one of our import side effects.\n */\nimport pg from 'pg';\nimport type { Pool, PoolClient, PoolConfig } from 'pg';\n\n/**\n * `pg`'s default parser for every other oid, so this config ADDS one decoding\n * rule instead of replacing the table.\n */\nconst defaultTypeParser = pg.types.getTypeParser;\n\nconst int8Parsers: PoolConfig['types'] = {\n getTypeParser(id, format) {\n if (id === pg.types.builtins.INT8) return (value: string) => BigInt(value);\n return defaultTypeParser(id, format);\n },\n};\n\nexport interface ByokPoolOptions extends Omit<PoolConfig, 'types'> {\n /** `postgres://user:password@host:port/database`. */\n readonly connectionString: string;\n /**\n * Where an IDLE client's error goes. See {@link createByokPool} — a pool\n * MUST carry an `'error'` listener or an idle-backend reset crashes the host.\n * This is where the host takes over that policy (log to its own sink, page,\n * increment a metric). It is NOT a `PoolConfig` field, so it is stripped\n * before the config reaches `pg.Pool`, exactly as `types` is kept off the\n * process-wide registry.\n *\n * Left unset, the pool still gets a listener — an observable default, not a\n * silent swallow.\n */\n readonly onPoolError?: (err: Error, client?: PoolClient) => void;\n}\n\n/**\n * Creates a pool wired with the int8 parser above.\n *\n * The caller owns the pool's lifetime: this package never holds a module-level\n * pool, because a process that composes two deployments (a migration runner and\n * a serving path, say) has to be able to close one without breaking the other.\n *\n * The `'error'` listener is MANDATORY, not defensive. A `pg.Pool` emits\n * `'error'` when a client that is sitting IDLE in the pool has its backend\n * connection reset from under it — a failover, an operator\n * `pg_terminate_backend`, an idle-timeout on a proxy, a network blip. There is\n * no `await` in flight to reject at that moment, so `pg` surfaces it on the\n * pool, and Node's rule for an `EventEmitter` `'error'` with no listener is to\n * rethrow it as an uncaught exception — which terminates the whole host\n * process. A bare `new pg.Pool(...)` therefore hands the host a latent crash on\n * an event it cannot see coming and did not cause. The listener converts that\n * into a handled, observable event: routed to the host's {@link\n * ByokPoolOptions.onPoolError} when supplied, or to a labelled `console.error`\n * so the reset is never invisible. It does not paper over live query errors —\n * those still reject their own `await`; this is only the idle-client path.\n */\nexport function createByokPool(options: ByokPoolOptions): Pool {\n // `onPoolError` is ours, not `pg`'s: strip it before the config reaches\n // `pg.Pool`, the same discipline `types` gets.\n const { onPoolError, ...poolConfig } = options;\n const pool = new pg.Pool({ ...poolConfig, types: int8Parsers });\n\n pool.on('error', (err: Error, client?: PoolClient) => {\n if (onPoolError) {\n onPoolError(err, client);\n return;\n }\n // Observable default: the host owns the policy, but the SDK never lets an\n // idle-client reset pass silently. `console.error` keeps it fail-safe (the\n // process survives) without pretending nothing happened.\n console.error('[byok-sdk] idle pg pool client error (handled, not fatal)', err);\n });\n\n return pool;\n}\n","/**\n * Postgres {@link ObjectStore} — the manifest, and only the manifest\n * (§12.7.4, §12.7.8).\n *\n * Zero bytes cross this file. The manifest is the transaction authority and the\n * object store holds the payload; the R2 adapter that moves bytes is S4A-c.\n * What lives here is the state machine that stands between a failed object-store\n * delete and either a leaked object or a deleted one a truth record still points\n * at.\n *\n * Three properties the SQL is shaped around:\n *\n * - **`ref_count` is recomputed, never incremented.** Every reference mutation\n * sets it to `count(*)` over `object_reference`. An increment drifts the\n * moment a retried `addReference` lands twice, and a drifted count strands\n * the object forever because `markDeletePending` refuses at `refCount != 0`.\n * The reference table's primary key already makes the write idempotent; the\n * count just reads it.\n * - **Reference mutations hold the manifest row under `FOR UPDATE`.** The\n * recomputation above is only authoritative because of this lock, not on its\n * own: under READ COMMITTED the `count(*)` subquery is evaluated on the\n * snapshot its statement started with, so an unlocked `addReference` reads a\n * `committed` state, and `markDeletePending`'s `ref_count = 0` guard can pass\n * in the window before the reference row lands — leaving `delete_pending`\n * with a live reference, which is a truth record pointing at bytes S4B's GC\n * is entitled to delete. Taking the manifest row exclusively first makes the\n * tombstone and the reference write queue against each other, exactly as\n * `PostgresQuotaStore.reserve` serializes reservers on the entitlement row.\n * - **Every state move is a guarded `UPDATE`.** The legal transitions are the\n * guard, so an illegal one writes nothing and the row is re-read to say which\n * typed rejection applies. `commit` additionally guards on the DECLARED size\n * and type, because the whole point of the check is that what the composition\n * observed on the object store and what the client declared can differ\n * (§12.7.7 step 4).\n */\nimport {\n ByokCoreError,\n assertCanonicalTimestamp,\n type Clock,\n type ContentHash,\n type ObjectCommitInput,\n type ObjectListQuery,\n type ObjectManifestEntry,\n type ObjectManifestInput,\n type ObjectReferenceInput,\n type ObjectState,\n type ObjectStore,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { Pool, PoolClient } from 'pg';\n\nconst DEFAULT_LIST_LIMIT = 100;\n\nconst MANIFEST_COLUMNS =\n 'tenant_id, hash, byte_size, content_type, state, ref_count, created_at, updated_at, delete_pending_at';\n\ninterface ManifestRow {\n readonly tenant_id: string;\n readonly hash: string;\n readonly byte_size: bigint;\n readonly content_type: string;\n readonly state: string;\n readonly ref_count: number;\n readonly created_at: string;\n readonly updated_at: string;\n readonly delete_pending_at: string | null;\n}\n\nfunction toEntry(row: ManifestRow): ObjectManifestEntry {\n return {\n tenantId: row.tenant_id as TenantId,\n hash: row.hash as ContentHash,\n byteSize: row.byte_size,\n contentType: row.content_type,\n state: row.state as ObjectState,\n refCount: row.ref_count,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n ...(row.delete_pending_at === null ? {} : { deletePendingAt: row.delete_pending_at }),\n };\n}\n\nexport class PostgresObjectStore implements ObjectStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async putManifest(\n tenant: TenantId,\n input: ObjectManifestInput,\n ): Promise<ObjectManifestEntry> {\n const now = this.#now();\n // Idempotent per (tenant, hash): a row that exists in any state but\n // `deleted` is returned untouched, so a retried reservation cannot reset a\n // committed object back to `pending` and orphan its references. A `deleted`\n // row is the one case where the same hash legitimately starts over, and the\n // `WHERE` on the conflict path is what limits the reset to it.\n const upserted = await this.#pool.query<ManifestRow>(\n `INSERT INTO object_manifest (${MANIFEST_COLUMNS})\n VALUES ($1, $2, $3::bigint, $4, 'pending', 0, $5, $5, NULL)\n ON CONFLICT (tenant_id, hash) DO UPDATE\n SET byte_size = EXCLUDED.byte_size,\n content_type = EXCLUDED.content_type,\n state = 'pending',\n ref_count = 0,\n created_at = EXCLUDED.created_at,\n updated_at = EXCLUDED.updated_at,\n delete_pending_at = NULL\n WHERE object_manifest.state = 'deleted'\n RETURNING ${MANIFEST_COLUMNS}`,\n [tenant, input.hash, input.byteSize, input.contentType, now],\n );\n const row = upserted.rows[0];\n if (row !== undefined) return toEntry(row);\n return this.#require(tenant, input.hash);\n }\n\n async commit(tenant: TenantId, input: ObjectCommitInput): Promise<ObjectManifestEntry> {\n const committed = await this.#pool.query<ManifestRow>(\n `UPDATE object_manifest\n SET state = 'committed', updated_at = $3\n WHERE tenant_id = $1 AND hash = $2\n AND state = 'pending'\n AND byte_size = $4::bigint\n AND content_type = $5\n RETURNING ${MANIFEST_COLUMNS}`,\n [tenant, input.hash, this.#now(), input.observedByteSize, input.observedContentType],\n );\n const row = committed.rows[0];\n if (row !== undefined) return toEntry(row);\n\n const current = await this.#require(tenant, input.hash);\n // Integrity outranks state: an object whose observed shape disagrees is a\n // mismatch whatever state the row is in, and it stays `pending` so the GC\n // worker can reclaim the bytes rather than a truth record pointing at them.\n if (\n current.byteSize !== input.observedByteSize ||\n current.contentType !== input.observedContentType\n ) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Observed object ${input.hash} (${String(input.observedByteSize)} bytes, ${input.observedContentType}) does not match the declared manifest.`,\n );\n }\n if (current.state === 'committed') return current;\n throw this.#stateInvalid(current.state, 'committed');\n }\n\n async get(tenant: TenantId, hash: ContentHash): Promise<ObjectManifestEntry | undefined> {\n const result = await this.#pool.query<ManifestRow>(\n `SELECT ${MANIFEST_COLUMNS} FROM object_manifest WHERE tenant_id = $1 AND hash = $2`,\n [tenant, hash],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toEntry(row);\n }\n\n async list(\n tenant: TenantId,\n query: ObjectListQuery,\n ): Promise<readonly ObjectManifestEntry[]> {\n // The cutoff is compared against `delete_pending_at` as text, which only\n // equals a time comparison for the canonical form. A GC sweep reading a\n // mis-parsed cutoff would either miss tombstones or take live objects, so\n // this rejects rather than interprets.\n if (query.deletePendingBefore !== undefined) {\n assertCanonicalTimestamp(query.deletePendingBefore, 'deletePendingBefore');\n }\n const result = await this.#pool.query<ManifestRow>(\n `SELECT ${MANIFEST_COLUMNS} FROM object_manifest\n WHERE tenant_id = $1\n AND ($2::text IS NULL OR state = $2::text)\n AND ($3::text IS NULL\n OR (delete_pending_at IS NOT NULL AND delete_pending_at < $3::text))\n ORDER BY hash COLLATE \"C\"\n LIMIT $4`,\n [\n tenant,\n query.state ?? null,\n query.deletePendingBefore ?? null,\n query.limit ?? DEFAULT_LIST_LIMIT,\n ],\n );\n return result.rows.map(toEntry);\n }\n\n async addReference(\n tenant: TenantId,\n input: ObjectReferenceInput,\n ): Promise<ObjectManifestEntry> {\n // The state read, the reference write, and the recount are one transaction\n // holding the manifest row, so `markDeletePending` cannot slip its guard\n // between the read and the write.\n return this.#withManifestLocked(tenant, input.hash, async (client, current) => {\n if (current.state !== 'committed') {\n return new ByokCoreError(\n 'object_state_invalid',\n `Only committed objects can be referenced; ${input.hash} is ${current.state}.`,\n );\n }\n await client.query(\n `INSERT INTO object_reference (tenant_id, hash, ref_kind, ref_id, created_at)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (tenant_id, hash, ref_kind, ref_id) DO NOTHING`,\n [tenant, input.hash, input.refKind, input.refId, this.#now()],\n );\n return this.#recount(client, tenant, input.hash);\n });\n }\n\n async removeReference(\n tenant: TenantId,\n input: ObjectReferenceInput,\n ): Promise<ObjectManifestEntry> {\n // The mirror of `addReference`, on the same lock. Holding the manifest row\n // is also what replaces the delete's old `EXISTS` guard: the lock already\n // established that this tenant has the row, so `object_not_found` is\n // reported before anything is removed rather than after.\n return this.#withManifestLocked(tenant, input.hash, async (client) => {\n await client.query(\n `DELETE FROM object_reference\n WHERE tenant_id = $1 AND hash = $2 AND ref_kind = $3 AND ref_id = $4`,\n [tenant, input.hash, input.refKind, input.refId],\n );\n return this.#recount(client, tenant, input.hash);\n });\n }\n\n async markDeletePending(\n tenant: TenantId,\n hash: ContentHash,\n ): Promise<ObjectManifestEntry> {\n // `ref_count = 0` is in the guard, not checked beforehand: a reference\n // added between a check and a write would otherwise tombstone an object a\n // truth record still points at. Nothing else is needed here — this `UPDATE`\n // takes the same manifest row exclusively that `addReference` locks, so a\n // concurrent reference write either lands entirely before this statement\n // (and the guard sees its count) or queues behind it (and re-reads the\n // tombstone it must refuse against).\n const marked = await this.#pool.query<ManifestRow>(\n `UPDATE object_manifest\n SET gc_accounted_bytes = CASE WHEN state = 'committed' THEN byte_size ELSE 0 END,\n gc_accounted_object = (state = 'committed'),\n state = 'delete_pending', delete_pending_at = $3, updated_at = $3\n WHERE tenant_id = $1 AND hash = $2\n AND ref_count = 0\n AND state IN ('pending', 'committed')\n RETURNING ${MANIFEST_COLUMNS}`,\n [tenant, hash, this.#now()],\n );\n const row = marked.rows[0];\n if (row !== undefined) return toEntry(row);\n\n const current = await this.#require(tenant, hash);\n if (current.refCount !== 0) {\n throw new ByokCoreError(\n 'object_state_invalid',\n `Object ${hash} still has ${current.refCount} reference(s).`,\n );\n }\n throw this.#stateInvalid(current.state, 'delete_pending');\n }\n\n async markDeleted(tenant: TenantId, hash: ContentHash): Promise<ObjectManifestEntry> {\n const deleted = await this.#pool.query<ManifestRow>(\n `UPDATE object_manifest\n SET state = 'deleted', updated_at = $3\n WHERE tenant_id = $1 AND hash = $2 AND state = 'delete_pending'\n RETURNING ${MANIFEST_COLUMNS}`,\n [tenant, hash, this.#now()],\n );\n const row = deleted.rows[0];\n if (row !== undefined) return toEntry(row);\n\n const current = await this.#require(tenant, hash);\n throw this.#stateInvalid(current.state, 'deleted');\n }\n\n /**\n * Runs a reference mutation with the manifest row held under `FOR UPDATE`.\n *\n * The lock is taken before anything is read, so the state the callback judges\n * is the state no concurrent `markDeletePending` can move underneath it. A\n * typed refusal is RETURNED rather than thrown, the way\n * `PostgresQuotaStore.reserve` defers its rejection past `COMMIT`: it keeps\n * the `catch` reserved for genuine faults, so a rollback that itself fails\n * cannot replace this store's own answer.\n */\n async #withManifestLocked(\n tenant: TenantId,\n hash: ContentHash,\n mutate: (\n client: PoolClient,\n current: ObjectManifestEntry,\n ) => Promise<ObjectManifestEntry | ByokCoreError>,\n ): Promise<ObjectManifestEntry> {\n const client = await this.#pool.connect();\n let settled: ObjectManifestEntry | ByokCoreError;\n try {\n await client.query('BEGIN');\n const locked = await client.query<ManifestRow>(\n `SELECT ${MANIFEST_COLUMNS} FROM object_manifest\n WHERE tenant_id = $1 AND hash = $2\n FOR UPDATE`,\n [tenant, hash],\n );\n const row = locked.rows[0];\n settled = row === undefined ? this.#notFound(hash) : await mutate(client, toEntry(row));\n await client.query('COMMIT');\n } catch (error) {\n // Best-effort, for the same reason the migration runner's is: a rollback\n // that throws must not replace the failure the caller needs to see.\n await client.query('ROLLBACK').catch(() => {});\n throw error;\n } finally {\n client.release();\n }\n\n if (settled instanceof ByokCoreError) throw settled;\n return settled;\n }\n\n /** Sets `ref_count` to what the reference rows actually say. */\n async #recount(\n client: PoolClient,\n tenant: TenantId,\n hash: ContentHash,\n ): Promise<ObjectManifestEntry> {\n const result = await client.query<ManifestRow>(\n `UPDATE object_manifest\n SET ref_count = (SELECT count(*) FROM object_reference r\n WHERE r.tenant_id = $1 AND r.hash = $2),\n updated_at = $3\n WHERE tenant_id = $1 AND hash = $2\n RETURNING ${MANIFEST_COLUMNS}`,\n [tenant, hash, this.#now()],\n );\n const row = result.rows[0];\n if (row === undefined) throw this.#notFound(hash);\n return toEntry(row);\n }\n\n async #require(tenant: TenantId, hash: ContentHash): Promise<ObjectManifestEntry> {\n const entry = await this.get(tenant, hash);\n if (entry === undefined) throw this.#notFound(hash);\n return entry;\n }\n\n #notFound(hash: ContentHash): ByokCoreError {\n return new ByokCoreError(\n 'object_not_found',\n `Object ${hash} has no manifest row in this tenant.`,\n );\n }\n\n #stateInvalid(from: ObjectState, to: ObjectState): ByokCoreError {\n return new ByokCoreError(\n 'object_state_invalid',\n `${from} to ${to} is not a legal object manifest transition.`,\n );\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * The R2/S3 {@link CloudBlobStore} — grants, and only grants (§12.7.4, §12.7.7).\n *\n * Zero bytes cross this file either, but for the opposite reason to\n * `stores/core/objects.ts`: the manifest store holds metadata because bytes are\n * not its job, and this store holds no bytes because the DEVICE talks to the\n * object store directly. What it mints is a presigned URL; what the device does\n * with it is between the device and R2. That is why this composition supplies\n * no `BlobContentProxy` — there is no byte path here to proxy, and the absence\n * is the honest declaration (`@byok-sdk/cloud`'s `ports.ts`, design §6).\n *\n * Manifest and bytes are one transaction authority split across two systems\n * with no shared transaction, so the protocol is reserve/verify rather than\n * write/trust:\n *\n * 1. `createUpload` writes the `pending` manifest row FIRST, then signs a PUT.\n * Row-before-bytes is what makes an abandoned upload a reclaimable\n * tombstone instead of an object nobody has a record of.\n * 2. The device PUTs straight to the object store. `Content-Length` and\n * `Content-Type` are in the signed headers, so a body of the wrong size or\n * the wrong type is refused by the object store itself — before a byte is\n * stored, and without this process being in the path.\n * 3. The explicit finalize route calls `observeUpload`, which performs an\n * unconditional `HEAD`. Unconditional because §12.7.7 step 4 is about what\n * the store OBSERVES versus what the client DECLARED, and signing the length\n * proves what one client sent, not what is at the key now. The quota\n * authority then commits manifest/reservation/usage in one Postgres\n * statement; download never performs that transition.\n * 4. `committed` is terminal for writes. Step 1 is re-runnable while a row is\n * `pending` — that is what makes a retried upload idempotent — and refused\n * once it is `committed`, because §12.7.4 lets truth reference a committed\n * manifest and the reference means nothing if the bytes can still be\n * replaced by a same-shaped body under a freshly signed PUT.\n *\n * **No checksum header.** `x-amz-checksum-sha256` was probed rather than\n * assumed (design §3 marked it `[unverified]`): MinIO honors it in a presigned\n * PUT and rejects mismatched bytes with `XAmzContentChecksumMismatch`, but R2's\n * S3 compatibility table lists SHA-256 as `COMPOSITE` only — `FULL_OBJECT`, the\n * type a single-shot PutObject uses, is ❌, and R2's PutObject feature row names\n * no `x-amz-checksum-*` header at all. Signing one would mint URLs that work\n * against the test substrate and fail against production, which is worse than\n * not signing it. The `HEAD` above was never conditional on it.\n *\n * The `blobId` this store mints IS the content hash. That is what makes \"no\n * naked object index\" constructive rather than disciplinary: there is no\n * surrogate id to look up, every read is `(tenant, hash)` against the manifest\n * primary key, and the object key is derived — once, in {@link #objectUrl} —\n * from a `ContentHash` that core already validated. A non-hex id cannot reach\n * key construction because it cannot become a `ContentHash`.\n */\nimport {\n ByokCoreError,\n contentHash,\n isContentHash,\n objectKeyPrefix,\n tenantObjectKey,\n type Clock,\n type ContentHash,\n type ObjectKeyPrefix,\n type ObjectStore,\n type StorageReservation,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { BlobObservation, CloudBlobStore } from '@byok-sdk/cloud';\nimport { AwsClient } from 'aws4fetch';\nimport { XMLParser } from 'fast-xml-parser';\n\n/** 15 minutes, matching the in-memory reference's `BLOB_URL_TTL_MS`. */\nexport const DEFAULT_PRESIGN_TTL_SECONDS = 15 * 60;\n\n/** `X-Amz-Expires` floor. Below a second there is no grant, only a signature. */\nexport const MIN_PRESIGN_TTL_SECONDS = 1;\n\n/** `X-Amz-Expires` ceiling: seven days, the longest lifetime R2 will honor. */\nexport const MAX_PRESIGN_TTL_SECONDS = 604_800;\n\n/** Three total attempts: the first plus two retries. */\nexport const DEFAULT_MAX_ATTEMPTS = 3;\n\n/** Doubles per retry. Deterministic — no jitter, so a test can assert the sequence. */\nexport const DEFAULT_RETRY_DELAY_MS = 100;\n\n/** The subset of `fetch` this store uses. The seam a fault injector replaces. */\nexport type ObjectStoreFetch = (request: Request) => Promise<Response>;\n\n/**\n * Raised when the object store answered something this adapter cannot act on —\n * a 4xx that is not \"absent\", or a transient failure that outlived its retries.\n *\n * A local class rather than a core code: core's taxonomy describes the manifest\n * contract, and \"R2 returned 503 three times\" is an adapter fault, not a\n * statement about the object.\n */\nexport class ObjectStoreRequestError extends Error {\n public readonly status: number | undefined;\n public readonly attempts: number;\n\n constructor(message: string, attempts: number, status?: number, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ObjectStoreRequestError';\n this.attempts = attempts;\n this.status = status;\n }\n}\n\n/**\n * What this adapter refuses on its own account, before anything is signed.\n *\n * A second local class rather than more core codes, for the same reason\n * {@link ObjectStoreRequestError} is one: core's taxonomy describes the\n * manifest contract, and \"this deployment's tenant ids cannot be key segments\"\n * or \"this deployment configured a lifetime R2 will not honor\" are facts about\n * an S3 adapter's configuration and inputs, not about an object. Core's code\n * union is closed and deliberately so; widening it from an adapter would put\n * an adapter's vocabulary on a wire contract every composition shares.\n *\n * Code-based branching, matching the idiom of every other error type here.\n */\nexport const R2_BLOB_ERROR_CODES = {\n /**\n * A tenant id that cannot be one safe path segment. Wire-relevant: it is the\n * only signal a control plane gets that the id it issued cannot address\n * object storage, and it is raised BEFORE any key is built.\n */\n storage_tenant_key_unsafe: 'storage_tenant_key_unsafe',\n /** A presign lifetime outside `[MIN_PRESIGN_TTL_SECONDS, MAX_PRESIGN_TTL_SECONDS]`. Construction-time only. */\n storage_presign_ttl_invalid: 'storage_presign_ttl_invalid',\n /** ListObjectsV2 accepts 1..1000 keys per page. Maintenance input only. */\n storage_list_limit_invalid: 'storage_list_limit_invalid',\n /** Continuation tokens are opaque but non-empty. Maintenance input only. */\n storage_list_cursor_invalid: 'storage_list_cursor_invalid',\n} as const;\n\nexport type R2BlobErrorCode = (typeof R2_BLOB_ERROR_CODES)[keyof typeof R2_BLOB_ERROR_CODES];\n\nexport class R2BlobStoreError extends Error {\n public readonly code: R2BlobErrorCode;\n\n constructor(code: R2BlobErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'R2BlobStoreError';\n this.code = code;\n }\n}\n\nexport interface R2BlobStoreOptions {\n /**\n * The manifest authority. Same `ObjectStore` the core composition supplies —\n * one row per (tenant, hash), and this store never opens a second one.\n */\n readonly objects: ObjectStore;\n /**\n * The clock SigV4's `X-Amz-Date` is read from — WALL time, and deliberately\n * NOT the composition's logical clock.\n *\n * Every other instant in this program comes from an injected clock so TTLs\n * are assertable without sleeping, and a store reaching for wall time is a\n * bug. A request signature is the exception, and not a soft one: its validity\n * window is adjudicated by the object store against the object store's own\n * clock. Signing with a logical instant produces a credential the remote side\n * rejects as skewed the moment the two disagree — a 403 at upload time, from\n * a decision made at composition time.\n *\n * Separate and required rather than defaulted, so the distinction is a choice\n * someone makes rather than one they inherit. A test that needs an EXPIRED\n * grant backdates this clock, which is also the only way to assert expiry\n * without sleeping through it.\n */\n readonly signingClock: Clock;\n /** Origin only, e.g. `https://<account>.r2.cloudflarestorage.com`. */\n readonly endpoint: string;\n readonly bucket: string;\n readonly accessKeyId: string;\n readonly secretAccessKey: string;\n /**\n * `auto` for R2. Required rather than defaulted: a signature scoped to the\n * wrong region fails as a 403 at upload time, which is a terrible place to\n * discover a config default nobody chose.\n */\n readonly region: string;\n /**\n * A key namespace for this deployment, e.g. `acme/prod` →\n * `acme/prod/tenants/<tenant>/objects/sha256/<hex>`. Omit it and the key is\n * the unprefixed `tenants/...` layout, byte for byte.\n *\n * What it is for: one bucket, several deployments. Without it every\n * deployment owns the bucket root, so a host running two products against\n * one R2 account has to open a bucket per product.\n *\n * **Immutable per deployment, and only for a NEW one.** This value is\n * spliced into the key at write time and at read time from the same field;\n * there is no second layout anything falls back to, by design. Change it on\n * a deployment that has already stored objects and those objects are\n * stranded — still in the bucket, no longer addressable, and invisible to\n * this SDK's own maintenance surface. A dual-read across the old and new\n * prefix is NOT a supported way to switch and will not be added: it would\n * make two key layouts simultaneously authoritative for the same object.\n * Moving an existing deployment onto a prefix is a separate, one-shot,\n * operator-invoked copy of the objects themselves, out of this SDK's scope.\n *\n * Validated at construction ({@link ObjectKeyPrefix}): slash-joined segments\n * of lowercase alphanumerics, `.`, `_`, `-`, each starting with an\n * alphanumeric, no leading/trailing slash, no empty segment. `''` is a\n * refusal, not a synonym for \"no prefix\" — it is what an unset environment\n * variable looks like, and silently treating it as the default would put a\n * deployment's objects somewhere nobody chose.\n */\n readonly keyPrefix?: string;\n readonly presignTtlSeconds?: number;\n /** Injected so a fault injector can sit in front of the real one. */\n readonly fetch?: ObjectStoreFetch;\n readonly maxAttempts?: number;\n readonly retryDelayMs?: number;\n}\n\ninterface HeadResult {\n readonly present: boolean;\n readonly byteSize: bigint;\n readonly contentType: string;\n}\n\n/** One tenant-prefixed R2 key returned by ListObjectsV2. */\nexport interface R2ListedObject {\n readonly key: string;\n /** Present only when the key is exactly `tenants/<tenant>/objects/sha256/<64 lowercase hex>`. */\n readonly hash?: ContentHash;\n readonly byteSize: bigint;\n}\n\nexport interface R2ObjectPage {\n readonly objects: readonly R2ListedObject[];\n readonly nextContinuationToken?: string;\n}\n\nexport type R2DeleteResult = 'deleted' | 'absent';\n\n/** Operations used only by the host-owned S4B-c maintenance worker. */\nexport interface R2ObjectMaintenance {\n inspectObject(tenant: TenantId, hash: ContentHash): Promise<BlobObservation | undefined>;\n deleteObject(tenant: TenantId, hash: ContentHash): Promise<R2DeleteResult>;\n listTenantObjects(\n tenant: TenantId,\n continuationToken?: string,\n limit?: number,\n ): Promise<R2ObjectPage>;\n}\n\nexport class R2CloudBlobStore implements CloudBlobStore {\n readonly #objects: ObjectStore;\n readonly #signingClock: Clock;\n readonly #client: AwsClient;\n readonly #origin: string;\n readonly #bucket: string;\n readonly #keyPrefix: ObjectKeyPrefix | undefined;\n readonly #presignTtlSeconds: number;\n readonly #fetch: ObjectStoreFetch;\n readonly #maxAttempts: number;\n readonly #retryDelayMs: number;\n\n constructor(options: R2BlobStoreOptions) {\n this.#objects = options.objects;\n this.#signingClock = options.signingClock;\n this.#client = new AwsClient({\n accessKeyId: options.accessKeyId,\n secretAccessKey: options.secretAccessKey,\n service: 's3',\n region: options.region,\n // The client's own retry loop is bypassed: this store only ever calls\n // `sign`, and drives its own bounded, jitter-free retries below so the\n // transient-error dimension can assert an exact attempt sequence.\n retries: 0,\n });\n this.#origin = options.endpoint.replace(/\\/+$/, '');\n this.#bucket = options.bucket;\n this.#keyPrefix = resolveKeyPrefix(options.keyPrefix);\n this.#presignTtlSeconds = assertPresignTtl(options.presignTtlSeconds ?? DEFAULT_PRESIGN_TTL_SECONDS);\n this.#fetch = options.fetch ?? ((request) => globalThis.fetch(request));\n this.#maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n this.#retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n }\n\n /**\n * Reserve the manifest row, then hand back a PUT bound to this tenant, this\n * key, this length, this type, and this expiry.\n *\n * `putManifest` is idempotent per (tenant, hash), so a device that declares\n * the same content twice while it is still `pending` gets the same row and\n * the same key — an interrupted upload is retried, not duplicated. It is\n * idempotent per TENANT, which is the same reason the key embeds the tenant:\n * two tenants holding identical bytes hold two independent objects, and\n * neither can learn of the other's.\n *\n * Idempotence stops at `committed`, and that boundary is the point: a\n * committed object is what a truth record is allowed to reference, so it has\n * to be immutable, and re-issuing a write grant for one is the only way this\n * adapter could make it otherwise.\n */\n async createUpload(\n tenant: TenantId,\n reservation: StorageReservation,\n ): Promise<{ readonly blobId: string; readonly uploadUrl: string }> {\n this.#assertReservedObject(tenant, reservation);\n const hash = contentHash(reservation.contentHash);\n const byteSize = reservation.expectedBytes;\n // The same guard {@link #objectUrl} enforces, run before the manifest is\n // touched. Ordering only — the authority is still the one key-construction\n // point — but a tenant whose id can never address a key should not get to\n // reserve a row on the way to being refused.\n assertKeySegmentTenant(tenant);\n\n const entry = await this.#objects.putManifest(tenant, {\n hash,\n byteSize,\n contentType: reservation.contentType,\n });\n // `putManifest` returns an existing non-`deleted` row untouched, which is\n // what makes a retried upload idempotent. The flip side is that a SECOND\n // declaration of the same hash under a different size or type would\n // silently get a URL signed for the FIRST declaration's headers, so the\n // disagreement is refused here rather than discovered as a 403.\n if (entry.byteSize !== byteSize || entry.contentType !== reservation.contentType) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Object ${hash} is already declared as ${String(entry.byteSize)} bytes of ${entry.contentType}; this upload declares ${String(byteSize)} bytes of ${reservation.contentType}.`,\n );\n }\n // A committed object is immutable, so no write authorization exists to\n // hand out for one. §12.7.4 lets a truth record reference only a committed\n // manifest, and the attestation is worth exactly as much as the promise\n // that the bytes under `sha256/<hex>` do not change afterwards. A fresh PUT\n // grant would be that promise's only counterexample: the object store\n // accepts any body matching the signed length and type, and the digest is\n // never recomputed anywhere. `pending` stays grantable — a device retrying\n // an interrupted upload is the case idempotence is FOR, and there is\n // nothing yet for a replacement to invalidate.\n if (entry.state !== 'pending') {\n throw new ByokCoreError(\n 'object_state_invalid',\n `Object ${hash} is ${entry.state}; only a pending object can receive an upload grant.`,\n );\n }\n\n const url = this.#objectUrl(tenant, hash);\n url.searchParams.set('X-Amz-Expires', String(this.#presignTtlSeconds));\n const signed = await this.#client.sign(\n new Request(url, {\n method: 'PUT',\n headers: {\n 'content-length': String(byteSize),\n 'content-type': reservation.contentType,\n },\n }),\n {\n // `allHeaders` is load-bearing: aws4fetch treats `content-length` and\n // `content-type` as unsignable by default (they are per-hop headers for\n // most services), and without this the grant would bind the key and the\n // expiry but not the SHAPE of what may be written to it.\n aws: { signQuery: true, allHeaders: true, datetime: this.#datetime() },\n },\n );\n\n return { blobId: hash, uploadUrl: signed.url };\n }\n\n async observeUpload(\n tenant: TenantId,\n blobId: string,\n reservation: StorageReservation,\n ): Promise<BlobObservation | undefined> {\n if (\n !isContentHash(blobId) ||\n reservation.tenantId !== tenant ||\n reservation.kind !== 'object' ||\n reservation.contentHash !== blobId\n ) {\n return undefined;\n }\n const entry = await this.#objects.get(tenant, reservation.contentHash);\n if (entry === undefined || (entry.state !== 'pending' && entry.state !== 'committed')) {\n return undefined;\n }\n const observed = await this.#head(tenant, reservation.contentHash);\n if (!observed.present) return undefined;\n return {\n observedByteSize: observed.byteSize,\n observedContentType: observed.contentType,\n };\n }\n\n /**\n * A GET for a committed object this tenant owns; `undefined` otherwise.\n *\n * Every miss answers identically — unknown hash, another tenant's object, a\n * malformed id, bytes that never landed, a tombstoned row. A caller cannot\n * tell them apart, which is what keeps `getDownloadUrl` from being an\n * existence oracle across tenants.\n *\n * This is a pure committed-manifest gate. Observation and commit belong to\n * the explicit finalize route; a download must never decide accounting.\n */\n async getDownloadUrl(tenant: TenantId, blobId: string): Promise<string | undefined> {\n // Not an error: a caller holding a junk id learns the same nothing a caller\n // holding another tenant's id learns. It is also the point past which a\n // non-hex value cannot travel — key construction is downstream of here.\n if (!isContentHash(blobId)) return undefined;\n const hash: ContentHash = blobId;\n\n const entry = await this.#objects.get(tenant, hash);\n if (entry === undefined) return undefined;\n\n if (entry.state !== 'committed') {\n // `delete_pending` and `deleted` are tombstones. Handing out a GET for\n // one would be a URL whose object the GC worker is entitled to remove.\n return undefined;\n }\n\n const url = this.#objectUrl(tenant, hash);\n url.searchParams.set('X-Amz-Expires', String(this.#presignTtlSeconds));\n const signed = await this.#client.sign(new Request(url, { method: 'GET' }), {\n aws: { signQuery: true, datetime: this.#datetime() },\n });\n return signed.url;\n }\n\n /**\n * The ONLY place an object key is built, and therefore the only place the\n * key's two segments have to be safe.\n *\n * The hash half is closed by construction: `tenantObjectKey` is core's and it\n * takes a `ContentHash` — a branded type with exactly one mint point that\n * rejects anything but 64 lowercase hex — so a traversal segment, an absolute\n * path, or an uppercase digest cannot be smuggled through a parameter that\n * will not accept them.\n *\n * The tenant half is NOT, and that asymmetry is why the guard below exists.\n * `tenantId()` fails closed on empty, padded, over-long, and `NUL`-bearing\n * values, and deliberately normalizes nothing else — normalizing would make\n * the SDK disagree with the control plane that issued the id about its\n * canonical form (`@byok-sdk/core`'s `tenant.ts`). So `a/../b` is a legitimate\n * tenant id, and the line below would otherwise hand it to `new URL()`, which\n * resolves the traversal and returns tenant `b`'s key. That is a cross-tenant\n * alias: `a/../b` could probe, overwrite, and read what `b` owns.\n *\n * Refused rather than encoded. Percent-encoding the segment would keep the\n * key distinct, and would also give every tenant id two spellings — the one\n * the control plane issued and the one at rest in the object store — which is\n * the second source of truth core refused to create in the first place.\n */\n #objectUrl(tenant: TenantId, hash: ContentHash): URL {\n assertKeySegmentTenant(tenant);\n return new URL(\n `${this.#origin}/${this.#bucket}/${tenantObjectKey(tenant, hash, this.#keyPrefix)}`,\n );\n }\n\n /**\n * `HEAD` the key, with bounded retries for transient faults.\n *\n * `HEAD` is idempotent by construction, so a retry can never double an\n * effect — which is the whole reason the retry loop is allowed to exist here\n * and not around anything that writes.\n */\n async #head(tenant: TenantId, hash: ContentHash): Promise<HeadResult> {\n const url = this.#objectUrl(tenant, hash);\n const { response, attempts } = await this.#send(new Request(url, { method: 'HEAD' }));\n\n if (response.status === 404) {\n return { present: false, byteSize: 0n, contentType: '' };\n }\n if (!response.ok) {\n throw new ObjectStoreRequestError(\n `HEAD on the object store answered ${response.status}.`,\n attempts,\n response.status,\n );\n }\n\n const length = response.headers.get('content-length');\n const contentType = response.headers.get('content-type');\n if (length === null || contentType === null) {\n // Fail closed. A HEAD without the two fields the commit guard compares\n // cannot be turned into a commit decision, and guessing either one would\n // be inventing the observation the check exists to make.\n throw new ObjectStoreRequestError(\n `HEAD on the object store omitted content-length or content-type, so ${hash} cannot be verified.`,\n attempts,\n response.status,\n );\n }\n return { present: true, byteSize: BigInt(length), contentType };\n }\n\n /**\n * Signs, sends, and retries 5xx/429/network faults with a doubling delay.\n *\n * Returns the attempt count alongside the response because the caller is what\n * decides the answer was a failure. A 4xx costs however many attempts the\n * transient faults before it did, and `attempts` is the only field\n * {@link ObjectStoreRequestError} carries that an operator can use to tell a\n * flapping remote from a hard refusal — so it has to be counted here, where\n * the loop is, rather than assumed to be 1 at the throw site.\n */\n async #send(request: Request): Promise<{ readonly response: Response; readonly attempts: number }> {\n const failures: string[] = [];\n\n for (let attempt = 1; attempt <= this.#maxAttempts; attempt += 1) {\n const signed = await this.#client.sign(request.clone(), {\n aws: { datetime: this.#datetime() },\n });\n\n const outcome = await this.#attempt(signed);\n if (outcome.response !== undefined) return { response: outcome.response, attempts: attempt };\n failures.push(outcome.failure);\n\n if (attempt < this.#maxAttempts) {\n await this.#sleep(this.#retryDelayMs * 2 ** (attempt - 1));\n }\n }\n\n throw new ObjectStoreRequestError(\n `The object store failed ${this.#maxAttempts} attempt(s): ${failures.join(', ')}.`,\n this.#maxAttempts,\n );\n }\n\n async #attempt(signed: Request): Promise<{ response?: Response; failure: string }> {\n try {\n const response = await this.#fetch(signed);\n // 429 and 5xx are the two the S3 contract calls retryable. Everything\n // else — including 403 and 404 — is an answer, not a fault.\n if (response.status !== 429 && response.status < 500) return { response, failure: '' };\n return { failure: `HTTP ${response.status}` };\n } catch (cause) {\n return { failure: cause instanceof Error ? cause.message : String(cause) };\n }\n }\n\n #sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n\n /** SigV4's `YYYYMMDDTHHmmssZ`, off the signing clock — see its doc for why that is a separate one. */\n #datetime(): string {\n return this.#signingClock.now().toISOString().replaceAll(/[:-]|\\.\\d{3}/g, '');\n }\n\n #assertReservedObject(tenant: TenantId, reservation: StorageReservation): void {\n if (\n reservation.tenantId === tenant &&\n reservation.kind === 'object' &&\n reservation.state === 'reserved' &&\n reservation.expectedBytes >= 0n\n ) {\n return;\n }\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n 'An upload grant requires a reserved object reservation owned by this tenant.',\n );\n }\n}\n\nexport type R2ObjectMaintenanceOptions = Omit<\n R2BlobStoreOptions,\n 'objects' | 'presignTtlSeconds'\n>;\n\n/**\n * R2 maintenance adapter kept deliberately outside `CloudBlobStore`.\n *\n * Cloud conformance certifies the device-facing blob port with an exact method\n * inventory. LIST/HEAD/DELETE are host operations, so putting them on\n * `R2CloudBlobStore` would over-declare a capability no other cloud composition\n * implements.\n */\nexport class R2ObjectMaintenanceStore implements R2ObjectMaintenance {\n readonly #signingClock: Clock;\n readonly #client: AwsClient;\n readonly #origin: string;\n readonly #bucket: string;\n readonly #keyPrefix: ObjectKeyPrefix | undefined;\n readonly #fetch: ObjectStoreFetch;\n readonly #maxAttempts: number;\n readonly #retryDelayMs: number;\n\n constructor(options: R2ObjectMaintenanceOptions) {\n this.#signingClock = options.signingClock;\n this.#client = new AwsClient({\n accessKeyId: options.accessKeyId,\n secretAccessKey: options.secretAccessKey,\n service: 's3',\n region: options.region,\n retries: 0,\n });\n this.#origin = options.endpoint.replace(/\\/+$/, '');\n this.#bucket = options.bucket;\n this.#keyPrefix = resolveKeyPrefix(options.keyPrefix);\n this.#fetch = options.fetch ?? ((request) => globalThis.fetch(request));\n this.#maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n this.#retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n }\n\n async inspectObject(\n tenant: TenantId,\n hash: ContentHash,\n ): Promise<BlobObservation | undefined> {\n const observed = await this.#head(tenant, hash);\n if (!observed.present) return undefined;\n return {\n observedByteSize: observed.byteSize,\n observedContentType: observed.contentType,\n };\n }\n\n async deleteObject(tenant: TenantId, hash: ContentHash): Promise<R2DeleteResult> {\n const url = this.#objectUrl(tenant, hash);\n const { response, attempts } = await this.#send(new Request(url, { method: 'DELETE' }));\n if (response.status === 404) return 'absent';\n if (!response.ok) {\n throw new ObjectStoreRequestError(\n `DELETE on the object store answered ${response.status}.`,\n attempts,\n response.status,\n );\n }\n return 'deleted';\n }\n\n async listTenantObjects(\n tenant: TenantId,\n continuationToken?: string,\n limit = 100,\n ): Promise<R2ObjectPage> {\n assertKeySegmentTenant(tenant);\n if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {\n throw new R2BlobStoreError(\n 'storage_list_limit_invalid',\n `A ListObjectsV2 page limit of ${String(limit)} is not a whole number in [1, 1000].`,\n );\n }\n\n // Use core's single key-construction point even for enumeration. The\n // previous abbreviated `${tenant}/sha256/` listing never matched objects\n // written by `tenantObjectKey`, silently hiding canonical R2 data from\n // maintenance. The synthetic valid hash is removed byte-for-byte.\n const prefix = tenantObjectKey(tenant, LIST_PREFIX_HASH, this.#keyPrefix).slice(0, -LIST_HASH_HEX_LENGTH);\n const url = new URL(`${this.#origin}/${this.#bucket}`);\n url.searchParams.set('list-type', '2');\n url.searchParams.set('prefix', prefix);\n url.searchParams.set('max-keys', String(limit));\n if (continuationToken !== undefined) {\n if (continuationToken.length === 0) {\n throw new R2BlobStoreError(\n 'storage_list_cursor_invalid',\n 'A ListObjectsV2 continuation token must not be empty.',\n );\n }\n url.searchParams.set('continuation-token', continuationToken);\n }\n\n const { response, attempts } = await this.#send(new Request(url, { method: 'GET' }));\n if (!response.ok) {\n throw new ObjectStoreRequestError(\n `ListObjectsV2 on the object store answered ${response.status}.`,\n attempts,\n response.status,\n );\n }\n return parseListObjectsV2(await response.text(), prefix, attempts);\n }\n\n async #head(tenant: TenantId, hash: ContentHash): Promise<HeadResult> {\n const { response, attempts } = await this.#send(\n new Request(this.#objectUrl(tenant, hash), { method: 'HEAD' }),\n );\n if (response.status === 404) {\n return { present: false, byteSize: 0n, contentType: '' };\n }\n if (!response.ok) {\n throw new ObjectStoreRequestError(\n `HEAD on the object store answered ${response.status}.`,\n attempts,\n response.status,\n );\n }\n const length = response.headers.get('content-length');\n const contentType = response.headers.get('content-type');\n if (length === null || contentType === null) {\n throw new ObjectStoreRequestError(\n `HEAD on the object store omitted content-length or content-type, so ${hash} cannot be observed.`,\n attempts,\n response.status,\n );\n }\n return { present: true, byteSize: BigInt(length), contentType };\n }\n\n #objectUrl(tenant: TenantId, hash: ContentHash): URL {\n assertKeySegmentTenant(tenant);\n return new URL(\n `${this.#origin}/${this.#bucket}/${tenantObjectKey(tenant, hash, this.#keyPrefix)}`,\n );\n }\n\n async #send(request: Request): Promise<{ readonly response: Response; readonly attempts: number }> {\n const failures: string[] = [];\n for (let attempt = 1; attempt <= this.#maxAttempts; attempt += 1) {\n const signed = await this.#client.sign(request.clone(), {\n aws: { datetime: this.#datetime() },\n });\n try {\n const response = await this.#fetch(signed);\n if (response.status !== 429 && response.status < 500) {\n return { response, attempts: attempt };\n }\n failures.push(`HTTP ${response.status}`);\n } catch (cause) {\n failures.push(cause instanceof Error ? cause.message : String(cause));\n }\n if (attempt < this.#maxAttempts) {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, this.#retryDelayMs * 2 ** (attempt - 1));\n });\n }\n }\n throw new ObjectStoreRequestError(\n `The object store failed ${this.#maxAttempts} attempt(s): ${failures.join(', ')}.`,\n this.#maxAttempts,\n );\n }\n\n #datetime(): string {\n return this.#signingClock.now().toISOString().replaceAll(/[:-]|\\.\\d{3}/g, '');\n }\n}\n\n/**\n * The character set a tenant id may use once it is a KEY SEGMENT.\n *\n * RFC 3986's unreserved set, and nothing else: those are exactly the characters\n * that survive `new URL()` unchanged. Anything outside it either changes the\n * path's STRUCTURE (`/`, `\\`) or changes its SPELLING (percent-encoding), and\n * both are disqualifying for the same reason — an id with two forms is an id\n * with two owners.\n */\nconst SAFE_TENANT_SEGMENT = /^[A-Za-z0-9._~-]+$/;\n\n/**\n * A tenant id is usable here only if it is ONE safe path segment.\n *\n * Conservative on purpose: it rejects rather than repairs, and it rejects\n * everything it is not certain survives URL resolution unchanged — separators\n * in either direction, a leading `.` (which covers `.` and `..`), and every\n * character that would be percent-encoded. A permissive guard that \"handles\"\n * traversal by rewriting it would be a second normalization authority, and the\n * one thing worse than a tenant id the object store cannot address is a tenant\n * id the object store addresses under a name the control plane never issued.\n */\nfunction assertKeySegmentTenant(tenant: TenantId): void {\n if (SAFE_TENANT_SEGMENT.test(tenant) && !tenant.startsWith('.')) return;\n throw new R2BlobStoreError(\n 'storage_tenant_key_unsafe',\n `Tenant id ${JSON.stringify(tenant)} is not a single safe object-key segment, so no key can be built for it.`,\n );\n}\n\n/**\n * The deployment's key namespace, decided once, here, at construction.\n *\n * Validation is core's, not this adapter's: the key layout is core's contract\n * ({@link tenantObjectKey}), and a second opinion about what a legal prefix\n * looks like is a second authority over where objects live. This function only\n * decides that an ABSENT option means the unprefixed layout — every other\n * value, `''` included, goes to the mint point and is either accepted verbatim\n * or refused here and now, before a single key is built.\n */\nfunction resolveKeyPrefix(keyPrefix: string | undefined): ObjectKeyPrefix | undefined {\n return keyPrefix === undefined ? undefined : objectKeyPrefix(keyPrefix);\n}\n\nfunction assertPresignTtl(seconds: number): number {\n if (\n Number.isInteger(seconds) &&\n seconds >= MIN_PRESIGN_TTL_SECONDS &&\n seconds <= MAX_PRESIGN_TTL_SECONDS\n ) {\n return seconds;\n }\n throw new R2BlobStoreError(\n 'storage_presign_ttl_invalid',\n `A presign lifetime of ${String(seconds)} is not a whole number of seconds in [${String(MIN_PRESIGN_TTL_SECONDS)}, ${String(MAX_PRESIGN_TTL_SECONDS)}], which is the range R2 will honor.`,\n );\n}\n\nconst LIST_OBJECTS_XML = new XMLParser({\n ignoreAttributes: true,\n parseTagValue: false,\n trimValues: true,\n processEntities: false,\n});\n\nfunction parseListObjectsV2(xml: string, prefix: string, attempts: number): R2ObjectPage {\n let parsed: unknown;\n try {\n parsed = LIST_OBJECTS_XML.parse(xml) as unknown;\n } catch (cause) {\n throw new ObjectStoreRequestError(\n 'ListObjectsV2 returned malformed XML.',\n attempts,\n undefined,\n { cause },\n );\n }\n\n const document = asRecord(parsed);\n const root = asRecord(document?.ListBucketResult);\n if (root === undefined) {\n throw new ObjectStoreRequestError(\n 'ListObjectsV2 XML omitted ListBucketResult.',\n attempts,\n );\n }\n\n const isTruncated = requiredText(root, 'IsTruncated', attempts);\n if (isTruncated !== 'true' && isTruncated !== 'false') {\n throw new ObjectStoreRequestError(\n `ListObjectsV2 XML contained invalid IsTruncated=${JSON.stringify(isTruncated)}.`,\n attempts,\n );\n }\n\n const rawContents = root.Contents === undefined\n ? []\n : Array.isArray(root.Contents)\n ? root.Contents\n : [root.Contents];\n const objects = rawContents.map((raw, index): R2ListedObject => {\n const content = asRecord(raw);\n if (content === undefined) {\n throw new ObjectStoreRequestError(\n `ListObjectsV2 XML contained a non-object Contents entry at index ${String(index)}.`,\n attempts,\n );\n }\n const key = requiredText(content, 'Key', attempts);\n const sizeText = requiredText(content, 'Size', attempts);\n let byteSize: bigint;\n try {\n byteSize = BigInt(sizeText);\n } catch (cause) {\n throw new ObjectStoreRequestError(\n `ListObjectsV2 XML contained invalid Size=${JSON.stringify(sizeText)}.`,\n attempts,\n undefined,\n { cause },\n );\n }\n if (byteSize < 0n) {\n throw new ObjectStoreRequestError(\n `ListObjectsV2 XML contained negative Size=${sizeText}.`,\n attempts,\n );\n }\n const suffix = key.startsWith(prefix) ? key.slice(prefix.length) : '';\n return {\n key,\n byteSize,\n ...(HASH_KEY_SUFFIX.test(suffix)\n ? { hash: contentHash(`sha256:${suffix}`) }\n : {}),\n };\n });\n\n if (isTruncated === 'false') return { objects };\n const nextContinuationToken = requiredText(root, 'NextContinuationToken', attempts);\n if (nextContinuationToken.length === 0) {\n throw new ObjectStoreRequestError(\n 'ListObjectsV2 XML was truncated but its continuation token was empty.',\n attempts,\n );\n }\n return { objects, nextContinuationToken };\n}\n\nconst HASH_KEY_SUFFIX = /^[0-9a-f]{64}$/;\nconst LIST_HASH_HEX_LENGTH = 64;\nconst LIST_PREFIX_HASH = contentHash(`sha256:${'0'.repeat(LIST_HASH_HEX_LENGTH)}`);\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction requiredText(\n record: Record<string, unknown>,\n field: string,\n attempts: number,\n): string {\n const value = record[field];\n if (typeof value === 'string') return value;\n throw new ObjectStoreRequestError(\n `ListObjectsV2 XML omitted text field ${field}.`,\n attempts,\n );\n}\n","/**\n * Postgres {@link DeviceDirectory}.\n *\n * Rows live under the composite key `(tenant_id, device_id)`, so a cross-tenant\n * read is not \"denied\" — it addresses a different key space and finds nothing\n * (§12.6.2 layer 3). `resolveByDeviceId` is the documented pre-tenant entry\n * point, and it is safe for exactly one reason: the row it returns CARRIES its\n * tenant, so the caller never compares a tenant it was handed against one it\n * guessed. One row, two access paths, never two copies to keep in sync — a\n * stale pre-tenant index would be a revoked device that can still get a token.\n */\nimport {\n type Clock,\n type PresenceStore,\n type PresenceLevel,\n type TenantId,\n type TenantReadinessDevice,\n type TenantReadiness,\n} from '@byok-sdk/core';\nimport type { DeviceDirectory, DeviceRecord, DeviceRegistration } from '@byok-sdk/cloud';\nimport type { Pool } from 'pg';\n\ninterface DeviceRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly product_id: string;\n readonly device_name: string;\n readonly device_public_key: string;\n readonly proof_key_id: string;\n readonly proof_key_epoch: number;\n readonly revoked: boolean;\n}\n\n/**\n * `tenant_id` is read back from the row rather than re-branded from the\n * argument, so `resolveByDeviceId` and `get` produce records the same way.\n * The cast is confined here: this module is the boundary where a database\n * string becomes the branded identity core mints elsewhere.\n */\nfunction toRecord(row: DeviceRow): DeviceRecord {\n return {\n tenantId: row.tenant_id as TenantId,\n productId: row.product_id,\n deviceId: row.device_id,\n deviceName: row.device_name,\n devicePublicKey: row.device_public_key,\n proofKeyId: row.proof_key_id,\n proofKeyEpoch: row.proof_key_epoch,\n revoked: row.revoked,\n };\n}\n\nconst SELECT_COLUMNS =\n 'tenant_id, device_id, product_id, device_name, device_public_key, proof_key_id, proof_key_epoch, revoked';\n\nexport class PostgresDeviceDirectory implements DeviceDirectory {\n readonly #pool: Pool;\n readonly #clock: Clock | undefined;\n\n constructor(pool: Pool, clock?: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async register(tenant: TenantId, input: DeviceRegistration): Promise<DeviceRecord> {\n // Re-pairing an existing device replaces its registration in place rather\n // than creating a second row, matching the in-memory reference. `revoked`\n // resets because a fresh pairing IS a new grant.\n const result = await this.#pool.query<DeviceRow>(\n `INSERT INTO device (\n tenant_id, device_id, product_id, device_name, device_public_key,\n proof_key_id, proof_key_epoch, revoked\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, false)\n ON CONFLICT (tenant_id, device_id) DO UPDATE\n SET product_id = EXCLUDED.product_id,\n device_name = EXCLUDED.device_name,\n device_public_key = EXCLUDED.device_public_key,\n proof_key_id = EXCLUDED.proof_key_id,\n proof_key_epoch = EXCLUDED.proof_key_epoch,\n revoked = false\n RETURNING ${SELECT_COLUMNS}`,\n [\n tenant,\n input.deviceId,\n input.productId,\n input.deviceName,\n input.devicePublicKey,\n input.proofKeyId,\n input.proofKeyEpoch,\n ],\n );\n return toRecord(result.rows[0]!);\n }\n\n async get(tenant: TenantId, deviceId: string): Promise<DeviceRecord | undefined> {\n const result = await this.#pool.query<DeviceRow>(\n `SELECT ${SELECT_COLUMNS} FROM device WHERE tenant_id = $1 AND device_id = $2`,\n [tenant, deviceId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toRecord(row);\n }\n\n async revoke(tenant: TenantId, deviceId: string): Promise<void> {\n // A no-op for a device this tenant does not own: revoking what you cannot\n // address changes nothing and reports nothing back.\n await this.#pool.query('UPDATE device SET revoked = true WHERE tenant_id = $1 AND device_id = $2', [\n tenant,\n deviceId,\n ]);\n }\n\n async list(tenant: TenantId): Promise<readonly DeviceRecord[]> {\n const result = await this.#pool.query<DeviceRow>(\n `SELECT ${SELECT_COLUMNS} FROM device WHERE tenant_id = $1 ORDER BY device_id`,\n [tenant],\n );\n return result.rows.map(toRecord);\n }\n\n async readiness(tenant: TenantId, _presence: PresenceStore): Promise<TenantReadiness> {\n // One tenant-scoped aggregate over durable devices and the latest live\n // presence row. The presence parameter keeps the port shape identical to\n // the reference implementation; SQL is the set-wise authority here.\n const result = await this.#pool.query<{\n device_id: string;\n product_id: string;\n device_name: string;\n revoked: boolean;\n presence_level: string | null;\n presence_detail: string | null;\n presence_configured_toolsets: readonly string[] | null;\n presence_client_version: string | null;\n presence_protocol_versions: readonly number[] | null;\n presence_runtimes: ReadonlyArray<{ id: string; version?: string; authPresent?: boolean }> | null;\n presence_observed_at: string | null;\n presence_expires_at: string | null;\n active_paired_device_count: number | string;\n revoked_device_count: number | string;\n observed_presence_count: number | string;\n observed_online_count: number | string;\n observed_thinking_count: number | string;\n observed_working_count: number | string;\n observed_error_count: number | string;\n observed_offline_count: number | string;\n }>(\n `SELECT\n d.device_id,\n d.product_id,\n d.device_name,\n d.revoked,\n CASE WHEN NOT d.revoked THEN p.level END AS presence_level,\n CASE WHEN NOT d.revoked THEN p.detail END AS presence_detail,\n CASE WHEN NOT d.revoked THEN p.configured_toolsets END AS presence_configured_toolsets,\n CASE WHEN NOT d.revoked THEN p.client_version END AS presence_client_version,\n CASE WHEN NOT d.revoked THEN p.protocol_versions END AS presence_protocol_versions,\n CASE WHEN NOT d.revoked THEN p.runtimes END AS presence_runtimes,\n CASE WHEN NOT d.revoked THEN p.observed_at END AS presence_observed_at,\n CASE WHEN NOT d.revoked THEN p.expires_at END AS presence_expires_at,\n (COUNT(*) FILTER (WHERE NOT d.revoked) OVER ())::int AS active_paired_device_count,\n (COUNT(*) FILTER (WHERE d.revoked) OVER ())::int AS revoked_device_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.device_id IS NOT NULL) OVER ())::int AS observed_presence_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.level = 'online') OVER ())::int AS observed_online_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.level = 'thinking') OVER ())::int AS observed_thinking_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.level = 'working') OVER ())::int AS observed_working_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.level = 'error') OVER ())::int AS observed_error_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.level = 'offline') OVER ())::int AS observed_offline_count\n FROM device d\n LEFT JOIN device_presence p\n ON p.tenant_id = d.tenant_id\n AND p.device_id = d.device_id\n AND p.expires_at > $2\n WHERE d.tenant_id = $1\n ORDER BY d.device_id`,\n [tenant, this.#clock?.now().toISOString() ?? new Date().toISOString()],\n );\n const row = result.rows[0];\n const count = (value: number | string): number => Number(value);\n const devices: TenantReadinessDevice[] = result.rows.map((device) => ({\n deviceId: device.device_id,\n productId: device.product_id,\n deviceName: device.device_name,\n revoked: device.revoked,\n ...(device.presence_level === null\n ? {}\n : {\n presence: {\n level: device.presence_level as PresenceLevel,\n ...(device.presence_detail === null ? {} : { detail: device.presence_detail }),\n ...(device.presence_configured_toolsets === null\n ? {}\n : { configuredToolsets: Object.freeze([...device.presence_configured_toolsets]) }),\n ...(device.presence_client_version === null\n ? {}\n : { clientVersion: device.presence_client_version }),\n ...(device.presence_protocol_versions === null\n ? {}\n : { protocolVersions: Object.freeze([...device.presence_protocol_versions]) }),\n ...(device.presence_runtimes === null\n ? {}\n : { runtimes: Object.freeze(device.presence_runtimes.map((runtime) => Object.freeze({ ...runtime }))) }),\n observedAt: device.presence_observed_at!,\n expiresAt: device.presence_expires_at!,\n },\n }),\n }));\n return {\n tenantId: tenant,\n activePairedDeviceCount: count(row?.active_paired_device_count ?? 0),\n revokedDeviceCount: count(row?.revoked_device_count ?? 0),\n observedPresenceCount: count(row?.observed_presence_count ?? 0),\n observedPresenceByLevel: {\n online: count(row?.observed_online_count ?? 0),\n thinking: count(row?.observed_thinking_count ?? 0),\n working: count(row?.observed_working_count ?? 0),\n error: count(row?.observed_error_count ?? 0),\n offline: count(row?.observed_offline_count ?? 0),\n },\n devices,\n };\n }\n\n async resolveByDeviceId(deviceId: string): Promise<DeviceRecord | undefined> {\n const result = await this.#pool.query<DeviceRow>(\n `SELECT ${SELECT_COLUMNS} FROM device WHERE device_id = $1`,\n [deviceId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toRecord(row);\n }\n}\n","/**\n * Postgres {@link InboundDedupStore} (N3): bounded at-most-once processing.\n *\n * Check-and-record is one `INSERT ... ON CONFLICT DO NOTHING`, so a\n * composition cannot accidentally split it into a racy read-then-write: the\n * primary key does the deciding, and zero returned rows means \"already seen\".\n *\n * Reclaim runs only on the path that actually grew the table, and it deletes\n * oldest-first down to `DEDUP_RING_CAPACITY` rows for that device — the same\n * bound the in-memory ring holds. The ids most likely to be redelivered are the\n * recent ones, so dropping the oldest is the retention that matches the wire's\n * behavior. An unbounded set would pass every duplicate assertion and still let\n * one chatty device grow this table without limit.\n */\nimport { DEDUP_RING_CAPACITY, type InboundDedupStore } from '@byok-sdk/cloud';\nimport type { TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\nexport class PostgresInboundDedupStore implements InboundDedupStore {\n readonly #pool: Pool;\n readonly #capacity: number;\n\n constructor(pool: Pool, capacity: number = DEDUP_RING_CAPACITY) {\n this.#pool = pool;\n this.#capacity = capacity;\n }\n\n async checkAndRecord(tenant: TenantId, deviceId: string, envelopeId: string): Promise<boolean> {\n const inserted = await this.#pool.query(\n `INSERT INTO inbound_dedup (tenant_id, device_id, envelope_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (tenant_id, device_id, envelope_id) DO NOTHING\n RETURNING 1`,\n [tenant, deviceId, envelopeId],\n );\n if (inserted.rowCount === 0) return true;\n\n // Everything at or below the capacity-th newest row goes. The subquery\n // returns no row until the device is over capacity, and `<= NULL` deletes\n // nothing, so the common case costs one index scan and no writes.\n await this.#pool.query(\n `DELETE FROM inbound_dedup\n WHERE tenant_id = $1 AND device_id = $2\n AND recorded_seq <= (\n SELECT recorded_seq FROM inbound_dedup\n WHERE tenant_id = $1 AND device_id = $2\n ORDER BY recorded_seq DESC\n OFFSET $3 LIMIT 1)`,\n [tenant, deviceId, this.#capacity],\n );\n return false;\n }\n}\n","/**\n * Postgres {@link NonceStore}: single-use challenge nonces bound to the\n * (tenant, device) they were issued for, expiring after `NONCE_TTL_MS`\n * (docs/protocol.md §6.2).\n *\n * Expiry is compared against the INJECTED clock, never the database's `now()`.\n * A store that asked the server for the time would be unassertable under a test\n * clock, and the conformance suite's TTL dimension would have to sleep — which\n * is how a replay-window regression ships unnoticed.\n *\n * `issue` sweeps this device's spent and expired rows inline, same posture as\n * the in-memory reference and the reference server: a long-lived deployment\n * never calls a sweep on a timer, and the sweep is bounded to one (tenant,\n * device) so it stays proportional to the caller that triggered it.\n */\nimport { NONCE_TTL_MS, type NonceStore } from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { CloudCrypto } from '@byok-sdk/cloud';\nimport type { Pool } from 'pg';\n\nconst NONCE_BYTES = 24;\n\nexport class PostgresNonceStore implements NonceStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n readonly #crypto: CloudCrypto;\n readonly #ttlMs: number;\n\n constructor(pool: Pool, clock: Clock, crypto: CloudCrypto, ttlMs: number = NONCE_TTL_MS) {\n this.#pool = pool;\n this.#clock = clock;\n this.#crypto = crypto;\n this.#ttlMs = ttlMs;\n }\n\n async issue(tenant: TenantId, deviceId: string): Promise<string> {\n const nowMs = this.#clock.now().getTime();\n const now = new Date(nowMs).toISOString();\n\n await this.#pool.query(\n 'DELETE FROM auth_nonce WHERE tenant_id = $1 AND device_id = $2 AND (used OR expires_at < $3)',\n [tenant, deviceId, now],\n );\n\n const nonce = this.#crypto.randomToken(NONCE_BYTES);\n await this.#pool.query(\n `INSERT INTO auth_nonce (tenant_id, device_id, nonce, expires_at, used)\n VALUES ($1, $2, $3, $4, false)`,\n [tenant, deviceId, nonce, new Date(nowMs + this.#ttlMs).toISOString()],\n );\n return nonce;\n }\n\n async validate(tenant: TenantId, deviceId: string, nonce: string): Promise<boolean> {\n // Never mutates: the gate calls `markUsed` only after every other check on\n // the request has passed, so validation and consumption are separate steps.\n const result = await this.#pool.query(\n `SELECT 1 FROM auth_nonce\n WHERE tenant_id = $1 AND device_id = $2 AND nonce = $3\n AND used = false AND expires_at >= $4`,\n [tenant, deviceId, nonce, this.#clock.now().toISOString()],\n );\n return result.rowCount === 1;\n }\n\n async markUsed(tenant: TenantId, nonce: string): Promise<void> {\n // Tenant-first even though the signature carries no device: a nonce\n // belonging to another tenant is not addressable here, so a cross-tenant\n // consume cannot burn the real owner's nonce.\n await this.#pool.query('UPDATE auth_nonce SET used = true WHERE tenant_id = $1 AND nonce = $2', [\n tenant,\n nonce,\n ]);\n }\n}\n","/**\n * Postgres {@link PairingCodeStore}: single-use codes bound to the tenant and\n * product they were minted for.\n *\n * Redemption is one guarded statement. `UPDATE ... WHERE redeemed_at IS NULL\n * AND expires_at >= $now RETURNING ...` consumes and reports in the same\n * round trip, and zero rows is the typed rejection. A read-then-write would let\n * two concurrent redemptions both observe an unused code, and single-use is\n * exactly what makes the caller's \"redeem, then register the device\" sequence\n * exclusive.\n *\n * Unknown, expired, and already-used all answer `undefined`. The reference\n * server distinguishes them in its 401 text; a hosted multi-tenant surface\n * deliberately does not — the code is a bearer credential addressable across\n * every tenant, and \"already used\" versus \"never existed\" is precisely the\n * difference an attacker enumerating codes would pay for.\n */\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type {\n PairingCodeClaims,\n PairingCodeInfo,\n PairingCodeIssueInput,\n PairingCodeStore,\n} from '@byok-sdk/cloud';\nimport type { Pool } from 'pg';\n\nexport class PostgresPairingCodeStore implements PairingCodeStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async issue(tenant: TenantId, input: PairingCodeIssueInput): Promise<PairingCodeInfo> {\n // Re-issuing a code the host's control plane already minted replaces it,\n // deadline and consumption state included: a mint is the control plane\n // speaking, and it is the only party that could have chosen this code.\n await this.#pool.query(\n `INSERT INTO pairing_code (code, tenant_id, product_id, expires_at, redeemed_at)\n VALUES ($1, $2, $3, $4, NULL)\n ON CONFLICT (code) DO UPDATE\n SET tenant_id = EXCLUDED.tenant_id,\n product_id = EXCLUDED.product_id,\n expires_at = EXCLUDED.expires_at,\n redeemed_at = NULL`,\n [input.code, tenant, input.productId, input.expiresAt],\n );\n // `expiresAt` is echoed from the input rather than read back: the caller\n // supplied a canonical instant and must get that exact string, not this\n // driver's rendering of a timestamptz round trip.\n return { code: input.code, expiresAt: input.expiresAt };\n }\n\n async redeem(code: string): Promise<PairingCodeClaims | undefined> {\n const now = this.#clock.now().toISOString();\n const result = await this.#pool.query<{ tenant_id: string; product_id: string }>(\n `UPDATE pairing_code\n SET redeemed_at = $2\n WHERE code = $1 AND redeemed_at IS NULL AND expires_at >= $2\n RETURNING tenant_id, product_id`,\n [code, now],\n );\n const row = result.rows[0];\n if (row === undefined) return undefined;\n return { tenantId: row.tenant_id as TenantId, productId: row.product_id };\n }\n}\n","/**\n * Postgres {@link RequestReceiptStore}: the first write is the fact.\n *\n * `INSERT ... ON CONFLICT DO NOTHING` and nothing else. The terminal a device\n * reports is a fact, and the retry the at-least-once wire guarantees must not\n * overwrite it (§12.6.4: 不覆写第一份事实). `created: false` is how the caller\n * learns it was a replay, which is why an upsert that UPDATED would be wrong in\n * a way no naive \"record it twice\" test would catch — it would pass, while\n * silently rewriting history and restamping `recorded_at`.\n */\nimport type { RequestReceipt, RequestReceiptStore } from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\ninterface ReceiptRow {\n readonly tenant_id: string;\n readonly key: string;\n readonly body: string;\n readonly recorded_at: Date;\n}\n\nconst SELECT_COLUMNS = 'tenant_id, key, body, recorded_at';\n\nfunction toReceipt(row: ReceiptRow): RequestReceipt {\n return {\n tenantId: row.tenant_id as TenantId,\n key: row.key,\n body: row.body,\n recordedAt: row.recorded_at.toISOString(),\n };\n}\n\nexport class PostgresRequestReceiptStore implements RequestReceiptStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async record(\n tenant: TenantId,\n input: { readonly key: string; readonly body: string },\n ): Promise<{ readonly receipt: RequestReceipt; readonly created: boolean }> {\n const inserted = await this.#pool.query<ReceiptRow>(\n `INSERT INTO device_request_receipts (tenant_id, key, body, recorded_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (tenant_id, key) DO NOTHING\n RETURNING ${SELECT_COLUMNS}`,\n [tenant, input.key, input.body, this.#clock.now().toISOString()],\n );\n const created = inserted.rows[0];\n if (created !== undefined) return { receipt: toReceipt(created), created: true };\n\n const existing = await this.get(tenant, input.key);\n // Unreachable in practice: the insert only declines when the row exists.\n if (existing === undefined) throw new Error(`receipt ${input.key} vanished during record`);\n return { receipt: existing, created: false };\n }\n\n async get(tenant: TenantId, key: string): Promise<RequestReceipt | undefined> {\n const result = await this.#pool.query<ReceiptRow>(\n `SELECT ${SELECT_COLUMNS} FROM device_request_receipts WHERE tenant_id = $1 AND key = $2`,\n [tenant, key],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toReceipt(row);\n }\n}\n","import type {\n ProofRequestReceipt,\n ProofRequestReceiptInput,\n ProofRequestReceiptStore,\n} from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\ninterface ProofReceiptRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly request_id: string;\n readonly operation: string;\n readonly resource: string;\n readonly body_sha256: string;\n readonly body_size: string;\n readonly response_status: number;\n readonly response_body: string;\n readonly recorded_at: Date;\n}\n\nconst SELECT_COLUMNS = `tenant_id, device_id, request_id, operation, resource,\n body_sha256, body_size, response_status, response_body, recorded_at`;\n\nfunction toReceipt(row: ProofReceiptRow): ProofRequestReceipt {\n return {\n tenantId: row.tenant_id as TenantId,\n deviceId: row.device_id,\n requestId: row.request_id,\n operation: row.operation,\n resource: row.resource,\n bodySha256: row.body_sha256,\n bodySize: BigInt(row.body_size),\n responseStatus: row.response_status,\n responseBody: row.response_body,\n recordedAt: row.recorded_at.toISOString(),\n };\n}\n\nexport class PostgresProofRequestReceiptStore implements ProofRequestReceiptStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async record(\n tenant: TenantId,\n input: ProofRequestReceiptInput,\n ): Promise<{ readonly receipt: ProofRequestReceipt; readonly created: boolean }> {\n const result = await this.#pool.query<ProofReceiptRow>(\n `INSERT INTO proof_request_receipt (\n tenant_id, device_id, request_id, operation, resource, body_sha256,\n body_size, response_status, response_body, recorded_at\n ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (tenant_id, device_id, request_id) DO NOTHING\n RETURNING ${SELECT_COLUMNS}`,\n [\n tenant,\n input.deviceId,\n input.requestId,\n input.operation,\n input.resource,\n input.bodySha256,\n input.bodySize.toString(),\n input.responseStatus,\n input.responseBody,\n this.#clock.now().toISOString(),\n ],\n );\n const inserted = result.rows[0];\n if (inserted !== undefined) return { receipt: toReceipt(inserted), created: true };\n const existing = await this.get(tenant, input.deviceId, input.requestId);\n if (existing === undefined) throw new Error(`proof receipt ${input.requestId} vanished during record`);\n return { receipt: existing, created: false };\n }\n\n async get(\n tenant: TenantId,\n deviceId: string,\n requestId: string,\n ): Promise<ProofRequestReceipt | undefined> {\n const result = await this.#pool.query<ProofReceiptRow>(\n `SELECT ${SELECT_COLUMNS}\n FROM proof_request_receipt\n WHERE tenant_id = $1 AND device_id = $2 AND request_id = $3`,\n [tenant, deviceId, requestId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toReceipt(row);\n }\n}\n","/**\n * Postgres {@link TaskAttemptStore} — the ownership authority the inbound gate\n * reads (N2).\n *\n * `claim` is a single guarded statement: `UPDATE ... WHERE owner_device_id IS\n * NULL RETURNING ...`. Two devices racing the same offer therefore produce one\n * owner, not a last writer. When the guard rejects, the row is re-read and\n * returned as-is, which makes a losing claim (and the winner's own re-claim)\n * idempotent rather than an error — the caller learns who owns the task either\n * way. Ownership never transfers: reassigning an owner is the one operation\n * that would make the gate's cross-device assertion unfalsifiable.\n *\n * Two deliberate no-ops, both about not letting a guessed id leave a trace:\n * `claim` and `recordStatus` on a task this tenant never offered write nothing\n * and return `undefined`.\n */\nimport type { TaskAttempt, TaskAttemptStatus, TaskAttemptStore } from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\nexport interface TaskRow {\n readonly tenant_id: string;\n readonly task_id: string;\n readonly device_id: string;\n readonly owner_device_id: string | null;\n readonly status: string;\n readonly cancel_requested_at: Date | null;\n readonly cancel_reason: string | null;\n readonly cancel_message_id: string | null;\n readonly updated_at: Date;\n}\n\nexport const TASK_SELECT_COLUMNS =\n 'tenant_id, task_id, device_id, owner_device_id, status, cancel_requested_at, cancel_reason, cancel_message_id, updated_at';\n\nexport function taskRowToAttempt(row: TaskRow): TaskAttempt {\n return {\n tenantId: row.tenant_id as TenantId,\n taskId: row.task_id,\n deviceId: row.device_id,\n // `exactOptionalPropertyTypes` is off here, but an explicit absent key is\n // still what the in-memory reference produces for an unclaimed attempt, and\n // `toEqual` in the suite treats `undefined` and absent alike only for the\n // former.\n ...(row.owner_device_id === null ? {} : { ownerDeviceId: row.owner_device_id }),\n status: row.status as TaskAttemptStatus,\n ...(row.cancel_requested_at === null\n ? {}\n : {\n cancellation: {\n requestedAt: row.cancel_requested_at.toISOString(),\n ...(row.cancel_reason === null ? {} : { reason: row.cancel_reason }),\n },\n }),\n updatedAt: row.updated_at.toISOString(),\n };\n}\n\nexport class PostgresTaskAttemptStore implements TaskAttemptStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async open(\n tenant: TenantId,\n input: { readonly taskId: string; readonly deviceId: string },\n ): Promise<TaskAttempt> {\n // First offer wins: a re-open returns the existing attempt untouched, so a\n // second offer cannot retarget a task at a different device.\n const inserted = await this.#pool.query<TaskRow>(\n `INSERT INTO task (tenant_id, task_id, device_id, owner_device_id, status, updated_at)\n VALUES ($1, $2, $3, NULL, 'offered', $4)\n ON CONFLICT (tenant_id, task_id) DO NOTHING\n RETURNING ${TASK_SELECT_COLUMNS}`,\n [tenant, input.taskId, input.deviceId, this.#now()],\n );\n const created = inserted.rows[0];\n if (created !== undefined) return taskRowToAttempt(created);\n\n const existing = await this.get(tenant, input.taskId);\n // Unreachable in practice: the insert only declines when the row exists.\n if (existing === undefined) throw new Error(`task ${input.taskId} vanished during open`);\n return existing;\n }\n\n async get(tenant: TenantId, taskId: string): Promise<TaskAttempt | undefined> {\n const result = await this.#pool.query<TaskRow>(\n `SELECT ${TASK_SELECT_COLUMNS} FROM task WHERE tenant_id = $1 AND task_id = $2`,\n [tenant, taskId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : taskRowToAttempt(row);\n }\n\n async getMany(tenant: TenantId, taskIds: readonly string[]): Promise<readonly TaskAttempt[]> {\n if (taskIds.length === 0) return [];\n const result = await this.#pool.query<TaskRow>(\n `SELECT ${TASK_SELECT_COLUMNS} FROM task WHERE tenant_id = $1 AND task_id = ANY($2::text[])`,\n [tenant, [...new Set(taskIds)]],\n );\n return result.rows.map(taskRowToAttempt);\n }\n\n async claim(\n tenant: TenantId,\n input: { readonly taskId: string; readonly deviceId: string },\n ): Promise<TaskAttempt | undefined> {\n const claimed = await this.#pool.query<TaskRow>(\n `UPDATE task\n SET owner_device_id = $3, status = 'claimed', updated_at = $4\n WHERE tenant_id = $1 AND task_id = $2 AND owner_device_id IS NULL\n AND cancel_requested_at IS NULL AND status = 'offered'\n RETURNING ${TASK_SELECT_COLUMNS}`,\n [tenant, input.taskId, input.deviceId, this.#now()],\n );\n const won = claimed.rows[0];\n if (won !== undefined) return taskRowToAttempt(won);\n\n // Either the task is already owned, or this tenant never offered it. The\n // re-read tells those apart without a second guard, and returns\n // `undefined` for the guess.\n return this.get(tenant, input.taskId);\n }\n\n async recordStatus(\n tenant: TenantId,\n input: { readonly taskId: string; readonly status: TaskAttemptStatus },\n ): Promise<TaskAttempt | undefined> {\n const result = await this.#pool.query<TaskRow>(\n `UPDATE task\n SET status = $3, updated_at = $4\n WHERE tenant_id = $1 AND task_id = $2\n AND (\n (cancel_requested_at IS NULL AND status NOT IN ('complete', 'failed', 'cancelled'))\n OR (cancel_requested_at IS NOT NULL AND $3 = 'cancelled' AND status <> 'cancelled')\n )\n RETURNING ${TASK_SELECT_COLUMNS}`,\n [tenant, input.taskId, input.status, this.#now()],\n );\n const row = result.rows[0];\n return row === undefined ? this.get(tenant, input.taskId) : taskRowToAttempt(row);\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * The one Postgres mailbox sequence allocator.\n *\n * The caller must already be in a transaction and must keep that transaction\n * open until its outbox row is inserted. The returned row lock is what makes a\n * lower sequence commit before any higher sequence for the same device.\n */\nimport type { TenantId } from '@byok-sdk/core';\nimport type { PoolClient } from 'pg';\n\nexport async function allocateMailboxSequence(\n client: PoolClient,\n tenant: TenantId,\n deviceId: string,\n now: string,\n): Promise<number> {\n const allocation = await client.query<{ readonly seq: bigint }>(\n `INSERT INTO device_stream (tenant_id, device_id, next_seq, acked_seq, acked_at)\n VALUES ($1, $2, 2, 0, $3)\n ON CONFLICT (tenant_id, device_id) DO UPDATE\n SET next_seq = device_stream.next_seq + 1\n RETURNING next_seq - 1 AS seq`,\n [tenant, deviceId, now],\n );\n return Number(allocation.rows[0]!.seq);\n}\n","/**\n * Postgres {@link MailboxStore} (§12.7.3).\n *\n * The load-bearing rule, and the one a composition can break silently:\n * **reading is not acknowledging.** `readAfter` is a `SELECT` and nothing else.\n * The only ack is `advanceCursor`, which the daemon calls after it has durably\n * journaled the envelope, and it is monotonic — a lower cursor is refused with\n * the cursor it lost to rather than quietly re-delivering work the device has\n * already run.\n *\n * `collectRetired` deletes acked rows and **marks** unacked ones `expired`. It\n * never deletes an unacked row. §12.7.5 requires an envelope that aged out\n * before anyone consumed it to stay visible; deleting it would make \"we dropped\n * work\" indistinguishable from \"there was no work\", and dead-lettering those\n * rows is S4B's job (O-009), not this one's.\n *\n * Every row lives under `(tenant_id, device_id, seq)`, so a cross-tenant read\n * is not denied — it addresses a different key space and finds nothing. That is\n * the SQL expression of §12.6.2 layer 3: there is no bare device index to\n * accidentally query.\n */\nimport {\n ByokCoreError,\n CoreConflictError,\n assertCanonicalTimestamp,\n type Clock,\n type ContentHash,\n type MailboxAdvanceCursorInput,\n type MailboxAppendInput,\n type MailboxCursorState,\n type MailboxMessage,\n type MailboxMessageState,\n type MailboxPage,\n type MailboxReadQuery,\n type MailboxRetentionInput,\n type MailboxRetentionResult,\n type MailboxStore,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { Pool } from 'pg';\nimport { allocateMailboxSequence } from './mailbox-sequence';\n\nconst DEFAULT_READ_LIMIT = 50;\n\nexport const OUTBOX_COLUMNS =\n 'tenant_id, device_id, seq, message_id, body, body_hash, byte_size, state, appended_at';\n\nexport interface OutboxRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly seq: bigint;\n readonly message_id: string;\n readonly body: string;\n readonly body_hash: string;\n readonly byte_size: bigint;\n readonly state: string;\n readonly appended_at: string;\n}\n\ninterface CursorRow {\n readonly acked_seq: bigint;\n readonly acked_at: string | null;\n}\n\ninterface RetentionRow {\n readonly deleted_count: bigint;\n readonly expired_count: bigint;\n readonly released_bytes: bigint;\n}\n\nexport function toMailboxMessage(row: OutboxRow): MailboxMessage {\n return {\n tenantId: row.tenant_id as TenantId,\n deviceId: row.device_id,\n // `seq` is bigint in the column and `number` on the port, because it is the\n // envelope `seq` on the wire. The column is wide so the counter cannot wrap\n // into a redelivery bug; the narrowing happens once, here.\n seq: Number(row.seq),\n messageId: row.message_id,\n body: row.body,\n bodyHash: row.body_hash as ContentHash,\n byteSize: row.byte_size,\n state: row.state as MailboxMessageState,\n appendedAt: row.appended_at,\n };\n}\n\nexport class PostgresMailboxStore implements MailboxStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async append(tenant: TenantId, input: MailboxAppendInput): Promise<MailboxMessage> {\n this.#requireDeviceId(input.deviceId);\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n\n const existing = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.messageId],\n );\n const replayed = existing.rows[0];\n if (replayed !== undefined) {\n await client.query('COMMIT');\n return toMailboxMessage(replayed);\n }\n\n // The device_stream row lock serializes the whole allocate -> materialize\n // -> insert unit. Releasing it before insertion would let seq N+1 become\n // visible before N; a daemon could then ack N+1 and permanently skip the\n // late N row.\n const seq = await allocateMailboxSequence(client, tenant, input.deviceId, this.#now());\n const serializedExisting = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.messageId],\n );\n const winnerAfterLock = serializedExisting.rows[0];\n if (winnerAfterLock !== undefined) {\n await client.query('ROLLBACK');\n return toMailboxMessage(winnerAfterLock);\n }\n const materialized = await input.materialize(seq);\n const now = this.#now();\n const inserted = await client.query<OutboxRow>(\n `INSERT INTO outbox (${OUTBOX_COLUMNS})\n VALUES ($1, $2, $3::bigint, $4, $5, $6, $7::bigint, 'pending', $8)\n ON CONFLICT (tenant_id, device_id, message_id) DO NOTHING\n RETURNING ${OUTBOX_COLUMNS}`,\n [\n tenant,\n input.deviceId,\n seq,\n input.messageId,\n materialized.body,\n materialized.bodyHash,\n materialized.byteSize,\n now,\n ],\n );\n const row = inserted.rows[0];\n if (row !== undefined) {\n await client.query('COMMIT');\n return toMailboxMessage(row);\n }\n\n // A concurrent append with the same idempotency key won while this\n // transaction waited on the per-device allocator. Roll back our sequence\n // bump so an idempotent retry consumes neither a row nor a number.\n const winner = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.messageId],\n );\n await client.query('ROLLBACK');\n const won = winner.rows[0];\n if (won === undefined) {\n throw new ByokCoreError(\n 'mailbox_message_not_found',\n `Message ${input.messageId} vanished during an idempotent append.`,\n );\n }\n return toMailboxMessage(won);\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n } finally {\n client.release();\n }\n }\n\n async readAfter(tenant: TenantId, query: MailboxReadQuery): Promise<MailboxPage> {\n const limit = query.limit ?? DEFAULT_READ_LIMIT;\n // One row past the page answers `hasMore` without a second count query, and\n // without the count and the page disagreeing about which snapshot they saw.\n const result = await this.#pool.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND state = 'pending' AND seq > $3::bigint\n ORDER BY seq\n LIMIT $4`,\n [tenant, query.deviceId, query.afterSeq, limit + 1],\n );\n\n const page = result.rows.slice(0, limit).map(toMailboxMessage);\n return {\n messages: page,\n // Nothing above was mutated, so an identical call replays the same page.\n // The returned position is a READ cursor and moves no ack.\n nextSeq: page.at(-1)?.seq ?? query.afterSeq,\n hasMore: result.rows.length > page.length,\n };\n }\n\n async advanceCursor(\n tenant: TenantId,\n input: MailboxAdvanceCursorInput,\n ): Promise<MailboxCursorState> {\n this.#requireDeviceId(input.deviceId);\n const now = this.#now();\n\n // The monotonic guard lives in `WHERE device_stream.acked_seq <=\n // EXCLUDED.acked_seq`, so a stale ack updates nothing rather than winning a\n // last-write race and re-opening envelopes the device already journaled.\n //\n // Marking the rows is folded into the same statement on purpose. Split\n // across two round trips, a crash between them would leave the cursor ahead\n // of the rows it acked, and `readAfter` would re-serve work the device has\n // run. When the guard rejects, `(SELECT acked_seq FROM moved)` is NULL and\n // `seq <= NULL` marks nothing — the rejection is total, not partial.\n const moved = await this.#pool.query<CursorRow>(\n `WITH moved AS (\n INSERT INTO device_stream (tenant_id, device_id, next_seq, acked_seq, acked_at)\n VALUES ($1, $2, 1, $3::bigint, $4)\n ON CONFLICT (tenant_id, device_id) DO UPDATE\n SET acked_seq = EXCLUDED.acked_seq, acked_at = EXCLUDED.acked_at\n WHERE device_stream.acked_seq <= EXCLUDED.acked_seq\n RETURNING acked_seq, acked_at\n ), marked AS (\n UPDATE outbox\n SET state = 'acked'\n WHERE tenant_id = $1 AND device_id = $2 AND state = 'pending'\n AND seq <= (SELECT acked_seq FROM moved)\n RETURNING 1\n )\n SELECT acked_seq, acked_at FROM moved`,\n [tenant, input.deviceId, input.ackedSeq, now],\n );\n\n const row = moved.rows[0];\n if (row !== undefined) {\n return {\n tenantId: tenant,\n deviceId: input.deviceId,\n ackedSeq: Number(row.acked_seq),\n updatedAt: row.acked_at ?? now,\n };\n }\n\n const current = await this.readCursor(tenant, input.deviceId);\n throw new CoreConflictError(\n 'mailbox_cursor_regression',\n `Cursor for device ${input.deviceId} is at ${current.ackedSeq}; refusing to move it back to ${input.ackedSeq}.`,\n current,\n this.#now(),\n );\n }\n\n async readCursor(tenant: TenantId, deviceId: string): Promise<MailboxCursorState> {\n const result = await this.#pool.query<CursorRow>(\n `SELECT acked_seq, acked_at FROM device_stream\n WHERE tenant_id = $1 AND device_id = $2`,\n [tenant, deviceId],\n );\n const row = result.rows[0];\n // No row, or a row the mailbox created without ever moving its cursor: the\n // position is 0 and there is no recorded ack instant to report, so the\n // read's own clock stands in.\n return {\n tenantId: tenant,\n deviceId,\n ackedSeq: row === undefined ? 0 : Number(row.acked_seq),\n updatedAt: row?.acked_at ?? this.#now(),\n };\n }\n\n async collectRetired(\n tenant: TenantId,\n input: MailboxRetentionInput,\n ): Promise<MailboxRetentionResult> {\n // Both cutoffs are compared against `appended_at` as text; the canonical\n // form is what makes that a time comparison rather than an arbitrary one.\n // Validate before the sweep so a malformed cutoff deletes nothing at all\n // rather than a wrong prefix of history.\n assertCanonicalTimestamp(input.ackedBefore, 'ackedBefore');\n assertCanonicalTimestamp(input.expireUnackedBefore, 'expireUnackedBefore');\n\n // Delete and dead-letter in one statement, so a sweep is all or nothing and\n // the two counts an operator reads describe the same moment. The two CTEs\n // select disjoint sets — one `acked`, one `pending` — so no row can be both\n // counted and marked.\n const swept = await this.#pool.query<RetentionRow>(\n `WITH deleted AS (\n DELETE FROM outbox\n WHERE tenant_id = $1\n AND ($2::text IS NULL OR device_id = $2::text)\n AND state = 'acked'\n AND appended_at < $3\n RETURNING byte_size\n ), expired AS (\n UPDATE outbox\n SET state = 'expired'\n WHERE tenant_id = $1\n AND ($2::text IS NULL OR device_id = $2::text)\n AND state = 'pending'\n AND appended_at < $4\n RETURNING 1\n )\n SELECT (SELECT count(*) FROM deleted) AS deleted_count,\n (SELECT count(*) FROM expired) AS expired_count,\n (SELECT COALESCE(SUM(byte_size), 0) FROM deleted)::bigint AS released_bytes`,\n [tenant, input.deviceId ?? null, input.ackedBefore, input.expireUnackedBefore],\n );\n\n const row = swept.rows[0]!;\n return {\n deletedCount: Number(row.deleted_count),\n expiredCount: Number(row.expired_count),\n releasedBytes: row.released_bytes,\n };\n }\n\n /**\n * The in-memory reference refuses an empty device id rather than opening a\n * mailbox nothing can address. Kept here so the two compositions answer the\n * same way; the table itself would happily store the row.\n */\n #requireDeviceId(deviceId: string): void {\n if (deviceId.length === 0) {\n throw new ByokCoreError('mailbox_message_not_found', 'Device id must not be empty.');\n }\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","import type {\n TaskCancellationMutation,\n TaskCancellationRequest,\n TaskCancellationStore,\n} from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\nimport {\n OUTBOX_COLUMNS,\n type OutboxRow,\n toMailboxMessage,\n} from './core/mailbox';\nimport { allocateMailboxSequence } from './core/mailbox-sequence';\nimport {\n TASK_SELECT_COLUMNS,\n type TaskRow,\n taskRowToAttempt,\n} from './task-attempts';\n\n/** PostgreSQL atomic authority for host cancellation state plus mailbox delivery. */\nexport class PostgresTaskCancellationStore implements TaskCancellationStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async request(\n tenant: TenantId,\n input: TaskCancellationRequest,\n ): Promise<TaskCancellationMutation | undefined> {\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n const selected = await client.query<TaskRow>(\n `SELECT ${TASK_SELECT_COLUMNS} FROM task\n WHERE tenant_id = $1 AND task_id = $2\n FOR UPDATE`,\n [tenant, input.taskId],\n );\n const current = selected.rows[0];\n if (current === undefined) {\n await client.query('ROLLBACK');\n return undefined;\n }\n\n if (\n current.cancel_requested_at === null &&\n (current.status === 'complete' || current.status === 'failed' || current.status === 'cancelled')\n ) {\n await client.query('COMMIT');\n return { attempt: taskRowToAttempt(current) };\n }\n\n if (current.cancel_message_id !== null) {\n const replayed = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, current.device_id, current.cancel_message_id],\n );\n const message = replayed.rows[0];\n if (message === undefined) {\n // Acked mailbox rows are retention-deletable. Once the attempt is\n // cancelled, the tombstone remains the durable idempotency outcome\n // even after that delivery evidence ages out. A still-requested\n // attempt with no row is corruption and must continue to fail closed.\n if (current.status === 'cancelled') {\n await client.query('COMMIT');\n return { attempt: taskRowToAttempt(current) };\n }\n throw new Error(`Cancellation delivery ${current.cancel_message_id} is missing for task ${input.taskId}`);\n }\n await client.query('COMMIT');\n return { attempt: taskRowToAttempt(current), message: toMailboxMessage(message) };\n }\n\n const now = this.#clock.now().toISOString();\n const messageId = input.proposedMessageId;\n const seq = await allocateMailboxSequence(client, tenant, current.device_id, now);\n const materialized = await input.materialize(seq, messageId);\n const insertedMessage = await client.query<OutboxRow>(\n `INSERT INTO outbox (${OUTBOX_COLUMNS})\n VALUES ($1, $2, $3::bigint, $4, $5, $6, $7::bigint, 'pending', $8)\n RETURNING ${OUTBOX_COLUMNS}`,\n [\n tenant,\n current.device_id,\n seq,\n messageId,\n materialized.body,\n materialized.bodyHash,\n materialized.byteSize,\n now,\n ],\n );\n const updated = await client.query<TaskRow>(\n `UPDATE task\n SET status = CASE WHEN owner_device_id IS NULL THEN 'cancelled' ELSE 'cancel_requested' END,\n cancel_requested_at = $3,\n cancel_reason = $4,\n cancel_message_id = $5,\n updated_at = $3\n WHERE tenant_id = $1 AND task_id = $2\n RETURNING ${TASK_SELECT_COLUMNS}`,\n [tenant, input.taskId, now, input.reason ?? null, messageId],\n );\n await client.query('COMMIT');\n return {\n attempt: taskRowToAttempt(updated.rows[0]!),\n message: toMailboxMessage(insertedMessage.rows[0]!),\n };\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n } finally {\n client.release();\n }\n }\n}\n","import {\n ByokCloudError,\n activityCursor,\n parseTimelineEvents,\n projectTimelineEvents,\n validateActivityAppend,\n type ActivityAppendInput,\n type ActivityStore,\n type ActivityTail,\n} from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\ninterface TailRow {\n readonly tenant_id: string;\n readonly task_id: string;\n readonly entries: unknown;\n readonly dropped: number;\n readonly capacity: number;\n readonly expires_at: string;\n}\n\nfunction toTail(row: TailRow): ActivityTail {\n const entries = parseTimelineEvents(row.entries);\n const cursor = activityCursor(entries);\n return {\n tenantId: row.tenant_id as TenantId,\n taskId: row.task_id,\n entries,\n ...(cursor === undefined ? {} : { cursor }),\n dropped: row.dropped,\n capacity: row.capacity,\n expiresAt: row.expires_at,\n };\n}\n\nexport class PostgresActivityStore implements ActivityStore {\n constructor(\n private readonly pool: Pool,\n private readonly clock: Clock,\n ) {}\n\n async append(tenant: TenantId, input: ActivityAppendInput): Promise<ActivityTail> {\n const capacity = validateActivityAppend(input);\n const now = this.clock.now();\n const receivedAt = now.toISOString();\n const incoming = projectTimelineEvents(input, receivedAt);\n const expiresAt = new Date(now.getTime() + input.ttlMs).toISOString();\n\n // The conflict arm reads activity_tail only after Postgres acquires the row\n // lock. It sorts the combined typed DTOs by the stable order key before\n // trimming, so concurrent or delayed batches have the same observable tail\n // as the in-memory reference.\n const result = await this.pool.query<TailRow>(\n `WITH incoming AS (\n SELECT entry\n FROM jsonb_array_elements($4::jsonb) AS element(entry)\n ), trimmed AS (\n SELECT COALESCE(jsonb_agg(entry ORDER BY\n (entry->>'batchSeq')::bigint,\n (entry->>'eventIndex')::bigint), '[]'::jsonb) AS entries,\n $5::integer + GREATEST(jsonb_array_length($4::jsonb) - $6, 0) AS dropped\n FROM (\n SELECT entry\n FROM incoming\n ORDER BY (entry->>'batchSeq')::bigint DESC,\n (entry->>'eventIndex')::bigint DESC\n LIMIT $6\n ) retained\n )\n INSERT INTO activity_tail (tenant_id, task_id, entries, dropped, capacity, expires_at)\n SELECT $1, $2, trimmed.entries, trimmed.dropped, $6, $7 FROM trimmed\n ON CONFLICT (tenant_id, task_id) DO UPDATE\n SET entries = (\n SELECT COALESCE(jsonb_agg(entry ORDER BY\n (entry->>'batchSeq')::bigint,\n (entry->>'eventIndex')::bigint), '[]'::jsonb)\n FROM (\n SELECT entry\n FROM jsonb_array_elements(\n (CASE WHEN activity_tail.expires_at > $3\n THEN activity_tail.entries ELSE '[]'::jsonb END) || $4::jsonb\n ) AS element(entry)\n ORDER BY (entry->>'batchSeq')::bigint DESC,\n (entry->>'eventIndex')::bigint DESC\n LIMIT $6\n ) retained\n ),\n dropped = (CASE WHEN activity_tail.expires_at > $3\n THEN activity_tail.dropped ELSE 0 END)\n + $5::integer\n + GREATEST(\n jsonb_array_length(\n (CASE WHEN activity_tail.expires_at > $3\n THEN activity_tail.entries ELSE '[]'::jsonb END) || $4::jsonb\n ) - $6,\n 0\n ),\n capacity = EXCLUDED.capacity,\n expires_at = EXCLUDED.expires_at\n WHERE activity_tail.expires_at <= $3\n OR (\n NOT EXISTS (\n SELECT 1\n FROM jsonb_array_elements(activity_tail.entries) AS stored(entry)\n WHERE jsonb_typeof(entry) <> 'object'\n OR NOT (entry ?& ARRAY[\n 'taskId', 'sourceEnvelopeId', 'batchSeq',\n 'eventIndex', 'receivedAt', 'event'\n ])\n )\n AND NOT EXISTS (\n SELECT 1\n FROM jsonb_array_elements(activity_tail.entries) AS old_element(entry)\n CROSS JOIN jsonb_array_elements($4::jsonb) AS new_element(candidate)\n WHERE (entry->>'batchSeq')::bigint = (candidate->>'batchSeq')::bigint\n AND (entry->>'eventIndex')::bigint = (candidate->>'eventIndex')::bigint\n AND entry->>'sourceEnvelopeId' <> candidate->>'sourceEnvelopeId'\n )\n )\n RETURNING tenant_id, task_id, entries, dropped, capacity, expires_at`,\n [tenant, input.taskId, receivedAt, JSON.stringify(incoming), input.dropped, capacity, expiresAt],\n );\n const row = result.rows[0];\n if (row === undefined) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Activity batch ${input.batchSeq} conflicts with the existing typed tail authority.`,\n );\n }\n return toTail(row);\n }\n\n async read(tenant: TenantId, taskId: string): Promise<ActivityTail | undefined> {\n const result = await this.pool.query<TailRow>(\n `SELECT tenant_id, task_id, entries, dropped, capacity, expires_at\n FROM activity_tail\n WHERE tenant_id = $1 AND task_id = $2 AND expires_at > $3`,\n [tenant, taskId, this.clock.now().toISOString()],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toTail(row);\n }\n}\n","import {\n ApprovalObservationSchema,\n ByokCloudError,\n approvalTimelineCursor,\n parseApprovalObservations,\n validateApprovalTimelineAppend,\n type ApprovalTimelineAppendInput,\n type ApprovalTimelineStore,\n type ApprovalTimelineTail,\n} from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool, PoolClient } from 'pg';\n\ninterface TailRow {\n readonly tenant_id: string;\n readonly task_id: string;\n readonly entries: unknown;\n readonly next_revision: string | number | bigint;\n readonly dropped: number;\n readonly capacity: number;\n readonly expires_at: string;\n}\n\nfunction toTail(row: TailRow): ApprovalTimelineTail {\n const entries = parseApprovalObservations(row.entries);\n const cursor = approvalTimelineCursor(entries);\n return {\n tenantId: row.tenant_id as TenantId,\n taskId: row.task_id,\n entries,\n ...(cursor === undefined ? {} : { cursor }),\n dropped: row.dropped,\n capacity: row.capacity,\n expiresAt: row.expires_at,\n };\n}\n\nasync function readLocked(\n client: PoolClient,\n tenant: TenantId,\n taskId: string,\n): Promise<TailRow | undefined> {\n const result = await client.query<TailRow>(\n `SELECT tenant_id, task_id, entries, next_revision, dropped, capacity, expires_at\n FROM approval_timeline_tail\n WHERE tenant_id = $1 AND task_id = $2\n FOR UPDATE`,\n [tenant, taskId],\n );\n return result.rows[0];\n}\n\nexport class PostgresApprovalTimelineStore implements ApprovalTimelineStore {\n constructor(\n private readonly pool: Pool,\n private readonly clock: Clock,\n ) {}\n\n async append(\n tenant: TenantId,\n input: ApprovalTimelineAppendInput,\n ): Promise<ApprovalTimelineTail> {\n const { capacity, ttlMs, event } = validateApprovalTimelineAppend(input);\n const now = this.clock.now();\n const receivedAt = now.toISOString();\n const expiresAt = new Date(now.getTime() + ttlMs).toISOString();\n const client = await this.pool.connect();\n try {\n await client.query('BEGIN');\n await client.query(\n `SELECT pg_advisory_xact_lock(hashtextextended($1 || E'\\\\x1f' || $2, 0))`,\n [tenant, input.taskId],\n );\n const stored = await readLocked(client, tenant, input.taskId);\n const live = stored !== undefined && receivedAt < stored.expires_at ? toTail(stored) : undefined;\n const duplicate = live?.entries.find(\n (entry) => entry.sourceEnvelopeId === input.sourceEnvelopeId,\n );\n if (duplicate !== undefined) {\n if (JSON.stringify(duplicate.event) !== JSON.stringify(event)) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Approval source envelope identity already belongs to another lifecycle event.',\n );\n }\n await client.query('COMMIT');\n return live!;\n }\n\n const revision = live === undefined ? 1 : Number(stored!.next_revision);\n const expectedRevision = (live?.cursor ?? 0) + 1;\n if (\n !Number.isSafeInteger(revision) ||\n revision <= 0 ||\n revision !== expectedRevision\n ) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Approval timeline revision authority is malformed.',\n );\n }\n const observation = ApprovalObservationSchema.parse({\n taskId: input.taskId,\n sourceEnvelopeId: input.sourceEnvelopeId,\n revision,\n receivedAt,\n event,\n });\n const allEntries = [...(live?.entries ?? []), observation];\n const evicted = Math.max(allEntries.length - capacity, 0);\n const entries = allEntries.slice(evicted);\n const dropped = (live?.dropped ?? 0) + evicted;\n const result = await client.query<TailRow>(\n `INSERT INTO approval_timeline_tail\n (tenant_id, task_id, entries, next_revision, dropped, capacity, expires_at)\n VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)\n ON CONFLICT (tenant_id, task_id) DO UPDATE\n SET entries = EXCLUDED.entries,\n next_revision = EXCLUDED.next_revision,\n dropped = EXCLUDED.dropped,\n capacity = EXCLUDED.capacity,\n expires_at = EXCLUDED.expires_at\n RETURNING tenant_id, task_id, entries, next_revision, dropped, capacity, expires_at`,\n [\n tenant,\n input.taskId,\n JSON.stringify(entries),\n revision + 1,\n dropped,\n capacity,\n expiresAt,\n ],\n );\n await client.query('COMMIT');\n return toTail(result.rows[0]!);\n } catch (caught) {\n await client.query('ROLLBACK');\n throw caught;\n } finally {\n client.release();\n }\n }\n\n async read(tenant: TenantId, taskId: string): Promise<ApprovalTimelineTail | undefined> {\n const result = await this.pool.query<TailRow>(\n `SELECT tenant_id, task_id, entries, next_revision, dropped, capacity, expires_at\n FROM approval_timeline_tail\n WHERE tenant_id = $1 AND task_id = $2 AND expires_at > $3`,\n [tenant, taskId, this.clock.now().toISOString()],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toTail(row);\n }\n}\n","import type {\n DeviceAssertionReplayAuthority,\n DeviceAssertionReplayConsumeInput,\n} from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\n/** Durable atomic replay authority for hosted device-assertion exchange. */\nexport class PostgresDeviceAssertionReplayAuthority implements DeviceAssertionReplayAuthority {\n readonly #pool: Pool;\n\n constructor(pool: Pool) {\n this.#pool = pool;\n }\n\n async consume(input: DeviceAssertionReplayConsumeInput): Promise<boolean> {\n if (!Number.isFinite(Date.parse(input.expiresAt))) {\n throw new Error('device assertion replay expiry is invalid');\n }\n const result = await this.#pool.query(\n `INSERT INTO device_assertion_replay (\n tenant_id, issuer, product_id, device_id, audience, jti, expires_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (tenant_id, issuer, product_id, device_id, audience, jti) DO NOTHING\n RETURNING jti`,\n [\n input.tenantId,\n input.issuer,\n input.productId,\n input.deviceId,\n input.audience,\n input.jti,\n input.expiresAt,\n ],\n );\n return result.rowCount === 1;\n }\n\n /** Bounded retention cleanup; callers choose cadence and batch size. */\n async deleteExpired(before: Date, limit: number): Promise<number> {\n if (!Number.isFinite(before.getTime()) || !Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error('device assertion replay cleanup bounds are invalid');\n }\n const result = await this.#pool.query(\n `DELETE FROM device_assertion_replay\n WHERE ctid IN (\n SELECT ctid\n FROM device_assertion_replay\n WHERE expires_at <= $1\n ORDER BY expires_at\n LIMIT $2\n )`,\n [before.toISOString(), limit],\n );\n return result.rowCount ?? 0;\n }\n}\n","/**\n * The Postgres composition of the cloud-local ports.\n *\n * Nine durable stores, one object-storage blob store, one in-memory limiter:\n *\n * - Six durable ones have rows in `deploy/sql/0001_cloud_local.sql`; S6's\n * proof receipt authority is the seventh, in `0004_device_proof_truth.sql`;\n * typed activity uses the JSONB tail row in `0002_core_domain.sql`; approval\n * lifecycle observations use `0007_approval_timeline.sql`.\n * - `blobs` is the R2 adapter over the `object_manifest` row the core store\n * already owns: metadata in Postgres, bytes in the object store, one\n * reserve/verify protocol binding them (design §6). It supplies grants only,\n * and this composition deliberately hands `createByokCloud` NO\n * `BlobContentProxy` — a device uploading straight to R2 is what having no\n * byte-proxy path means, and saying so by absence is what keeps the two\n * `/content` routes from mounting on a deployment that cannot serve them.\n * - `rateLimiter` gets the allow-all reference and NO table, by design\n * (docs/researches/s4a-dataplane-design.md §5). Persisting an allow-all would\n * create a table that is always empty, and a real limiter is edge/infra work\n * whose implementation would not be a per-request Postgres write either.\n */\nimport { AllowAllRateLimiter, type CloudStores } from '@byok-sdk/cloud';\nimport type { CloudCrypto } from '@byok-sdk/cloud';\nimport type { Clock } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\nimport { PostgresObjectStore } from './core/objects';\nimport { R2CloudBlobStore, type R2BlobStoreOptions } from './r2-blobs';\nimport { PostgresDeviceDirectory } from './devices';\nimport { PostgresInboundDedupStore } from './dedup';\nimport { PostgresNonceStore } from './nonces';\nimport { PostgresPairingCodeStore } from './pairing-codes';\nimport { PostgresRequestReceiptStore } from './receipts';\nimport { PostgresProofRequestReceiptStore } from './proof-receipts';\nimport { PostgresTaskAttemptStore } from './task-attempts';\nimport { PostgresTaskCancellationStore } from './task-cancellations';\nimport { PostgresActivityStore } from './activity';\nimport { PostgresApprovalTimelineStore } from './approval-timeline';\n\nexport { PostgresDeviceDirectory } from './devices';\nexport { PostgresInboundDedupStore } from './dedup';\nexport { PostgresNonceStore } from './nonces';\nexport { PostgresPairingCodeStore } from './pairing-codes';\nexport { PostgresRequestReceiptStore } from './receipts';\nexport { PostgresProofRequestReceiptStore } from './proof-receipts';\nexport { PostgresTaskAttemptStore } from './task-attempts';\nexport { PostgresTaskCancellationStore } from './task-cancellations';\nexport { PostgresActivityStore } from './activity';\nexport { PostgresApprovalTimelineStore } from './approval-timeline';\nexport { PostgresDeviceAssertionReplayAuthority } from './device-assertion-replay';\nexport {\n DEFAULT_MAX_ATTEMPTS,\n DEFAULT_PRESIGN_TTL_SECONDS,\n DEFAULT_RETRY_DELAY_MS,\n MAX_PRESIGN_TTL_SECONDS,\n MIN_PRESIGN_TTL_SECONDS,\n ObjectStoreRequestError,\n R2_BLOB_ERROR_CODES,\n R2BlobStoreError,\n R2CloudBlobStore,\n R2ObjectMaintenanceStore,\n} from './r2-blobs';\nexport type { ObjectStoreFetch, R2BlobErrorCode, R2BlobStoreOptions } from './r2-blobs';\nexport type {\n R2DeleteResult,\n R2ListedObject,\n R2ObjectMaintenance,\n R2ObjectMaintenanceOptions,\n R2ObjectPage,\n} from './r2-blobs';\n\n/** Every cloud-local port. All eleven, or it is not a composition. */\nexport type PostgresCloudStores = CloudStores;\n\n/** Everything the blob store needs that is not already a composition-wide input. */\nexport type PostgresObjectStorageOptions = Omit<R2BlobStoreOptions, 'objects'>;\n\nexport interface PostgresCloudStoreOptions {\n readonly pool: Pool;\n /**\n * The clock every TTL and timestamp in this composition reads. Injected, not\n * the database's own: expiry has to be assertable under a test clock, and a\n * store that asks the server for the time cannot be.\n */\n readonly clock: Clock;\n readonly crypto: CloudCrypto;\n /**\n * Where the bytes go. Required, because a composition that cannot say where\n * its objects live cannot honestly claim the `blobs` port — and the\n * conformance suite certifies compositions whole, never in parts.\n */\n readonly objectStorage: PostgresObjectStorageOptions;\n}\n\nexport function createPostgresCloudStores(\n options: PostgresCloudStoreOptions,\n): PostgresCloudStores {\n const { pool, clock, crypto } = options;\n return {\n activity: new PostgresActivityStore(pool, clock),\n approvals: new PostgresApprovalTimelineStore(pool, clock),\n devices: new PostgresDeviceDirectory(pool, clock),\n pairingCodes: new PostgresPairingCodeStore(pool, clock),\n nonces: new PostgresNonceStore(pool, clock, crypto),\n dedup: new PostgresInboundDedupStore(pool),\n tasks: new PostgresTaskAttemptStore(pool, clock),\n cancellations: new PostgresTaskCancellationStore(pool, clock),\n receipts: new PostgresRequestReceiptStore(pool, clock),\n proofReceipts: new PostgresProofRequestReceiptStore(pool, clock),\n // A second `PostgresObjectStore` instance, not a shared one: it is a\n // stateless wrapper over the pool, so the two read and write the same rows\n // under the same locks, and requiring the caller to build the core\n // composition first would be an ordering dependency bought for nothing.\n blobs: new R2CloudBlobStore({\n ...options.objectStorage,\n objects: new PostgresObjectStore(pool, clock),\n }),\n rateLimiter: new AllowAllRateLimiter(),\n };\n}\n","/**\n * Postgres {@link PresenceStore} (§12.3).\n *\n * Presence is lossy, TTL-bounded, unsigned, and never authoritative. It is a\n * bounded upsert with one row per device. Nothing here may be\n * used to derive coordination state, execution state, authorization, billing or\n * recovery — which is why this file shares no vocabulary with `board.ts` and\n * none with the frozen wire states.\n *\n * **Expiry is absence, and it is expressed as a read filter.** A hint past its\n * `expiresAt` is invisible to every read, so no reader can observe a stale\n * level and mistake it for a live one. The in-memory reference deletes the\n * entry lazily on read; here the row stays and the predicate excludes it. Same\n * observable answer, and a `SELECT` that does not write to answer itself.\n *\n * Every instant is the injected clock's. Asserting TTL behavior against a wall\n * clock means sleeping or accepting flakes, which is why the port takes `ttlMs`\n * and the composition supplies the clock.\n */\nimport {\n ByokCoreError,\n type Clock,\n type PresenceHint,\n type PresenceHintInput,\n type PresenceLevel,\n type PresenceRuntimeFact,\n type PresenceStore,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\nconst PRESENCE_COLUMNS =\n 'tenant_id, device_id, level, detail, configured_toolsets, client_version, protocol_versions, runtimes, observed_at, expires_at';\n\ninterface PresenceRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly level: string;\n readonly detail: string | null;\n readonly configured_toolsets: readonly string[] | null;\n readonly client_version: string | null;\n readonly protocol_versions: readonly number[] | null;\n readonly runtimes: readonly PresenceRuntimeFact[] | null;\n readonly observed_at: string;\n readonly expires_at: string;\n}\n\nfunction toHint(row: PresenceRow): PresenceHint {\n return {\n tenantId: row.tenant_id as TenantId,\n deviceId: row.device_id,\n level: row.level as PresenceLevel,\n ...(row.detail === null ? {} : { detail: row.detail }),\n ...(row.configured_toolsets === null\n ? {}\n : { configuredToolsets: Object.freeze([...row.configured_toolsets]) }),\n ...(row.client_version === null ? {} : { clientVersion: row.client_version }),\n ...(row.protocol_versions === null\n ? {}\n : { protocolVersions: Object.freeze([...row.protocol_versions]) }),\n ...(row.runtimes === null\n ? {}\n : {\n runtimes: Object.freeze(\n row.runtimes.map((runtime) =>\n Object.freeze({\n id: runtime.id,\n ...(runtime.version === undefined ? {} : { version: runtime.version }),\n ...(runtime.authPresent === undefined ? {} : { authPresent: runtime.authPresent }),\n }),\n ),\n ),\n }),\n observedAt: row.observed_at,\n expiresAt: row.expires_at,\n };\n}\n\nfunction assertTtl(ttlMs: number): void {\n if (!Number.isFinite(ttlMs) || ttlMs <= 0) {\n throw new ByokCoreError(\n 'hint_ttl_invalid',\n `Hint ttl must be a positive number of milliseconds, received ${String(ttlMs)}.`,\n );\n }\n}\n\nfunction assertMinimumInterval(minimumIntervalMs: number): void {\n if (!Number.isFinite(minimumIntervalMs) || minimumIntervalMs < 0) {\n throw new ByokCoreError(\n 'hint_ttl_invalid',\n `Hint minimum interval must be a non-negative number of milliseconds, received ${String(minimumIntervalMs)}.`,\n );\n }\n}\n\nexport class PostgresPresenceStore implements PresenceStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async publish(tenant: TenantId, input: PresenceHintInput): Promise<PresenceHint> {\n assertTtl(input.ttlMs);\n assertMinimumInterval(input.minimumIntervalMs);\n const now = this.#clock.now();\n const observedAt = now.toISOString();\n const allowedBefore = new Date(now.getTime() - input.minimumIntervalMs).toISOString();\n const result = await this.#pool.query<PresenceRow>(\n `INSERT INTO device_presence (${PRESENCE_COLUMNS})\n VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7::jsonb, $8::jsonb, $9, $10)\n ON CONFLICT (tenant_id, device_id) DO UPDATE\n SET level = EXCLUDED.level,\n detail = EXCLUDED.detail,\n configured_toolsets = EXCLUDED.configured_toolsets,\n client_version = EXCLUDED.client_version,\n protocol_versions = EXCLUDED.protocol_versions,\n runtimes = EXCLUDED.runtimes,\n observed_at = EXCLUDED.observed_at,\n expires_at = EXCLUDED.expires_at\n WHERE device_presence.expires_at <= EXCLUDED.observed_at\n OR device_presence.observed_at <= $11\n RETURNING ${PRESENCE_COLUMNS}`,\n [\n tenant,\n input.deviceId,\n input.level,\n input.detail ?? null,\n input.configuredToolsets === undefined ? null : JSON.stringify(input.configuredToolsets),\n input.clientVersion ?? null,\n input.protocolVersions === undefined ? null : JSON.stringify(input.protocolVersions),\n input.runtimes === undefined ? null : JSON.stringify(input.runtimes),\n observedAt,\n new Date(now.getTime() + input.ttlMs).toISOString(),\n allowedBefore,\n ],\n );\n const row = result.rows[0];\n if (row === undefined) {\n throw new ByokCoreError(\n 'hint_rate_limited',\n `Presence for ${input.deviceId} was published more recently than the configured minimum interval.`,\n );\n }\n return toHint(row);\n }\n\n async read(tenant: TenantId, deviceId: string): Promise<PresenceHint | undefined> {\n const result = await this.#pool.query<PresenceRow>(\n `SELECT ${PRESENCE_COLUMNS} FROM device_presence\n WHERE tenant_id = $1 AND device_id = $2 AND expires_at > $3`,\n [tenant, deviceId, this.#now()],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toHint(row);\n }\n\n async list(tenant: TenantId): Promise<readonly PresenceHint[]> {\n const result = await this.#pool.query<PresenceRow>(\n `SELECT ${PRESENCE_COLUMNS} FROM device_presence\n WHERE tenant_id = $1 AND expires_at > $2\n ORDER BY device_id COLLATE \"C\"`,\n [tenant, this.#now()],\n );\n return result.rows.map(toHint);\n }\n\n #expiry(ttlMs: number): string {\n return new Date(this.#clock.now().getTime() + ttlMs).toISOString();\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * Postgres {@link BoardStore} (§12.3).\n *\n * Every mutation is one guarded `UPDATE ... WHERE`, and the guard carries the\n * caller's whole expectation: who holds the item, what status it is in, and —\n * for `claim` — that it is claimable at all. Zero rows is the rejection, and\n * the store then re-reads the item to say WHICH rejection and to hand the\n * caller the snapshot it lost to. A conflict that reports only \"conflict\"\n * forces a second round trip and invites a retry loop that eventually\n * overwrites the winner (§12.3: no silent last-write-wins).\n *\n * The concurrent-claim property comes out of Postgres' own re-check: three\n * sessions issue the same `UPDATE ... WHERE holder_id IS NULL`, one wins, and\n * the other two re-evaluate the qual against the winner's committed row and\n * match nothing. The suite asserts the outcome, not the mechanism — the\n * in-memory reference gets the same outcome from its `await` boundaries.\n *\n * **`board_seq` is allocated in its own statement, before the guarded write.**\n * Folding the allocator into a data-modifying CTE would let one session lock\n * `tenant_stream` then `board_item` while another locks them in the order the\n * planner picked for it, which is a deadlock rather than a conflict. Allocating\n * first, in an autocommitted statement that releases immediately, gives every\n * writer one lock order. A rejected write therefore burns a sequence number:\n * `boardSeq` is contractually monotonic, never contractually gapless, and the\n * incremental feed reads `> afterSeq` either way.\n */\nimport {\n ByokCoreError,\n CoreConflictError,\n isLegalBoardTransition,\n type BoardClaimInput,\n type BoardItem,\n type BoardItemInput,\n type BoardListQuery,\n type BoardPage,\n type BoardStatus,\n type BoardStatusUpdateInput,\n type BoardStore,\n type BoardUnclaimInput,\n type Clock,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\nconst DEFAULT_LIST_LIMIT = 50;\n\nconst BOARD_COLUMNS =\n 'tenant_id, item_id, channel, title, status, holder_id, held_since, board_seq, created_at, updated_at';\n\ninterface BoardRow {\n readonly tenant_id: string;\n readonly item_id: string;\n readonly channel: string;\n readonly title: string;\n readonly status: string;\n readonly holder_id: string | null;\n readonly held_since: string | null;\n readonly board_seq: bigint;\n readonly created_at: string;\n readonly updated_at: string;\n}\n\nfunction toItem(row: BoardRow): BoardItem {\n return {\n tenantId: row.tenant_id as TenantId,\n itemId: row.item_id,\n channel: row.channel,\n title: row.title,\n status: row.status as BoardStatus,\n // An unheld item has NO assignee rather than an assignee with an empty\n // holder, which is what lets `expect(item.assignee).toBeUndefined()` mean\n // \"nobody holds this\" in both compositions.\n ...(row.holder_id === null || row.held_since === null\n ? {}\n : { assignee: { holderId: row.holder_id, heldSince: row.held_since } }),\n boardSeq: Number(row.board_seq),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nexport class PostgresBoardStore implements BoardStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async create(tenant: TenantId, input: BoardItemInput): Promise<BoardItem> {\n const now = this.#now();\n const boardSeq = await this.#allocateSeq(tenant);\n const inserted = await this.#pool.query<BoardRow>(\n `INSERT INTO board_item (${BOARD_COLUMNS})\n VALUES ($1, $2, $3, $4, $5, NULL, NULL, $6::bigint, $7, $7)\n ON CONFLICT (tenant_id, item_id) DO NOTHING\n RETURNING ${BOARD_COLUMNS}`,\n [tenant, input.itemId, input.channel, input.title, input.status ?? 'todo', boardSeq, now],\n );\n const row = inserted.rows[0];\n if (row === undefined) {\n throw new ByokCoreError(\n 'board_item_exists',\n `Board item ${input.itemId} already exists in this tenant.`,\n );\n }\n return toItem(row);\n }\n\n async get(tenant: TenantId, itemId: string): Promise<BoardItem | undefined> {\n const result = await this.#pool.query<BoardRow>(\n `SELECT ${BOARD_COLUMNS} FROM board_item WHERE tenant_id = $1 AND item_id = $2`,\n [tenant, itemId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toItem(row);\n }\n\n async list(tenant: TenantId, query: BoardListQuery): Promise<BoardPage> {\n const afterSeq = query.afterSeq ?? 0;\n const limit = query.limit ?? DEFAULT_LIST_LIMIT;\n const result = await this.#pool.query<BoardRow>(\n `SELECT ${BOARD_COLUMNS} FROM board_item\n WHERE tenant_id = $1\n AND board_seq > $2::bigint\n AND ($3::text IS NULL OR channel = $3::text)\n AND ($4::text IS NULL OR status = $4::text)\n ORDER BY board_seq\n LIMIT $5`,\n [tenant, afterSeq, query.channel ?? null, query.status ?? null, limit + 1],\n );\n\n const page = result.rows.slice(0, limit).map(toItem);\n return {\n items: page,\n nextSeq: page.at(-1)?.boardSeq ?? afterSeq,\n hasMore: result.rows.length > page.length,\n };\n }\n\n async claim(tenant: TenantId, input: BoardClaimInput): Promise<BoardItem> {\n const expectedStatus = input.expectedStatus ?? 'todo';\n const now = this.#now();\n const boardSeq = await this.#allocateSeq(tenant);\n\n // `holder_id IS NULL` is the CAS on \"unheld\"; `status = $4` is the caller's\n // status expectation; `status IN ('todo','in_progress')` is the claimability\n // rule. All three in one guard, so exactly one concurrent caller wins.\n const claimed = await this.#pool.query<BoardRow>(\n `UPDATE board_item\n SET status = CASE WHEN status = 'todo' THEN 'in_progress' ELSE status END,\n holder_id = $3,\n held_since = $5,\n board_seq = $6::bigint,\n updated_at = $5\n WHERE tenant_id = $1 AND item_id = $2\n AND holder_id IS NULL\n AND status = $4::text\n AND status IN ('todo', 'in_progress')\n RETURNING ${BOARD_COLUMNS}`,\n [tenant, input.itemId, input.holderId, expectedStatus, now, boardSeq],\n );\n const won = claimed.rows[0];\n if (won !== undefined) return toItem(won);\n\n const current = await this.get(tenant, input.itemId);\n if (current === undefined) throw this.#itemNotFound(input.itemId);\n\n if (current.assignee !== undefined) {\n if (current.assignee.holderId === input.holderId) {\n // The same holder retrying is not a second winner. But an EXPLICIT\n // `expectedStatus` is a full CAS by contract, and short-circuiting past\n // it here would let the holder's retry confirm a status it no longer\n // believes in. The `todo` default is deliberately not applied on this\n // path: a retry of a successful claim legitimately observes\n // `in_progress`.\n if (input.expectedStatus !== undefined && current.status !== input.expectedStatus) {\n throw this.#statusConflict(input.itemId, current, input.expectedStatus);\n }\n return current;\n }\n throw new CoreConflictError(\n 'board_claim_conflict',\n `Board item ${input.itemId} is held by ${current.assignee.holderId}.`,\n current,\n this.#now(),\n );\n }\n if (current.status !== expectedStatus) {\n throw this.#statusConflict(input.itemId, current, expectedStatus);\n }\n throw new CoreConflictError(\n 'board_transition_invalid',\n `Board item ${input.itemId} cannot be claimed from ${current.status}.`,\n current,\n this.#now(),\n );\n }\n\n async unclaim(tenant: TenantId, input: BoardUnclaimInput): Promise<BoardItem> {\n const now = this.#now();\n const boardSeq = await this.#allocateSeq(tenant);\n\n // Releasing someone else's item is not a legal move, so the holder is part\n // of the guard rather than a comparison the caller is trusted to have made.\n const released = await this.#pool.query<BoardRow>(\n `UPDATE board_item\n SET status = CASE WHEN status = 'in_progress' THEN 'todo' ELSE status END,\n holder_id = NULL,\n held_since = NULL,\n board_seq = $4::bigint,\n updated_at = $5\n WHERE tenant_id = $1 AND item_id = $2 AND holder_id = $3\n RETURNING ${BOARD_COLUMNS}`,\n [tenant, input.itemId, input.holderId, boardSeq, now],\n );\n const row = released.rows[0];\n if (row !== undefined) return toItem(row);\n\n const current = await this.get(tenant, input.itemId);\n if (current === undefined) throw this.#itemNotFound(input.itemId);\n if (current.assignee === undefined) {\n throw new ByokCoreError(\n 'board_not_held',\n `Board item ${input.itemId} is not held by anyone.`,\n );\n }\n throw new CoreConflictError(\n 'board_claim_conflict',\n `Board item ${input.itemId} is held by ${current.assignee.holderId}, not ${input.holderId}.`,\n current,\n this.#now(),\n );\n }\n\n async updateStatus(tenant: TenantId, input: BoardStatusUpdateInput): Promise<BoardItem> {\n // Legality is a pure function of two caller-supplied values, so it is\n // decided before the statement rather than smuggled into the guard as a\n // boolean parameter. An illegal move skips the write entirely and falls\n // straight to the rejection ladder below, whose order is the contract's:\n // a missed `expectedStatus` outranks a holder mismatch, which outranks an\n // illegal transition.\n if (isLegalBoardTransition(input.expectedStatus, input.status)) {\n const now = this.#now();\n const boardSeq = await this.#allocateSeq(tenant);\n const updated = await this.#pool.query<BoardRow>(\n `UPDATE board_item\n SET status = $4::text, board_seq = $6::bigint, updated_at = $7\n WHERE tenant_id = $1 AND item_id = $2\n AND status = $3::text\n AND ($5::text IS NULL OR holder_id = $5::text)\n RETURNING ${BOARD_COLUMNS}`,\n [\n tenant,\n input.itemId,\n input.expectedStatus,\n input.status,\n input.holderId ?? null,\n boardSeq,\n now,\n ],\n );\n const row = updated.rows[0];\n if (row !== undefined) return toItem(row);\n }\n\n const current = await this.get(tenant, input.itemId);\n if (current === undefined) throw this.#itemNotFound(input.itemId);\n if (current.status !== input.expectedStatus) {\n throw this.#statusConflict(input.itemId, current, input.expectedStatus);\n }\n if (input.holderId !== undefined && current.assignee?.holderId !== input.holderId) {\n throw new CoreConflictError(\n 'board_claim_conflict',\n `Board item ${input.itemId} is not held by ${input.holderId}.`,\n current,\n this.#now(),\n );\n }\n if (!isLegalBoardTransition(input.expectedStatus, input.status)) {\n throw new CoreConflictError(\n 'board_transition_invalid',\n `${input.expectedStatus} to ${input.status} is not a legal board transition.`,\n current,\n this.#now(),\n );\n }\n // Every guard the CAS checked reads as satisfied now, so the row moved and\n // moved back between the write and this read. The caller lost a race, and\n // saying so with the current snapshot is more useful than retrying into it.\n throw this.#statusConflict(input.itemId, current, input.expectedStatus);\n }\n\n /**\n * One statement, its own transaction, lock released immediately. See the file\n * header for why this is not a CTE inside the write it feeds.\n */\n async #allocateSeq(tenant: TenantId): Promise<bigint> {\n const result = await this.#pool.query<{ board_seq: bigint }>(\n `INSERT INTO tenant_stream (tenant_id, board_seq)\n VALUES ($1, 1)\n ON CONFLICT (tenant_id) DO UPDATE SET board_seq = tenant_stream.board_seq + 1\n RETURNING board_seq`,\n [tenant],\n );\n return result.rows[0]!.board_seq;\n }\n\n #itemNotFound(itemId: string): ByokCoreError {\n return new ByokCoreError(\n 'board_item_not_found',\n `Board item ${itemId} does not exist in this tenant.`,\n );\n }\n\n #statusConflict(\n itemId: string,\n current: BoardItem,\n expected: BoardStatus,\n ): CoreConflictError<BoardItem> {\n return new CoreConflictError(\n 'board_status_conflict',\n `Board item ${itemId} is ${current.status}, not ${expected}.`,\n current,\n this.#now(),\n );\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * Postgres {@link QuotaStore} — entitlement, usage, reservation (§12.7.6-12.7.7).\n *\n * The invariant this file exists to hold is\n * `committed + reserved + expected <= hardLimitBytes`, and the reason it is the\n * hardest statement in the slice is that the obvious shapes all get it wrong in\n * a way nothing throws about.\n *\n * **Why `reserve` opens a transaction.** Admission is one guarded\n * `INSERT ... SELECT ... WHERE`, exactly as every other CAS in this package is\n * one guarded statement. But the guard's operand is an AGGREGATE over the\n * tenant's live reservations, and under READ COMMITTED a statement's snapshot\n * is taken when the statement starts. Two concurrent reservers therefore both\n * read a pre-insert world and both pass — the classic oversell. Postgres'\n * EvalPlanQual re-check, which is what makes `UPDATE ... WHERE status = $x` a\n * genuine CAS elsewhere in this package, re-evaluates the qual only against the\n * updated TARGET row; a subquery over another table keeps the original\n * snapshot. So no single statement over this shape can serialize reservers.\n *\n * The two ways out are a counter column CAS'd in place, or a lock. The counter\n * loses: it has to be decremented on all three of finalize / abort / expire,\n * and a path that settles without decrementing leaves a tenant permanently\n * short of quota it actually released — durable drift, invisible until someone\n * audits. So `storage_usage` has NO `reserved_bytes` column and\n * `TenantStorageUsage.reservedBytes` is a `SUM` over live reservations, which\n * cannot drift, and admission takes `FOR UPDATE` on the tenant's entitlement\n * row first. The next statement in that transaction takes a FRESH snapshot,\n * acquired behind the lock, so it sees every committed reservation. This is the\n * \"row-locked transaction\" `packages/core/src/in-memory/quota.ts` names as the\n * Postgres shape.\n *\n * What is NOT happening here: a read whose result is compared in TypeScript and\n * then written. Every admission decision lives in the SQL guard. The reads on\n * the rejection path exist only to answer \"which of the five typed rejections\n * is this\", after the write has already been refused.\n *\n * Nothing in this file calls SQL `now()`. Every instant is the injected clock's,\n * so reservation expiry is assertable under a test clock — and\n * `__tests__/constraints.test.ts` scans this directory to keep it that way.\n */\nimport {\n ByokCoreError,\n CoreConflictError,\n assertCanonicalTimestamp,\n type Clock,\n type ContentHash,\n type MailboxUsageDeltaInput,\n type QuotaStore,\n type StorageFinalizeInput,\n type StorageFinalizeResult,\n type StorageReservation,\n type StorageReservationInput,\n type StorageReservationState,\n type StorageStatus,\n type StorageWriteKind,\n type StorageWritePosture,\n type TenantId,\n type TenantStorageEntitlement,\n type TenantStorageEntitlementInput,\n type TenantStorageUsage,\n} from '@byok-sdk/core';\nimport type { Pool, PoolClient } from 'pg';\n\n/** Warning threshold from §12.7.8: 80% of the hard limit. */\nconst WARNING_NUMERATOR = 80n;\nconst WARNING_DENOMINATOR = 100n;\n\nconst ENTITLEMENT_COLUMNS =\n 'tenant_id, version, hard_limit_bytes, max_object_bytes, max_inline_bytes, mailbox_limit_bytes, retention_policy_id, downgrade_grace_until';\n\nconst RESERVATION_COLUMNS =\n 'tenant_id, reservation_id, state, kind, expected_bytes, content_hash, content_type, created_at, expires_at, settled_at, deduplicated';\nconst QUALIFIED_RESERVATION_COLUMNS = RESERVATION_COLUMNS.split(', ')\n .map((column) => `r.${column}`)\n .join(', ');\n\ninterface EntitlementRow {\n readonly tenant_id: string;\n readonly version: bigint;\n readonly hard_limit_bytes: bigint;\n readonly max_object_bytes: bigint;\n readonly max_inline_bytes: bigint;\n readonly mailbox_limit_bytes: bigint;\n readonly retention_policy_id: string;\n readonly downgrade_grace_until: string | null;\n}\n\ninterface ReservationRow {\n readonly tenant_id: string;\n readonly reservation_id: string;\n readonly state: string;\n readonly kind: string;\n readonly expected_bytes: bigint;\n readonly content_hash: string;\n readonly content_type: string;\n readonly created_at: string;\n readonly expires_at: string;\n readonly settled_at: string | null;\n readonly deduplicated: boolean;\n}\n\ninterface UsageRow {\n readonly committed_object_bytes: bigint;\n readonly committed_inline_bytes: bigint;\n readonly reserved_bytes: bigint;\n readonly mailbox_bytes: bigint;\n readonly object_count: bigint;\n readonly updated_at: string;\n}\n\nfunction toEntitlement(row: EntitlementRow): TenantStorageEntitlement {\n return {\n tenantId: row.tenant_id as TenantId,\n version: row.version,\n hardLimitBytes: row.hard_limit_bytes,\n maxObjectBytes: row.max_object_bytes,\n maxInlineBytes: row.max_inline_bytes,\n mailboxLimitBytes: row.mailbox_limit_bytes,\n retentionPolicyId: row.retention_policy_id,\n ...(row.downgrade_grace_until === null\n ? {}\n : { downgradeGraceUntil: row.downgrade_grace_until }),\n };\n}\n\nfunction toReservation(row: ReservationRow): StorageReservation {\n return {\n tenantId: row.tenant_id as TenantId,\n reservationId: row.reservation_id,\n state: row.state as StorageReservationState,\n kind: row.kind as StorageWriteKind,\n expectedBytes: row.expected_bytes,\n contentHash: row.content_hash as ContentHash,\n contentType: row.content_type,\n createdAt: row.created_at,\n expiresAt: row.expires_at,\n ...(row.settled_at === null ? {} : { settledAt: row.settled_at }),\n };\n}\n\nfunction toUsage(row: UsageRow): TenantStorageUsage {\n return {\n committedObjectBytes: row.committed_object_bytes,\n committedInlineBytes: row.committed_inline_bytes,\n reservedBytes: row.reserved_bytes,\n mailboxBytes: row.mailbox_bytes,\n objectCount: row.object_count,\n updatedAt: row.updated_at,\n };\n}\n\n/**\n * `reservedBytes` is derived here, not stored — see the file header. The\n * `LEFT JOIN` is what lets a tenant with no usage row read as all zeros without\n * a write happening on a read path.\n */\nconst USAGE_SQL = `\n SELECT\n COALESCE(u.committed_object_bytes, 0)::bigint AS committed_object_bytes,\n COALESCE(u.committed_inline_bytes, 0)::bigint AS committed_inline_bytes,\n COALESCE(u.mailbox_bytes, 0)::bigint AS mailbox_bytes,\n COALESCE(u.object_count, 0)::bigint AS object_count,\n COALESCE(u.updated_at, $2) AS updated_at,\n COALESCE((SELECT SUM(r.expected_bytes) FROM storage_reservation r\n WHERE r.tenant_id = $1 AND r.state = 'reserved'), 0)::bigint AS reserved_bytes\n FROM (SELECT $1::text AS tenant_id) AS scope\n LEFT JOIN storage_usage u ON u.tenant_id = scope.tenant_id`;\n\nexport class PostgresQuotaStore implements QuotaStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async readEntitlement(tenant: TenantId): Promise<TenantStorageEntitlement | undefined> {\n const result = await this.#pool.query<EntitlementRow>(\n `SELECT ${ENTITLEMENT_COLUMNS} FROM storage_entitlement WHERE tenant_id = $1`,\n [tenant],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toEntitlement(row);\n }\n\n async writeEntitlement(\n tenant: TenantId,\n input: TenantStorageEntitlementInput,\n ): Promise<TenantStorageEntitlement> {\n // Validated before the version CAS and before any statement runs: an\n // unusable deadline is a bad write regardless of which version wins, and a\n // rejected entitlement must not be a partially written one.\n if (input.downgradeGraceUntil !== undefined) {\n assertCanonicalTimestamp(input.downgradeGraceUntil, 'downgradeGraceUntil');\n }\n\n // The `seeded` CTE is what establishes this composition's standing\n // invariant: a `storage_usage` row exists whenever a `storage_entitlement`\n // row does. Every later accounting write is then a guarded `UPDATE` rather\n // than an upsert that would have to restate its guard in two places.\n const applied = await this.#pool.query<EntitlementRow>(\n `WITH applied AS (\n INSERT INTO storage_entitlement (${ENTITLEMENT_COLUMNS})\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (tenant_id) DO UPDATE\n SET version = EXCLUDED.version,\n hard_limit_bytes = EXCLUDED.hard_limit_bytes,\n max_object_bytes = EXCLUDED.max_object_bytes,\n max_inline_bytes = EXCLUDED.max_inline_bytes,\n mailbox_limit_bytes = EXCLUDED.mailbox_limit_bytes,\n retention_policy_id = EXCLUDED.retention_policy_id,\n downgrade_grace_until = EXCLUDED.downgrade_grace_until\n WHERE storage_entitlement.version < EXCLUDED.version\n RETURNING ${ENTITLEMENT_COLUMNS}\n ), seeded AS (\n INSERT INTO storage_usage (tenant_id, updated_at)\n SELECT $1, $9 FROM applied\n ON CONFLICT (tenant_id) DO NOTHING\n RETURNING 1\n )\n SELECT ${ENTITLEMENT_COLUMNS} FROM applied`,\n [\n tenant,\n input.version,\n input.hardLimitBytes,\n input.maxObjectBytes,\n input.maxInlineBytes,\n input.mailboxLimitBytes,\n input.retentionPolicyId,\n input.downgradeGraceUntil ?? null,\n this.#now(),\n ],\n );\n const row = applied.rows[0];\n if (row !== undefined) return toEntitlement(row);\n\n // The guard rejected: the stored version is at or above the one offered.\n // Version is monotonic, not merely different, so an equal version is stale\n // too — and the caller gets the row it lost to rather than a bare failure.\n const current = await this.readEntitlement(tenant);\n if (current === undefined) {\n throw new Error(`entitlement for ${tenant} vanished during a version CAS`);\n }\n throw new CoreConflictError(\n 'storage_entitlement_version_conflict',\n `Entitlement is at version ${String(current.version)}; refusing to apply version ${String(input.version)}.`,\n current,\n this.#now(),\n );\n }\n\n async readUsage(tenant: TenantId): Promise<TenantStorageUsage> {\n const result = await this.#pool.query<UsageRow>(USAGE_SQL, [tenant, this.#now()]);\n return toUsage(result.rows[0]!);\n }\n\n async readStatus(tenant: TenantId): Promise<StorageStatus> {\n const entitlement = await this.readEntitlement(tenant);\n if (entitlement === undefined) throw this.#entitlementMissing();\n const usage = await this.readUsage(tenant);\n const used = usedBytes(usage);\n const graceActive = this.#graceActive(entitlement);\n return {\n entitlement,\n usage,\n posture: posture(entitlement, usage, graceActive),\n availableBytes:\n used >= entitlement.hardLimitBytes ? 0n : entitlement.hardLimitBytes - used,\n graceActive,\n };\n }\n\n async readReservation(\n tenant: TenantId,\n reservationId: string,\n ): Promise<StorageReservation | undefined> {\n return (await this.#readReservation(tenant, reservationId))?.reservation;\n }\n\n async reserve(\n tenant: TenantId,\n input: StorageReservationInput,\n ): Promise<StorageReservation> {\n const client = await this.#pool.connect();\n let admitted: StorageReservation | undefined;\n let rejection: ByokCoreError | undefined;\n try {\n await client.query('BEGIN');\n\n // The serialization point. Every reserver for this tenant queues here,\n // and the guarded insert below runs on a snapshot taken AFTER the lock is\n // held — which is the only way its aggregate sees a competitor's row.\n const entitlement = await this.#lockEntitlement(client, tenant);\n if (entitlement === undefined) {\n rejection = this.#entitlementMissing();\n } else {\n const now = this.#now();\n // The tenant entitlement lock also serializes this bounded reap with\n // admission. A client can disappear after PUT grant issuance; stale\n // reservations must not remain in the aggregate and permanently\n // consume the tenant's hard limit until an external scheduler runs.\n await client.query(\n `UPDATE storage_reservation\n SET state = 'expired', settled_at = $2\n WHERE tenant_id = $1 AND state = 'reserved' AND expires_at <= $2`,\n [tenant, now],\n );\n const inserted = await client.query<ReservationRow>(\n `WITH ent AS (\n SELECT hard_limit_bytes, max_object_bytes, max_inline_bytes, downgrade_grace_until\n FROM storage_entitlement WHERE tenant_id = $1\n ), used AS (\n SELECT COALESCE((SELECT committed_object_bytes + committed_inline_bytes\n FROM storage_usage WHERE tenant_id = $1), 0)::bigint\n + COALESCE((SELECT SUM(expected_bytes) FROM storage_reservation\n WHERE tenant_id = $1 AND state = 'reserved'), 0)::bigint\n AS used_bytes\n )\n INSERT INTO storage_reservation\n (tenant_id, reservation_id, state, kind, expected_bytes,\n content_hash, content_type, created_at, expires_at)\n SELECT $1, $2, 'reserved', $3::text, $4::bigint, $5, $6, $7, $8\n FROM ent, used\n WHERE $4::bigint <= (CASE WHEN $3::text = 'object'\n THEN ent.max_object_bytes\n ELSE ent.max_inline_bytes END)\n AND used.used_bytes + $4::bigint <= ent.hard_limit_bytes\n AND ($3::text <> 'object' OR NOT EXISTS (\n SELECT 1 FROM object_manifest m\n WHERE m.tenant_id = $1 AND m.hash = $5\n AND m.state = 'delete_pending'\n ))\n AND NOT (used.used_bytes >= ent.hard_limit_bytes\n AND ent.downgrade_grace_until IS NOT NULL\n AND ent.downgrade_grace_until <= $9)\n ON CONFLICT (tenant_id, reservation_id) DO NOTHING\n RETURNING ${RESERVATION_COLUMNS}`,\n [\n tenant,\n input.reservationId,\n input.kind,\n input.expectedBytes,\n input.contentHash,\n input.contentType,\n now,\n this.#expiry(input.ttlMs),\n now,\n ],\n );\n const row = inserted.rows[0];\n if (row !== undefined) {\n admitted = toReservation(row);\n } else {\n const outcome = await this.#explainRefusedReservation(\n client,\n tenant,\n input,\n entitlement,\n );\n if (outcome instanceof ByokCoreError) rejection = outcome;\n else admitted = outcome;\n }\n }\n\n await client.query('COMMIT');\n } catch (error) {\n // Best-effort, for the same reason the migration runner's is: a rollback\n // that throws must not replace the failure the caller needs to see.\n await client.query('ROLLBACK').catch(() => {});\n throw error;\n } finally {\n client.release();\n }\n\n // Thrown outside the transaction block so the catch above stays reserved\n // for genuine faults rather than for this store's own typed rejections.\n if (rejection !== undefined) throw rejection;\n return admitted!;\n }\n\n async finalizeReservation(\n tenant: TenantId,\n input: StorageFinalizeInput,\n ): Promise<StorageFinalizeResult> {\n const existing = await this.#readReservation(tenant, input.reservationId);\n if (existing === undefined) throw this.#reservationMissing(input.reservationId);\n\n if (existing.reservation.state === 'committed') {\n // A replayed finalize answers the same way the original did, including\n // `deduplicated` — which is why that flag is stored rather than\n // recomputed against a set this row is now a member of.\n return {\n reservation: existing.reservation,\n usage: await this.readUsage(tenant),\n deduplicated: existing.deduplicated,\n };\n }\n if (existing.reservation.state !== 'reserved') {\n throw new ByokCoreError(\n 'storage_reservation_expired',\n `Reservation ${input.reservationId} is ${existing.reservation.state}.`,\n );\n }\n if (this.#now() >= existing.reservation.expiresAt) {\n await this.#settle(tenant, input.reservationId, 'expired');\n throw new ByokCoreError(\n 'storage_reservation_expired',\n `Reservation ${input.reservationId} expired at ${existing.reservation.expiresAt}.`,\n );\n }\n if (\n input.observedByteSize !== existing.reservation.expectedBytes ||\n input.observedContentType !== existing.reservation.contentType\n ) {\n // §12.7.7 step 6: a failed finalize releases the bytes and the uploaded\n // object becomes an orphan candidate for the GC worker. Releasing is the\n // state transition itself — nothing decrements a counter.\n await this.#settle(tenant, input.reservationId, 'aborted');\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Observed object does not match reservation ${input.reservationId}.`,\n );\n }\n\n // One statement owns all three durable facts: object manifest, reservation,\n // and usage. `candidate` reads the pre-transition manifest state so object\n // deduplication is defined by manifest authority, not by a second shadow\n // set of committed reservation rows. A missing or mismatched manifest\n // aborts the reservation in this same statement and is surfaced below.\n // Hash identity comes from the reservation row: HEAD observes only\n // size/type (ADR-024), so there is no second digest to compare or persist.\n const settled = await this.#pool.query<ReservationRow>(\n `WITH candidate AS MATERIALIZED (\n SELECT r.tenant_id,\n r.reservation_id,\n r.kind,\n r.content_hash,\n r.expected_bytes,\n r.content_type,\n m.state AS manifest_state,\n (m.tenant_id IS NOT NULL\n AND m.state IN ('pending', 'committed')\n AND m.byte_size = $4::bigint\n AND m.content_type = $5) AS manifest_valid,\n EXISTS (\n SELECT 1 FROM storage_reservation p\n WHERE p.tenant_id = r.tenant_id\n AND p.content_hash = r.content_hash\n AND p.state = 'committed'\n ) AS inline_deduplicated\n FROM storage_reservation r\n LEFT JOIN object_manifest m\n ON m.tenant_id = r.tenant_id AND m.hash = r.content_hash\n WHERE r.tenant_id = $1\n AND r.reservation_id = $2\n AND r.state = 'reserved'\n ), committed_manifest AS (\n UPDATE object_manifest m\n SET state = 'committed', updated_at = $3\n FROM candidate c\n WHERE c.kind = 'object'\n AND c.manifest_valid\n AND m.state = 'pending'\n AND m.tenant_id = c.tenant_id\n AND m.hash = c.content_hash\n RETURNING 1\n ), settled AS (\n UPDATE storage_reservation r\n SET state = CASE\n WHEN c.kind = 'object' AND NOT c.manifest_valid\n THEN 'aborted'\n ELSE 'committed'\n END,\n settled_at = $3,\n deduplicated = CASE\n WHEN c.kind = 'object'\n THEN NOT EXISTS (SELECT 1 FROM committed_manifest)\n ELSE c.inline_deduplicated\n END\n FROM candidate c,\n (SELECT COUNT(*) FROM committed_manifest) AS manifest_barrier\n WHERE r.tenant_id = c.tenant_id\n AND r.reservation_id = c.reservation_id\n AND r.state = 'reserved'\n RETURNING ${QUALIFIED_RESERVATION_COLUMNS}\n ), accounted AS (\n UPDATE storage_usage u\n SET committed_object_bytes = u.committed_object_bytes\n + CASE WHEN s.kind = 'object' AND NOT s.deduplicated\n THEN s.expected_bytes ELSE 0 END,\n committed_inline_bytes = u.committed_inline_bytes\n + CASE WHEN s.kind = 'inline' AND NOT s.deduplicated\n THEN s.expected_bytes ELSE 0 END,\n object_count = u.object_count\n + CASE WHEN s.kind = 'object' AND NOT s.deduplicated THEN 1 ELSE 0 END,\n updated_at = $3\n FROM settled s\n WHERE u.tenant_id = $1 AND s.state = 'committed'\n RETURNING 1\n )\n SELECT ${RESERVATION_COLUMNS} FROM settled`,\n [\n tenant,\n input.reservationId,\n this.#now(),\n input.observedByteSize,\n input.observedContentType,\n ],\n );\n\n const row = settled.rows[0];\n if (row === undefined) {\n // Lost the transition to a concurrent settle between the read above and\n // this statement. Report whatever actually happened rather than retrying\n // into it.\n const raced = await this.#readReservation(tenant, input.reservationId);\n if (raced !== undefined && raced.reservation.state === 'committed') {\n return {\n reservation: raced.reservation,\n usage: await this.readUsage(tenant),\n deduplicated: raced.deduplicated,\n };\n }\n throw new ByokCoreError(\n 'storage_reservation_expired',\n `Reservation ${input.reservationId} was settled concurrently.`,\n );\n }\n\n const reservation = toReservation(row);\n if (reservation.state === 'aborted') {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Reservation ${input.reservationId} has no matching committable object manifest.`,\n );\n }\n\n return {\n reservation,\n usage: await this.readUsage(tenant),\n deduplicated: row.deduplicated,\n };\n }\n\n async abortReservation(\n tenant: TenantId,\n reservationId: string,\n ): Promise<StorageReservation> {\n const existing = await this.#readReservation(tenant, reservationId);\n if (existing === undefined) throw this.#reservationMissing(reservationId);\n // Idempotent by contract: an already-settled reservation returns its\n // settled row instead of failing a retry that has nothing left to release.\n if (existing.reservation.state !== 'reserved') return existing.reservation;\n\n const settled = await this.#settle(tenant, reservationId, 'aborted');\n if (settled !== undefined) return settled;\n const raced = await this.#readReservation(tenant, reservationId);\n if (raced === undefined) throw this.#reservationMissing(reservationId);\n return raced.reservation;\n }\n\n async expireReservations(tenant: TenantId): Promise<readonly StorageReservation[]> {\n // The cutoff is the injected clock's instant, passed as a parameter. A SQL\n // `now()` here would make reservation expiry unassertable without sleeping,\n // and the suite advances a test clock instead.\n const expired = await this.#pool.query<ReservationRow>(\n `UPDATE storage_reservation\n SET state = 'expired', settled_at = $2\n WHERE tenant_id = $1 AND state = 'reserved' AND expires_at <= $2\n RETURNING ${RESERVATION_COLUMNS}`,\n [tenant, this.#now()],\n );\n return expired.rows\n .map(toReservation)\n .sort((left, right) => left.reservationId.localeCompare(right.reservationId));\n }\n\n async applyMailboxDelta(\n tenant: TenantId,\n input: MailboxUsageDeltaInput,\n ): Promise<TenantStorageUsage> {\n // Mailbox bytes are platform-protection accounting, not user capacity: the\n // bound is its own entitlement field. A release (negative delta) is never\n // refused and clamps at zero, so a retention sweep that double-reports\n // cannot drive the counter negative.\n const applied = await this.#pool.query(\n `WITH ent AS (\n SELECT mailbox_limit_bytes FROM storage_entitlement WHERE tenant_id = $1\n )\n UPDATE storage_usage u\n SET mailbox_bytes = GREATEST(u.mailbox_bytes + $2::bigint, 0::bigint),\n updated_at = $3\n FROM ent\n WHERE u.tenant_id = $1\n AND ($2::bigint <= 0 OR u.mailbox_bytes + $2::bigint <= ent.mailbox_limit_bytes)\n RETURNING 1`,\n [tenant, input.deltaBytes, this.#now()],\n );\n\n if (applied.rowCount === 0) {\n const entitlement = await this.readEntitlement(tenant);\n if (entitlement === undefined) throw this.#entitlementMissing();\n const usage = await this.readUsage(tenant);\n throw new ByokCoreError(\n 'storage_quota_exceeded',\n `Mailbox would reach ${String(usage.mailboxBytes + input.deltaBytes)} bytes, over the limit of ${String(entitlement.mailboxLimitBytes)} bytes.`,\n );\n }\n return this.readUsage(tenant);\n }\n\n async #lockEntitlement(\n client: PoolClient,\n tenant: TenantId,\n ): Promise<TenantStorageEntitlement | undefined> {\n const result = await client.query<EntitlementRow>(\n `SELECT ${ENTITLEMENT_COLUMNS} FROM storage_entitlement WHERE tenant_id = $1 FOR UPDATE`,\n [tenant],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toEntitlement(row);\n }\n\n /**\n * Names the refusal. Runs only after the guarded insert has already declined,\n * inside the same locked transaction, so the state it reads is the state that\n * refused. The order matches the contract's precedence: an existing\n * reservation is an idempotent answer, not a rejection; a suspended tenant is\n * read-only (423) before it is over-quota (507); a single oversized write is\n * 413 regardless of how much room is left.\n */\n async #explainRefusedReservation(\n client: PoolClient,\n tenant: TenantId,\n input: StorageReservationInput,\n entitlement: TenantStorageEntitlement,\n ): Promise<StorageReservation | ByokCoreError> {\n const existing = await client.query<ReservationRow>(\n `SELECT ${RESERVATION_COLUMNS} FROM storage_reservation\n WHERE tenant_id = $1 AND reservation_id = $2`,\n [tenant, input.reservationId],\n );\n const held = existing.rows[0];\n if (held !== undefined) {\n if (held.state === 'reserved') {\n if (\n held.kind !== input.kind ||\n held.expected_bytes !== input.expectedBytes ||\n held.content_hash !== input.contentHash ||\n held.content_type !== input.contentType\n ) {\n return new ByokCoreError(\n 'storage_integrity_mismatch',\n `Reservation ${input.reservationId} already binds a different storage declaration.`,\n );\n }\n return toReservation(held);\n }\n return new ByokCoreError(\n 'storage_reservation_expired',\n `Reservation ${input.reservationId} is already ${held.state}.`,\n );\n }\n\n if (input.kind === 'object') {\n const tombstone = await client.query<{ readonly state: string }>(\n `SELECT state FROM object_manifest\n WHERE tenant_id = $1 AND hash = $2 AND state = 'delete_pending'`,\n [tenant, input.contentHash],\n );\n if (tombstone.rows[0] !== undefined) {\n return new ByokCoreError(\n 'object_state_invalid',\n `Object ${input.contentHash} is pending deletion and cannot accept a new reservation.`,\n );\n }\n }\n\n const usageResult = await client.query<UsageRow>(USAGE_SQL, [tenant, this.#now()]);\n const usage = toUsage(usageResult.rows[0]!);\n if (posture(entitlement, usage, this.#graceActive(entitlement)) === 'suspended') {\n return new ByokCoreError(\n 'storage_write_suspended',\n 'Tenant is over its hard limit and its downgrade grace has ended; durable writes are suspended.',\n );\n }\n\n const perWriteLimit =\n input.kind === 'object' ? entitlement.maxObjectBytes : entitlement.maxInlineBytes;\n if (input.expectedBytes > perWriteLimit) {\n return new ByokCoreError(\n 'storage_object_too_large',\n `${String(input.expectedBytes)} bytes exceeds the ${input.kind} limit of ${String(perWriteLimit)} bytes.`,\n );\n }\n return new ByokCoreError(\n 'storage_quota_exceeded',\n `Reserving ${String(input.expectedBytes)} bytes would exceed the hard limit of ${String(entitlement.hardLimitBytes)} bytes.`,\n );\n }\n\n async #readReservation(\n tenant: TenantId,\n reservationId: string,\n ): Promise<{ reservation: StorageReservation; deduplicated: boolean } | undefined> {\n const result = await this.#pool.query<ReservationRow>(\n `SELECT ${RESERVATION_COLUMNS} FROM storage_reservation\n WHERE tenant_id = $1 AND reservation_id = $2`,\n [tenant, reservationId],\n );\n const row = result.rows[0];\n if (row === undefined) return undefined;\n return { reservation: toReservation(row), deduplicated: row.deduplicated };\n }\n\n /**\n * The settle guard. `WHERE state = 'reserved'` is what makes two settlements\n * of the same reservation produce one winner; the loser gets zero rows and\n * re-reads rather than stamping a second `settled_at` over the first.\n * Releasing the reserved bytes needs no second write: they were never a\n * counter, only the sum of rows in this state.\n */\n async #settle(\n tenant: TenantId,\n reservationId: string,\n state: Exclude<StorageReservationState, 'reserved'>,\n ): Promise<StorageReservation | undefined> {\n const result = await this.#pool.query<ReservationRow>(\n `UPDATE storage_reservation\n SET state = $3, settled_at = $4\n WHERE tenant_id = $1 AND reservation_id = $2 AND state = 'reserved'\n RETURNING ${RESERVATION_COLUMNS}`,\n [tenant, reservationId, state, this.#now()],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toReservation(row);\n }\n\n #graceActive(entitlement: TenantStorageEntitlement): boolean {\n return (\n entitlement.downgradeGraceUntil !== undefined &&\n this.#now() < entitlement.downgradeGraceUntil\n );\n }\n\n #entitlementMissing(): ByokCoreError {\n return new ByokCoreError(\n 'storage_entitlement_missing',\n 'No storage entitlement has been issued for this tenant.',\n );\n }\n\n #reservationMissing(reservationId: string): ByokCoreError {\n return new ByokCoreError(\n 'storage_reservation_not_found',\n `Reservation ${reservationId} does not exist in this tenant.`,\n );\n }\n\n #expiry(ttlMs: number): string {\n return new Date(this.#clock.now().getTime() + ttlMs).toISOString();\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n\nfunction usedBytes(usage: TenantStorageUsage): bigint {\n return usage.committedObjectBytes + usage.committedInlineBytes + usage.reservedBytes;\n}\n\n/**\n * Effective write posture (§12.7.8). A tenant that was downgraded gets its\n * configured grace window; once it ends and usage is still over the limit, the\n * tenant is read-only (423) rather than merely unable to add bytes (507).\n */\nfunction posture(\n entitlement: TenantStorageEntitlement,\n usage: TenantStorageUsage,\n graceActive: boolean,\n): StorageWritePosture {\n const used = usedBytes(usage);\n if (used >= entitlement.hardLimitBytes) {\n const graceConfigured = entitlement.downgradeGraceUntil !== undefined;\n return graceConfigured && !graceActive ? 'suspended' : 'blocked';\n }\n if (\n entitlement.hardLimitBytes > 0n &&\n used * WARNING_DENOMINATOR >= entitlement.hardLimitBytes * WARNING_NUMERATOR\n ) {\n return 'warning';\n }\n return 'normal';\n}\n","/**\n * Postgres {@link SkillPackStore} (plan `skill-pack-delivery-channel`, Phase 2).\n *\n * A faithful projection of {@link InMemorySkillPackStore}: same validators, same\n * refusals, same read shape. What `publish` checks and what it rejects is core's\n * decision, not this store's — it reuses `checkSkillPackManifest` /\n * `checkSkillPackEntry` and the manifest/file cross-checks the reference\n * performs, because this store cannot hash (integrity is the installing device's\n * job) but it CAN refuse to persist a pack whose declared path set or byte sizes\n * already disagree with the bytes it was handed. Storing that pair unchecked\n * would hand a device a corrupt publication it could not tell from a tampered\n * response.\n *\n * Two tables, one per level of the manifest (`deploy/sql/0005_skill_packs.sql`):\n * `skill_pack` carries the pack-level fields a `SkillPackManifest` needs to be\n * reconstructed (version, description, the pack content hash), and\n * `skill_pack_file` carries one row per declared file with its content hash,\n * byte size, and the UTF-8 text itself. A publish is a single transaction that\n * upserts the pack row and REPLACES its file set, so a re-publish of a changed\n * pack under the same name never leaves a stale file behind.\n *\n * `byte_size` is `integer`, not `bigint`: `SkillPackFile.byteSize` is a core\n * `number` bounded by `SKILL_PACK_FILE_MAX_BYTES` (256 KiB), unlike the quota\n * and truth byte fields the contract declares as `bigint`. `integer` is the\n * type that round-trips a `number` without a cast at the boundary — the same\n * call `object_manifest.ref_count` makes for a small count.\n *\n * No injected clock: a manifest carries no timestamp, so this store writes none\n * and asks the database for none. That mirrors the reference, which takes no\n * clock either.\n */\nimport {\n ByokCoreError,\n SKILL_PACK_ENTRY_PATH,\n SKILL_PACK_MANIFEST_SCHEMA_ID,\n checkSkillPackEntry,\n checkSkillPackManifest,\n type ContentHash,\n type SkillPackFile,\n type SkillPackFileContent,\n type SkillPackListQuery,\n type SkillPackManifest,\n type SkillPackPublishInput,\n type SkillPackStore,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { Pool, PoolClient } from 'pg';\n\nconst DEFAULT_LIST_LIMIT = 50;\n\ninterface PackRow {\n readonly name: string;\n readonly version: string;\n readonly description: string;\n readonly content_hash: string;\n}\n\ninterface FileRow {\n readonly pack_name: string;\n readonly path: string;\n readonly content_hash: string;\n readonly byte_size: number;\n readonly content: string;\n}\n\n/** Reassembles the manifest a `publish` validated, from its two-level row set. */\nfunction toManifest(pack: PackRow, files: readonly FileRow[]): SkillPackManifest {\n return {\n schema: SKILL_PACK_MANIFEST_SCHEMA_ID,\n name: pack.name,\n version: pack.version,\n description: pack.description,\n files: files.map(toFile),\n contentHash: pack.content_hash as ContentHash,\n };\n}\n\nfunction toFile(row: FileRow): SkillPackFile {\n return {\n path: row.path,\n contentHash: row.content_hash as ContentHash,\n byteSize: row.byte_size,\n };\n}\n\nexport class PostgresSkillPackStore implements SkillPackStore {\n readonly #pool: Pool;\n\n constructor(pool: Pool) {\n this.#pool = pool;\n }\n\n async publish(tenant: TenantId, input: SkillPackPublishInput): Promise<SkillPackManifest> {\n const { manifest } = input;\n const structural = checkSkillPackManifest(manifest);\n if (!structural.ok) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${structural.reason} — ${structural.detail}`,\n );\n }\n\n // The delivered path set and the declared path set must be exactly equal,\n // and every delivered file's UTF-8 byte length must equal its declared\n // size. Same checks the reference performs, in the same order, so a pack\n // rejected against one composition is rejected against the other.\n const contents = new Map<string, string>();\n for (const file of input.files) {\n if (contents.has(file.path)) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(file.path)} was supplied twice.`,\n );\n }\n contents.set(file.path, file.content);\n }\n\n for (const declared of manifest.files) {\n const content = contents.get(declared.path);\n if (content === undefined) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(declared.path)} is declared but was not supplied.`,\n );\n }\n const bytes = new TextEncoder().encode(content).length;\n if (bytes !== declared.byteSize) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(declared.path)} declares ${declared.byteSize} bytes and supplies ${bytes}.`,\n );\n }\n }\n if (contents.size !== manifest.files.length) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${contents.size} files were supplied for ${manifest.files.length} declared rows.`,\n );\n }\n\n const entry = checkSkillPackEntry(manifest, contents.get(SKILL_PACK_ENTRY_PATH)!);\n if (!entry.ok) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${entry.reason} — ${entry.detail}`,\n );\n }\n\n await this.#inTransaction(async (client) => {\n await client.query(\n `INSERT INTO skill_pack (tenant_id, name, version, description, content_hash)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (tenant_id, name) DO UPDATE\n SET version = EXCLUDED.version,\n description = EXCLUDED.description,\n content_hash = EXCLUDED.content_hash`,\n [tenant, manifest.name, manifest.version, manifest.description, manifest.contentHash],\n );\n // Replace, never merge: a re-publish under the same name is a full\n // overwrite, so a file dropped from the new manifest must not linger.\n await client.query(`DELETE FROM skill_pack_file WHERE tenant_id = $1 AND pack_name = $2`, [\n tenant,\n manifest.name,\n ]);\n for (const declared of manifest.files) {\n await client.query(\n `INSERT INTO skill_pack_file (tenant_id, pack_name, path, content_hash, byte_size, content)\n VALUES ($1, $2, $3, $4, $5, $6)`,\n [\n tenant,\n manifest.name,\n declared.path,\n declared.contentHash,\n declared.byteSize,\n contents.get(declared.path)!,\n ],\n );\n }\n });\n\n return manifest;\n }\n\n async get(tenant: TenantId, name: string): Promise<SkillPackManifest | undefined> {\n const packResult = await this.#pool.query<PackRow>(\n `SELECT name, version, description, content_hash\n FROM skill_pack WHERE tenant_id = $1 AND name = $2`,\n [tenant, name],\n );\n const pack = packResult.rows[0];\n if (pack === undefined) return undefined;\n\n const files = await this.#filesFor(tenant, [name]);\n return toManifest(pack, files);\n }\n\n async list(tenant: TenantId, query: SkillPackListQuery): Promise<readonly SkillPackManifest[]> {\n // Byte-order name sort, capped — the same order and default limit the\n // reference produces. `COLLATE \"C\"` pins it to code-point order rather than\n // the server's initialized collation.\n const packs = await this.#pool.query<PackRow>(\n `SELECT name, version, description, content_hash\n FROM skill_pack WHERE tenant_id = $1\n ORDER BY name COLLATE \"C\"\n LIMIT $2`,\n [tenant, query.limit ?? DEFAULT_LIST_LIMIT],\n );\n if (packs.rows.length === 0) return [];\n\n const files = await this.#filesFor(\n tenant,\n packs.rows.map((row) => row.name),\n );\n const byPack = new Map<string, FileRow[]>();\n for (const file of files) {\n const bucket = byPack.get(file.pack_name);\n if (bucket === undefined) byPack.set(file.pack_name, [file]);\n else bucket.push(file);\n }\n return packs.rows.map((pack) => toManifest(pack, byPack.get(pack.name) ?? []));\n }\n\n async readFile(\n tenant: TenantId,\n name: string,\n path: string,\n ): Promise<SkillPackFileContent | undefined> {\n const result = await this.#pool.query<FileRow>(\n `SELECT pack_name, path, content_hash, byte_size, content\n FROM skill_pack_file\n WHERE tenant_id = $1 AND pack_name = $2 AND path = $3`,\n [tenant, name, path],\n );\n const row = result.rows[0];\n if (row === undefined) return undefined;\n return {\n path: row.path,\n contentHash: row.content_hash as ContentHash,\n byteSize: row.byte_size,\n content: row.content,\n };\n }\n\n /** Every file row for the named packs, in byte order of (pack_name, path). */\n async #filesFor(tenant: TenantId, names: readonly string[]): Promise<FileRow[]> {\n const result = await this.#pool.query<FileRow>(\n `SELECT pack_name, path, content_hash, byte_size, content\n FROM skill_pack_file\n WHERE tenant_id = $1 AND pack_name = ANY($2::text[])\n ORDER BY pack_name COLLATE \"C\", path COLLATE \"C\"`,\n [tenant, names],\n );\n return result.rows;\n }\n\n async #inTransaction(run: (client: PoolClient) => Promise<void>): Promise<void> {\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n await run(client);\n await client.query('COMMIT');\n } catch (error) {\n // Best-effort rollback, for the same reason the object store's is: a\n // rollback that itself throws must not replace the failure the caller\n // needs to see.\n await client.query('ROLLBACK').catch(() => {});\n throw error;\n } finally {\n client.release();\n }\n }\n}\n","/**\n * Postgres {@link TruthStore} (§12.3, §12.6.4).\n *\n * Two write models over one table, and the primary key does the deciding for\n * both.\n *\n * - `task.terminal` is first-write-wins: `INSERT ... ON CONFLICT DO NOTHING`\n * plus an equality re-read. A replay of the identical hash returns the\n * ORIGINAL row — same `rev`, same `writtenAt`, same `requestId` — and a\n * different hash for the same task is refused with the record already\n * committed attached. An upsert would pass a naive \"write it twice\" check\n * while quietly restamping the first fact, which §12.6.4 forbids outright.\n * - `profile` / `memory` are per-key snapshots under an `expectedRev` CAS:\n * `UPDATE ... WHERE rev = $expectedRev`, with `expectedRev = 0` expressed as\n * the insert. Zero rows is the conflict, and the caller gets the current\n * record — or `undefined` when it claimed a revision of a record that does\n * not exist.\n *\n * The store never merges bodies. A conflict hands back what it lost to and\n * stops, because the device holding the context is the only party that can\n * decide what the merged truth should be (§12.3).\n */\nimport {\n CoreConflictError,\n type Clock,\n type ContentHash,\n type SnapshotWriteInput,\n type TenantId,\n type TerminalWriteInput,\n type TruthBodyRef,\n type TruthManifestEntry,\n type TruthManifestQuery,\n type TruthRecord,\n type TruthRecordKind,\n type TruthRecordSelector,\n type TruthStore,\n} from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\nconst DEFAULT_MANIFEST_LIMIT = 100;\n\nconst RECORD_COLUMNS =\n 'tenant_id, kind, subject_id, rev, content_hash, byte_size, body_kind, body_inline, body_object_hash, label, request_id, written_at';\n\ninterface RecordRow {\n readonly tenant_id: string;\n readonly kind: string;\n readonly subject_id: string;\n readonly rev: number;\n readonly content_hash: string;\n readonly byte_size: bigint;\n readonly body_kind: string;\n readonly body_inline: string | null;\n readonly body_object_hash: string | null;\n readonly label: string | null;\n readonly request_id: string | null;\n readonly written_at: string;\n}\n\ninterface ManifestRow {\n readonly kind: string;\n readonly subject_id: string;\n readonly rev: number;\n readonly content_hash: string;\n readonly byte_size: bigint;\n readonly label: string | null;\n readonly written_at: string;\n}\n\nfunction toBody(row: RecordRow): TruthBodyRef {\n return row.body_kind === 'inline'\n ? { kind: 'inline', body: row.body_inline ?? '' }\n : { kind: 'object', hash: (row.body_object_hash ?? '') as ContentHash };\n}\n\nfunction toRecord(row: RecordRow): TruthRecord {\n return {\n tenantId: row.tenant_id as TenantId,\n kind: row.kind as TruthRecordKind,\n recordKey: row.subject_id,\n rev: row.rev,\n contentHash: row.content_hash as ContentHash,\n byteSize: row.byte_size,\n body: toBody(row),\n ...(row.label === null ? {} : { label: row.label }),\n ...(row.request_id === null ? {} : { requestId: row.request_id }),\n writtenAt: row.written_at,\n };\n}\n\n/** Splits the two-case `TruthBodyRef` union into the two nullable columns. */\nfunction bodyColumns(body: TruthBodyRef): readonly [string, string | null, string | null] {\n return body.kind === 'inline'\n ? ['inline', body.body, null]\n : ['object', null, body.hash as string];\n}\n\nexport class PostgresTruthStore implements TruthStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async writeTerminal(tenant: TenantId, input: TerminalWriteInput): Promise<TruthRecord> {\n const [bodyKind, bodyInline, bodyObjectHash] = bodyColumns(input.body);\n const inserted = await this.#pool.query<RecordRow>(\n `INSERT INTO attested_record (${RECORD_COLUMNS})\n VALUES ($1, 'task.terminal', $2, 1, $3, $4::bigint, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (tenant_id, kind, subject_id) DO NOTHING\n RETURNING ${RECORD_COLUMNS}`,\n [\n tenant,\n input.taskId,\n input.contentHash,\n input.byteSize,\n bodyKind,\n bodyInline,\n bodyObjectHash,\n input.label ?? null,\n input.requestId ?? null,\n this.#now(),\n ],\n );\n const row = inserted.rows[0];\n if (row !== undefined) return toRecord(row);\n\n const existing = await this.getRecord(tenant, {\n kind: 'task.terminal',\n recordKey: input.taskId,\n });\n if (existing === undefined) {\n throw new Error(`terminal record for ${input.taskId} vanished during a first write`);\n }\n // Exact replay of a committed fact: the original, unchanged. A retry after\n // a lost response is therefore safe and observably a no-op.\n if (existing.contentHash === input.contentHash) return existing;\n throw new CoreConflictError(\n 'terminal_conflict',\n `Task ${input.taskId} already has an immutable terminal record with a different hash.`,\n existing,\n this.#now(),\n );\n }\n\n async writeSnapshot(tenant: TenantId, input: SnapshotWriteInput): Promise<TruthRecord> {\n const [bodyKind, bodyInline, bodyObjectHash] = bodyColumns(input.body);\n const now = this.#now();\n\n // `expectedRev = 0` asserts \"no record yet\", which in SQL is the insert\n // itself: the primary key rejects a caller whose assertion is stale. Every\n // other expected revision is the `rev = $expectedRev` guard on the update.\n // Both are one statement, and both report zero rows as the same conflict.\n const written =\n input.expectedRev === 0\n ? await this.#pool.query<RecordRow>(\n `INSERT INTO attested_record (${RECORD_COLUMNS})\n VALUES ($1, $2, $3, 1, $4, $5::bigint, $6, $7, $8, $9, $10, $11)\n ON CONFLICT (tenant_id, kind, subject_id) DO NOTHING\n RETURNING ${RECORD_COLUMNS}`,\n [\n tenant,\n input.kind,\n input.recordKey,\n input.contentHash,\n input.byteSize,\n bodyKind,\n bodyInline,\n bodyObjectHash,\n input.label ?? null,\n input.requestId ?? null,\n now,\n ],\n )\n : await this.#pool.query<RecordRow>(\n `UPDATE attested_record\n SET rev = rev + 1,\n content_hash = $4,\n byte_size = $5::bigint,\n body_kind = $6,\n body_inline = $7,\n body_object_hash = $8,\n label = $9,\n request_id = $10,\n written_at = $11\n WHERE tenant_id = $1 AND kind = $2 AND subject_id = $3 AND rev = $12\n RETURNING ${RECORD_COLUMNS}`,\n [\n tenant,\n input.kind,\n input.recordKey,\n input.contentHash,\n input.byteSize,\n bodyKind,\n bodyInline,\n bodyObjectHash,\n input.label ?? null,\n input.requestId ?? null,\n now,\n input.expectedRev,\n ],\n );\n\n const row = written.rows[0];\n if (row !== undefined) return toRecord(row);\n\n const current = await this.getRecord(tenant, {\n kind: input.kind,\n recordKey: input.recordKey,\n });\n throw new CoreConflictError<TruthRecord | undefined>(\n 'truth_revision_conflict',\n `Record ${input.kind}/${input.recordKey} is at rev ${current?.rev ?? 0}, not ${input.expectedRev}.`,\n current,\n this.#now(),\n );\n }\n\n async getRecord(\n tenant: TenantId,\n selector: TruthRecordSelector,\n ): Promise<TruthRecord | undefined> {\n const result = await this.#pool.query<RecordRow>(\n `SELECT ${RECORD_COLUMNS} FROM attested_record\n WHERE tenant_id = $1 AND kind = $2 AND subject_id = $3`,\n [tenant, selector.kind, selector.recordKey],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toRecord(row);\n }\n\n async listManifest(\n tenant: TenantId,\n query: TruthManifestQuery,\n ): Promise<readonly TruthManifestEntry[]> {\n // Metadata only — the body columns are not in the projection at all, so a\n // manifest listing cannot accidentally ship payloads. Selecting which\n // bodies to fetch is a local decision (§S6.4), and an unbounded response\n // would defeat it.\n //\n // `COLLATE \"C\"` pins the order to byte order, which is what the in-memory\n // reference's `localeCompare` produces for these keys and, unlike the\n // database's default collation, does not depend on how the server was\n // initialized.\n const result = await this.#pool.query<ManifestRow>(\n `SELECT kind, subject_id, rev, content_hash, byte_size, label, written_at\n FROM attested_record\n WHERE tenant_id = $1\n AND ($2::text IS NULL OR kind = $2::text)\n AND ($3::text IS NULL OR starts_with(subject_id, $3::text))\n ORDER BY kind COLLATE \"C\", subject_id COLLATE \"C\"\n LIMIT $4`,\n [tenant, query.kind ?? null, query.keyPrefix ?? null, query.limit ?? DEFAULT_MANIFEST_LIMIT],\n );\n\n return result.rows.map((row) => ({\n kind: row.kind as TruthRecordKind,\n recordKey: row.subject_id,\n rev: row.rev,\n contentHash: row.content_hash as ContentHash,\n byteSize: row.byte_size,\n ...(row.label === null ? {} : { label: row.label }),\n updatedAt: row.written_at,\n }));\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * The Postgres composition of the seven `@byok-sdk/core` ports.\n *\n * All seven, or none: `runCoreConformance`'s port-inventory dimension asserts a\n * composition supplies exactly `CORE_STORE_NAMES` and exactly the methods\n * `CORE_PORT_METHODS` declares, so there is no such thing as a partial core\n * composition to certify. The original seven landed in one slice (design §11);\n * `skillPacks` joined in Phase 2 of `skill-pack-delivery-channel`\n * when it graduated from a bridge port to a mandatory `CoreStores` member. This\n * function returns a full `CoreStores` where the cloud-local sibling returns a\n * named subset.\n *\n * Everything that reads time reads the injected clock. Nothing calls SQL\n * `now()` — presence expiry and reservation expiry are both\n * contract behavior the suite asserts by moving a test clock, and a store that\n * asked the database for the time would make every one of those assertions\n * either a sleep or a flake.\n */\nimport type { Clock, CoreStores } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\nimport { PostgresPresenceStore } from './presence';\nimport { PostgresBoardStore } from './board';\nimport { PostgresMailboxStore } from './mailbox';\nimport { PostgresObjectStore } from './objects';\nimport { PostgresQuotaStore } from './quota';\nimport { PostgresSkillPackStore } from './skill-pack';\nimport { PostgresTruthStore } from './truth';\n\nexport { PostgresMailboxStore } from './mailbox';\nexport { PostgresBoardStore } from './board';\nexport { PostgresTruthStore } from './truth';\nexport { PostgresPresenceStore } from './presence';\nexport { PostgresObjectStore } from './objects';\nexport { PostgresQuotaStore } from './quota';\nexport { PostgresSkillPackStore } from './skill-pack';\n\nexport interface PostgresCoreStoreOptions {\n readonly pool: Pool;\n /**\n * The clock every TTL and timestamp in this composition reads. Injected, not\n * the database's `now()`: expiry has to be assertable under a test clock, and\n * a store that asks the server for the time cannot be.\n */\n readonly clock: Clock;\n}\n\nexport function createPostgresCoreStores(options: PostgresCoreStoreOptions): CoreStores {\n const { pool, clock } = options;\n return {\n mailbox: new PostgresMailboxStore(pool, clock),\n board: new PostgresBoardStore(pool, clock),\n truth: new PostgresTruthStore(pool, clock),\n presence: new PostgresPresenceStore(pool, clock),\n objects: new PostgresObjectStore(pool, clock),\n quota: new PostgresQuotaStore(pool, clock),\n // No clock: a skill-pack manifest carries no timestamp, so this store reads\n // none — the same shape as the cloud-local `devices` directory.\n skillPacks: new PostgresSkillPackStore(pool),\n };\n}\n","import {\n TRUTH_REQUEST_ID_MAX_LENGTH,\n TruthCommitResponseSchema,\n TruthCommitError,\n truthRecordMetadata,\n type CloudCrypto,\n type PreparedTruthWrite,\n type ProofRequestReceipt,\n type TruthCommitInput,\n type TruthCommitResponse,\n type TruthCommitResult,\n type TruthCommitter,\n} from '@byok-sdk/cloud';\nimport {\n ByokCoreError,\n CoreConflictError,\n type Clock,\n type ContentHash,\n type TenantId,\n type TruthBodyRef,\n type TruthRecord,\n type TruthRecordKind,\n} from '@byok-sdk/core';\nimport type { Pool, PoolClient } from 'pg';\nimport { PostgresTruthStore } from './stores/core/truth';\n\nconst RECORD_COLUMNS =\n 'tenant_id, kind, subject_id, rev, content_hash, byte_size, body_kind, body_inline, body_object_hash, label, request_id, written_at';\nconst RECEIPT_COLUMNS =\n 'tenant_id, device_id, request_id, operation, resource, body_sha256, body_size, response_status, response_body, recorded_at';\n\ninterface RecordRow {\n readonly tenant_id: string;\n readonly kind: string;\n readonly subject_id: string;\n readonly rev: number;\n readonly content_hash: string;\n readonly byte_size: bigint;\n readonly body_kind: string;\n readonly body_inline: string | null;\n readonly body_object_hash: string | null;\n readonly label: string | null;\n readonly request_id: string | null;\n readonly written_at: string;\n}\n\ninterface ReceiptRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly request_id: string;\n readonly operation: string;\n readonly resource: string;\n readonly body_sha256: string;\n readonly body_size: bigint;\n readonly response_status: number;\n readonly response_body: string;\n readonly recorded_at: Date;\n}\n\ninterface EntitlementRow {\n readonly hard_limit_bytes: bigint;\n readonly max_inline_bytes: bigint;\n readonly downgrade_grace_until: string | null;\n}\n\ninterface UsageRow {\n readonly committed_object_bytes: bigint;\n readonly committed_inline_bytes: bigint;\n readonly reserved_bytes: bigint;\n}\n\ninterface ManifestRow {\n readonly hash: string;\n readonly byte_size: bigint;\n readonly state: string;\n}\n\ninterface InlineHashRow {\n readonly content_hash: string;\n readonly byte_size: bigint;\n readonly ref_count: bigint;\n}\n\ninterface AppliedWrite {\n readonly input: PreparedTruthWrite;\n readonly before: TruthRecord | undefined;\n readonly record: TruthRecord;\n readonly mutated: boolean;\n}\n\nexport interface PostgresTruthCommitterOptions {\n readonly pool: Pool;\n readonly clock: Clock;\n readonly crypto: Pick<CloudCrypto, 'sha256'>;\n}\n\nfunction toBody(row: RecordRow): TruthBodyRef {\n return row.body_kind === 'inline'\n ? { kind: 'inline', body: row.body_inline ?? '' }\n : { kind: 'object', hash: (row.body_object_hash ?? '') as ContentHash };\n}\n\nfunction toRecord(tenant: TenantId, row: RecordRow): TruthRecord {\n return {\n tenantId: tenant,\n kind: row.kind as TruthRecordKind,\n recordKey: row.subject_id,\n rev: row.rev,\n contentHash: row.content_hash as ContentHash,\n byteSize: row.byte_size,\n body: toBody(row),\n ...(row.label === null ? {} : { label: row.label }),\n ...(row.request_id === null ? {} : { requestId: row.request_id }),\n writtenAt: row.written_at,\n };\n}\n\nfunction toReceipt(tenant: TenantId, row: ReceiptRow): ProofRequestReceipt {\n return {\n tenantId: tenant,\n deviceId: row.device_id,\n requestId: row.request_id,\n operation: row.operation,\n resource: row.resource,\n bodySha256: row.body_sha256,\n bodySize: row.body_size,\n responseStatus: row.response_status,\n responseBody: row.response_body,\n recordedAt: row.recorded_at.toISOString(),\n };\n}\n\nfunction sameBinding(receipt: ProofRequestReceipt, input: TruthCommitInput): boolean {\n return (\n receipt.operation === input.operation &&\n receipt.resource === input.resource &&\n receipt.bodySha256 === input.proofBodySha256 &&\n receipt.bodySize === input.proofBodySize\n );\n}\n\nfunction bodyColumns(body: TruthBodyRef): readonly [string, string | null, string | null] {\n return body.kind === 'inline'\n ? ['inline', body.body, null]\n : ['object', null, body.hash];\n}\n\nfunction writeKey(write: PreparedTruthWrite): string {\n return `${write.kind}\\u0000${write.recordKey}`;\n}\n\nfunction referenceId(write: PreparedTruthWrite): string {\n return `${write.kind}:${write.recordKey}`;\n}\n\nexport class PostgresTruthCommitter implements TruthCommitter {\n readonly #pool: Pool;\n readonly #clock: Clock;\n readonly #crypto: Pick<CloudCrypto, 'sha256'>;\n readonly #truth: PostgresTruthStore;\n\n constructor(options: PostgresTruthCommitterOptions) {\n this.#pool = options.pool;\n this.#clock = options.clock;\n this.#crypto = options.crypto;\n this.#truth = new PostgresTruthStore(options.pool, options.clock);\n }\n\n getRecord(tenant: TenantId, selector: Parameters<TruthCommitter['getRecord']>[1]) {\n return this.#truth.getRecord(tenant, selector);\n }\n\n listManifest(tenant: TenantId, query: Parameters<TruthCommitter['listManifest']>[1]) {\n return this.#truth.listManifest(tenant, query);\n }\n\n async commit(tenant: TenantId, input: TruthCommitInput): Promise<TruthCommitResult> {\n await this.#validateInput(input);\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n // Serializes the absence case too. A row lock cannot lock a receipt that\n // does not exist; without this, two first deliveries could both mutate\n // truth before one loses the receipt PK race.\n await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [\n JSON.stringify(['truth-receipt', tenant, input.deviceId, input.requestId]),\n ]);\n\n const replay = await this.#readReceipt(client, tenant, input.deviceId, input.requestId);\n if (replay !== undefined) {\n if (!sameBinding(replay, input)) {\n throw new TruthCommitError(\n 'proof_request_conflict',\n `Request ${input.requestId} was already used with a different binding.`,\n );\n }\n const response = TruthCommitResponseSchema.parse(JSON.parse(replay.responseBody));\n await client.query('COMMIT');\n return { response, replayed: true };\n }\n\n const before = await this.#lockCurrentRecords(client, tenant, input.writes);\n this.#assertWritePreconditions(input.writes, before);\n await this.#lockAndVerifyObjects(client, tenant, input.writes, before);\n\n const inlineAffected = input.writes.some((write) => {\n const current = before.get(writeKey(write));\n if (write.kind === 'task.terminal' && current !== undefined) return false;\n return current?.body.kind === 'inline' || write.body.kind === 'inline';\n });\n const inlineDelta = inlineAffected\n ? await this.#prepareInlineAccounting(client, tenant, input.writes, before)\n : 0n;\n\n const applied = await this.#applyWrites(client, tenant, input, before);\n await this.#replaceObjectReferences(client, tenant, applied);\n await this.#settleInlineAccounting(client, tenant, inlineDelta);\n\n const response: TruthCommitResponse = {\n primary: truthRecordMetadata(applied[0]!.record),\n snapshots: applied.slice(1).map((entry) => truthRecordMetadata(entry.record)),\n };\n await client.query(\n `INSERT INTO proof_request_receipt (${RECEIPT_COLUMNS})\n VALUES ($1, $2, $3, $4, $5, $6, $7::bigint, 200, $8, $9)`,\n [\n tenant,\n input.deviceId,\n input.requestId,\n input.operation,\n input.resource,\n input.proofBodySha256,\n input.proofBodySize,\n JSON.stringify(response),\n this.#now(),\n ],\n );\n await client.query('COMMIT');\n return { response, replayed: false };\n } catch (error) {\n await client.query('ROLLBACK').catch(() => undefined);\n throw error;\n } finally {\n client.release();\n }\n }\n\n async #validateInput(input: TruthCommitInput): Promise<void> {\n if (input.requestId.length === 0 || input.requestId.length > TRUTH_REQUEST_ID_MAX_LENGTH) {\n throw new TruthCommitError('proof_request_conflict', 'Request id is outside the record contract.');\n }\n const seen = new Set<string>();\n const objectSizes = new Map<string, bigint>();\n for (const write of input.writes) {\n const key = writeKey(write);\n if (seen.has(key)) {\n throw new TruthCommitError('proof_request_conflict', `Duplicate truth write ${key}.`);\n }\n seen.add(key);\n if (write.body.kind === 'inline') {\n const bytes = new TextEncoder().encode(write.body.body);\n if (BigInt(bytes.byteLength) !== write.byteSize) {\n throw new ByokCoreError('storage_integrity_mismatch', 'Inline byte size disagrees with its content.');\n }\n if ((await this.#crypto.sha256(bytes)) !== write.contentHash) {\n throw new ByokCoreError('storage_integrity_mismatch', 'Inline hash disagrees with its content.');\n }\n } else if (write.body.hash !== write.contentHash) {\n throw new ByokCoreError('storage_integrity_mismatch', 'Object body hash disagrees with record hash.');\n } else {\n const priorSize = objectSizes.get(write.body.hash);\n if (priorSize !== undefined && priorSize !== write.byteSize) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Object ${write.body.hash} was declared with inconsistent byte sizes.`,\n );\n }\n objectSizes.set(write.body.hash, write.byteSize);\n }\n }\n }\n\n async #readReceipt(\n client: PoolClient,\n tenant: TenantId,\n deviceId: string,\n requestId: string,\n ): Promise<ProofRequestReceipt | undefined> {\n const result = await client.query<ReceiptRow>(\n `SELECT ${RECEIPT_COLUMNS} FROM proof_request_receipt\n WHERE tenant_id = $1 AND device_id = $2 AND request_id = $3`,\n [tenant, deviceId, requestId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toReceipt(tenant, row);\n }\n\n async #lockCurrentRecords(\n client: PoolClient,\n tenant: TenantId,\n writes: readonly PreparedTruthWrite[],\n ): Promise<Map<string, TruthRecord | undefined>> {\n const current = new Map<string, TruthRecord | undefined>();\n const ordered = [...writes].sort((a, b) => writeKey(a).localeCompare(writeKey(b)));\n // Row locks cannot protect a missing snapshot. Per-key advisory locks make\n // expectedRev=0 deterministic: the waiter observes the winner and raises a\n // typed revision conflict instead of leaking a unique-constraint error.\n for (const write of ordered) {\n await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [\n JSON.stringify(['truth-record', tenant, write.kind, write.recordKey]),\n ]);\n }\n for (const write of ordered) {\n const result = await client.query<RecordRow>(\n `SELECT ${RECORD_COLUMNS} FROM attested_record\n WHERE tenant_id = $1 AND kind = $2 AND subject_id = $3\n FOR UPDATE`,\n [tenant, write.kind, write.recordKey],\n );\n current.set(\n writeKey(write),\n result.rows[0] === undefined ? undefined : toRecord(tenant, result.rows[0]),\n );\n }\n return current;\n }\n\n #assertWritePreconditions(\n writes: readonly PreparedTruthWrite[],\n current: ReadonlyMap<string, TruthRecord | undefined>,\n ): void {\n for (const write of writes) {\n const before = current.get(writeKey(write));\n if (write.kind === 'task.terminal') {\n if (before !== undefined && before.contentHash !== write.contentHash) {\n throw new CoreConflictError(\n 'terminal_conflict',\n `Task ${write.recordKey} already has a different immutable terminal.`,\n before,\n this.#now(),\n );\n }\n } else if ((before?.rev ?? 0) !== write.expectedRev) {\n throw new CoreConflictError(\n 'truth_revision_conflict',\n `${write.kind}/${write.recordKey} is at rev ${before?.rev ?? 0}, not ${write.expectedRev}.`,\n before,\n this.#now(),\n );\n }\n }\n }\n\n async #lockAndVerifyObjects(\n client: PoolClient,\n tenant: TenantId,\n writes: readonly PreparedTruthWrite[],\n current: ReadonlyMap<string, TruthRecord | undefined>,\n ): Promise<void> {\n const requested = new Map<string, bigint>();\n const affected = new Set<string>();\n for (const write of writes) {\n const before = current.get(writeKey(write));\n if (write.kind === 'task.terminal' && before !== undefined) continue;\n if (before?.body.kind === 'object') affected.add(before.body.hash);\n if (write.body.kind === 'object') {\n const existing = requested.get(write.body.hash);\n if (existing !== undefined && existing !== write.byteSize) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Object ${write.body.hash} was declared with inconsistent byte sizes.`,\n );\n }\n requested.set(write.body.hash, write.byteSize);\n affected.add(write.body.hash);\n }\n }\n // Lock both the old and new manifests in one global order. Locking only\n // the new side lets two snapshots swapping A/B each hold its destination\n // and deadlock while recounting the other's source reference.\n for (const hash of [...affected].sort()) {\n const result = await client.query<ManifestRow>(\n `SELECT hash, byte_size, state FROM object_manifest\n WHERE tenant_id = $1 AND hash = $2 FOR UPDATE`,\n [tenant, hash],\n );\n const manifest = result.rows[0];\n const byteSize = requested.get(hash);\n if (\n manifest === undefined ||\n (byteSize !== undefined &&\n (manifest.state !== 'committed' || manifest.byte_size !== byteSize))\n ) {\n throw new TruthCommitError(\n 'truth_object_not_committed',\n `Object ${hash} is not a committed matching manifest.`,\n );\n }\n }\n }\n\n async #prepareInlineAccounting(\n client: PoolClient,\n tenant: TenantId,\n writes: readonly PreparedTruthWrite[],\n current: ReadonlyMap<string, TruthRecord | undefined>,\n ): Promise<bigint> {\n const entitlementResult = await client.query<EntitlementRow>(\n `SELECT hard_limit_bytes, max_inline_bytes, downgrade_grace_until\n FROM storage_entitlement WHERE tenant_id = $1 FOR UPDATE`,\n [tenant],\n );\n const entitlement = entitlementResult.rows[0];\n if (entitlement === undefined) {\n throw new ByokCoreError('storage_entitlement_missing', 'Tenant has no storage entitlement.');\n }\n const now = this.#now();\n await client.query(\n `UPDATE storage_reservation SET state = 'expired', settled_at = $2\n WHERE tenant_id = $1 AND state = 'reserved' AND expires_at <= $2`,\n [tenant, now],\n );\n const usageResult = await client.query<UsageRow>(\n `SELECT u.committed_object_bytes, u.committed_inline_bytes,\n COALESCE((SELECT SUM(expected_bytes) FROM storage_reservation r\n WHERE r.tenant_id = $1 AND r.state = 'reserved'), 0)::bigint AS reserved_bytes\n FROM storage_usage u WHERE u.tenant_id = $1 FOR UPDATE`,\n [tenant],\n );\n const usage = usageResult.rows[0];\n if (usage === undefined) throw new Error(`storage usage for ${tenant} is missing`);\n\n const affectedHashes = new Set<string>();\n const sizes = new Map<string, bigint>();\n for (const write of writes) {\n const before = current.get(writeKey(write));\n if (write.kind === 'task.terminal' && before !== undefined) continue;\n if (before?.body.kind === 'inline') {\n affectedHashes.add(before.contentHash);\n sizes.set(before.contentHash, before.byteSize);\n }\n if (write.body.kind !== 'inline') continue;\n if (write.byteSize > entitlement.max_inline_bytes) {\n throw new ByokCoreError(\n 'storage_object_too_large',\n `Inline truth ${write.kind}/${write.recordKey} exceeds maxInlineBytes.`,\n );\n }\n const knownSize = sizes.get(write.contentHash);\n if (knownSize !== undefined && knownSize !== write.byteSize) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Inline hash ${write.contentHash} was declared with inconsistent byte sizes.`,\n );\n }\n affectedHashes.add(write.contentHash);\n sizes.set(write.contentHash, write.byteSize);\n }\n\n const hashes = [...affectedHashes].sort();\n const baseline = new Map<string, bigint>(hashes.map((hash) => [hash, 0n]));\n const existing = await client.query<InlineHashRow>(\n `SELECT content_hash, byte_size, count(*)::bigint AS ref_count\n FROM attested_record\n WHERE tenant_id = $1 AND body_kind = 'inline' AND content_hash = ANY($2::text[])\n GROUP BY content_hash, byte_size`,\n [tenant, hashes],\n );\n for (const row of existing.rows) {\n const knownSize = sizes.get(row.content_hash);\n if (knownSize !== undefined && knownSize !== row.byte_size) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Stored inline hash ${row.content_hash} disagrees on byte size.`,\n );\n }\n if ((baseline.get(row.content_hash) ?? 0n) !== 0n) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Stored inline hash ${row.content_hash} has multiple byte sizes.`,\n );\n }\n baseline.set(row.content_hash, row.ref_count);\n sizes.set(row.content_hash, row.byte_size);\n }\n\n const projected = new Map(baseline);\n for (const write of writes) {\n const before = current.get(writeKey(write));\n if (write.kind === 'task.terminal' && before !== undefined) continue;\n if (before?.body.kind === 'inline') {\n projected.set(before.contentHash, (projected.get(before.contentHash) ?? 0n) - 1n);\n }\n if (write.body.kind === 'inline') {\n projected.set(write.contentHash, (projected.get(write.contentHash) ?? 0n) + 1n);\n }\n }\n\n let delta = 0n;\n let newlyCommitted = 0n;\n for (const hash of hashes) {\n const before = baseline.get(hash) ?? 0n;\n const after = projected.get(hash) ?? 0n;\n if (after < 0n) throw new Error(`inline reference count for ${hash} would become negative`);\n const byteSize = sizes.get(hash);\n if (byteSize === undefined) throw new Error(`inline byte size for ${hash} is missing`);\n if (before === 0n && after > 0n) {\n delta += byteSize;\n newlyCommitted += byteSize;\n } else if (before > 0n && after === 0n) {\n delta -= byteSize;\n }\n }\n\n const used = usage.committed_object_bytes + usage.committed_inline_bytes + usage.reserved_bytes;\n if (\n newlyCommitted > 0n &&\n used >= entitlement.hard_limit_bytes &&\n entitlement.downgrade_grace_until !== null &&\n entitlement.downgrade_grace_until <= now\n ) {\n throw new ByokCoreError('storage_write_suspended', 'Durable writes are suspended.');\n }\n if (used + delta > entitlement.hard_limit_bytes) {\n throw new ByokCoreError('storage_quota_exceeded', 'Final inline truth usage exceeds quota.');\n }\n return delta;\n }\n\n async #applyWrites(\n client: PoolClient,\n tenant: TenantId,\n input: TruthCommitInput,\n current: ReadonlyMap<string, TruthRecord | undefined>,\n ): Promise<AppliedWrite[]> {\n const applied: AppliedWrite[] = [];\n for (const write of input.writes) {\n const before = current.get(writeKey(write));\n if (write.kind === 'task.terminal' && before !== undefined) {\n applied.push({ input: write, before, record: before, mutated: false });\n continue;\n }\n const [bodyKind, bodyInline, bodyObjectHash] = bodyColumns(write.body);\n const values = [\n tenant,\n write.kind,\n write.recordKey,\n write.contentHash,\n write.byteSize,\n bodyKind,\n bodyInline,\n bodyObjectHash,\n write.label ?? null,\n input.requestId,\n this.#now(),\n ];\n const result =\n before === undefined\n ? await client.query<RecordRow>(\n `INSERT INTO attested_record (${RECORD_COLUMNS})\n VALUES ($1, $2, $3, 1, $4, $5, $6, $7, $8, $9, $10, $11)\n RETURNING ${RECORD_COLUMNS}`,\n values,\n )\n : await client.query<RecordRow>(\n `UPDATE attested_record\n SET rev = rev + 1, content_hash = $4, byte_size = $5,\n body_kind = $6, body_inline = $7, body_object_hash = $8,\n label = $9, request_id = $10, written_at = $11\n WHERE tenant_id = $1 AND kind = $2 AND subject_id = $3\n RETURNING ${RECORD_COLUMNS}`,\n values,\n );\n applied.push({\n input: write,\n before,\n record: toRecord(tenant, result.rows[0]!),\n mutated: true,\n });\n }\n return applied;\n }\n\n async #replaceObjectReferences(\n client: PoolClient,\n tenant: TenantId,\n applied: readonly AppliedWrite[],\n ): Promise<void> {\n const affected = new Set<string>();\n for (const entry of applied) {\n if (!entry.mutated) continue;\n const refId = referenceId(entry.input);\n if (entry.input.body.kind === 'object') {\n affected.add(entry.input.body.hash);\n await client.query(\n `INSERT INTO object_reference (tenant_id, hash, ref_kind, ref_id, created_at)\n VALUES ($1, $2, 'truth', $3, $4)\n ON CONFLICT (tenant_id, hash, ref_kind, ref_id) DO NOTHING`,\n [tenant, entry.input.body.hash, refId, this.#now()],\n );\n }\n if (\n entry.before?.body.kind === 'object' &&\n (entry.input.body.kind !== 'object' || entry.input.body.hash !== entry.before.body.hash)\n ) {\n affected.add(entry.before.body.hash);\n await client.query(\n `DELETE FROM object_reference\n WHERE tenant_id = $1 AND hash = $2 AND ref_kind = 'truth' AND ref_id = $3`,\n [tenant, entry.before.body.hash, refId],\n );\n }\n }\n for (const hash of [...affected].sort()) {\n await client.query(\n `UPDATE object_manifest\n SET ref_count = (SELECT count(*) FROM object_reference r\n WHERE r.tenant_id = $1 AND r.hash = $2),\n updated_at = $3\n WHERE tenant_id = $1 AND hash = $2`,\n [tenant, hash, this.#now()],\n );\n }\n }\n\n async #settleInlineAccounting(\n client: PoolClient,\n tenant: TenantId,\n delta: bigint,\n ): Promise<void> {\n if (delta !== 0n) {\n const updated = await client.query(\n `UPDATE storage_usage\n SET committed_inline_bytes = committed_inline_bytes + $2::bigint,\n updated_at = $3\n WHERE tenant_id = $1 AND committed_inline_bytes + $2::bigint >= 0\n RETURNING 1`,\n [tenant, delta, this.#now()],\n );\n if (updated.rowCount !== 1) throw new Error('inline accounting would become negative');\n }\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * Where this package's own migration files are.\n *\n * `migrate(pool, directory)` takes a directory rather than defaulting to one,\n * because a runner that guesses where a host keeps deployment assets can\n * silently migrate nothing. That contract is unchanged — this function just\n * means the answer no longer has to come from a git checkout the installed\n * package cannot see. The build copies `deploy/sql/*.sql` into `dist/sql/`\n * (`scripts/copy-migrations.mjs`), so the files sit next to the compiled entry\n * point and resolve relative to it.\n *\n * Resolution is relative to THIS module's own URL, never to `process.cwd()` or\n * a `require.resolve` of the package name: an installed copy is the only thing\n * in reach, and `fileURLToPath` is what turns a `file:///C:/...` URL into a path\n * Windows can open.\n */\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Absolute path to the migration directory shipped inside this package, ready\n * to hand to {@link migrate}. The directory exists in an installed package and\n * in this repository after a build; it does not exist in an unbuilt checkout,\n * where `deploy/sql/` is the thing to read.\n */\nexport function migrationsDir(): string {\n return fileURLToPath(new URL('./sql', import.meta.url));\n}\n","/**\n * The forward-only migration runner.\n *\n * Six rules, and each one exists because the alternative is a schema incident\n * (docs/researches/s4a-dataplane-design.md §2):\n *\n * 1. **Ordering comes from filenames.** `deploy/sql/NNNN_*.sql`, sorted by the\n * four-digit prefix — the same constraint `check-deploy-sql-order` already\n * enforces in CI. Two ordering authorities cannot coexist, which is the\n * whole reason this is a hand-written runner instead of a migration\n * framework with its own directory convention.\n * 2. **One runner at a time**, via a session-level `pg_advisory_lock` held on a\n * single checked-out client for the entire run. Two deploy jobs starting\n * together is normal; two of them applying the same file is not.\n * 3. **The ledger bootstraps itself.** `byok_schema_migration` is the ONLY DDL\n * outside `deploy/sql/`. Putting it in `0001` would force the runner to\n * special-case \"the ledger does not exist yet\" before it can read the\n * ledger — two sources of truth for one table.\n * 4. **One transaction per file**, covering the file's statements AND its\n * ledger row. A crash leaves a migration entirely applied or entirely\n * absent, never applied-but-unrecorded (which the next run would replay).\n * 5. **Checksums are verified, not recorded and forgotten.** An already-applied\n * file whose sha256 no longer matches the ledger raises\n * {@link MigrationChecksumMismatchError} and the run STOPS. \"Forward-only\"\n * means published files are immutable; without this check that is a slogan.\n * 6. **There is no down path.** Not \"unimplemented\" — absent. Rollback is\n * \"revert the application, leave the tables\" (sprint S4A.6), and a\n * destructive path that exists is a destructive path that eventually runs.\n *\n * Known boundary of rule 4: a statement that cannot run inside a transaction\n * (`CREATE INDEX CONCURRENTLY`, and `ALTER TYPE ... ADD VALUE` on older\n * servers) cannot appear in a migration file. That is a deliberate trade —\n * per-file atomicity is worth more here than building an index without a lock,\n * and the day it is not, it needs its own reviewed mechanism rather than a\n * quiet exception.\n */\nimport { createHash } from 'node:crypto';\nimport { readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Pool, PoolClient } from 'pg';\nimport { migrationsDir } from './migrations-dir';\n\n/**\n * An arbitrary but permanently fixed advisory-lock key. Its only requirement is\n * that every runner in every process picks the same one; changing it would let\n * an old and a new deployment migrate concurrently exactly once.\n */\nconst MIGRATION_ADVISORY_LOCK_KEY = '4021960801';\n\n/** `NNNN_name.sql` — the same shape `scripts/check-deploy-sql-order.sh` enforces. */\nconst MIGRATION_FILENAME_PATTERN = /^(\\d{4})[_-].+\\.sql$/;\n\n/**\n * The migration ledger, and the sole DDL statement in this package: every other\n * table a deployment owns is created by a file under `deploy/sql/`.\n */\nconst LEDGER_DDL = `\nCREATE TABLE IF NOT EXISTS byok_schema_migration (\n version text PRIMARY KEY,\n checksum text NOT NULL,\n applied_at timestamptz NOT NULL\n)`;\n\nconst MIGRATION_LEDGER_TABLE = 'byok_schema_migration';\nconst LEDGER_READ_SQL = 'SELECT version, checksum FROM byok_schema_migration';\n\n/** One file on disk, already ordered and checksummed. */\nexport interface MigrationFile {\n /** The filename, e.g. `0001_cloud_local.sql`. This is the ledger's `version`. */\n readonly version: string;\n /** The four-digit prefix as a number, used for ordering only. */\n readonly ordinal: number;\n readonly checksum: string;\n readonly sql: string;\n}\n\n/** What a run did. `applied` is empty when the database was already up to date. */\nexport interface MigrationResult {\n readonly applied: readonly string[];\n readonly alreadyApplied: readonly string[];\n}\n\n/** The exact package-owned row returned after a successful ledger readback. */\nexport interface MigrationVerificationRow {\n readonly version: string;\n readonly checksum: string;\n}\n\nexport type MigrationStateIssue =\n | {\n readonly kind: 'missing';\n readonly version: string;\n readonly expectedChecksum: string;\n }\n | {\n readonly kind: 'unexpected';\n readonly version: string;\n readonly actualChecksum: string;\n }\n | {\n readonly kind: 'checksum_mismatch';\n readonly version: string;\n readonly expectedChecksum: string;\n readonly actualChecksum: string;\n }\n | {\n readonly kind: 'ledger_missing';\n readonly table: 'byok_schema_migration';\n };\n\n/**\n * The database's migration state does not exactly match this package's files.\n *\n * This is deliberately aggregate and fail-closed: a host can report every\n * drift fact in one readiness result, but it cannot continue as though a\n * partially matching schema were usable.\n */\nexport class MigrationStateMismatchError extends Error {\n readonly issues: readonly MigrationStateIssue[];\n\n constructor(issues: readonly MigrationStateIssue[], options?: ErrorOptions) {\n const detail = issues\n .map((issue) => {\n switch (issue.kind) {\n case 'missing':\n return `missing ${issue.version}`;\n case 'unexpected':\n return `unexpected ${issue.version}`;\n case 'checksum_mismatch':\n return `checksum mismatch ${issue.version}`;\n case 'ledger_missing':\n return `ledger table missing ${issue.table}`;\n }\n })\n .join('; ');\n super(`Migration state does not match package files: ${detail}`, options);\n this.name = 'MigrationStateMismatchError';\n this.issues = Object.freeze([...issues]);\n }\n}\n\n/**\n * A published migration file changed after it was applied.\n *\n * Fail-closed by design: the runner cannot know whether the edit was a harmless\n * comment or a dropped column, and a deployment that guesses wrong corrupts a\n * schema. The fix is a NEW migration file, never an edit to an old one.\n */\nexport class MigrationChecksumMismatchError extends Error {\n readonly version: string;\n readonly expectedChecksum: string;\n readonly actualChecksum: string;\n\n constructor(version: string, expectedChecksum: string, actualChecksum: string) {\n super(\n `Migration ${version} was already applied with checksum ${expectedChecksum}, but the file on disk hashes to ${actualChecksum}. ` +\n 'Published migrations are immutable: add a new file instead of editing this one.',\n );\n this.name = 'MigrationChecksumMismatchError';\n this.version = version;\n this.expectedChecksum = expectedChecksum;\n this.actualChecksum = actualChecksum;\n }\n}\n\n/** A file in the migration directory that the naming contract does not admit. */\nexport class MigrationFilenameError extends Error {\n readonly filename: string;\n\n constructor(filename: string, reason: string) {\n super(`Migration file ${filename} is not usable: ${reason}`);\n this.name = 'MigrationFilenameError';\n this.filename = filename;\n }\n}\n\nfunction sha256(text: string): string {\n return createHash('sha256').update(text, 'utf8').digest('hex');\n}\n\n/**\n * Reads and orders the migration files in `directory`.\n *\n * Ordering is by the four-digit prefix, not by whatever order the filesystem\n * hands back — `readdir` makes no promise, and on some filesystems it is\n * effectively insertion order. A non-conforming filename or a duplicated prefix\n * is an error rather than a skip: silently ignoring a `.sql` file someone\n * dropped in this directory is how a migration goes missing.\n */\nexport async function readMigrationFiles(directory: string): Promise<readonly MigrationFile[]> {\n const entries = await readdir(directory, { withFileTypes: true });\n const files: MigrationFile[] = [];\n\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith('.sql')) continue;\n const match = MIGRATION_FILENAME_PATTERN.exec(entry.name);\n if (match === null) {\n throw new MigrationFilenameError(\n entry.name,\n 'expected a four-digit prefix, e.g. 0001_cloud_local.sql',\n );\n }\n const sql = await readFile(join(directory, entry.name), 'utf8');\n files.push({\n version: entry.name,\n ordinal: Number.parseInt(match[1]!, 10),\n checksum: sha256(sql),\n sql,\n });\n }\n\n files.sort((left, right) => left.ordinal - right.ordinal);\n\n for (let index = 1; index < files.length; index += 1) {\n const previous = files[index - 1]!;\n const current = files[index]!;\n if (previous.ordinal === current.ordinal) {\n throw new MigrationFilenameError(\n current.version,\n `duplicate prefix ${String(current.ordinal).padStart(4, '0')}, already used by ${previous.version}`,\n );\n }\n }\n\n return files;\n}\n\ninterface MigrationLedgerRow {\n readonly version: string;\n readonly checksum: string;\n}\n\nasync function readLedgerRows(client: PoolClient): Promise<readonly MigrationLedgerRow[]> {\n const result = await client.query<MigrationLedgerRow>(LEDGER_READ_SQL);\n return result.rows;\n}\n\nasync function readLedger(client: PoolClient): Promise<Map<string, string>> {\n const rows = await readLedgerRows(client);\n return new Map(rows.map((row) => [row.version, row.checksum]));\n}\n\nfunction isMissingLedgerTable(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n error.code === '42P01'\n );\n}\n\nfunction compareVersions(left: string, right: string): number {\n if (left < right) return -1;\n if (left > right) return 1;\n return 0;\n}\n\n/**\n * Reads the package migration files and the existing ledger, then requires an\n * exact version/checksum match.\n *\n * The default directory is the migration projection shipped by this package.\n * This function only reads state: it never creates the ledger, applies a\n * migration, or synthesizes a compatible result for a missing/changed row.\n */\nexport async function verifyMigrations(\n pool: Pool,\n directory: string = migrationsDir(),\n): Promise<readonly MigrationVerificationRow[]> {\n const files = await readMigrationFiles(directory);\n const client = await pool.connect();\n\n try {\n let ledgerRows: readonly MigrationLedgerRow[];\n try {\n ledgerRows = await readLedgerRows(client);\n } catch (error) {\n if (!isMissingLedgerTable(error)) throw error;\n throw new MigrationStateMismatchError(\n [{ kind: 'ledger_missing', table: MIGRATION_LEDGER_TABLE }],\n { cause: error },\n );\n }\n\n const ledger = new Map(ledgerRows.map((row) => [row.version, row.checksum]));\n const expectedVersions = new Set(files.map((file) => file.version));\n const issues: MigrationStateIssue[] = [];\n\n for (const file of files) {\n const actualChecksum = ledger.get(file.version);\n if (actualChecksum === undefined) {\n issues.push({\n kind: 'missing',\n version: file.version,\n expectedChecksum: file.checksum,\n });\n } else if (actualChecksum !== file.checksum) {\n issues.push({\n kind: 'checksum_mismatch',\n version: file.version,\n expectedChecksum: file.checksum,\n actualChecksum,\n });\n }\n }\n\n const unexpectedRows = ledgerRows\n .filter((row) => !expectedVersions.has(row.version))\n .slice()\n .sort((left, right) => compareVersions(left.version, right.version));\n for (const row of unexpectedRows) {\n issues.push({ kind: 'unexpected', version: row.version, actualChecksum: row.checksum });\n }\n\n if (issues.length > 0) throw new MigrationStateMismatchError(issues);\n\n return files.map(({ version, checksum }) => ({ version, checksum }));\n } finally {\n client.release();\n }\n}\n\n/**\n * Applies every pending migration in `directory`, in prefix order.\n *\n * @param pool The pool to migrate. One client is checked out for the whole run\n * because the advisory lock is session-scoped.\n * @param directory Absolute path to the migration directory (this repo's\n * `deploy/sql/`). Required rather than defaulted: a published package cannot\n * guess where its consumer keeps deployment assets, and guessing wrong would\n * mean silently migrating nothing.\n */\nexport async function migrate(pool: Pool, directory: string): Promise<MigrationResult> {\n // Read the files BEFORE taking the lock: a filename error is a mistake in the\n // repository, and there is no reason to make a second runner queue behind it.\n const files = await readMigrationFiles(directory);\n\n const client = await pool.connect();\n try {\n await client.query('SELECT pg_advisory_lock($1)', [MIGRATION_ADVISORY_LOCK_KEY]);\n try {\n await client.query(LEDGER_DDL);\n const ledger = await readLedger(client);\n\n const applied: string[] = [];\n const alreadyApplied: string[] = [];\n\n for (const file of files) {\n const recordedChecksum = ledger.get(file.version);\n if (recordedChecksum !== undefined) {\n if (recordedChecksum !== file.checksum) {\n throw new MigrationChecksumMismatchError(file.version, recordedChecksum, file.checksum);\n }\n alreadyApplied.push(file.version);\n continue;\n }\n\n // One transaction: the file's statements and its ledger row land or\n // vanish together. A multi-statement string goes over the simple\n // protocol, which runs inside the transaction opened here.\n await client.query('BEGIN');\n try {\n await client.query(file.sql);\n await client.query(\n 'INSERT INTO byok_schema_migration (version, checksum, applied_at) VALUES ($1, $2, now())',\n [file.version, file.checksum],\n );\n await client.query('COMMIT');\n } catch (error) {\n // The rollback is best-effort on purpose. When the failure was a lost\n // connection, `ROLLBACK` rejects too — and an unguarded await here\n // would replace the migration error with a transport error, hiding\n // the one fact an operator needs: which file failed and why. The\n // server discards an abandoned transaction on disconnect anyway, so\n // swallowing this rejection loses nothing and rethrowing the original\n // keeps the diagnosis intact.\n await client.query('ROLLBACK').catch(() => {});\n throw error;\n }\n applied.push(file.version);\n }\n\n return { applied, alreadyApplied };\n } finally {\n await client.query('SELECT pg_advisory_unlock($1)', [MIGRATION_ADVISORY_LOCK_KEY]);\n }\n } finally {\n client.release();\n }\n}\n","/**\n * Host-owned S4B-c maintenance for the Postgres + R2 composition.\n *\n * Postgres remains the manifest/accounting authority. R2 is touched only after\n * a durable `delete_pending` tombstone, and a missing object is an idempotent\n * DELETE replay — never evidence that a committed manifest was truthful.\n */\nimport { createHash } from 'node:crypto';\nimport {\n ByokCoreError,\n contentHash,\n tenantId,\n type Clock,\n type ContentHash,\n type MailboxMessage,\n type MailboxMessageState,\n type TenantId,\n} from '@byok-sdk/core';\nimport { decodeEnvelope, encodeEnvelope, EnvelopeSchema, isServerToDaemonType } from '@byok-sdk/protocol';\nimport type { Pool, PoolClient } from 'pg';\nimport {\n R2ObjectMaintenanceStore,\n type R2BlobStoreOptions,\n type R2ObjectMaintenance,\n} from './stores/r2-blobs';\nimport { allocateMailboxSequence } from './stores/core/mailbox-sequence';\n\nconst DEFAULT_BATCH_SIZE = 100;\nconst MAX_BATCH_SIZE = 1000;\nconst ADVISORY_LOCK_NAMESPACE = 1_106_736_963;\nconst OUTBOX_COLUMNS =\n 'tenant_id, device_id, seq, message_id, body, body_hash, byte_size, state, appended_at, replay_source_seq';\n\nexport const CLOUD_CLEANUP_ERROR_CODES = {\n cleanup_invalid_input: 'cleanup_invalid_input',\n cleanup_policy_missing: 'cleanup_policy_missing',\n cleanup_job_running: 'cleanup_job_running',\n cleanup_dead_letter_not_found: 'cleanup_dead_letter_not_found',\n cleanup_accounting_drift: 'cleanup_accounting_drift',\n} as const;\n\nexport type CloudCleanupErrorCode =\n (typeof CLOUD_CLEANUP_ERROR_CODES)[keyof typeof CLOUD_CLEANUP_ERROR_CODES];\n\nexport class CloudCleanupError extends Error {\n readonly code: CloudCleanupErrorCode;\n\n constructor(code: CloudCleanupErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'CloudCleanupError';\n this.code = code;\n }\n}\n\nexport interface TenantRetentionPolicyInput {\n readonly policyId: string;\n readonly mailboxAckedRetentionMs: bigint;\n readonly mailboxUnackedRetentionMs: bigint;\n readonly requestReceiptRetentionMs: bigint;\n readonly objectOrphanGraceMs: bigint;\n}\n\nexport interface TenantRetentionPolicy extends TenantRetentionPolicyInput {\n readonly tenantId: TenantId;\n readonly updatedAt: string;\n}\n\nexport type CleanupJobState = 'running' | 'completed' | 'completed_with_errors' | 'failed';\n\nexport interface CloudCleanupResult {\n readonly tenantId: TenantId;\n readonly jobId: string;\n readonly state: CleanupJobState;\n readonly startedAt: string;\n readonly finishedAt?: string;\n readonly mailboxDeletedCount: bigint;\n readonly mailboxExpiredCount: bigint;\n readonly mailboxReleasedBytes: bigint;\n readonly reservationsExpired: bigint;\n readonly ttlRowsDeleted: bigint;\n readonly objectsTombstoned: bigint;\n readonly objectsDeleted: bigint;\n readonly objectReleasedBytes: bigint;\n readonly orphanWitnessesCreated: bigint;\n readonly missingObjects: bigint;\n readonly shapeDrift: bigint;\n readonly invalidObjectKeys: bigint;\n readonly operationErrors: bigint;\n readonly errorMessage?: string;\n}\n\nexport interface DeadLetterQuery {\n readonly deviceId?: string;\n /** Exclusive composite cursor; use the last message from the prior page. */\n readonly after?: DeadLetterRef;\n readonly limit?: number;\n}\n\nexport interface DeadLetterPage {\n readonly messages: readonly MailboxMessage[];\n readonly hasMore: boolean;\n}\n\nexport interface DeadLetterReplayInput {\n readonly deviceId: string;\n readonly seq: number;\n /** Operator-issued idempotency key for the new delivery. */\n readonly replayMessageId: string;\n}\n\nexport interface DeadLetterRef {\n readonly deviceId: string;\n readonly seq: number;\n}\n\nexport interface ObjectUsageRebuildResult {\n readonly committedObjectBytes: bigint;\n readonly objectCount: bigint;\n readonly updatedAt: string;\n}\n\nexport interface PostgresCloudCleanupOptions {\n readonly pool: Pool;\n readonly clock: Clock;\n readonly objectStorage: R2ObjectMaintenance;\n readonly batchSize?: number;\n}\n\nexport interface PostgresCloudMaintenanceOptions {\n readonly pool: Pool;\n readonly clock: Clock;\n readonly objectStorage: Omit<R2BlobStoreOptions, 'objects'>;\n readonly batchSize?: number;\n}\n\ninterface RetentionPolicyRow {\n readonly tenant_id: string;\n readonly policy_id: string;\n readonly mailbox_acked_retention_ms: bigint;\n readonly mailbox_unacked_retention_ms: bigint;\n readonly request_receipt_retention_ms: bigint;\n readonly object_orphan_grace_ms: bigint;\n readonly updated_at: string;\n}\n\ninterface CleanupJobRow {\n readonly tenant_id: string;\n readonly job_id: string;\n readonly state: string;\n readonly started_at: string;\n readonly finished_at: string | null;\n readonly mailbox_deleted_count: bigint;\n readonly mailbox_expired_count: bigint;\n readonly mailbox_released_bytes: bigint;\n readonly reservations_expired: bigint;\n readonly ttl_rows_deleted: bigint;\n readonly objects_tombstoned: bigint;\n readonly objects_deleted: bigint;\n readonly object_released_bytes: bigint;\n readonly orphan_witnesses_created: bigint;\n readonly missing_objects: bigint;\n readonly shape_drift: bigint;\n readonly invalid_object_keys: bigint;\n readonly operation_errors: bigint;\n readonly error_message: string | null;\n}\n\ninterface RetentionResultRow {\n readonly mailbox_deleted_count: bigint;\n readonly mailbox_expired_count: bigint;\n readonly mailbox_released_bytes: bigint;\n readonly usage_accounted: bigint;\n readonly reservations_expired: bigint;\n readonly ttl_rows_deleted: bigint;\n}\n\ninterface ManifestMaintenanceRow {\n readonly hash: string;\n readonly byte_size: bigint;\n readonly content_type: string;\n readonly state: string;\n readonly gc_accounted_bytes: bigint | null;\n readonly gc_accounted_object: boolean | null;\n}\n\ninterface OutboxRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly seq: bigint;\n readonly message_id: string;\n readonly body: string;\n readonly body_hash: string;\n readonly byte_size: bigint;\n readonly state: string;\n readonly appended_at: string;\n readonly replay_source_seq: bigint | null;\n}\n\ninterface MutableCounts {\n mailboxDeletedCount: bigint;\n mailboxExpiredCount: bigint;\n mailboxReleasedBytes: bigint;\n reservationsExpired: bigint;\n ttlRowsDeleted: bigint;\n objectsTombstoned: bigint;\n objectsDeleted: bigint;\n objectReleasedBytes: bigint;\n orphanWitnessesCreated: bigint;\n missingObjects: bigint;\n shapeDrift: bigint;\n invalidObjectKeys: bigint;\n operationErrors: bigint;\n}\n\nexport class PostgresCloudCleanup {\n readonly #pool: Pool;\n readonly #clock: Clock;\n readonly #objectStorage: R2ObjectMaintenance;\n readonly #batchSize: number;\n\n constructor(options: PostgresCloudCleanupOptions) {\n this.#pool = options.pool;\n this.#clock = options.clock;\n this.#objectStorage = options.objectStorage;\n this.#batchSize = assertBatchSize(options.batchSize ?? DEFAULT_BATCH_SIZE);\n }\n\n async writeRetentionPolicy(\n tenant: TenantId,\n input: TenantRetentionPolicyInput,\n ): Promise<TenantRetentionPolicy> {\n assertPolicy(input);\n const written = await this.#pool.query<RetentionPolicyRow>(\n `INSERT INTO tenant_retention_policy (\n tenant_id, policy_id, mailbox_acked_retention_ms,\n mailbox_unacked_retention_ms, request_receipt_retention_ms,\n object_orphan_grace_ms, updated_at\n ) VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (tenant_id, policy_id) DO UPDATE\n SET mailbox_acked_retention_ms = EXCLUDED.mailbox_acked_retention_ms,\n mailbox_unacked_retention_ms = EXCLUDED.mailbox_unacked_retention_ms,\n request_receipt_retention_ms = EXCLUDED.request_receipt_retention_ms,\n object_orphan_grace_ms = EXCLUDED.object_orphan_grace_ms,\n updated_at = EXCLUDED.updated_at\n RETURNING tenant_id, policy_id, mailbox_acked_retention_ms,\n mailbox_unacked_retention_ms, request_receipt_retention_ms,\n object_orphan_grace_ms, updated_at`,\n [\n tenant,\n input.policyId,\n input.mailboxAckedRetentionMs,\n input.mailboxUnackedRetentionMs,\n input.requestReceiptRetentionMs,\n input.objectOrphanGraceMs,\n this.#now(),\n ],\n );\n return toPolicy(written.rows[0]!);\n }\n\n async readRetentionPolicy(tenant: TenantId): Promise<TenantRetentionPolicy> {\n return this.#readRetentionPolicy(this.#pool, tenant);\n }\n\n /** Run one bounded tenant maintenance cycle. Completed job ids are replay-safe. */\n async runTenant(tenant: TenantId, jobId: string): Promise<CloudCleanupResult> {\n assertIdentifier(jobId, 'jobId');\n const client = await this.#pool.connect();\n let jobStarted = false;\n try {\n const lock = await client.query<{ readonly locked: boolean }>(\n 'SELECT pg_try_advisory_lock(hashtextextended($1, $2)) AS locked',\n [tenant, ADVISORY_LOCK_NAMESPACE],\n );\n if (lock.rows[0]?.locked !== true) {\n throw new CloudCleanupError(\n 'cleanup_job_running',\n `A cleanup job is already running for tenant ${tenant}.`,\n );\n }\n\n const replay = await this.#startJob(client, tenant, jobId);\n if (replay !== undefined) return replay;\n jobStarted = true;\n\n const policy = await this.#readRetentionPolicy(client, tenant);\n const counts = emptyCounts();\n const retention = await this.#runRetention(client, tenant, policy);\n counts.mailboxDeletedCount = retention.mailbox_deleted_count;\n counts.mailboxExpiredCount = retention.mailbox_expired_count;\n counts.mailboxReleasedBytes = retention.mailbox_released_bytes;\n counts.reservationsExpired = retention.reservations_expired;\n counts.ttlRowsDeleted = retention.ttl_rows_deleted;\n\n const orphanCutoff = cutoff(this.#clock.now(), policy.objectOrphanGraceMs);\n counts.objectsTombstoned = await this.#markTombstones(client, tenant, orphanCutoff);\n\n const deleteCursor = await this.#readCursor(client, tenant, 'delete');\n const pending = await client.query<ManifestMaintenanceRow>(\n `SELECT hash, byte_size, content_type, state,\n gc_accounted_bytes, gc_accounted_object\n FROM object_manifest\n WHERE tenant_id = $1\n AND state = 'delete_pending'\n AND gc_accounted_bytes IS NOT NULL\n AND gc_accounted_object IS NOT NULL\n AND hash > $2\n ORDER BY hash\n LIMIT $3`,\n [tenant, deleteCursor ?? '', this.#batchSize],\n );\n for (const manifest of pending.rows) {\n try {\n await this.#objectStorage.deleteObject(tenant, manifest.hash as ContentHash);\n const released = await this.#settleDeleted(client, tenant, manifest.hash as ContentHash);\n if (released !== undefined) {\n counts.objectsDeleted += 1n;\n counts.objectReleasedBytes += released;\n }\n } catch {\n // The tombstone is the retry record. Preserve it and expose the\n // failure count; a later run repeats DELETE and settlement.\n counts.operationErrors += 1n;\n }\n }\n await this.#advanceLexicalCursor(\n client,\n tenant,\n 'delete',\n pending.rows.at(-1)?.hash,\n pending.rows.length,\n );\n\n await this.#reconcileManifests(client, tenant, counts);\n await this.#reconcileR2(client, tenant, counts);\n\n const state: CleanupJobState =\n counts.operationErrors === 0n ? 'completed' : 'completed_with_errors';\n return this.#finishJob(client, tenant, jobId, state, counts);\n } catch (cause) {\n if (jobStarted) {\n await this.#failJob(client, tenant, jobId, cause).catch(() => {});\n }\n throw cause;\n } finally {\n await client\n .query('SELECT pg_advisory_unlock(hashtextextended($1, $2))', [\n tenant,\n ADVISORY_LOCK_NAMESPACE,\n ])\n .catch(() => {});\n client.release();\n }\n }\n\n async listDeadLetters(tenant: TenantId, query: DeadLetterQuery = {}): Promise<DeadLetterPage> {\n const limit = assertBatchSize(query.limit ?? DEFAULT_BATCH_SIZE);\n if (query.deviceId !== undefined) assertIdentifier(query.deviceId, 'deviceId');\n if (query.after !== undefined) assertDeadLetterRef(query.after);\n if (\n query.deviceId !== undefined &&\n query.after !== undefined &&\n query.deviceId !== query.after.deviceId\n ) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n 'A device-scoped dead-letter cursor must belong to the same device.',\n );\n }\n const listed = await this.#pool.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1\n AND state = 'expired'\n AND ($2::text IS NULL OR device_id = $2::text)\n AND (device_id > $3 OR (device_id = $3 AND seq > $4::bigint))\n ORDER BY device_id, seq\n LIMIT $5`,\n [\n tenant,\n query.deviceId ?? null,\n query.after?.deviceId ?? '',\n query.after?.seq ?? 0,\n limit + 1,\n ],\n );\n return {\n messages: listed.rows.slice(0, limit).map(toMailboxMessage),\n hasMore: listed.rows.length > limit,\n };\n }\n\n /** Clone an expired row to a new monotonic seq. The original remains evidence. */\n async replayDeadLetter(\n tenant: TenantId,\n input: DeadLetterReplayInput,\n ): Promise<MailboxMessage> {\n assertDeadLetterRef(input);\n assertIdentifier(input.replayMessageId, 'replayMessageId');\n const client = await this.#pool.connect();\n let result: MailboxMessage | undefined;\n let rejection: Error | undefined;\n let rollbackAllocation = false;\n try {\n await client.query('BEGIN');\n const originalResult = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND seq = $3::bigint\n AND state = 'expired'\n FOR UPDATE`,\n [tenant, input.deviceId, input.seq],\n );\n const original = originalResult.rows[0];\n if (original === undefined) {\n rejection = deadLetterMissing(input);\n } else {\n const existingResult = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.replayMessageId],\n );\n const existing = existingResult.rows[0];\n if (existing !== undefined) {\n if (!replayMatches(existing, original)) {\n rejection = new CloudCleanupError(\n 'cleanup_invalid_input',\n `Replay id ${input.replayMessageId} already binds a different replay delivery.`,\n );\n } else {\n result = toMailboxMessage(existing);\n }\n } else {\n const entitlement = await client.query<{\n readonly mailbox_limit_bytes: bigint;\n readonly mailbox_bytes: bigint;\n }>(\n `SELECT e.mailbox_limit_bytes, u.mailbox_bytes\n FROM storage_entitlement e\n JOIN storage_usage u ON u.tenant_id = e.tenant_id\n WHERE e.tenant_id = $1\n FOR UPDATE OF e, u`,\n [tenant],\n );\n const capacity = entitlement.rows[0];\n // A different dead-letter row may race on the same operator-issued\n // replay id. The usage lock above is the serialization point; read\n // the idempotency key again after acquiring it so the loser returns\n // the winner instead of surfacing a raw unique violation.\n const serializedExisting = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.replayMessageId],\n );\n const winner = serializedExisting.rows[0];\n if (winner !== undefined) {\n if (!replayMatches(winner, original)) {\n rejection = new CloudCleanupError(\n 'cleanup_invalid_input',\n `Replay id ${input.replayMessageId} already binds a different replay delivery.`,\n );\n } else {\n result = toMailboxMessage(winner);\n }\n } else if (capacity === undefined) {\n rejection = new CloudCleanupError(\n 'cleanup_policy_missing',\n `Tenant ${tenant} has no storage entitlement/usage row.`,\n );\n } else {\n // Hold the same per-device allocator lock as normal mailbox append\n // until the rebound envelope row is inserted. This keeps replay\n // commits ordered with live offers.\n const seq = await allocateMailboxSequence(\n client,\n tenant,\n input.deviceId,\n this.#now(),\n );\n // Normal mailbox append uses this same device lock. Recheck after\n // acquiring it so an append that won between the usage check and\n // allocation resolves through typed idempotency rather than a raw\n // unique violation. Roll back the unused allocation either way.\n const afterAllocation = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.replayMessageId],\n );\n const appendWinner = afterAllocation.rows[0];\n if (appendWinner !== undefined) {\n rollbackAllocation = true;\n if (!replayMatches(appendWinner, original)) {\n rejection = new CloudCleanupError(\n 'cleanup_invalid_input',\n `Replay id ${input.replayMessageId} already binds a different replay delivery.`,\n );\n } else {\n result = toMailboxMessage(appendWinner);\n }\n } else {\n const rebound = materializeReplayBody(original, seq);\n if (capacity.mailbox_bytes + rebound.byteSize > capacity.mailbox_limit_bytes) {\n rejection = new ByokCoreError(\n 'storage_quota_exceeded',\n `Replaying the dead letter would exceed tenant ${tenant}'s mailbox limit.`,\n );\n } else {\n const inserted = await client.query<OutboxRow>(\n `INSERT INTO outbox (${OUTBOX_COLUMNS})\n VALUES ($1, $2, $3::bigint, $4, $5, $6, $7::bigint, 'pending', $8, $9)\n RETURNING ${OUTBOX_COLUMNS}`,\n [\n tenant,\n input.deviceId,\n seq,\n input.replayMessageId,\n rebound.body,\n rebound.bodyHash,\n rebound.byteSize,\n this.#now(),\n original.seq,\n ],\n );\n await client.query(\n `UPDATE storage_usage\n SET mailbox_bytes = mailbox_bytes + $2::bigint, updated_at = $3\n WHERE tenant_id = $1`,\n [tenant, rebound.byteSize, this.#now()],\n );\n result = toMailboxMessage(inserted.rows[0]!);\n }\n }\n }\n }\n }\n if (rejection === undefined && !rollbackAllocation) await client.query('COMMIT');\n else await client.query('ROLLBACK');\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n } finally {\n client.release();\n }\n if (rejection !== undefined) throw rejection;\n return result!;\n }\n\n /** Explicit operator discard. Automatic retention never deletes dead letters. */\n async discardDeadLetter(tenant: TenantId, ref: DeadLetterRef): Promise<MailboxMessage> {\n assertDeadLetterRef(ref);\n const client = await this.#pool.connect();\n let row: OutboxRow | undefined;\n let rejection: Error | undefined;\n try {\n await client.query('BEGIN');\n const existing = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND seq = $3::bigint\n AND state = 'expired'\n FOR UPDATE`,\n [tenant, ref.deviceId, ref.seq],\n );\n const deadLetter = existing.rows[0];\n const usage = await client.query<{ readonly mailbox_bytes: bigint }>(\n 'SELECT mailbox_bytes FROM storage_usage WHERE tenant_id = $1 FOR UPDATE',\n [tenant],\n );\n if (deadLetter === undefined) {\n rejection = deadLetterMissing(ref);\n } else if (usage.rows[0] === undefined || usage.rows[0].mailbox_bytes < deadLetter.byte_size) {\n rejection = new CloudCleanupError(\n 'cleanup_accounting_drift',\n `Mailbox accounting cannot release dead letter ${ref.deviceId}/${String(ref.seq)}.`,\n );\n } else {\n const removed = await client.query<OutboxRow>(\n `DELETE FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND seq = $3::bigint\n AND state = 'expired'\n RETURNING ${OUTBOX_COLUMNS}`,\n [tenant, ref.deviceId, ref.seq],\n );\n await client.query(\n `UPDATE storage_usage\n SET mailbox_bytes = mailbox_bytes - $2::bigint, updated_at = $3\n WHERE tenant_id = $1`,\n [tenant, deadLetter.byte_size, this.#now()],\n );\n row = removed.rows[0];\n }\n if (rejection === undefined) await client.query('COMMIT');\n else await client.query('ROLLBACK');\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n } finally {\n client.release();\n }\n if (rejection !== undefined) throw rejection;\n return toMailboxMessage(row!);\n }\n\n /**\n * Explicit recovery operation: rebuild object accounting from committed\n * Postgres manifests. Reconciliation must run first; R2 LIST is never used as\n * billing authority and inline/mailbox usage is left untouched.\n */\n async rebuildObjectUsage(tenant: TenantId): Promise<ObjectUsageRebuildResult> {\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n const locked = await client.query(\n 'SELECT 1 FROM storage_usage WHERE tenant_id = $1 FOR UPDATE',\n [tenant],\n );\n if (locked.rowCount === 0) {\n throw new CloudCleanupError(\n 'cleanup_policy_missing',\n `Tenant ${tenant} has no storage usage row to rebuild.`,\n );\n }\n const rebuilt = await client.query<{\n readonly committed_object_bytes: bigint;\n readonly object_count: bigint;\n readonly updated_at: string;\n }>(\n `WITH authority AS MATERIALIZED (\n SELECT COALESCE(SUM(byte_size), 0)::bigint AS committed_object_bytes,\n count(*)::bigint AS object_count\n FROM object_manifest\n WHERE tenant_id = $1 AND state = 'committed'\n )\n UPDATE storage_usage u\n SET committed_object_bytes = authority.committed_object_bytes,\n object_count = authority.object_count,\n updated_at = $2\n FROM authority\n WHERE u.tenant_id = $1\n RETURNING u.committed_object_bytes, u.object_count, u.updated_at`,\n [tenant, this.#now()],\n );\n await client.query('COMMIT');\n const row = rebuilt.rows[0]!;\n return {\n committedObjectBytes: row.committed_object_bytes,\n objectCount: row.object_count,\n updatedAt: row.updated_at,\n };\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n } finally {\n client.release();\n }\n }\n\n async #readRetentionPolicy(\n queryable: Pick<Pool, 'query'> | Pick<PoolClient, 'query'>,\n tenant: TenantId,\n ): Promise<TenantRetentionPolicy> {\n const result = await queryable.query<RetentionPolicyRow>(\n `SELECT p.tenant_id, p.policy_id, p.mailbox_acked_retention_ms,\n p.mailbox_unacked_retention_ms, p.request_receipt_retention_ms,\n p.object_orphan_grace_ms, p.updated_at\n FROM storage_entitlement e\n JOIN tenant_retention_policy p\n ON p.tenant_id = e.tenant_id AND p.policy_id = e.retention_policy_id\n WHERE e.tenant_id = $1`,\n [tenant],\n );\n const row = result.rows[0];\n if (row === undefined) {\n throw new CloudCleanupError(\n 'cleanup_policy_missing',\n `Tenant ${tenant} has no retention policy matching its entitlement.`,\n );\n }\n const policy = toPolicy(row);\n assertPolicy(policy);\n return policy;\n }\n\n async #startJob(\n client: PoolClient,\n tenant: TenantId,\n jobId: string,\n ): Promise<CloudCleanupResult | undefined> {\n const now = this.#now();\n const started = await client.query<CleanupJobRow>(\n `INSERT INTO cleanup_job (tenant_id, job_id, kind, state, started_at)\n VALUES ($1, $2, 'tenant_cleanup', 'running', $3)\n ON CONFLICT (tenant_id, job_id) DO UPDATE\n SET state = 'running', started_at = EXCLUDED.started_at,\n finished_at = NULL, error_message = NULL\n WHERE cleanup_job.state IN ('running', 'failed')\n RETURNING ${JOB_COLUMNS}`,\n [tenant, jobId, now],\n );\n if (started.rows[0] !== undefined) return undefined;\n const existing = await this.#readJob(client, tenant, jobId);\n return toCleanupResult(existing);\n }\n\n async #runRetention(\n client: PoolClient,\n tenant: TenantId,\n policy: TenantRetentionPolicy,\n ): Promise<RetentionResultRow> {\n const ackedBefore = cutoff(this.#clock.now(), policy.mailboxAckedRetentionMs);\n const expireBefore = cutoff(this.#clock.now(), policy.mailboxUnackedRetentionMs);\n const receiptBefore = cutoff(this.#clock.now(), policy.requestReceiptRetentionMs);\n const now = this.#now();\n try {\n await client.query('BEGIN');\n const swept = await client.query<RetentionResultRow>(\n `WITH deleted AS (\n DELETE FROM outbox\n WHERE tenant_id = $1 AND state = 'acked' AND appended_at < $2\n RETURNING byte_size\n ), released AS MATERIALIZED (\n SELECT COALESCE(SUM(byte_size), 0)::bigint AS bytes FROM deleted\n ), expired AS (\n UPDATE outbox SET state = 'expired'\n WHERE tenant_id = $1 AND state = 'pending' AND appended_at < $3\n RETURNING 1\n ), reservations AS (\n UPDATE storage_reservation SET state = 'expired', settled_at = $4\n WHERE tenant_id = $1 AND state = 'reserved' AND expires_at <= $4\n RETURNING 1\n ), nonces AS (\n DELETE FROM auth_nonce\n WHERE tenant_id = $1 AND (used OR expires_at <= $4::timestamptz)\n RETURNING 1\n ), pairing_codes AS (\n DELETE FROM pairing_code\n WHERE tenant_id = $1\n AND (redeemed_at IS NOT NULL OR expires_at <= $4::timestamptz)\n RETURNING 1\n ), receipts AS (\n DELETE FROM device_request_receipts\n WHERE tenant_id = $1 AND recorded_at < $5::timestamptz\n RETURNING 1\n ), presence AS (\n DELETE FROM device_presence\n WHERE tenant_id = $1 AND expires_at <= $4\n RETURNING 1\n ), activity AS (\n DELETE FROM activity_tail\n WHERE tenant_id = $1 AND expires_at <= $4\n RETURNING 1\n ), approvals AS (\n DELETE FROM approval_timeline_tail\n WHERE tenant_id = $1 AND expires_at <= $4\n RETURNING 1\n ), accounted AS (\n UPDATE storage_usage u\n SET mailbox_bytes = u.mailbox_bytes - released.bytes, updated_at = $4\n FROM released\n WHERE u.tenant_id = $1 AND u.mailbox_bytes >= released.bytes\n RETURNING released.bytes\n )\n SELECT (SELECT count(*) FROM deleted)::bigint AS mailbox_deleted_count,\n (SELECT count(*) FROM expired)::bigint AS mailbox_expired_count,\n (SELECT bytes FROM released)::bigint AS mailbox_released_bytes,\n (SELECT count(*) FROM accounted)::bigint AS usage_accounted,\n (SELECT count(*) FROM reservations)::bigint AS reservations_expired,\n ((SELECT count(*) FROM nonces)\n + (SELECT count(*) FROM pairing_codes)\n + (SELECT count(*) FROM receipts)\n + (SELECT count(*) FROM presence)\n + (SELECT count(*) FROM activity)\n + (SELECT count(*) FROM approvals))::bigint AS ttl_rows_deleted`,\n [tenant, ackedBefore, expireBefore, now, receiptBefore],\n );\n const result = swept.rows[0]!;\n if (result.usage_accounted !== 1n) {\n throw new CloudCleanupError(\n 'cleanup_accounting_drift',\n `Mailbox accounting cannot release ${String(result.mailbox_released_bytes)} deleted bytes for tenant ${tenant}.`,\n );\n }\n await client.query('COMMIT');\n return result;\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n }\n }\n\n async #markTombstones(\n client: PoolClient,\n tenant: TenantId,\n orphanCutoff: string,\n ): Promise<bigint> {\n try {\n await client.query('BEGIN');\n // Reservation admission uses this same tenant row as its serialization\n // point. Acquiring it before the candidate statement gives that\n // statement a fresh snapshot after every already-started reservation,\n // while later reservations see `delete_pending` and fail closed.\n await client.query(\n 'SELECT 1 FROM storage_entitlement WHERE tenant_id = $1 FOR UPDATE',\n [tenant],\n );\n const marked = await client.query<{ readonly hash: string }>(\n `WITH candidates AS MATERIALIZED (\n SELECT m.tenant_id, m.hash\n FROM object_manifest m\n WHERE m.tenant_id = $1\n AND m.state IN ('pending', 'committed')\n AND m.ref_count = 0\n AND m.updated_at < $2\n AND NOT EXISTS (\n SELECT 1 FROM object_reference r\n WHERE r.tenant_id = m.tenant_id AND r.hash = m.hash\n )\n AND NOT EXISTS (\n SELECT 1 FROM storage_reservation s\n WHERE s.tenant_id = m.tenant_id AND s.content_hash = m.hash\n AND s.state = 'reserved'\n )\n ORDER BY m.updated_at, m.hash\n LIMIT $3\n FOR UPDATE OF m SKIP LOCKED\n )\n UPDATE object_manifest m\n SET gc_accounted_bytes = CASE WHEN m.state = 'committed' THEN m.byte_size ELSE 0 END,\n gc_accounted_object = (m.state = 'committed'),\n state = 'delete_pending', delete_pending_at = $4, updated_at = $4\n FROM candidates c\n WHERE m.tenant_id = c.tenant_id AND m.hash = c.hash\n RETURNING m.hash`,\n [tenant, orphanCutoff, this.#batchSize, this.#now()],\n );\n await client.query('COMMIT');\n return BigInt(marked.rowCount ?? 0);\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n }\n }\n\n async #settleDeleted(\n client: PoolClient,\n tenant: TenantId,\n hash: ContentHash,\n ): Promise<bigint | undefined> {\n const settled = await client.query<{\n readonly gc_accounted_bytes: bigint;\n }>(\n `WITH candidate AS MATERIALIZED (\n SELECT m.gc_accounted_bytes, m.gc_accounted_object\n FROM object_manifest m\n JOIN storage_usage u ON u.tenant_id = m.tenant_id\n WHERE m.tenant_id = $1 AND m.hash = $2\n AND m.state = 'delete_pending'\n AND m.ref_count = 0\n AND m.gc_accounted_bytes IS NOT NULL\n AND m.gc_accounted_object IS NOT NULL\n AND NOT EXISTS (\n SELECT 1 FROM object_reference r\n WHERE r.tenant_id = m.tenant_id AND r.hash = m.hash\n )\n AND u.committed_object_bytes >= m.gc_accounted_bytes\n AND u.object_count >= CASE WHEN m.gc_accounted_object THEN 1 ELSE 0 END\n FOR UPDATE OF m, u\n ), moved AS (\n UPDATE object_manifest m\n SET state = 'deleted', updated_at = $3\n FROM candidate c\n WHERE m.tenant_id = $1 AND m.hash = $2 AND m.state = 'delete_pending'\n RETURNING c.gc_accounted_bytes, c.gc_accounted_object\n ), accounted AS (\n UPDATE storage_usage u\n SET committed_object_bytes = u.committed_object_bytes - moved.gc_accounted_bytes,\n object_count = u.object_count - CASE WHEN moved.gc_accounted_object THEN 1 ELSE 0 END,\n updated_at = $3\n FROM moved\n WHERE u.tenant_id = $1\n RETURNING moved.gc_accounted_bytes\n )\n SELECT gc_accounted_bytes FROM accounted`,\n [tenant, hash, this.#now()],\n );\n const row = settled.rows[0];\n if (row !== undefined) return row.gc_accounted_bytes;\n const current = await client.query<{ readonly state: string }>(\n 'SELECT state FROM object_manifest WHERE tenant_id = $1 AND hash = $2',\n [tenant, hash],\n );\n if (current.rows[0]?.state === 'deleted') return undefined;\n throw new CloudCleanupError(\n 'cleanup_accounting_drift',\n `Object ${hash} could not settle its delete tombstone against storage usage.`,\n );\n }\n\n async #reconcileManifests(\n client: PoolClient,\n tenant: TenantId,\n counts: MutableCounts,\n ): Promise<void> {\n const cursor = await this.#readCursor(client, tenant, 'manifest');\n const page = await client.query<ManifestMaintenanceRow>(\n `SELECT hash, byte_size, content_type, state,\n gc_accounted_bytes, gc_accounted_object\n FROM object_manifest\n WHERE tenant_id = $1\n AND state IN ('committed', 'delete_pending')\n AND hash > $2\n ORDER BY hash\n LIMIT $3`,\n [tenant, cursor ?? '', this.#batchSize],\n );\n for (const manifest of page.rows) {\n const observed = await this.#objectStorage.inspectObject(\n tenant,\n manifest.hash as ContentHash,\n );\n if (manifest.state === 'delete_pending') {\n if (observed === undefined) {\n try {\n const released = await this.#settleDeleted(\n client,\n tenant,\n manifest.hash as ContentHash,\n );\n if (released !== undefined) {\n counts.objectsDeleted += 1n;\n counts.objectReleasedBytes += released;\n }\n } catch {\n counts.operationErrors += 1n;\n }\n }\n continue;\n }\n if (observed === undefined) {\n counts.missingObjects += 1n;\n } else if (\n observed.observedByteSize !== manifest.byte_size ||\n observed.observedContentType !== manifest.content_type\n ) {\n counts.shapeDrift += 1n;\n }\n }\n await this.#advanceLexicalCursor(\n client,\n tenant,\n 'manifest',\n page.rows.at(-1)?.hash,\n page.rows.length,\n );\n }\n\n async #reconcileR2(\n client: PoolClient,\n tenant: TenantId,\n counts: MutableCounts,\n ): Promise<void> {\n const cursor = await this.#readCursor(client, tenant, 'r2');\n const page = await this.#objectStorage.listTenantObjects(\n tenant,\n cursor ?? undefined,\n this.#batchSize,\n );\n for (const object of page.objects) {\n if (object.hash === undefined) {\n counts.invalidObjectKeys += 1n;\n continue;\n }\n const manifest = await client.query<{ readonly state: string }>(\n 'SELECT state FROM object_manifest WHERE tenant_id = $1 AND hash = $2',\n [tenant, object.hash],\n );\n const state = manifest.rows[0]?.state;\n if (state !== undefined && state !== 'deleted') continue;\n const observed = await this.#objectStorage.inspectObject(tenant, object.hash);\n if (observed === undefined) continue;\n const witnessed = await client.query(\n `INSERT INTO object_manifest (\n tenant_id, hash, byte_size, content_type, state, ref_count,\n created_at, updated_at, delete_pending_at,\n gc_accounted_bytes, gc_accounted_object\n ) VALUES ($1, $2, $3, $4, 'pending', 0, $5, $5, NULL, NULL, NULL)\n ON CONFLICT (tenant_id, hash) DO UPDATE\n SET byte_size = EXCLUDED.byte_size,\n content_type = EXCLUDED.content_type,\n state = 'pending', ref_count = 0,\n created_at = EXCLUDED.created_at,\n updated_at = EXCLUDED.updated_at,\n delete_pending_at = NULL,\n gc_accounted_bytes = NULL,\n gc_accounted_object = NULL\n WHERE object_manifest.state = 'deleted'\n RETURNING 1`,\n [\n tenant,\n object.hash,\n observed.observedByteSize,\n observed.observedContentType,\n this.#now(),\n ],\n );\n counts.orphanWitnessesCreated += BigInt(witnessed.rowCount ?? 0);\n }\n if (page.nextContinuationToken === undefined) {\n await this.#clearCursor(client, tenant, 'r2');\n } else {\n await this.#writeCursor(client, tenant, 'r2', page.nextContinuationToken);\n }\n }\n\n async #advanceLexicalCursor(\n client: PoolClient,\n tenant: TenantId,\n kind: string,\n lastValue: string | undefined,\n rowCount: number,\n ): Promise<void> {\n if (lastValue === undefined || rowCount < this.#batchSize) {\n await this.#clearCursor(client, tenant, kind);\n } else {\n await this.#writeCursor(client, tenant, kind, lastValue);\n }\n }\n\n async #readCursor(\n client: PoolClient,\n tenant: TenantId,\n kind: string,\n ): Promise<string | null> {\n const result = await client.query<{ readonly cursor_value: string | null }>(\n 'SELECT cursor_value FROM gc_cursor WHERE tenant_id = $1 AND cursor_kind = $2',\n [tenant, kind],\n );\n return result.rows[0]?.cursor_value ?? null;\n }\n\n async #writeCursor(\n client: PoolClient,\n tenant: TenantId,\n kind: string,\n value: string,\n ): Promise<void> {\n await client.query(\n `INSERT INTO gc_cursor (tenant_id, cursor_kind, cursor_value, updated_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (tenant_id, cursor_kind) DO UPDATE\n SET cursor_value = EXCLUDED.cursor_value, updated_at = EXCLUDED.updated_at`,\n [tenant, kind, value, this.#now()],\n );\n }\n\n async #clearCursor(client: PoolClient, tenant: TenantId, kind: string): Promise<void> {\n await client.query(\n 'DELETE FROM gc_cursor WHERE tenant_id = $1 AND cursor_kind = $2',\n [tenant, kind],\n );\n }\n\n async #finishJob(\n client: PoolClient,\n tenant: TenantId,\n jobId: string,\n state: CleanupJobState,\n counts: MutableCounts,\n ): Promise<CloudCleanupResult> {\n const finished = await client.query<CleanupJobRow>(\n `UPDATE cleanup_job SET\n state = $3, finished_at = $4,\n mailbox_deleted_count = $5, mailbox_expired_count = $6,\n mailbox_released_bytes = $7, reservations_expired = $8,\n ttl_rows_deleted = $9,\n objects_tombstoned = $10, objects_deleted = $11,\n object_released_bytes = $12, orphan_witnesses_created = $13,\n missing_objects = $14, shape_drift = $15,\n invalid_object_keys = $16, operation_errors = $17,\n error_message = NULL\n WHERE tenant_id = $1 AND job_id = $2\n RETURNING ${JOB_COLUMNS}`,\n [\n tenant,\n jobId,\n state,\n this.#now(),\n counts.mailboxDeletedCount,\n counts.mailboxExpiredCount,\n counts.mailboxReleasedBytes,\n counts.reservationsExpired,\n counts.ttlRowsDeleted,\n counts.objectsTombstoned,\n counts.objectsDeleted,\n counts.objectReleasedBytes,\n counts.orphanWitnessesCreated,\n counts.missingObjects,\n counts.shapeDrift,\n counts.invalidObjectKeys,\n counts.operationErrors,\n ],\n );\n return toCleanupResult(finished.rows[0]!);\n }\n\n async #failJob(\n client: PoolClient,\n tenant: TenantId,\n jobId: string,\n cause: unknown,\n ): Promise<void> {\n const message = (cause instanceof Error ? cause.message : String(cause)).slice(0, 2000);\n await client.query(\n `UPDATE cleanup_job\n SET state = 'failed', finished_at = $3, error_message = $4\n WHERE tenant_id = $1 AND job_id = $2`,\n [tenant, jobId, this.#now(), message],\n );\n }\n\n async #readJob(client: PoolClient, tenant: TenantId, jobId: string): Promise<CleanupJobRow> {\n const result = await client.query<CleanupJobRow>(\n `SELECT ${JOB_COLUMNS} FROM cleanup_job WHERE tenant_id = $1 AND job_id = $2`,\n [tenant, jobId],\n );\n return result.rows[0]!;\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n\n/** Build the maintenance composition against the same Postgres/R2 authority. */\nexport function createPostgresCloudMaintenance(\n options: PostgresCloudMaintenanceOptions,\n): PostgresCloudCleanup {\n const objectStorage = new R2ObjectMaintenanceStore(options.objectStorage);\n return new PostgresCloudCleanup({\n pool: options.pool,\n clock: options.clock,\n objectStorage,\n ...(options.batchSize === undefined ? {} : { batchSize: options.batchSize }),\n });\n}\n\nconst JOB_COLUMNS = [\n 'tenant_id',\n 'job_id',\n 'state',\n 'started_at',\n 'finished_at',\n 'mailbox_deleted_count',\n 'mailbox_expired_count',\n 'mailbox_released_bytes',\n 'reservations_expired',\n 'ttl_rows_deleted',\n 'objects_tombstoned',\n 'objects_deleted',\n 'object_released_bytes',\n 'orphan_witnesses_created',\n 'missing_objects',\n 'shape_drift',\n 'invalid_object_keys',\n 'operation_errors',\n 'error_message',\n].join(', ');\n\nfunction emptyCounts(): MutableCounts {\n return {\n mailboxDeletedCount: 0n,\n mailboxExpiredCount: 0n,\n mailboxReleasedBytes: 0n,\n reservationsExpired: 0n,\n ttlRowsDeleted: 0n,\n objectsTombstoned: 0n,\n objectsDeleted: 0n,\n objectReleasedBytes: 0n,\n orphanWitnessesCreated: 0n,\n missingObjects: 0n,\n shapeDrift: 0n,\n invalidObjectKeys: 0n,\n operationErrors: 0n,\n };\n}\n\nfunction toPolicy(row: RetentionPolicyRow): TenantRetentionPolicy {\n return {\n tenantId: tenantId(row.tenant_id),\n policyId: row.policy_id,\n mailboxAckedRetentionMs: row.mailbox_acked_retention_ms,\n mailboxUnackedRetentionMs: row.mailbox_unacked_retention_ms,\n requestReceiptRetentionMs: row.request_receipt_retention_ms,\n objectOrphanGraceMs: row.object_orphan_grace_ms,\n updatedAt: row.updated_at,\n };\n}\n\nfunction toCleanupResult(row: CleanupJobRow): CloudCleanupResult {\n return {\n tenantId: tenantId(row.tenant_id),\n jobId: row.job_id,\n state: row.state as CleanupJobState,\n startedAt: row.started_at,\n ...(row.finished_at === null ? {} : { finishedAt: row.finished_at }),\n mailboxDeletedCount: row.mailbox_deleted_count,\n mailboxExpiredCount: row.mailbox_expired_count,\n mailboxReleasedBytes: row.mailbox_released_bytes,\n reservationsExpired: row.reservations_expired,\n ttlRowsDeleted: row.ttl_rows_deleted,\n objectsTombstoned: row.objects_tombstoned,\n objectsDeleted: row.objects_deleted,\n objectReleasedBytes: row.object_released_bytes,\n orphanWitnessesCreated: row.orphan_witnesses_created,\n missingObjects: row.missing_objects,\n shapeDrift: row.shape_drift,\n invalidObjectKeys: row.invalid_object_keys,\n operationErrors: row.operation_errors,\n ...(row.error_message === null ? {} : { errorMessage: row.error_message }),\n };\n}\n\nfunction toMailboxMessage(row: OutboxRow): MailboxMessage {\n return {\n tenantId: tenantId(row.tenant_id),\n deviceId: row.device_id,\n seq: Number(row.seq),\n messageId: row.message_id,\n body: row.body,\n bodyHash: row.body_hash as ContentHash,\n byteSize: row.byte_size,\n state: row.state as MailboxMessageState,\n appendedAt: row.appended_at,\n };\n}\n\ninterface ReplayBody {\n readonly body: string;\n readonly bodyHash: ContentHash;\n readonly byteSize: bigint;\n}\n\nfunction materializeReplayBody(original: OutboxRow, seq: number): ReplayBody {\n try {\n const envelope = decodeEnvelope(original.body);\n if (!isServerToDaemonType(envelope.type)) {\n throw new Error(`Envelope type ${envelope.type} is not server-to-daemon.`);\n }\n const rebound = EnvelopeSchema.parse({ ...envelope, seq });\n const body = encodeEnvelope(rebound);\n const bytes = new TextEncoder().encode(body);\n return {\n body,\n bodyHash: contentHash(`sha256:${createHash('sha256').update(bytes).digest('hex')}`),\n byteSize: BigInt(bytes.length),\n };\n } catch (cause) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n `Dead letter ${original.device_id}/${String(original.seq)} is not a replayable server-to-daemon envelope.`,\n { cause },\n );\n }\n}\n\nfunction replayMatches(row: OutboxRow, original: OutboxRow): boolean {\n if (row.replay_source_seq !== original.seq) return false;\n const expected = materializeReplayBody(original, Number(row.seq));\n return (\n row.body === expected.body &&\n row.body_hash === expected.bodyHash &&\n row.byte_size === expected.byteSize\n );\n}\n\nfunction assertPolicy(input: TenantRetentionPolicyInput): void {\n assertIdentifier(input.policyId, 'policyId');\n for (const [field, value] of [\n ['mailboxAckedRetentionMs', input.mailboxAckedRetentionMs],\n ['mailboxUnackedRetentionMs', input.mailboxUnackedRetentionMs],\n ['requestReceiptRetentionMs', input.requestReceiptRetentionMs],\n ['objectOrphanGraceMs', input.objectOrphanGraceMs],\n ] as const) {\n if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n `${field} must be a non-negative duration no larger than Number.MAX_SAFE_INTEGER milliseconds.`,\n );\n }\n }\n}\n\nfunction assertBatchSize(value: number): number {\n if (!Number.isInteger(value) || value < 1 || value > MAX_BATCH_SIZE) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n `batchSize/limit must be a whole number in [1, ${String(MAX_BATCH_SIZE)}].`,\n );\n }\n return value;\n}\n\nfunction assertIdentifier(value: string, field: string): void {\n if (value.length === 0 || value.length > 256 || value.trim() !== value) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n `${field} must be a non-empty, unpadded string no longer than 256 characters.`,\n );\n }\n}\n\nfunction assertDeadLetterRef(ref: DeadLetterRef): void {\n assertIdentifier(ref.deviceId, 'deviceId');\n if (!Number.isSafeInteger(ref.seq) || ref.seq < 1) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n 'A dead-letter seq must be a positive safe integer.',\n );\n }\n}\n\nfunction cutoff(now: Date, durationMs: bigint): string {\n return new Date(now.getTime() - Number(durationMs)).toISOString();\n}\n\nfunction deadLetterMissing(ref: DeadLetterRef): CloudCleanupError {\n return new CloudCleanupError(\n 'cleanup_dead_letter_not_found',\n `Expired mailbox row ${ref.deviceId}/${String(ref.seq)} was not found.`,\n );\n}\n","/**\n * Package-owned, resumable tenant erasure for the Node maintenance surface.\n *\n * Cleanup's policy/cursor/accounting lifecycle is intentionally not reused.\n * Here the durable operation receipt is the authority: it records the opaque\n * R2 cursor before any SQL is touched, carries a short CAS lease while one\n * caller advances bounded work, and survives every product-data deletion.\n */\nimport { randomUUID } from 'node:crypto';\nimport { tenantId, type Clock, type TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\nimport {\n R2ObjectMaintenanceStore,\n type R2BlobStoreOptions,\n type R2ObjectMaintenance,\n} from './stores/r2-blobs';\n\nconst DEFAULT_BATCH_SIZE = 100;\nconst DEFAULT_MAX_PAGES_PER_RUN = 10;\nconst DEFAULT_LEASE_MS = 30_000;\nconst MAX_BATCH_SIZE = 1_000;\nconst MAX_PAGES_PER_RUN = 100;\nconst MAX_LEASE_MS = 5 * 60_000;\n\n/** Every tenant-owned table as of 0010, in child-before-parent deletion order. */\nexport const TENANT_ERASURE_TABLES = [\n 'object_reference',\n 'object_manifest',\n 'storage_reservation',\n 'storage_usage',\n 'storage_entitlement',\n 'gc_cursor',\n 'cleanup_job',\n 'tenant_retention_policy',\n 'skill_pack_file',\n 'skill_pack',\n 'approval_timeline_tail',\n 'activity_tail',\n 'attested_record',\n 'board_item',\n 'tenant_stream',\n 'outbox',\n 'device_request_receipts',\n 'proof_request_receipt',\n 'task',\n 'device_presence',\n 'device_assertion_replay',\n 'device_stream',\n 'inbound_dedup',\n 'auth_nonce',\n 'pairing_code',\n 'device',\n] as const;\n\nconst TENANT_ERASURE_TABLE_SET = new Set<string>(TENANT_ERASURE_TABLES);\n\nexport const TENANT_ERASURE_ERROR_CODES = {\n tenant_erasure_invalid_input: 'tenant_erasure_invalid_input',\n tenant_erasure_schema_drift: 'tenant_erasure_schema_drift',\n tenant_erasure_object_key_invalid: 'tenant_erasure_object_key_invalid',\n tenant_erasure_storage_failure: 'tenant_erasure_storage_failure',\n tenant_erasure_database_failure: 'tenant_erasure_database_failure',\n tenant_erasure_cas_lost: 'tenant_erasure_cas_lost',\n} as const;\n\nexport type TenantErasureErrorCode =\n (typeof TENANT_ERASURE_ERROR_CODES)[keyof typeof TENANT_ERASURE_ERROR_CODES];\n\nexport class TenantErasureError extends Error {\n readonly code: TenantErasureErrorCode;\n\n constructor(code: TenantErasureErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'TenantErasureError';\n this.code = code;\n }\n}\n\nexport type TenantErasureStatus = 'outstanding' | 'partial' | 'completed';\n\nexport interface TenantErasureReadback {\n readonly status: TenantErasureStatus;\n readonly tenantId: TenantId;\n readonly operationId: string;\n readonly startedAt: string;\n readonly updatedAt: string;\n readonly completedAt?: string;\n readonly r2Complete: boolean;\n readonly sqlTableIndex: number;\n readonly r2ObjectsDeleted: bigint;\n readonly sqlRowsDeleted: bigint;\n /** A closed, audit-safe class. Remote messages and object names are never retained. */\n readonly errorCode?: TenantErasureErrorCode;\n}\n\nexport interface TenantErasureConflict {\n readonly status: 'conflict';\n readonly tenantId: TenantId;\n readonly operationId: string;\n readonly activeOperationId: string;\n}\n\nexport type TenantErasureResult = TenantErasureReadback | TenantErasureConflict;\n\nexport interface PostgresTenantErasureOptions {\n /** A Node direct-DSN pool. The host owns pool lifetime and write quiescence. */\n readonly pool: Pool;\n readonly clock: Clock;\n readonly objectStorage: R2ObjectMaintenance;\n /** ListObjectsV2 and one SQL DELETE use this bound; valid range is 1..1000. */\n readonly batchSize?: number;\n /** Maximum R2/SQL pages one operator invocation may advance; valid range is 1..100. */\n readonly maxPagesPerRun?: number;\n /** Crash-recovery lease; a retry may take an expired lease using the operation CAS. */\n readonly leaseMs?: number;\n}\n\nexport interface PostgresTenantErasureCompositionOptions {\n readonly pool: Pool;\n readonly clock: Clock;\n readonly objectStorage: Omit<R2BlobStoreOptions, 'objects'>;\n readonly batchSize?: number;\n readonly maxPagesPerRun?: number;\n readonly leaseMs?: number;\n}\n\ninterface OperationRow {\n readonly tenant_id: string;\n readonly operation_id: string;\n readonly state: 'running' | 'completed';\n readonly revision: bigint;\n readonly lease_token: string | null;\n readonly lease_expires_at: Date | null;\n readonly r2_cursor: string | null;\n readonly r2_complete: boolean;\n readonly sql_table_index: number;\n readonly r2_objects_deleted: bigint;\n readonly sql_rows_deleted: bigint;\n readonly started_at: Date;\n readonly updated_at: Date;\n readonly completed_at: Date | null;\n readonly last_error_code: string | null;\n}\n\nconst OPERATION_COLUMNS = [\n 'tenant_id',\n 'operation_id',\n 'state',\n 'revision',\n 'lease_token',\n 'lease_expires_at',\n 'r2_cursor',\n 'r2_complete',\n 'sql_table_index',\n 'r2_objects_deleted',\n 'sql_rows_deleted',\n 'started_at',\n 'updated_at',\n 'completed_at',\n 'last_error_code',\n].join(', ');\n\n/**\n * The Node-only erasure authority. It has no raw-table or raw-key API: the\n * static inventory and canonical R2 adapter are the only deletion authority.\n */\nexport class PostgresTenantErasure {\n readonly #pool: Pool;\n readonly #clock: Clock;\n readonly #objectStorage: R2ObjectMaintenance;\n readonly #batchSize: number;\n readonly #maxPagesPerRun: number;\n readonly #leaseMs: number;\n\n constructor(options: PostgresTenantErasureOptions) {\n this.#pool = options.pool;\n this.#clock = options.clock;\n this.#objectStorage = options.objectStorage;\n this.#batchSize = assertBoundedWhole(options.batchSize ?? DEFAULT_BATCH_SIZE, 'batchSize', MAX_BATCH_SIZE);\n this.#maxPagesPerRun = assertBoundedWhole(\n options.maxPagesPerRun ?? DEFAULT_MAX_PAGES_PER_RUN,\n 'maxPagesPerRun',\n MAX_PAGES_PER_RUN,\n );\n this.#leaseMs = assertBoundedWhole(options.leaseMs ?? DEFAULT_LEASE_MS, 'leaseMs', MAX_LEASE_MS);\n }\n\n /** Read a durable operation receipt without advancing it. */\n async readTenantErasure(tenant: TenantId, operationId: string): Promise<TenantErasureReadback | undefined> {\n assertOperationId(operationId);\n const row = await this.#readOperation(tenant, operationId);\n return row === undefined ? undefined : toReadback(row);\n }\n\n /**\n * Advance one bounded operation slice. Calls with a completed id replay its\n * receipt; another running id for the same tenant gets a typed conflict.\n */\n async eraseTenant(tenant: TenantId, operationId: string): Promise<TenantErasureResult> {\n assertOperationId(operationId);\n\n // A completed receipt is frozen operator evidence, not tenant product\n // data. Replay must therefore remain stable even when a later migration\n // makes the product-table inventory unsafe for every new/running erase.\n // No running or absent operation passes this branch: those still assert\n // the exact live inventory before acquiring or advancing a lease.\n let existing: OperationRow | undefined;\n try {\n existing = await this.#readOperation(tenant, operationId);\n } catch (cause) {\n throw databaseFailure('reading tenant erasure operation', cause);\n }\n if (existing?.state === 'completed') return toReadback(existing);\n\n await this.#assertSchemaInventory();\n\n let row: OperationRow;\n try {\n const opened = await this.#openOperation(tenant, operationId);\n if ('status' in opened) return opened;\n row = opened;\n } catch (cause) {\n throw databaseFailure('opening tenant erasure operation', cause);\n }\n\n if (row.state === 'completed') return toReadback(row);\n\n const leaseToken = randomUUID();\n let claimed: OperationRow | undefined;\n try {\n claimed = await this.#claim(tenant, operationId, row.revision, leaseToken);\n if (claimed === undefined) return await this.#readConflictOrReceipt(tenant, operationId);\n\n for (let page = 0; page < this.#maxPagesPerRun; page += 1) {\n if (!claimed.r2_complete) {\n claimed = await this.#eraseR2Page(tenant, claimed, leaseToken);\n continue;\n }\n if (claimed.sql_table_index < TENANT_ERASURE_TABLES.length) {\n claimed = await this.#eraseSqlPage(tenant, claimed, leaseToken);\n continue;\n }\n claimed = await this.#verifyAndComplete(tenant, claimed, leaseToken);\n if (claimed.state === 'completed') return toReadback(claimed);\n }\n\n return toReadback(await this.#release(tenant, operationId, claimed.revision, leaseToken));\n } catch (cause) {\n if (claimed === undefined) throw databaseFailure('claiming tenant erasure operation', cause);\n const code = cause instanceof TenantErasureError\n ? cause.code\n : TENANT_ERASURE_ERROR_CODES.tenant_erasure_database_failure;\n try {\n return toReadback(await this.#recordPartial(tenant, operationId, claimed.revision, leaseToken, code));\n } catch (recordCause) {\n throw databaseFailure('recording tenant erasure partial outcome', recordCause);\n }\n }\n }\n\n async #assertSchemaInventory(): Promise<void> {\n const found = await this.#pool.query<{ readonly relname: string }>(\n `SELECT t.relname\n FROM pg_class t\n JOIN pg_namespace n ON n.oid = t.relnamespace\n WHERE n.nspname = current_schema()\n AND t.relkind = 'r'\n AND t.relname NOT IN ('byok_schema_migration', 'tenant_erasure_operation')\n ORDER BY t.relname`,\n );\n const actual = new Set(found.rows.map((row) => row.relname));\n const missing = TENANT_ERASURE_TABLES.filter((name) => !actual.has(name));\n const unexpected = [...actual].filter((name) => !TENANT_ERASURE_TABLE_SET.has(name));\n if (missing.length === 0 && unexpected.length === 0 && actual.size === TENANT_ERASURE_TABLES.length) return;\n throw new TenantErasureError(\n 'tenant_erasure_schema_drift',\n `Tenant erasure inventory drift: missing=[${missing.join(',')}], unexpected=[${unexpected.join(',')}].`,\n );\n }\n\n async #openOperation(\n tenant: TenantId,\n operationId: string,\n ): Promise<OperationRow | TenantErasureConflict> {\n const now = this.#clock.now();\n try {\n await this.#pool.query(\n `INSERT INTO tenant_erasure_operation (\n tenant_id, operation_id, state, started_at, updated_at\n ) VALUES ($1, $2, 'running', $3, $3)\n ON CONFLICT (tenant_id, operation_id) DO NOTHING`,\n [tenant, operationId, now],\n );\n } catch (cause) {\n if (postgresCode(cause) !== '23505') throw cause;\n return this.#conflict(tenant, operationId);\n }\n\n const own = await this.#readOperation(tenant, operationId);\n if (own !== undefined) return own;\n // The only possible winner is another active operation. If it finished in\n // the intervening instant, retrying is an operator decision, not a silent\n // second erase under an id that never acquired a receipt.\n return this.#conflict(tenant, operationId);\n }\n\n async #claim(\n tenant: TenantId,\n operationId: string,\n revision: bigint,\n leaseToken: string,\n ): Promise<OperationRow | undefined> {\n const now = this.#clock.now();\n const leaseExpiresAt = new Date(now.getTime() + this.#leaseMs);\n const result = await this.#pool.query<OperationRow>(\n `UPDATE tenant_erasure_operation\n SET lease_token = $1,\n lease_expires_at = $2,\n revision = revision + 1,\n updated_at = $3,\n last_error_code = NULL\n WHERE tenant_id = $4\n AND operation_id = $5\n AND state = 'running'\n AND revision = $6::bigint\n AND (lease_token IS NULL OR lease_expires_at <= $3)\n RETURNING ${OPERATION_COLUMNS}`,\n [leaseToken, leaseExpiresAt, now, tenant, operationId, revision],\n );\n return result.rows[0];\n }\n\n async #eraseR2Page(tenant: TenantId, row: OperationRow, leaseToken: string): Promise<OperationRow> {\n let page;\n try {\n page = await this.#objectStorage.listTenantObjects(\n tenant,\n row.r2_cursor ?? undefined,\n this.#batchSize,\n );\n } catch (cause) {\n throw storageFailure('listing the tenant R2 namespace', cause);\n }\n\n for (const object of page.objects) {\n if (object.hash === undefined) {\n throw new TenantErasureError(\n 'tenant_erasure_object_key_invalid',\n 'Tenant R2 namespace contains a non-canonical object key; erasure refused before SQL deletion.',\n );\n }\n try {\n await this.#objectStorage.deleteObject(tenant, object.hash);\n } catch (cause) {\n throw storageFailure('deleting a tenant R2 object', cause);\n }\n }\n\n return this.#casUpdate(tenant, row.operation_id, row.revision, leaseToken,\n `r2_cursor = $1,\n r2_complete = $2,\n r2_objects_deleted = r2_objects_deleted + $3::bigint`,\n [page.nextContinuationToken ?? null, page.nextContinuationToken === undefined, page.objects.length],\n );\n }\n\n async #eraseSqlPage(tenant: TenantId, row: OperationRow, leaseToken: string): Promise<OperationRow> {\n const table = TENANT_ERASURE_TABLES[row.sql_table_index];\n if (table === undefined) {\n throw new TenantErasureError('tenant_erasure_cas_lost', 'Tenant erasure SQL progress escaped its static inventory.');\n }\n let deleted: bigint;\n try {\n const result = await this.#pool.query<{ readonly deleted: bigint }>(\n `WITH deleted AS (\n DELETE FROM ${table}\n WHERE ctid IN (\n SELECT ctid FROM ${table}\n WHERE tenant_id = $1\n LIMIT $2\n )\n RETURNING 1\n )\n SELECT count(*)::bigint AS deleted FROM deleted`,\n [tenant, this.#batchSize],\n );\n deleted = result.rows[0]!.deleted;\n } catch (cause) {\n throw databaseFailure(`deleting tenant rows from ${table}`, cause);\n }\n\n const nextTableIndex = deleted < BigInt(this.#batchSize)\n ? row.sql_table_index + 1\n : row.sql_table_index;\n return this.#casUpdate(tenant, row.operation_id, row.revision, leaseToken,\n `sql_table_index = $1,\n sql_rows_deleted = sql_rows_deleted + $2::bigint`,\n [nextTableIndex, deleted],\n );\n }\n\n async #verifyAndComplete(tenant: TenantId, row: OperationRow, leaseToken: string): Promise<OperationRow> {\n try {\n const r2 = await this.#objectStorage.listTenantObjects(tenant, undefined, 1);\n if (r2.objects.length > 0) {\n return this.#casUpdate(tenant, row.operation_id, row.revision, leaseToken,\n 'r2_cursor = NULL, r2_complete = false',\n [],\n );\n }\n } catch (cause) {\n throw storageFailure('verifying the tenant R2 namespace is empty', cause);\n }\n\n for (const table of TENANT_ERASURE_TABLES) {\n let present: boolean;\n try {\n const result = await this.#pool.query<{ readonly present: boolean }>(\n `SELECT EXISTS (SELECT 1 FROM ${table} WHERE tenant_id = $1) AS present`,\n [tenant],\n );\n present = result.rows[0]!.present;\n } catch (cause) {\n throw databaseFailure(`verifying tenant rows in ${table}`, cause);\n }\n if (present) {\n return this.#casUpdate(tenant, row.operation_id, row.revision, leaseToken,\n 'sql_table_index = 0',\n [],\n );\n }\n }\n\n const now = this.#clock.now();\n return this.#casUpdate(tenant, row.operation_id, row.revision, leaseToken,\n `state = 'completed',\n completed_at = $1,\n lease_token = NULL,\n lease_expires_at = NULL,\n last_error_code = NULL`,\n [now],\n false,\n );\n }\n\n async #release(tenant: TenantId, operationId: string, revision: bigint, leaseToken: string): Promise<OperationRow> {\n return this.#casUpdate(tenant, operationId, revision, leaseToken,\n 'lease_token = NULL, lease_expires_at = NULL',\n [],\n false,\n );\n }\n\n async #recordPartial(\n tenant: TenantId,\n operationId: string,\n revision: bigint,\n leaseToken: string,\n errorCode: TenantErasureErrorCode,\n ): Promise<OperationRow> {\n return this.#casUpdate(tenant, operationId, revision, leaseToken,\n `lease_token = NULL,\n lease_expires_at = NULL,\n last_error_code = $1`,\n [errorCode],\n false,\n );\n }\n\n async #casUpdate(\n tenant: TenantId,\n operationId: string,\n revision: bigint,\n leaseToken: string,\n setClause: string,\n setValues: readonly unknown[],\n refreshLease = true,\n ): Promise<OperationRow> {\n const now = this.#clock.now();\n const values = [...setValues];\n let refreshClause = '';\n if (refreshLease) {\n values.push(new Date(now.getTime() + this.#leaseMs));\n refreshClause = `, lease_expires_at = $${String(values.length)}`;\n }\n values.push(now, tenant, operationId, revision, leaseToken);\n const updatedAtIndex = values.length - 4;\n const tenantIndex = values.length - 3;\n const operationIndex = values.length - 2;\n const revisionIndex = values.length - 1;\n const leaseIndex = values.length;\n const result = await this.#pool.query<OperationRow>(\n `UPDATE tenant_erasure_operation\n SET ${setClause}${refreshClause},\n revision = revision + 1,\n updated_at = $${String(updatedAtIndex)}\n WHERE tenant_id = $${String(tenantIndex)}\n AND operation_id = $${String(operationIndex)}\n AND state = 'running'\n AND revision = $${String(revisionIndex)}::bigint\n AND lease_token = $${String(leaseIndex)}\n RETURNING ${OPERATION_COLUMNS}`,\n values,\n );\n const row = result.rows[0];\n if (row !== undefined) return row;\n throw new TenantErasureError(\n 'tenant_erasure_cas_lost',\n 'Tenant erasure operation no longer owns its durable progress lease.',\n );\n }\n\n async #readOperation(tenant: TenantId, operationId: string): Promise<OperationRow | undefined> {\n const result = await this.#pool.query<OperationRow>(\n `SELECT ${OPERATION_COLUMNS}\n FROM tenant_erasure_operation\n WHERE tenant_id = $1 AND operation_id = $2`,\n [tenant, operationId],\n );\n return result.rows[0];\n }\n\n async #readConflictOrReceipt(tenant: TenantId, operationId: string): Promise<TenantErasureResult> {\n const own = await this.#readOperation(tenant, operationId);\n if (own?.state === 'completed') return toReadback(own);\n // The same id is idempotent only after its receipt is terminal. While a\n // caller holds the CAS lease, a second concurrent caller receives the\n // same typed conflict a distinct operation id receives; it must not be\n // handed an \"outstanding\" result that suggests it owns progress.\n if (\n own !== undefined &&\n own.lease_token !== null &&\n own.lease_expires_at !== null &&\n own.lease_expires_at > this.#clock.now()\n ) {\n return { status: 'conflict', tenantId: tenant, operationId, activeOperationId: own.operation_id };\n }\n if (own !== undefined) return toReadback(own);\n return this.#conflict(tenant, operationId);\n }\n\n async #conflict(tenant: TenantId, operationId: string): Promise<TenantErasureConflict> {\n const active = await this.#pool.query<{ readonly operation_id: string }>(\n `SELECT operation_id\n FROM tenant_erasure_operation\n WHERE tenant_id = $1 AND state = 'running'`,\n [tenant],\n );\n const winner = active.rows[0];\n if (winner === undefined) {\n throw new TenantErasureError(\n 'tenant_erasure_cas_lost',\n 'Tenant erasure operation changed while acquiring its receipt; retry with the same operation id.',\n );\n }\n return { status: 'conflict', tenantId: tenant, operationId, activeOperationId: winner.operation_id };\n }\n}\n\n/** Build the Node maintenance composition against the same direct Postgres/R2 authorities. */\nexport function createPostgresTenantErasure(\n options: PostgresTenantErasureCompositionOptions,\n): PostgresTenantErasure {\n return new PostgresTenantErasure({\n pool: options.pool,\n clock: options.clock,\n objectStorage: new R2ObjectMaintenanceStore(options.objectStorage),\n ...(options.batchSize === undefined ? {} : { batchSize: options.batchSize }),\n ...(options.maxPagesPerRun === undefined ? {} : { maxPagesPerRun: options.maxPagesPerRun }),\n ...(options.leaseMs === undefined ? {} : { leaseMs: options.leaseMs }),\n });\n}\n\nfunction toReadback(row: OperationRow): TenantErasureReadback {\n const status: TenantErasureStatus = row.state === 'completed'\n ? 'completed'\n : row.last_error_code === null\n ? 'outstanding'\n : 'partial';\n return {\n status,\n tenantId: tenantId(row.tenant_id),\n operationId: row.operation_id,\n startedAt: row.started_at.toISOString(),\n updatedAt: row.updated_at.toISOString(),\n ...(row.completed_at === null ? {} : { completedAt: row.completed_at.toISOString() }),\n r2Complete: row.r2_complete,\n sqlTableIndex: row.sql_table_index,\n r2ObjectsDeleted: row.r2_objects_deleted,\n sqlRowsDeleted: row.sql_rows_deleted,\n ...(row.last_error_code === null ? {} : { errorCode: row.last_error_code as TenantErasureErrorCode }),\n };\n}\n\nfunction assertOperationId(operationId: string): void {\n if (operationId.length === 0 || operationId.length > 256 || operationId.trim() !== operationId) {\n throw new TenantErasureError(\n 'tenant_erasure_invalid_input',\n 'operationId must be a non-empty, unpadded string no longer than 256 characters.',\n );\n }\n}\n\nfunction assertBoundedWhole(value: number, field: string, max: number): number {\n if (!Number.isSafeInteger(value) || value < 1 || value > max) {\n throw new TenantErasureError(\n 'tenant_erasure_invalid_input',\n `${field} must be a whole number in [1, ${String(max)}].`,\n );\n }\n return value;\n}\n\nfunction postgresCode(cause: unknown): string | undefined {\n return typeof cause === 'object' && cause !== null && 'code' in cause && typeof cause.code === 'string'\n ? cause.code\n : undefined;\n}\n\nfunction storageFailure(action: string, cause: unknown): TenantErasureError {\n return new TenantErasureError(\n 'tenant_erasure_storage_failure',\n `Tenant erasure could not finish ${action}; no SQL progress was advanced.`,\n { cause },\n );\n}\n\nfunction databaseFailure(action: string, cause: unknown): TenantErasureError {\n return cause instanceof TenantErasureError\n ? cause\n : new TenantErasureError(\n 'tenant_erasure_database_failure',\n `Tenant erasure could not finish ${action}; retry with the same operation id.`,\n { cause },\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/pool.ts","../src/stores/core/objects.ts","../src/stores/r2-blobs.ts","../src/stores/devices.ts","../src/stores/dedup.ts","../src/stores/nonces.ts","../src/stores/pairing-codes.ts","../src/stores/receipts.ts","../src/stores/proof-receipts.ts","../src/stores/task-attempts.ts","../src/stores/core/mailbox-sequence.ts","../src/stores/core/mailbox.ts","../src/stores/task-cancellations.ts","../src/stores/activity.ts","../src/stores/approval-timeline.ts","../src/stores/agent-egress.ts","../src/stores/device-assertion-replay.ts","../src/stores/index.ts","../src/stores/core/presence.ts","../src/stores/core/board.ts","../src/stores/core/quota.ts","../src/stores/core/skill-pack.ts","../src/stores/core/truth.ts","../src/stores/core/index.ts","../src/truth-committer.ts","../src/migrations-dir.ts","../src/migrate.ts","../src/cleanup.ts","../src/tenant-erasure.ts"],"names":["ByokCoreError","SELECT_COLUMNS","toReceipt","assertCanonicalTimestamp","toTail","ByokCloudError","toRecord","DEFAULT_LIST_LIMIT","CoreConflictError","RECORD_COLUMNS","toBody","bodyColumns","response","OUTBOX_COLUMNS","toMailboxMessage","contentHash","createHash","DEFAULT_BATCH_SIZE","MAX_BATCH_SIZE","tenantId"],"mappings":";;;;;;;;;;;;AAwBA,IAAM,iBAAA,GAAoB,GAAG,KAAA,CAAM,aAAA;AAEnC,IAAM,WAAA,GAAmC;AAAA,EACvC,aAAA,CAAc,IAAI,MAAA,EAAQ;AACxB,IAAA,IAAI,EAAA,KAAO,GAAG,KAAA,CAAM,QAAA,CAAS,MAAM,OAAO,CAAC,KAAA,KAAkB,MAAA,CAAO,KAAK,CAAA;AACzE,IAAA,OAAO,iBAAA,CAAkB,IAAI,MAAM,CAAA;AAAA,EACrC;AACF,CAAA;AAwCO,SAAS,eAAe,OAAA,EAAgC;AAG7D,EAAA,MAAM,EAAE,WAAA,EAAa,GAAG,UAAA,EAAW,GAAI,OAAA;AACvC,EAAA,MAAM,IAAA,GAAO,IAAI,EAAA,CAAG,IAAA,CAAK,EAAE,GAAG,UAAA,EAAY,KAAA,EAAO,WAAA,EAAa,CAAA;AAE9D,EAAA,IAAA,CAAK,EAAA,CAAG,OAAA,EAAS,CAAC,GAAA,EAAY,MAAA,KAAwB;AACpD,IAAA,IAAI,WAAA,EAAa;AACf,MAAA,WAAA,CAAY,KAAK,MAAM,CAAA;AACvB,MAAA;AAAA,IACF;AAIA,IAAA,OAAA,CAAQ,KAAA,CAAM,6DAA6D,GAAG,CAAA;AAAA,EAChF,CAAC,CAAA;AAED,EAAA,OAAO,IAAA;AACT;AC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AAA,IAAS,OAAO,KAAA,CAAM,IAAA,KAAS,QAAA,GAC3F,KAAA,CAAM,IAAA,GACN,MAAA;AACN;AAEA,SAAS,cAAA,CAAe,QAAgB,KAAA,EAAoC;AAC1E,EAAA,OAAO,IAAI,kBAAA;AAAA,IACT,gCAAA;AAAA,IACA,mCAAmC,MAAM,CAAA,+BAAA,CAAA;AAAA,IACzC,EAAE,KAAA;AAAM,GACV;AACF;AAEA,SAAS,eAAA,CAAgB,QAAgB,KAAA,EAAoC;AAC3E,EAAA,OAAO,KAAA,YAAiB,kBAAA,GACpB,KAAA,GACA,IAAI,kBAAA;AAAA,IACJ,iCAAA;AAAA,IACA,mCAAmC,MAAM,CAAA,mCAAA,CAAA;AAAA,IACzC,EAAE,KAAA;AAAM,GACV;AACJ","file":"index.js","sourcesContent":["/**\n * The `pg` Pool factory.\n *\n * One thing here is load-bearing and easy to get wrong: **int8 parsing**.\n * `pg` decodes `bigint` columns as strings by default, because a 64-bit value\n * does not fit a JS `number`. Every byte-count contract in `@byok-sdk/core` is\n * declared `bigint` (`byteSize`, `releasedBytes`, the whole quota surface), so\n * a default-configured pool would hand the stores strings, and\n * `usage.reservedBytes > limit` would silently become a lexicographic string\n * comparison that answers a different question. Nothing would throw.\n *\n * The parser is injected **into the pool config**, never onto `pg.types`. That\n * registry is process-wide: mutating it would reach into every other `pg`\n * consumer in the host application, including ones that deliberately want\n * strings back. A host composing this SDK next to its own database code must\n * not have its decoding changed by one of our import side effects.\n */\nimport pg from 'pg';\nimport type { Pool, PoolClient, PoolConfig } from 'pg';\n\n/**\n * `pg`'s default parser for every other oid, so this config ADDS one decoding\n * rule instead of replacing the table.\n */\nconst defaultTypeParser = pg.types.getTypeParser;\n\nconst int8Parsers: PoolConfig['types'] = {\n getTypeParser(id, format) {\n if (id === pg.types.builtins.INT8) return (value: string) => BigInt(value);\n return defaultTypeParser(id, format);\n },\n};\n\nexport interface ByokPoolOptions extends Omit<PoolConfig, 'types'> {\n /** `postgres://user:password@host:port/database`. */\n readonly connectionString: string;\n /**\n * Where an IDLE client's error goes. See {@link createByokPool} — a pool\n * MUST carry an `'error'` listener or an idle-backend reset crashes the host.\n * This is where the host takes over that policy (log to its own sink, page,\n * increment a metric). It is NOT a `PoolConfig` field, so it is stripped\n * before the config reaches `pg.Pool`, exactly as `types` is kept off the\n * process-wide registry.\n *\n * Left unset, the pool still gets a listener — an observable default, not a\n * silent swallow.\n */\n readonly onPoolError?: (err: Error, client?: PoolClient) => void;\n}\n\n/**\n * Creates a pool wired with the int8 parser above.\n *\n * The caller owns the pool's lifetime: this package never holds a module-level\n * pool, because a process that composes two deployments (a migration runner and\n * a serving path, say) has to be able to close one without breaking the other.\n *\n * The `'error'` listener is MANDATORY, not defensive. A `pg.Pool` emits\n * `'error'` when a client that is sitting IDLE in the pool has its backend\n * connection reset from under it — a failover, an operator\n * `pg_terminate_backend`, an idle-timeout on a proxy, a network blip. There is\n * no `await` in flight to reject at that moment, so `pg` surfaces it on the\n * pool, and Node's rule for an `EventEmitter` `'error'` with no listener is to\n * rethrow it as an uncaught exception — which terminates the whole host\n * process. A bare `new pg.Pool(...)` therefore hands the host a latent crash on\n * an event it cannot see coming and did not cause. The listener converts that\n * into a handled, observable event: routed to the host's {@link\n * ByokPoolOptions.onPoolError} when supplied, or to a labelled `console.error`\n * so the reset is never invisible. It does not paper over live query errors —\n * those still reject their own `await`; this is only the idle-client path.\n */\nexport function createByokPool(options: ByokPoolOptions): Pool {\n // `onPoolError` is ours, not `pg`'s: strip it before the config reaches\n // `pg.Pool`, the same discipline `types` gets.\n const { onPoolError, ...poolConfig } = options;\n const pool = new pg.Pool({ ...poolConfig, types: int8Parsers });\n\n pool.on('error', (err: Error, client?: PoolClient) => {\n if (onPoolError) {\n onPoolError(err, client);\n return;\n }\n // Observable default: the host owns the policy, but the SDK never lets an\n // idle-client reset pass silently. `console.error` keeps it fail-safe (the\n // process survives) without pretending nothing happened.\n console.error('[byok-sdk] idle pg pool client error (handled, not fatal)', err);\n });\n\n return pool;\n}\n","/**\n * Postgres {@link ObjectStore} — the manifest, and only the manifest\n * (§12.7.4, §12.7.8).\n *\n * Zero bytes cross this file. The manifest is the transaction authority and the\n * object store holds the payload; the R2 adapter that moves bytes is S4A-c.\n * What lives here is the state machine that stands between a failed object-store\n * delete and either a leaked object or a deleted one a truth record still points\n * at.\n *\n * Three properties the SQL is shaped around:\n *\n * - **`ref_count` is recomputed, never incremented.** Every reference mutation\n * sets it to `count(*)` over `object_reference`. An increment drifts the\n * moment a retried `addReference` lands twice, and a drifted count strands\n * the object forever because `markDeletePending` refuses at `refCount != 0`.\n * The reference table's primary key already makes the write idempotent; the\n * count just reads it.\n * - **Reference mutations hold the manifest row under `FOR UPDATE`.** The\n * recomputation above is only authoritative because of this lock, not on its\n * own: under READ COMMITTED the `count(*)` subquery is evaluated on the\n * snapshot its statement started with, so an unlocked `addReference` reads a\n * `committed` state, and `markDeletePending`'s `ref_count = 0` guard can pass\n * in the window before the reference row lands — leaving `delete_pending`\n * with a live reference, which is a truth record pointing at bytes S4B's GC\n * is entitled to delete. Taking the manifest row exclusively first makes the\n * tombstone and the reference write queue against each other, exactly as\n * `PostgresQuotaStore.reserve` serializes reservers on the entitlement row.\n * - **Every state move is a guarded `UPDATE`.** The legal transitions are the\n * guard, so an illegal one writes nothing and the row is re-read to say which\n * typed rejection applies. `commit` additionally guards on the DECLARED size\n * and type, because the whole point of the check is that what the composition\n * observed on the object store and what the client declared can differ\n * (§12.7.7 step 4).\n */\nimport {\n ByokCoreError,\n assertCanonicalTimestamp,\n type Clock,\n type ContentHash,\n type ObjectCommitInput,\n type ObjectListQuery,\n type ObjectManifestEntry,\n type ObjectManifestInput,\n type ObjectReferenceInput,\n type ObjectState,\n type ObjectStore,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { Pool, PoolClient } from 'pg';\n\nconst DEFAULT_LIST_LIMIT = 100;\n\nconst MANIFEST_COLUMNS =\n 'tenant_id, hash, byte_size, content_type, state, ref_count, created_at, updated_at, delete_pending_at';\n\ninterface ManifestRow {\n readonly tenant_id: string;\n readonly hash: string;\n readonly byte_size: bigint;\n readonly content_type: string;\n readonly state: string;\n readonly ref_count: number;\n readonly created_at: string;\n readonly updated_at: string;\n readonly delete_pending_at: string | null;\n}\n\nfunction toEntry(row: ManifestRow): ObjectManifestEntry {\n return {\n tenantId: row.tenant_id as TenantId,\n hash: row.hash as ContentHash,\n byteSize: row.byte_size,\n contentType: row.content_type,\n state: row.state as ObjectState,\n refCount: row.ref_count,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n ...(row.delete_pending_at === null ? {} : { deletePendingAt: row.delete_pending_at }),\n };\n}\n\nexport class PostgresObjectStore implements ObjectStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async putManifest(\n tenant: TenantId,\n input: ObjectManifestInput,\n ): Promise<ObjectManifestEntry> {\n const now = this.#now();\n // Idempotent per (tenant, hash): a row that exists in any state but\n // `deleted` is returned untouched, so a retried reservation cannot reset a\n // committed object back to `pending` and orphan its references. A `deleted`\n // row is the one case where the same hash legitimately starts over, and the\n // `WHERE` on the conflict path is what limits the reset to it.\n const upserted = await this.#pool.query<ManifestRow>(\n `INSERT INTO object_manifest (${MANIFEST_COLUMNS})\n VALUES ($1, $2, $3::bigint, $4, 'pending', 0, $5, $5, NULL)\n ON CONFLICT (tenant_id, hash) DO UPDATE\n SET byte_size = EXCLUDED.byte_size,\n content_type = EXCLUDED.content_type,\n state = 'pending',\n ref_count = 0,\n created_at = EXCLUDED.created_at,\n updated_at = EXCLUDED.updated_at,\n delete_pending_at = NULL\n WHERE object_manifest.state = 'deleted'\n RETURNING ${MANIFEST_COLUMNS}`,\n [tenant, input.hash, input.byteSize, input.contentType, now],\n );\n const row = upserted.rows[0];\n if (row !== undefined) return toEntry(row);\n return this.#require(tenant, input.hash);\n }\n\n async commit(tenant: TenantId, input: ObjectCommitInput): Promise<ObjectManifestEntry> {\n const committed = await this.#pool.query<ManifestRow>(\n `UPDATE object_manifest\n SET state = 'committed', updated_at = $3\n WHERE tenant_id = $1 AND hash = $2\n AND state = 'pending'\n AND byte_size = $4::bigint\n AND content_type = $5\n RETURNING ${MANIFEST_COLUMNS}`,\n [tenant, input.hash, this.#now(), input.observedByteSize, input.observedContentType],\n );\n const row = committed.rows[0];\n if (row !== undefined) return toEntry(row);\n\n const current = await this.#require(tenant, input.hash);\n // Integrity outranks state: an object whose observed shape disagrees is a\n // mismatch whatever state the row is in, and it stays `pending` so the GC\n // worker can reclaim the bytes rather than a truth record pointing at them.\n if (\n current.byteSize !== input.observedByteSize ||\n current.contentType !== input.observedContentType\n ) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Observed object ${input.hash} (${String(input.observedByteSize)} bytes, ${input.observedContentType}) does not match the declared manifest.`,\n );\n }\n if (current.state === 'committed') return current;\n throw this.#stateInvalid(current.state, 'committed');\n }\n\n async get(tenant: TenantId, hash: ContentHash): Promise<ObjectManifestEntry | undefined> {\n const result = await this.#pool.query<ManifestRow>(\n `SELECT ${MANIFEST_COLUMNS} FROM object_manifest WHERE tenant_id = $1 AND hash = $2`,\n [tenant, hash],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toEntry(row);\n }\n\n async list(\n tenant: TenantId,\n query: ObjectListQuery,\n ): Promise<readonly ObjectManifestEntry[]> {\n // The cutoff is compared against `delete_pending_at` as text, which only\n // equals a time comparison for the canonical form. A GC sweep reading a\n // mis-parsed cutoff would either miss tombstones or take live objects, so\n // this rejects rather than interprets.\n if (query.deletePendingBefore !== undefined) {\n assertCanonicalTimestamp(query.deletePendingBefore, 'deletePendingBefore');\n }\n const result = await this.#pool.query<ManifestRow>(\n `SELECT ${MANIFEST_COLUMNS} FROM object_manifest\n WHERE tenant_id = $1\n AND ($2::text IS NULL OR state = $2::text)\n AND ($3::text IS NULL\n OR (delete_pending_at IS NOT NULL AND delete_pending_at < $3::text))\n ORDER BY hash COLLATE \"C\"\n LIMIT $4`,\n [\n tenant,\n query.state ?? null,\n query.deletePendingBefore ?? null,\n query.limit ?? DEFAULT_LIST_LIMIT,\n ],\n );\n return result.rows.map(toEntry);\n }\n\n async addReference(\n tenant: TenantId,\n input: ObjectReferenceInput,\n ): Promise<ObjectManifestEntry> {\n // The state read, the reference write, and the recount are one transaction\n // holding the manifest row, so `markDeletePending` cannot slip its guard\n // between the read and the write.\n return this.#withManifestLocked(tenant, input.hash, async (client, current) => {\n if (current.state !== 'committed') {\n return new ByokCoreError(\n 'object_state_invalid',\n `Only committed objects can be referenced; ${input.hash} is ${current.state}.`,\n );\n }\n await client.query(\n `INSERT INTO object_reference (tenant_id, hash, ref_kind, ref_id, created_at)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (tenant_id, hash, ref_kind, ref_id) DO NOTHING`,\n [tenant, input.hash, input.refKind, input.refId, this.#now()],\n );\n return this.#recount(client, tenant, input.hash);\n });\n }\n\n async removeReference(\n tenant: TenantId,\n input: ObjectReferenceInput,\n ): Promise<ObjectManifestEntry> {\n // The mirror of `addReference`, on the same lock. Holding the manifest row\n // is also what replaces the delete's old `EXISTS` guard: the lock already\n // established that this tenant has the row, so `object_not_found` is\n // reported before anything is removed rather than after.\n return this.#withManifestLocked(tenant, input.hash, async (client) => {\n await client.query(\n `DELETE FROM object_reference\n WHERE tenant_id = $1 AND hash = $2 AND ref_kind = $3 AND ref_id = $4`,\n [tenant, input.hash, input.refKind, input.refId],\n );\n return this.#recount(client, tenant, input.hash);\n });\n }\n\n async markDeletePending(\n tenant: TenantId,\n hash: ContentHash,\n ): Promise<ObjectManifestEntry> {\n // `ref_count = 0` is in the guard, not checked beforehand: a reference\n // added between a check and a write would otherwise tombstone an object a\n // truth record still points at. Nothing else is needed here — this `UPDATE`\n // takes the same manifest row exclusively that `addReference` locks, so a\n // concurrent reference write either lands entirely before this statement\n // (and the guard sees its count) or queues behind it (and re-reads the\n // tombstone it must refuse against).\n const marked = await this.#pool.query<ManifestRow>(\n `UPDATE object_manifest\n SET gc_accounted_bytes = CASE WHEN state = 'committed' THEN byte_size ELSE 0 END,\n gc_accounted_object = (state = 'committed'),\n state = 'delete_pending', delete_pending_at = $3, updated_at = $3\n WHERE tenant_id = $1 AND hash = $2\n AND ref_count = 0\n AND state IN ('pending', 'committed')\n RETURNING ${MANIFEST_COLUMNS}`,\n [tenant, hash, this.#now()],\n );\n const row = marked.rows[0];\n if (row !== undefined) return toEntry(row);\n\n const current = await this.#require(tenant, hash);\n if (current.refCount !== 0) {\n throw new ByokCoreError(\n 'object_state_invalid',\n `Object ${hash} still has ${current.refCount} reference(s).`,\n );\n }\n throw this.#stateInvalid(current.state, 'delete_pending');\n }\n\n async markDeleted(tenant: TenantId, hash: ContentHash): Promise<ObjectManifestEntry> {\n const deleted = await this.#pool.query<ManifestRow>(\n `UPDATE object_manifest\n SET state = 'deleted', updated_at = $3\n WHERE tenant_id = $1 AND hash = $2 AND state = 'delete_pending'\n RETURNING ${MANIFEST_COLUMNS}`,\n [tenant, hash, this.#now()],\n );\n const row = deleted.rows[0];\n if (row !== undefined) return toEntry(row);\n\n const current = await this.#require(tenant, hash);\n throw this.#stateInvalid(current.state, 'deleted');\n }\n\n /**\n * Runs a reference mutation with the manifest row held under `FOR UPDATE`.\n *\n * The lock is taken before anything is read, so the state the callback judges\n * is the state no concurrent `markDeletePending` can move underneath it. A\n * typed refusal is RETURNED rather than thrown, the way\n * `PostgresQuotaStore.reserve` defers its rejection past `COMMIT`: it keeps\n * the `catch` reserved for genuine faults, so a rollback that itself fails\n * cannot replace this store's own answer.\n */\n async #withManifestLocked(\n tenant: TenantId,\n hash: ContentHash,\n mutate: (\n client: PoolClient,\n current: ObjectManifestEntry,\n ) => Promise<ObjectManifestEntry | ByokCoreError>,\n ): Promise<ObjectManifestEntry> {\n const client = await this.#pool.connect();\n let settled: ObjectManifestEntry | ByokCoreError;\n try {\n await client.query('BEGIN');\n const locked = await client.query<ManifestRow>(\n `SELECT ${MANIFEST_COLUMNS} FROM object_manifest\n WHERE tenant_id = $1 AND hash = $2\n FOR UPDATE`,\n [tenant, hash],\n );\n const row = locked.rows[0];\n settled = row === undefined ? this.#notFound(hash) : await mutate(client, toEntry(row));\n await client.query('COMMIT');\n } catch (error) {\n // Best-effort, for the same reason the migration runner's is: a rollback\n // that throws must not replace the failure the caller needs to see.\n await client.query('ROLLBACK').catch(() => {});\n throw error;\n } finally {\n client.release();\n }\n\n if (settled instanceof ByokCoreError) throw settled;\n return settled;\n }\n\n /** Sets `ref_count` to what the reference rows actually say. */\n async #recount(\n client: PoolClient,\n tenant: TenantId,\n hash: ContentHash,\n ): Promise<ObjectManifestEntry> {\n const result = await client.query<ManifestRow>(\n `UPDATE object_manifest\n SET ref_count = (SELECT count(*) FROM object_reference r\n WHERE r.tenant_id = $1 AND r.hash = $2),\n updated_at = $3\n WHERE tenant_id = $1 AND hash = $2\n RETURNING ${MANIFEST_COLUMNS}`,\n [tenant, hash, this.#now()],\n );\n const row = result.rows[0];\n if (row === undefined) throw this.#notFound(hash);\n return toEntry(row);\n }\n\n async #require(tenant: TenantId, hash: ContentHash): Promise<ObjectManifestEntry> {\n const entry = await this.get(tenant, hash);\n if (entry === undefined) throw this.#notFound(hash);\n return entry;\n }\n\n #notFound(hash: ContentHash): ByokCoreError {\n return new ByokCoreError(\n 'object_not_found',\n `Object ${hash} has no manifest row in this tenant.`,\n );\n }\n\n #stateInvalid(from: ObjectState, to: ObjectState): ByokCoreError {\n return new ByokCoreError(\n 'object_state_invalid',\n `${from} to ${to} is not a legal object manifest transition.`,\n );\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * The R2/S3 {@link CloudBlobStore} — grants, and only grants (§12.7.4, §12.7.7).\n *\n * Zero bytes cross this file either, but for the opposite reason to\n * `stores/core/objects.ts`: the manifest store holds metadata because bytes are\n * not its job, and this store holds no bytes because the DEVICE talks to the\n * object store directly. What it mints is a presigned URL; what the device does\n * with it is between the device and R2. That is why this composition supplies\n * no `BlobContentProxy` — there is no byte path here to proxy, and the absence\n * is the honest declaration (`@byok-sdk/cloud`'s `ports.ts`, design §6).\n *\n * Manifest and bytes are one transaction authority split across two systems\n * with no shared transaction, so the protocol is reserve/verify rather than\n * write/trust:\n *\n * 1. `createUpload` writes the `pending` manifest row FIRST, then signs a PUT.\n * Row-before-bytes is what makes an abandoned upload a reclaimable\n * tombstone instead of an object nobody has a record of.\n * 2. The device PUTs straight to the object store. `Content-Length` and\n * `Content-Type` are in the signed headers, so a body of the wrong size or\n * the wrong type is refused by the object store itself — before a byte is\n * stored, and without this process being in the path.\n * 3. The explicit finalize route calls `observeUpload`, which performs an\n * unconditional `HEAD`. Unconditional because §12.7.7 step 4 is about what\n * the store OBSERVES versus what the client DECLARED, and signing the length\n * proves what one client sent, not what is at the key now. The quota\n * authority then commits manifest/reservation/usage in one Postgres\n * statement; download never performs that transition.\n * 4. `committed` is terminal for writes. Step 1 is re-runnable while a row is\n * `pending` — that is what makes a retried upload idempotent — and refused\n * once it is `committed`, because §12.7.4 lets truth reference a committed\n * manifest and the reference means nothing if the bytes can still be\n * replaced by a same-shaped body under a freshly signed PUT.\n *\n * **No checksum header.** `x-amz-checksum-sha256` was probed rather than\n * assumed (design §3 marked it `[unverified]`): MinIO honors it in a presigned\n * PUT and rejects mismatched bytes with `XAmzContentChecksumMismatch`, but R2's\n * S3 compatibility table lists SHA-256 as `COMPOSITE` only — `FULL_OBJECT`, the\n * type a single-shot PutObject uses, is ❌, and R2's PutObject feature row names\n * no `x-amz-checksum-*` header at all. Signing one would mint URLs that work\n * against the test substrate and fail against production, which is worse than\n * not signing it. The `HEAD` above was never conditional on it.\n *\n * The `blobId` this store mints IS the content hash. That is what makes \"no\n * naked object index\" constructive rather than disciplinary: there is no\n * surrogate id to look up, every read is `(tenant, hash)` against the manifest\n * primary key, and the object key is derived — once, in {@link #objectUrl} —\n * from a `ContentHash` that core already validated. A non-hex id cannot reach\n * key construction because it cannot become a `ContentHash`.\n */\nimport {\n ByokCoreError,\n contentHash,\n isContentHash,\n objectKeyPrefix,\n tenantObjectKey,\n type Clock,\n type ContentHash,\n type ObjectKeyPrefix,\n type ObjectStore,\n type StorageReservation,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { BlobObservation, CloudBlobStore } from '@byok-sdk/cloud';\nimport { AwsClient } from 'aws4fetch';\nimport { XMLParser } from 'fast-xml-parser';\n\n/** 15 minutes, matching the in-memory reference's `BLOB_URL_TTL_MS`. */\nexport const DEFAULT_PRESIGN_TTL_SECONDS = 15 * 60;\n\n/** `X-Amz-Expires` floor. Below a second there is no grant, only a signature. */\nexport const MIN_PRESIGN_TTL_SECONDS = 1;\n\n/** `X-Amz-Expires` ceiling: seven days, the longest lifetime R2 will honor. */\nexport const MAX_PRESIGN_TTL_SECONDS = 604_800;\n\n/** Three total attempts: the first plus two retries. */\nexport const DEFAULT_MAX_ATTEMPTS = 3;\n\n/** Doubles per retry. Deterministic — no jitter, so a test can assert the sequence. */\nexport const DEFAULT_RETRY_DELAY_MS = 100;\n\n/** The subset of `fetch` this store uses. The seam a fault injector replaces. */\nexport type ObjectStoreFetch = (request: Request) => Promise<Response>;\n\n/**\n * Raised when the object store answered something this adapter cannot act on —\n * a 4xx that is not \"absent\", or a transient failure that outlived its retries.\n *\n * A local class rather than a core code: core's taxonomy describes the manifest\n * contract, and \"R2 returned 503 three times\" is an adapter fault, not a\n * statement about the object.\n */\nexport class ObjectStoreRequestError extends Error {\n public readonly status: number | undefined;\n public readonly attempts: number;\n\n constructor(message: string, attempts: number, status?: number, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ObjectStoreRequestError';\n this.attempts = attempts;\n this.status = status;\n }\n}\n\n/**\n * What this adapter refuses on its own account, before anything is signed.\n *\n * A second local class rather than more core codes, for the same reason\n * {@link ObjectStoreRequestError} is one: core's taxonomy describes the\n * manifest contract, and \"this deployment's tenant ids cannot be key segments\"\n * or \"this deployment configured a lifetime R2 will not honor\" are facts about\n * an S3 adapter's configuration and inputs, not about an object. Core's code\n * union is closed and deliberately so; widening it from an adapter would put\n * an adapter's vocabulary on a wire contract every composition shares.\n *\n * Code-based branching, matching the idiom of every other error type here.\n */\nexport const R2_BLOB_ERROR_CODES = {\n /**\n * A tenant id that cannot be one safe path segment. Wire-relevant: it is the\n * only signal a control plane gets that the id it issued cannot address\n * object storage, and it is raised BEFORE any key is built.\n */\n storage_tenant_key_unsafe: 'storage_tenant_key_unsafe',\n /** A presign lifetime outside `[MIN_PRESIGN_TTL_SECONDS, MAX_PRESIGN_TTL_SECONDS]`. Construction-time only. */\n storage_presign_ttl_invalid: 'storage_presign_ttl_invalid',\n /** ListObjectsV2 accepts 1..1000 keys per page. Maintenance input only. */\n storage_list_limit_invalid: 'storage_list_limit_invalid',\n /** Continuation tokens are opaque but non-empty. Maintenance input only. */\n storage_list_cursor_invalid: 'storage_list_cursor_invalid',\n} as const;\n\nexport type R2BlobErrorCode = (typeof R2_BLOB_ERROR_CODES)[keyof typeof R2_BLOB_ERROR_CODES];\n\nexport class R2BlobStoreError extends Error {\n public readonly code: R2BlobErrorCode;\n\n constructor(code: R2BlobErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'R2BlobStoreError';\n this.code = code;\n }\n}\n\nexport interface R2BlobStoreOptions {\n /**\n * The manifest authority. Same `ObjectStore` the core composition supplies —\n * one row per (tenant, hash), and this store never opens a second one.\n */\n readonly objects: ObjectStore;\n /**\n * The clock SigV4's `X-Amz-Date` is read from — WALL time, and deliberately\n * NOT the composition's logical clock.\n *\n * Every other instant in this program comes from an injected clock so TTLs\n * are assertable without sleeping, and a store reaching for wall time is a\n * bug. A request signature is the exception, and not a soft one: its validity\n * window is adjudicated by the object store against the object store's own\n * clock. Signing with a logical instant produces a credential the remote side\n * rejects as skewed the moment the two disagree — a 403 at upload time, from\n * a decision made at composition time.\n *\n * Separate and required rather than defaulted, so the distinction is a choice\n * someone makes rather than one they inherit. A test that needs an EXPIRED\n * grant backdates this clock, which is also the only way to assert expiry\n * without sleeping through it.\n */\n readonly signingClock: Clock;\n /** Origin only, e.g. `https://<account>.r2.cloudflarestorage.com`. */\n readonly endpoint: string;\n readonly bucket: string;\n readonly accessKeyId: string;\n readonly secretAccessKey: string;\n /**\n * `auto` for R2. Required rather than defaulted: a signature scoped to the\n * wrong region fails as a 403 at upload time, which is a terrible place to\n * discover a config default nobody chose.\n */\n readonly region: string;\n /**\n * A key namespace for this deployment, e.g. `acme/prod` →\n * `acme/prod/tenants/<tenant>/objects/sha256/<hex>`. Omit it and the key is\n * the unprefixed `tenants/...` layout, byte for byte.\n *\n * What it is for: one bucket, several deployments. Without it every\n * deployment owns the bucket root, so a host running two products against\n * one R2 account has to open a bucket per product.\n *\n * **Immutable per deployment, and only for a NEW one.** This value is\n * spliced into the key at write time and at read time from the same field;\n * there is no second layout anything falls back to, by design. Change it on\n * a deployment that has already stored objects and those objects are\n * stranded — still in the bucket, no longer addressable, and invisible to\n * this SDK's own maintenance surface. A dual-read across the old and new\n * prefix is NOT a supported way to switch and will not be added: it would\n * make two key layouts simultaneously authoritative for the same object.\n * Moving an existing deployment onto a prefix is a separate, one-shot,\n * operator-invoked copy of the objects themselves, out of this SDK's scope.\n *\n * Validated at construction ({@link ObjectKeyPrefix}): slash-joined segments\n * of lowercase alphanumerics, `.`, `_`, `-`, each starting with an\n * alphanumeric, no leading/trailing slash, no empty segment. `''` is a\n * refusal, not a synonym for \"no prefix\" — it is what an unset environment\n * variable looks like, and silently treating it as the default would put a\n * deployment's objects somewhere nobody chose.\n */\n readonly keyPrefix?: string;\n readonly presignTtlSeconds?: number;\n /** Injected so a fault injector can sit in front of the real one. */\n readonly fetch?: ObjectStoreFetch;\n readonly maxAttempts?: number;\n readonly retryDelayMs?: number;\n}\n\ninterface HeadResult {\n readonly present: boolean;\n readonly byteSize: bigint;\n readonly contentType: string;\n}\n\n/** One tenant-prefixed R2 key returned by ListObjectsV2. */\nexport interface R2ListedObject {\n readonly key: string;\n /** Present only when the key is exactly `tenants/<tenant>/objects/sha256/<64 lowercase hex>`. */\n readonly hash?: ContentHash;\n readonly byteSize: bigint;\n}\n\nexport interface R2ObjectPage {\n readonly objects: readonly R2ListedObject[];\n readonly nextContinuationToken?: string;\n}\n\nexport type R2DeleteResult = 'deleted' | 'absent';\n\n/** Operations used only by the host-owned S4B-c maintenance worker. */\nexport interface R2ObjectMaintenance {\n inspectObject(tenant: TenantId, hash: ContentHash): Promise<BlobObservation | undefined>;\n deleteObject(tenant: TenantId, hash: ContentHash): Promise<R2DeleteResult>;\n listTenantObjects(\n tenant: TenantId,\n continuationToken?: string,\n limit?: number,\n ): Promise<R2ObjectPage>;\n}\n\nexport class R2CloudBlobStore implements CloudBlobStore {\n readonly #objects: ObjectStore;\n readonly #signingClock: Clock;\n readonly #client: AwsClient;\n readonly #origin: string;\n readonly #bucket: string;\n readonly #keyPrefix: ObjectKeyPrefix | undefined;\n readonly #presignTtlSeconds: number;\n readonly #fetch: ObjectStoreFetch;\n readonly #maxAttempts: number;\n readonly #retryDelayMs: number;\n\n constructor(options: R2BlobStoreOptions) {\n this.#objects = options.objects;\n this.#signingClock = options.signingClock;\n this.#client = new AwsClient({\n accessKeyId: options.accessKeyId,\n secretAccessKey: options.secretAccessKey,\n service: 's3',\n region: options.region,\n // The client's own retry loop is bypassed: this store only ever calls\n // `sign`, and drives its own bounded, jitter-free retries below so the\n // transient-error dimension can assert an exact attempt sequence.\n retries: 0,\n });\n this.#origin = options.endpoint.replace(/\\/+$/, '');\n this.#bucket = options.bucket;\n this.#keyPrefix = resolveKeyPrefix(options.keyPrefix);\n this.#presignTtlSeconds = assertPresignTtl(options.presignTtlSeconds ?? DEFAULT_PRESIGN_TTL_SECONDS);\n this.#fetch = options.fetch ?? ((request) => globalThis.fetch(request));\n this.#maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n this.#retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n }\n\n /**\n * Reserve the manifest row, then hand back a PUT bound to this tenant, this\n * key, this length, this type, and this expiry.\n *\n * `putManifest` is idempotent per (tenant, hash), so a device that declares\n * the same content twice while it is still `pending` gets the same row and\n * the same key — an interrupted upload is retried, not duplicated. It is\n * idempotent per TENANT, which is the same reason the key embeds the tenant:\n * two tenants holding identical bytes hold two independent objects, and\n * neither can learn of the other's.\n *\n * Idempotence stops at `committed`, and that boundary is the point: a\n * committed object is what a truth record is allowed to reference, so it has\n * to be immutable, and re-issuing a write grant for one is the only way this\n * adapter could make it otherwise.\n */\n async createUpload(\n tenant: TenantId,\n reservation: StorageReservation,\n ): Promise<{ readonly blobId: string; readonly uploadUrl: string }> {\n this.#assertReservedObject(tenant, reservation);\n const hash = contentHash(reservation.contentHash);\n const byteSize = reservation.expectedBytes;\n // The same guard {@link #objectUrl} enforces, run before the manifest is\n // touched. Ordering only — the authority is still the one key-construction\n // point — but a tenant whose id can never address a key should not get to\n // reserve a row on the way to being refused.\n assertKeySegmentTenant(tenant);\n\n const entry = await this.#objects.putManifest(tenant, {\n hash,\n byteSize,\n contentType: reservation.contentType,\n });\n // `putManifest` returns an existing non-`deleted` row untouched, which is\n // what makes a retried upload idempotent. The flip side is that a SECOND\n // declaration of the same hash under a different size or type would\n // silently get a URL signed for the FIRST declaration's headers, so the\n // disagreement is refused here rather than discovered as a 403.\n if (entry.byteSize !== byteSize || entry.contentType !== reservation.contentType) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Object ${hash} is already declared as ${String(entry.byteSize)} bytes of ${entry.contentType}; this upload declares ${String(byteSize)} bytes of ${reservation.contentType}.`,\n );\n }\n // A committed object is immutable, so no write authorization exists to\n // hand out for one. §12.7.4 lets a truth record reference only a committed\n // manifest, and the attestation is worth exactly as much as the promise\n // that the bytes under `sha256/<hex>` do not change afterwards. A fresh PUT\n // grant would be that promise's only counterexample: the object store\n // accepts any body matching the signed length and type, and the digest is\n // never recomputed anywhere. `pending` stays grantable — a device retrying\n // an interrupted upload is the case idempotence is FOR, and there is\n // nothing yet for a replacement to invalidate.\n if (entry.state !== 'pending') {\n throw new ByokCoreError(\n 'object_state_invalid',\n `Object ${hash} is ${entry.state}; only a pending object can receive an upload grant.`,\n );\n }\n\n const url = this.#objectUrl(tenant, hash);\n url.searchParams.set('X-Amz-Expires', String(this.#presignTtlSeconds));\n const signed = await this.#client.sign(\n new Request(url, {\n method: 'PUT',\n headers: {\n 'content-length': String(byteSize),\n 'content-type': reservation.contentType,\n },\n }),\n {\n // `allHeaders` is load-bearing: aws4fetch treats `content-length` and\n // `content-type` as unsignable by default (they are per-hop headers for\n // most services), and without this the grant would bind the key and the\n // expiry but not the SHAPE of what may be written to it.\n aws: { signQuery: true, allHeaders: true, datetime: this.#datetime() },\n },\n );\n\n return { blobId: hash, uploadUrl: signed.url };\n }\n\n async observeUpload(\n tenant: TenantId,\n blobId: string,\n reservation: StorageReservation,\n ): Promise<BlobObservation | undefined> {\n if (\n !isContentHash(blobId) ||\n reservation.tenantId !== tenant ||\n reservation.kind !== 'object' ||\n reservation.contentHash !== blobId\n ) {\n return undefined;\n }\n const entry = await this.#objects.get(tenant, reservation.contentHash);\n if (entry === undefined || (entry.state !== 'pending' && entry.state !== 'committed')) {\n return undefined;\n }\n const observed = await this.#head(tenant, reservation.contentHash);\n if (!observed.present) return undefined;\n return {\n observedByteSize: observed.byteSize,\n observedContentType: observed.contentType,\n };\n }\n\n /**\n * A GET for a committed object this tenant owns; `undefined` otherwise.\n *\n * Every miss answers identically — unknown hash, another tenant's object, a\n * malformed id, bytes that never landed, a tombstoned row. A caller cannot\n * tell them apart, which is what keeps `getDownloadUrl` from being an\n * existence oracle across tenants.\n *\n * This is a pure committed-manifest gate. Observation and commit belong to\n * the explicit finalize route; a download must never decide accounting.\n */\n async getDownloadUrl(tenant: TenantId, blobId: string): Promise<string | undefined> {\n // Not an error: a caller holding a junk id learns the same nothing a caller\n // holding another tenant's id learns. It is also the point past which a\n // non-hex value cannot travel — key construction is downstream of here.\n if (!isContentHash(blobId)) return undefined;\n const hash: ContentHash = blobId;\n\n const entry = await this.#objects.get(tenant, hash);\n if (entry === undefined) return undefined;\n\n if (entry.state !== 'committed') {\n // `delete_pending` and `deleted` are tombstones. Handing out a GET for\n // one would be a URL whose object the GC worker is entitled to remove.\n return undefined;\n }\n\n const url = this.#objectUrl(tenant, hash);\n url.searchParams.set('X-Amz-Expires', String(this.#presignTtlSeconds));\n const signed = await this.#client.sign(new Request(url, { method: 'GET' }), {\n aws: { signQuery: true, datetime: this.#datetime() },\n });\n return signed.url;\n }\n\n /**\n * The ONLY place an object key is built, and therefore the only place the\n * key's two segments have to be safe.\n *\n * The hash half is closed by construction: `tenantObjectKey` is core's and it\n * takes a `ContentHash` — a branded type with exactly one mint point that\n * rejects anything but 64 lowercase hex — so a traversal segment, an absolute\n * path, or an uppercase digest cannot be smuggled through a parameter that\n * will not accept them.\n *\n * The tenant half is NOT, and that asymmetry is why the guard below exists.\n * `tenantId()` fails closed on empty, padded, over-long, and `NUL`-bearing\n * values, and deliberately normalizes nothing else — normalizing would make\n * the SDK disagree with the control plane that issued the id about its\n * canonical form (`@byok-sdk/core`'s `tenant.ts`). So `a/../b` is a legitimate\n * tenant id, and the line below would otherwise hand it to `new URL()`, which\n * resolves the traversal and returns tenant `b`'s key. That is a cross-tenant\n * alias: `a/../b` could probe, overwrite, and read what `b` owns.\n *\n * Refused rather than encoded. Percent-encoding the segment would keep the\n * key distinct, and would also give every tenant id two spellings — the one\n * the control plane issued and the one at rest in the object store — which is\n * the second source of truth core refused to create in the first place.\n */\n #objectUrl(tenant: TenantId, hash: ContentHash): URL {\n assertKeySegmentTenant(tenant);\n return new URL(\n `${this.#origin}/${this.#bucket}/${tenantObjectKey(tenant, hash, this.#keyPrefix)}`,\n );\n }\n\n /**\n * `HEAD` the key, with bounded retries for transient faults.\n *\n * `HEAD` is idempotent by construction, so a retry can never double an\n * effect — which is the whole reason the retry loop is allowed to exist here\n * and not around anything that writes.\n */\n async #head(tenant: TenantId, hash: ContentHash): Promise<HeadResult> {\n const url = this.#objectUrl(tenant, hash);\n const { response, attempts } = await this.#send(new Request(url, { method: 'HEAD' }));\n\n if (response.status === 404) {\n return { present: false, byteSize: 0n, contentType: '' };\n }\n if (!response.ok) {\n throw new ObjectStoreRequestError(\n `HEAD on the object store answered ${response.status}.`,\n attempts,\n response.status,\n );\n }\n\n const length = response.headers.get('content-length');\n const contentType = response.headers.get('content-type');\n if (length === null || contentType === null) {\n // Fail closed. A HEAD without the two fields the commit guard compares\n // cannot be turned into a commit decision, and guessing either one would\n // be inventing the observation the check exists to make.\n throw new ObjectStoreRequestError(\n `HEAD on the object store omitted content-length or content-type, so ${hash} cannot be verified.`,\n attempts,\n response.status,\n );\n }\n return { present: true, byteSize: BigInt(length), contentType };\n }\n\n /**\n * Signs, sends, and retries 5xx/429/network faults with a doubling delay.\n *\n * Returns the attempt count alongside the response because the caller is what\n * decides the answer was a failure. A 4xx costs however many attempts the\n * transient faults before it did, and `attempts` is the only field\n * {@link ObjectStoreRequestError} carries that an operator can use to tell a\n * flapping remote from a hard refusal — so it has to be counted here, where\n * the loop is, rather than assumed to be 1 at the throw site.\n */\n async #send(request: Request): Promise<{ readonly response: Response; readonly attempts: number }> {\n const failures: string[] = [];\n\n for (let attempt = 1; attempt <= this.#maxAttempts; attempt += 1) {\n const signed = await this.#client.sign(request.clone(), {\n aws: { datetime: this.#datetime() },\n });\n\n const outcome = await this.#attempt(signed);\n if (outcome.response !== undefined) return { response: outcome.response, attempts: attempt };\n failures.push(outcome.failure);\n\n if (attempt < this.#maxAttempts) {\n await this.#sleep(this.#retryDelayMs * 2 ** (attempt - 1));\n }\n }\n\n throw new ObjectStoreRequestError(\n `The object store failed ${this.#maxAttempts} attempt(s): ${failures.join(', ')}.`,\n this.#maxAttempts,\n );\n }\n\n async #attempt(signed: Request): Promise<{ response?: Response; failure: string }> {\n try {\n const response = await this.#fetch(signed);\n // 429 and 5xx are the two the S3 contract calls retryable. Everything\n // else — including 403 and 404 — is an answer, not a fault.\n if (response.status !== 429 && response.status < 500) return { response, failure: '' };\n return { failure: `HTTP ${response.status}` };\n } catch (cause) {\n return { failure: cause instanceof Error ? cause.message : String(cause) };\n }\n }\n\n #sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n\n /** SigV4's `YYYYMMDDTHHmmssZ`, off the signing clock — see its doc for why that is a separate one. */\n #datetime(): string {\n return this.#signingClock.now().toISOString().replaceAll(/[:-]|\\.\\d{3}/g, '');\n }\n\n #assertReservedObject(tenant: TenantId, reservation: StorageReservation): void {\n if (\n reservation.tenantId === tenant &&\n reservation.kind === 'object' &&\n reservation.state === 'reserved' &&\n reservation.expectedBytes >= 0n\n ) {\n return;\n }\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n 'An upload grant requires a reserved object reservation owned by this tenant.',\n );\n }\n}\n\nexport type R2ObjectMaintenanceOptions = Omit<\n R2BlobStoreOptions,\n 'objects' | 'presignTtlSeconds'\n>;\n\n/**\n * R2 maintenance adapter kept deliberately outside `CloudBlobStore`.\n *\n * Cloud conformance certifies the device-facing blob port with an exact method\n * inventory. LIST/HEAD/DELETE are host operations, so putting them on\n * `R2CloudBlobStore` would over-declare a capability no other cloud composition\n * implements.\n */\nexport class R2ObjectMaintenanceStore implements R2ObjectMaintenance {\n readonly #signingClock: Clock;\n readonly #client: AwsClient;\n readonly #origin: string;\n readonly #bucket: string;\n readonly #keyPrefix: ObjectKeyPrefix | undefined;\n readonly #fetch: ObjectStoreFetch;\n readonly #maxAttempts: number;\n readonly #retryDelayMs: number;\n\n constructor(options: R2ObjectMaintenanceOptions) {\n this.#signingClock = options.signingClock;\n this.#client = new AwsClient({\n accessKeyId: options.accessKeyId,\n secretAccessKey: options.secretAccessKey,\n service: 's3',\n region: options.region,\n retries: 0,\n });\n this.#origin = options.endpoint.replace(/\\/+$/, '');\n this.#bucket = options.bucket;\n this.#keyPrefix = resolveKeyPrefix(options.keyPrefix);\n this.#fetch = options.fetch ?? ((request) => globalThis.fetch(request));\n this.#maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n this.#retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n }\n\n async inspectObject(\n tenant: TenantId,\n hash: ContentHash,\n ): Promise<BlobObservation | undefined> {\n const observed = await this.#head(tenant, hash);\n if (!observed.present) return undefined;\n return {\n observedByteSize: observed.byteSize,\n observedContentType: observed.contentType,\n };\n }\n\n async deleteObject(tenant: TenantId, hash: ContentHash): Promise<R2DeleteResult> {\n const url = this.#objectUrl(tenant, hash);\n const { response, attempts } = await this.#send(new Request(url, { method: 'DELETE' }));\n if (response.status === 404) return 'absent';\n if (!response.ok) {\n throw new ObjectStoreRequestError(\n `DELETE on the object store answered ${response.status}.`,\n attempts,\n response.status,\n );\n }\n return 'deleted';\n }\n\n async listTenantObjects(\n tenant: TenantId,\n continuationToken?: string,\n limit = 100,\n ): Promise<R2ObjectPage> {\n assertKeySegmentTenant(tenant);\n if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {\n throw new R2BlobStoreError(\n 'storage_list_limit_invalid',\n `A ListObjectsV2 page limit of ${String(limit)} is not a whole number in [1, 1000].`,\n );\n }\n\n // Use core's single key-construction point even for enumeration. The\n // previous abbreviated `${tenant}/sha256/` listing never matched objects\n // written by `tenantObjectKey`, silently hiding canonical R2 data from\n // maintenance. The synthetic valid hash is removed byte-for-byte.\n const prefix = tenantObjectKey(tenant, LIST_PREFIX_HASH, this.#keyPrefix).slice(0, -LIST_HASH_HEX_LENGTH);\n const url = new URL(`${this.#origin}/${this.#bucket}`);\n url.searchParams.set('list-type', '2');\n url.searchParams.set('prefix', prefix);\n url.searchParams.set('max-keys', String(limit));\n if (continuationToken !== undefined) {\n if (continuationToken.length === 0) {\n throw new R2BlobStoreError(\n 'storage_list_cursor_invalid',\n 'A ListObjectsV2 continuation token must not be empty.',\n );\n }\n url.searchParams.set('continuation-token', continuationToken);\n }\n\n const { response, attempts } = await this.#send(new Request(url, { method: 'GET' }));\n if (!response.ok) {\n throw new ObjectStoreRequestError(\n `ListObjectsV2 on the object store answered ${response.status}.`,\n attempts,\n response.status,\n );\n }\n return parseListObjectsV2(await response.text(), prefix, attempts);\n }\n\n async #head(tenant: TenantId, hash: ContentHash): Promise<HeadResult> {\n const { response, attempts } = await this.#send(\n new Request(this.#objectUrl(tenant, hash), { method: 'HEAD' }),\n );\n if (response.status === 404) {\n return { present: false, byteSize: 0n, contentType: '' };\n }\n if (!response.ok) {\n throw new ObjectStoreRequestError(\n `HEAD on the object store answered ${response.status}.`,\n attempts,\n response.status,\n );\n }\n const length = response.headers.get('content-length');\n const contentType = response.headers.get('content-type');\n if (length === null || contentType === null) {\n throw new ObjectStoreRequestError(\n `HEAD on the object store omitted content-length or content-type, so ${hash} cannot be observed.`,\n attempts,\n response.status,\n );\n }\n return { present: true, byteSize: BigInt(length), contentType };\n }\n\n #objectUrl(tenant: TenantId, hash: ContentHash): URL {\n assertKeySegmentTenant(tenant);\n return new URL(\n `${this.#origin}/${this.#bucket}/${tenantObjectKey(tenant, hash, this.#keyPrefix)}`,\n );\n }\n\n async #send(request: Request): Promise<{ readonly response: Response; readonly attempts: number }> {\n const failures: string[] = [];\n for (let attempt = 1; attempt <= this.#maxAttempts; attempt += 1) {\n const signed = await this.#client.sign(request.clone(), {\n aws: { datetime: this.#datetime() },\n });\n try {\n const response = await this.#fetch(signed);\n if (response.status !== 429 && response.status < 500) {\n return { response, attempts: attempt };\n }\n failures.push(`HTTP ${response.status}`);\n } catch (cause) {\n failures.push(cause instanceof Error ? cause.message : String(cause));\n }\n if (attempt < this.#maxAttempts) {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, this.#retryDelayMs * 2 ** (attempt - 1));\n });\n }\n }\n throw new ObjectStoreRequestError(\n `The object store failed ${this.#maxAttempts} attempt(s): ${failures.join(', ')}.`,\n this.#maxAttempts,\n );\n }\n\n #datetime(): string {\n return this.#signingClock.now().toISOString().replaceAll(/[:-]|\\.\\d{3}/g, '');\n }\n}\n\n/**\n * The character set a tenant id may use once it is a KEY SEGMENT.\n *\n * RFC 3986's unreserved set, and nothing else: those are exactly the characters\n * that survive `new URL()` unchanged. Anything outside it either changes the\n * path's STRUCTURE (`/`, `\\`) or changes its SPELLING (percent-encoding), and\n * both are disqualifying for the same reason — an id with two forms is an id\n * with two owners.\n */\nconst SAFE_TENANT_SEGMENT = /^[A-Za-z0-9._~-]+$/;\n\n/**\n * A tenant id is usable here only if it is ONE safe path segment.\n *\n * Conservative on purpose: it rejects rather than repairs, and it rejects\n * everything it is not certain survives URL resolution unchanged — separators\n * in either direction, a leading `.` (which covers `.` and `..`), and every\n * character that would be percent-encoded. A permissive guard that \"handles\"\n * traversal by rewriting it would be a second normalization authority, and the\n * one thing worse than a tenant id the object store cannot address is a tenant\n * id the object store addresses under a name the control plane never issued.\n */\nfunction assertKeySegmentTenant(tenant: TenantId): void {\n if (SAFE_TENANT_SEGMENT.test(tenant) && !tenant.startsWith('.')) return;\n throw new R2BlobStoreError(\n 'storage_tenant_key_unsafe',\n `Tenant id ${JSON.stringify(tenant)} is not a single safe object-key segment, so no key can be built for it.`,\n );\n}\n\n/**\n * The deployment's key namespace, decided once, here, at construction.\n *\n * Validation is core's, not this adapter's: the key layout is core's contract\n * ({@link tenantObjectKey}), and a second opinion about what a legal prefix\n * looks like is a second authority over where objects live. This function only\n * decides that an ABSENT option means the unprefixed layout — every other\n * value, `''` included, goes to the mint point and is either accepted verbatim\n * or refused here and now, before a single key is built.\n */\nfunction resolveKeyPrefix(keyPrefix: string | undefined): ObjectKeyPrefix | undefined {\n return keyPrefix === undefined ? undefined : objectKeyPrefix(keyPrefix);\n}\n\nfunction assertPresignTtl(seconds: number): number {\n if (\n Number.isInteger(seconds) &&\n seconds >= MIN_PRESIGN_TTL_SECONDS &&\n seconds <= MAX_PRESIGN_TTL_SECONDS\n ) {\n return seconds;\n }\n throw new R2BlobStoreError(\n 'storage_presign_ttl_invalid',\n `A presign lifetime of ${String(seconds)} is not a whole number of seconds in [${String(MIN_PRESIGN_TTL_SECONDS)}, ${String(MAX_PRESIGN_TTL_SECONDS)}], which is the range R2 will honor.`,\n );\n}\n\nconst LIST_OBJECTS_XML = new XMLParser({\n ignoreAttributes: true,\n parseTagValue: false,\n trimValues: true,\n processEntities: false,\n});\n\nfunction parseListObjectsV2(xml: string, prefix: string, attempts: number): R2ObjectPage {\n let parsed: unknown;\n try {\n parsed = LIST_OBJECTS_XML.parse(xml) as unknown;\n } catch (cause) {\n throw new ObjectStoreRequestError(\n 'ListObjectsV2 returned malformed XML.',\n attempts,\n undefined,\n { cause },\n );\n }\n\n const document = asRecord(parsed);\n const root = asRecord(document?.ListBucketResult);\n if (root === undefined) {\n throw new ObjectStoreRequestError(\n 'ListObjectsV2 XML omitted ListBucketResult.',\n attempts,\n );\n }\n\n const isTruncated = requiredText(root, 'IsTruncated', attempts);\n if (isTruncated !== 'true' && isTruncated !== 'false') {\n throw new ObjectStoreRequestError(\n `ListObjectsV2 XML contained invalid IsTruncated=${JSON.stringify(isTruncated)}.`,\n attempts,\n );\n }\n\n const rawContents = root.Contents === undefined\n ? []\n : Array.isArray(root.Contents)\n ? root.Contents\n : [root.Contents];\n const objects = rawContents.map((raw, index): R2ListedObject => {\n const content = asRecord(raw);\n if (content === undefined) {\n throw new ObjectStoreRequestError(\n `ListObjectsV2 XML contained a non-object Contents entry at index ${String(index)}.`,\n attempts,\n );\n }\n const key = requiredText(content, 'Key', attempts);\n const sizeText = requiredText(content, 'Size', attempts);\n let byteSize: bigint;\n try {\n byteSize = BigInt(sizeText);\n } catch (cause) {\n throw new ObjectStoreRequestError(\n `ListObjectsV2 XML contained invalid Size=${JSON.stringify(sizeText)}.`,\n attempts,\n undefined,\n { cause },\n );\n }\n if (byteSize < 0n) {\n throw new ObjectStoreRequestError(\n `ListObjectsV2 XML contained negative Size=${sizeText}.`,\n attempts,\n );\n }\n const suffix = key.startsWith(prefix) ? key.slice(prefix.length) : '';\n return {\n key,\n byteSize,\n ...(HASH_KEY_SUFFIX.test(suffix)\n ? { hash: contentHash(`sha256:${suffix}`) }\n : {}),\n };\n });\n\n if (isTruncated === 'false') return { objects };\n const nextContinuationToken = requiredText(root, 'NextContinuationToken', attempts);\n if (nextContinuationToken.length === 0) {\n throw new ObjectStoreRequestError(\n 'ListObjectsV2 XML was truncated but its continuation token was empty.',\n attempts,\n );\n }\n return { objects, nextContinuationToken };\n}\n\nconst HASH_KEY_SUFFIX = /^[0-9a-f]{64}$/;\nconst LIST_HASH_HEX_LENGTH = 64;\nconst LIST_PREFIX_HASH = contentHash(`sha256:${'0'.repeat(LIST_HASH_HEX_LENGTH)}`);\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction requiredText(\n record: Record<string, unknown>,\n field: string,\n attempts: number,\n): string {\n const value = record[field];\n if (typeof value === 'string') return value;\n throw new ObjectStoreRequestError(\n `ListObjectsV2 XML omitted text field ${field}.`,\n attempts,\n );\n}\n","/**\n * Postgres {@link DeviceDirectory}.\n *\n * Rows live under the composite key `(tenant_id, device_id)`, so a cross-tenant\n * read is not \"denied\" — it addresses a different key space and finds nothing\n * (§12.6.2 layer 3). `resolveByDeviceId` is the documented pre-tenant entry\n * point, and it is safe for exactly one reason: the row it returns CARRIES its\n * tenant, so the caller never compares a tenant it was handed against one it\n * guessed. One row, two access paths, never two copies to keep in sync — a\n * stale pre-tenant index would be a revoked device that can still get a token.\n */\nimport {\n type Clock,\n type PresenceStore,\n type PresenceLevel,\n type TenantId,\n type TenantReadinessDevice,\n type TenantReadiness,\n} from '@byok-sdk/core';\nimport type { DeviceDirectory, DeviceRecord, DeviceRegistration } from '@byok-sdk/cloud';\nimport type { Pool } from 'pg';\n\ninterface DeviceRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly product_id: string;\n readonly device_name: string;\n readonly device_public_key: string;\n readonly proof_key_id: string;\n readonly proof_key_epoch: number;\n readonly revoked: boolean;\n readonly capabilities: readonly string[] | null;\n}\n\n/**\n * `tenant_id` is read back from the row rather than re-branded from the\n * argument, so `resolveByDeviceId` and `get` produce records the same way.\n * The cast is confined here: this module is the boundary where a database\n * string becomes the branded identity core mints elsewhere.\n */\nfunction toRecord(row: DeviceRow): DeviceRecord {\n return {\n tenantId: row.tenant_id as TenantId,\n productId: row.product_id,\n deviceId: row.device_id,\n deviceName: row.device_name,\n devicePublicKey: row.device_public_key,\n proofKeyId: row.proof_key_id,\n proofKeyEpoch: row.proof_key_epoch,\n revoked: row.revoked,\n ...(row.capabilities == null ? {} : { capabilities: Object.freeze([...row.capabilities]) }),\n };\n}\n\nconst SELECT_COLUMNS =\n 'tenant_id, device_id, product_id, device_name, device_public_key, proof_key_id, proof_key_epoch, revoked, capabilities';\n\nexport class PostgresDeviceDirectory implements DeviceDirectory {\n readonly #pool: Pool;\n readonly #clock: Clock | undefined;\n\n constructor(pool: Pool, clock?: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async register(tenant: TenantId, input: DeviceRegistration): Promise<DeviceRecord> {\n // Re-pairing an existing device replaces its registration in place rather\n // than creating a second row, matching the in-memory reference. `revoked`\n // resets because a fresh pairing IS a new grant.\n const result = await this.#pool.query<DeviceRow>(\n `INSERT INTO device (\n tenant_id, device_id, product_id, device_name, device_public_key,\n proof_key_id, proof_key_epoch, revoked\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, false)\n ON CONFLICT (tenant_id, device_id) DO UPDATE\n SET product_id = EXCLUDED.product_id,\n device_name = EXCLUDED.device_name,\n device_public_key = EXCLUDED.device_public_key,\n proof_key_id = EXCLUDED.proof_key_id,\n proof_key_epoch = EXCLUDED.proof_key_epoch,\n revoked = false,\n capabilities = NULL\n RETURNING ${SELECT_COLUMNS}`,\n [\n tenant,\n input.deviceId,\n input.productId,\n input.deviceName,\n input.devicePublicKey,\n input.proofKeyId,\n input.proofKeyEpoch,\n ],\n );\n return toRecord(result.rows[0]!);\n }\n\n async get(tenant: TenantId, deviceId: string): Promise<DeviceRecord | undefined> {\n const result = await this.#pool.query<DeviceRow>(\n `SELECT ${SELECT_COLUMNS} FROM device WHERE tenant_id = $1 AND device_id = $2`,\n [tenant, deviceId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toRecord(row);\n }\n\n async revoke(tenant: TenantId, deviceId: string): Promise<void> {\n // A no-op for a device this tenant does not own: revoking what you cannot\n // address changes nothing and reports nothing back.\n await this.#pool.query('UPDATE device SET revoked = true WHERE tenant_id = $1 AND device_id = $2', [\n tenant,\n deviceId,\n ]);\n }\n\n async recordCapabilities(\n tenant: TenantId,\n input: { readonly deviceId: string; readonly capabilities: readonly string[] },\n ): Promise<DeviceRecord | undefined> {\n const result = await this.#pool.query<DeviceRow>(\n `UPDATE device\n SET capabilities = $3::jsonb\n WHERE tenant_id = $1 AND device_id = $2 AND revoked = false\n RETURNING ${SELECT_COLUMNS}`,\n [tenant, input.deviceId, JSON.stringify([...input.capabilities])],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toRecord(row);\n }\n\n async list(tenant: TenantId): Promise<readonly DeviceRecord[]> {\n const result = await this.#pool.query<DeviceRow>(\n `SELECT ${SELECT_COLUMNS} FROM device WHERE tenant_id = $1 ORDER BY device_id`,\n [tenant],\n );\n return result.rows.map(toRecord);\n }\n\n async readiness(tenant: TenantId, _presence: PresenceStore): Promise<TenantReadiness> {\n // One tenant-scoped aggregate over durable devices and the latest live\n // presence row. The presence parameter keeps the port shape identical to\n // the reference implementation; SQL is the set-wise authority here.\n const result = await this.#pool.query<{\n device_id: string;\n product_id: string;\n device_name: string;\n revoked: boolean;\n presence_level: string | null;\n presence_detail: string | null;\n presence_configured_toolsets: readonly string[] | null;\n presence_client_version: string | null;\n presence_protocol_versions: readonly number[] | null;\n presence_runtimes: ReadonlyArray<{ id: string; version?: string; authPresent?: boolean }> | null;\n presence_observed_at: string | null;\n presence_expires_at: string | null;\n active_paired_device_count: number | string;\n revoked_device_count: number | string;\n observed_presence_count: number | string;\n observed_online_count: number | string;\n observed_thinking_count: number | string;\n observed_working_count: number | string;\n observed_error_count: number | string;\n observed_offline_count: number | string;\n }>(\n `SELECT\n d.device_id,\n d.product_id,\n d.device_name,\n d.revoked,\n CASE WHEN NOT d.revoked THEN p.level END AS presence_level,\n CASE WHEN NOT d.revoked THEN p.detail END AS presence_detail,\n CASE WHEN NOT d.revoked THEN p.configured_toolsets END AS presence_configured_toolsets,\n CASE WHEN NOT d.revoked THEN p.client_version END AS presence_client_version,\n CASE WHEN NOT d.revoked THEN p.protocol_versions END AS presence_protocol_versions,\n CASE WHEN NOT d.revoked THEN p.runtimes END AS presence_runtimes,\n CASE WHEN NOT d.revoked THEN p.observed_at END AS presence_observed_at,\n CASE WHEN NOT d.revoked THEN p.expires_at END AS presence_expires_at,\n (COUNT(*) FILTER (WHERE NOT d.revoked) OVER ())::int AS active_paired_device_count,\n (COUNT(*) FILTER (WHERE d.revoked) OVER ())::int AS revoked_device_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.device_id IS NOT NULL) OVER ())::int AS observed_presence_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.level = 'online') OVER ())::int AS observed_online_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.level = 'thinking') OVER ())::int AS observed_thinking_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.level = 'working') OVER ())::int AS observed_working_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.level = 'error') OVER ())::int AS observed_error_count,\n (COUNT(*) FILTER (WHERE NOT d.revoked AND p.level = 'offline') OVER ())::int AS observed_offline_count\n FROM device d\n LEFT JOIN device_presence p\n ON p.tenant_id = d.tenant_id\n AND p.device_id = d.device_id\n AND p.expires_at > $2\n WHERE d.tenant_id = $1\n ORDER BY d.device_id`,\n [tenant, this.#clock?.now().toISOString() ?? new Date().toISOString()],\n );\n const row = result.rows[0];\n const count = (value: number | string): number => Number(value);\n const devices: TenantReadinessDevice[] = result.rows.map((device) => ({\n deviceId: device.device_id,\n productId: device.product_id,\n deviceName: device.device_name,\n revoked: device.revoked,\n ...(device.presence_level === null\n ? {}\n : {\n presence: {\n level: device.presence_level as PresenceLevel,\n ...(device.presence_detail === null ? {} : { detail: device.presence_detail }),\n ...(device.presence_configured_toolsets === null\n ? {}\n : { configuredToolsets: Object.freeze([...device.presence_configured_toolsets]) }),\n ...(device.presence_client_version === null\n ? {}\n : { clientVersion: device.presence_client_version }),\n ...(device.presence_protocol_versions === null\n ? {}\n : { protocolVersions: Object.freeze([...device.presence_protocol_versions]) }),\n ...(device.presence_runtimes === null\n ? {}\n : { runtimes: Object.freeze(device.presence_runtimes.map((runtime) => Object.freeze({ ...runtime }))) }),\n observedAt: device.presence_observed_at!,\n expiresAt: device.presence_expires_at!,\n },\n }),\n }));\n return {\n tenantId: tenant,\n activePairedDeviceCount: count(row?.active_paired_device_count ?? 0),\n revokedDeviceCount: count(row?.revoked_device_count ?? 0),\n observedPresenceCount: count(row?.observed_presence_count ?? 0),\n observedPresenceByLevel: {\n online: count(row?.observed_online_count ?? 0),\n thinking: count(row?.observed_thinking_count ?? 0),\n working: count(row?.observed_working_count ?? 0),\n error: count(row?.observed_error_count ?? 0),\n offline: count(row?.observed_offline_count ?? 0),\n },\n devices,\n };\n }\n\n async resolveByDeviceId(deviceId: string): Promise<DeviceRecord | undefined> {\n const result = await this.#pool.query<DeviceRow>(\n `SELECT ${SELECT_COLUMNS} FROM device WHERE device_id = $1`,\n [deviceId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toRecord(row);\n }\n}\n","/**\n * Postgres {@link InboundDedupStore} (N3): bounded at-most-once processing.\n *\n * Check-and-record is one `INSERT ... ON CONFLICT DO NOTHING`, so a\n * composition cannot accidentally split it into a racy read-then-write: the\n * primary key does the deciding, and zero returned rows means \"already seen\".\n *\n * Reclaim runs only on the path that actually grew the table, and it deletes\n * oldest-first down to `DEDUP_RING_CAPACITY` rows for that device — the same\n * bound the in-memory ring holds. The ids most likely to be redelivered are the\n * recent ones, so dropping the oldest is the retention that matches the wire's\n * behavior. An unbounded set would pass every duplicate assertion and still let\n * one chatty device grow this table without limit.\n */\nimport { DEDUP_RING_CAPACITY, type InboundDedupStore } from '@byok-sdk/cloud';\nimport type { TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\nexport class PostgresInboundDedupStore implements InboundDedupStore {\n readonly #pool: Pool;\n readonly #capacity: number;\n\n constructor(pool: Pool, capacity: number = DEDUP_RING_CAPACITY) {\n this.#pool = pool;\n this.#capacity = capacity;\n }\n\n async checkAndRecord(tenant: TenantId, deviceId: string, envelopeId: string): Promise<boolean> {\n const inserted = await this.#pool.query(\n `INSERT INTO inbound_dedup (tenant_id, device_id, envelope_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (tenant_id, device_id, envelope_id) DO NOTHING\n RETURNING 1`,\n [tenant, deviceId, envelopeId],\n );\n if (inserted.rowCount === 0) return true;\n\n // Everything at or below the capacity-th newest row goes. The subquery\n // returns no row until the device is over capacity, and `<= NULL` deletes\n // nothing, so the common case costs one index scan and no writes.\n await this.#pool.query(\n `DELETE FROM inbound_dedup\n WHERE tenant_id = $1 AND device_id = $2\n AND recorded_seq <= (\n SELECT recorded_seq FROM inbound_dedup\n WHERE tenant_id = $1 AND device_id = $2\n ORDER BY recorded_seq DESC\n OFFSET $3 LIMIT 1)`,\n [tenant, deviceId, this.#capacity],\n );\n return false;\n }\n}\n","/**\n * Postgres {@link NonceStore}: single-use challenge nonces bound to the\n * (tenant, device) they were issued for, expiring after `NONCE_TTL_MS`\n * (docs/protocol.md §6.2).\n *\n * Expiry is compared against the INJECTED clock, never the database's `now()`.\n * A store that asked the server for the time would be unassertable under a test\n * clock, and the conformance suite's TTL dimension would have to sleep — which\n * is how a replay-window regression ships unnoticed.\n *\n * `issue` sweeps this device's spent and expired rows inline, same posture as\n * the in-memory reference and the reference server: a long-lived deployment\n * never calls a sweep on a timer, and the sweep is bounded to one (tenant,\n * device) so it stays proportional to the caller that triggered it.\n */\nimport { NONCE_TTL_MS, type NonceStore } from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { CloudCrypto } from '@byok-sdk/cloud';\nimport type { Pool } from 'pg';\n\nconst NONCE_BYTES = 24;\n\nexport class PostgresNonceStore implements NonceStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n readonly #crypto: CloudCrypto;\n readonly #ttlMs: number;\n\n constructor(pool: Pool, clock: Clock, crypto: CloudCrypto, ttlMs: number = NONCE_TTL_MS) {\n this.#pool = pool;\n this.#clock = clock;\n this.#crypto = crypto;\n this.#ttlMs = ttlMs;\n }\n\n async issue(tenant: TenantId, deviceId: string): Promise<string> {\n const nowMs = this.#clock.now().getTime();\n const now = new Date(nowMs).toISOString();\n\n await this.#pool.query(\n 'DELETE FROM auth_nonce WHERE tenant_id = $1 AND device_id = $2 AND (used OR expires_at < $3)',\n [tenant, deviceId, now],\n );\n\n const nonce = this.#crypto.randomToken(NONCE_BYTES);\n await this.#pool.query(\n `INSERT INTO auth_nonce (tenant_id, device_id, nonce, expires_at, used)\n VALUES ($1, $2, $3, $4, false)`,\n [tenant, deviceId, nonce, new Date(nowMs + this.#ttlMs).toISOString()],\n );\n return nonce;\n }\n\n async validate(tenant: TenantId, deviceId: string, nonce: string): Promise<boolean> {\n // Never mutates: the gate calls `markUsed` only after every other check on\n // the request has passed, so validation and consumption are separate steps.\n const result = await this.#pool.query(\n `SELECT 1 FROM auth_nonce\n WHERE tenant_id = $1 AND device_id = $2 AND nonce = $3\n AND used = false AND expires_at >= $4`,\n [tenant, deviceId, nonce, this.#clock.now().toISOString()],\n );\n return result.rowCount === 1;\n }\n\n async markUsed(tenant: TenantId, nonce: string): Promise<void> {\n // Tenant-first even though the signature carries no device: a nonce\n // belonging to another tenant is not addressable here, so a cross-tenant\n // consume cannot burn the real owner's nonce.\n await this.#pool.query('UPDATE auth_nonce SET used = true WHERE tenant_id = $1 AND nonce = $2', [\n tenant,\n nonce,\n ]);\n }\n}\n","/**\n * Postgres {@link PairingCodeStore}: single-use codes bound to the tenant and\n * product they were minted for.\n *\n * Redemption is one guarded statement. `UPDATE ... WHERE redeemed_at IS NULL\n * AND expires_at >= $now RETURNING ...` consumes and reports in the same\n * round trip, and zero rows is the typed rejection. A read-then-write would let\n * two concurrent redemptions both observe an unused code, and single-use is\n * exactly what makes the caller's \"redeem, then register the device\" sequence\n * exclusive.\n *\n * Unknown, expired, and already-used all answer `undefined`. The reference\n * server distinguishes them in its 401 text; a hosted multi-tenant surface\n * deliberately does not — the code is a bearer credential addressable across\n * every tenant, and \"already used\" versus \"never existed\" is precisely the\n * difference an attacker enumerating codes would pay for.\n */\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type {\n PairingCodeClaims,\n PairingCodeInfo,\n PairingCodeIssueInput,\n PairingCodeStore,\n} from '@byok-sdk/cloud';\nimport type { Pool } from 'pg';\n\nexport class PostgresPairingCodeStore implements PairingCodeStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async issue(tenant: TenantId, input: PairingCodeIssueInput): Promise<PairingCodeInfo> {\n // Re-issuing a code the host's control plane already minted replaces it,\n // deadline and consumption state included: a mint is the control plane\n // speaking, and it is the only party that could have chosen this code.\n await this.#pool.query(\n `INSERT INTO pairing_code (code, tenant_id, product_id, expires_at, redeemed_at)\n VALUES ($1, $2, $3, $4, NULL)\n ON CONFLICT (code) DO UPDATE\n SET tenant_id = EXCLUDED.tenant_id,\n product_id = EXCLUDED.product_id,\n expires_at = EXCLUDED.expires_at,\n redeemed_at = NULL`,\n [input.code, tenant, input.productId, input.expiresAt],\n );\n // `expiresAt` is echoed from the input rather than read back: the caller\n // supplied a canonical instant and must get that exact string, not this\n // driver's rendering of a timestamptz round trip.\n return { code: input.code, expiresAt: input.expiresAt };\n }\n\n async redeem(code: string): Promise<PairingCodeClaims | undefined> {\n const now = this.#clock.now().toISOString();\n const result = await this.#pool.query<{ tenant_id: string; product_id: string }>(\n `UPDATE pairing_code\n SET redeemed_at = $2\n WHERE code = $1 AND redeemed_at IS NULL AND expires_at >= $2\n RETURNING tenant_id, product_id`,\n [code, now],\n );\n const row = result.rows[0];\n if (row === undefined) return undefined;\n return { tenantId: row.tenant_id as TenantId, productId: row.product_id };\n }\n}\n","/**\n * Postgres {@link RequestReceiptStore}: the first write is the fact.\n *\n * `INSERT ... ON CONFLICT DO NOTHING` and nothing else. The terminal a device\n * reports is a fact, and the retry the at-least-once wire guarantees must not\n * overwrite it (§12.6.4: 不覆写第一份事实). `created: false` is how the caller\n * learns it was a replay, which is why an upsert that UPDATED would be wrong in\n * a way no naive \"record it twice\" test would catch — it would pass, while\n * silently rewriting history and restamping `recorded_at`.\n */\nimport type { RequestReceipt, RequestReceiptStore } from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\ninterface ReceiptRow {\n readonly tenant_id: string;\n readonly key: string;\n readonly body: string;\n readonly recorded_at: Date;\n}\n\nconst SELECT_COLUMNS = 'tenant_id, key, body, recorded_at';\n\nfunction toReceipt(row: ReceiptRow): RequestReceipt {\n return {\n tenantId: row.tenant_id as TenantId,\n key: row.key,\n body: row.body,\n recordedAt: row.recorded_at.toISOString(),\n };\n}\n\nexport class PostgresRequestReceiptStore implements RequestReceiptStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async record(\n tenant: TenantId,\n input: { readonly key: string; readonly body: string },\n ): Promise<{ readonly receipt: RequestReceipt; readonly created: boolean }> {\n const inserted = await this.#pool.query<ReceiptRow>(\n `INSERT INTO device_request_receipts (tenant_id, key, body, recorded_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (tenant_id, key) DO NOTHING\n RETURNING ${SELECT_COLUMNS}`,\n [tenant, input.key, input.body, this.#clock.now().toISOString()],\n );\n const created = inserted.rows[0];\n if (created !== undefined) return { receipt: toReceipt(created), created: true };\n\n const existing = await this.get(tenant, input.key);\n // Unreachable in practice: the insert only declines when the row exists.\n if (existing === undefined) throw new Error(`receipt ${input.key} vanished during record`);\n return { receipt: existing, created: false };\n }\n\n async get(tenant: TenantId, key: string): Promise<RequestReceipt | undefined> {\n const result = await this.#pool.query<ReceiptRow>(\n `SELECT ${SELECT_COLUMNS} FROM device_request_receipts WHERE tenant_id = $1 AND key = $2`,\n [tenant, key],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toReceipt(row);\n }\n}\n","import type {\n ProofRequestReceipt,\n ProofRequestReceiptInput,\n ProofRequestReceiptStore,\n} from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\ninterface ProofReceiptRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly request_id: string;\n readonly operation: string;\n readonly resource: string;\n readonly body_sha256: string;\n readonly body_size: string;\n readonly response_status: number;\n readonly response_body: string;\n readonly recorded_at: Date;\n}\n\nconst SELECT_COLUMNS = `tenant_id, device_id, request_id, operation, resource,\n body_sha256, body_size, response_status, response_body, recorded_at`;\n\nfunction toReceipt(row: ProofReceiptRow): ProofRequestReceipt {\n return {\n tenantId: row.tenant_id as TenantId,\n deviceId: row.device_id,\n requestId: row.request_id,\n operation: row.operation,\n resource: row.resource,\n bodySha256: row.body_sha256,\n bodySize: BigInt(row.body_size),\n responseStatus: row.response_status,\n responseBody: row.response_body,\n recordedAt: row.recorded_at.toISOString(),\n };\n}\n\nexport class PostgresProofRequestReceiptStore implements ProofRequestReceiptStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async record(\n tenant: TenantId,\n input: ProofRequestReceiptInput,\n ): Promise<{ readonly receipt: ProofRequestReceipt; readonly created: boolean }> {\n const result = await this.#pool.query<ProofReceiptRow>(\n `INSERT INTO proof_request_receipt (\n tenant_id, device_id, request_id, operation, resource, body_sha256,\n body_size, response_status, response_body, recorded_at\n ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (tenant_id, device_id, request_id) DO NOTHING\n RETURNING ${SELECT_COLUMNS}`,\n [\n tenant,\n input.deviceId,\n input.requestId,\n input.operation,\n input.resource,\n input.bodySha256,\n input.bodySize.toString(),\n input.responseStatus,\n input.responseBody,\n this.#clock.now().toISOString(),\n ],\n );\n const inserted = result.rows[0];\n if (inserted !== undefined) return { receipt: toReceipt(inserted), created: true };\n const existing = await this.get(tenant, input.deviceId, input.requestId);\n if (existing === undefined) throw new Error(`proof receipt ${input.requestId} vanished during record`);\n return { receipt: existing, created: false };\n }\n\n async get(\n tenant: TenantId,\n deviceId: string,\n requestId: string,\n ): Promise<ProofRequestReceipt | undefined> {\n const result = await this.#pool.query<ProofReceiptRow>(\n `SELECT ${SELECT_COLUMNS}\n FROM proof_request_receipt\n WHERE tenant_id = $1 AND device_id = $2 AND request_id = $3`,\n [tenant, deviceId, requestId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toReceipt(row);\n }\n}\n","/**\n * Postgres {@link TaskAttemptStore} — the ownership authority the inbound gate\n * reads (N2).\n *\n * `claim` is a single guarded statement: `UPDATE ... WHERE owner_device_id IS\n * NULL RETURNING ...`. Two devices racing the same offer therefore produce one\n * owner, not a last writer. When the guard rejects, the row is re-read and\n * returned as-is, which makes a losing claim (and the winner's own re-claim)\n * idempotent rather than an error — the caller learns who owns the task either\n * way. Ownership never transfers: reassigning an owner is the one operation\n * that would make the gate's cross-device assertion unfalsifiable.\n *\n * Two deliberate no-ops, both about not letting a guessed id leave a trace:\n * `claim` and `recordStatus` on a task this tenant never offered write nothing\n * and return `undefined`.\n */\nimport type { AgentRef, TaskAttempt, TaskAttemptStatus, TaskAttemptStore } from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\nexport interface TaskRow {\n readonly tenant_id: string;\n readonly task_id: string;\n readonly device_id: string;\n readonly agent_id: string | null;\n readonly agent_profile_revision: string | null;\n readonly owner_device_id: string | null;\n readonly status: string;\n readonly terminal_cause: string | null;\n readonly cancel_requested_at: Date | null;\n readonly cancel_reason: string | null;\n readonly cancel_message_id: string | null;\n readonly updated_at: Date;\n}\n\nexport const TASK_SELECT_COLUMNS =\n 'tenant_id, task_id, device_id, agent_id, agent_profile_revision, owner_device_id, status, terminal_cause, cancel_requested_at, cancel_reason, cancel_message_id, updated_at';\n\nexport function taskRowToAttempt(row: TaskRow): TaskAttempt {\n return {\n tenantId: row.tenant_id as TenantId,\n taskId: row.task_id,\n deviceId: row.device_id,\n ...(row.agent_id == null || row.agent_profile_revision == null\n ? {}\n : {\n agentRef: {\n agentId: row.agent_id,\n profileRevision: row.agent_profile_revision,\n },\n }),\n // `exactOptionalPropertyTypes` is off here, but an explicit absent key is\n // still what the in-memory reference produces for an unclaimed attempt, and\n // `toEqual` in the suite treats `undefined` and absent alike only for the\n // former.\n ...(row.owner_device_id === null ? {} : { ownerDeviceId: row.owner_device_id }),\n status: row.status as TaskAttemptStatus,\n ...(row.terminal_cause == null ? {} : { terminalCause: row.terminal_cause }),\n ...(row.cancel_requested_at === null\n ? {}\n : {\n cancellation: {\n requestedAt: row.cancel_requested_at.toISOString(),\n ...(row.cancel_reason === null ? {} : { reason: row.cancel_reason }),\n },\n }),\n updatedAt: row.updated_at.toISOString(),\n };\n}\n\nexport class PostgresTaskAttemptStore implements TaskAttemptStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async open(\n tenant: TenantId,\n input: { readonly taskId: string; readonly deviceId: string; readonly agentRef?: AgentRef },\n ): Promise<TaskAttempt> {\n // First offer wins: a re-open returns the existing attempt untouched, so a\n // second offer cannot retarget a task at a different device.\n const inserted = await this.#pool.query<TaskRow>(\n `INSERT INTO task (\n tenant_id, task_id, device_id, agent_id, agent_profile_revision,\n owner_device_id, status, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, NULL, 'offered', $6)\n ON CONFLICT (tenant_id, task_id) DO NOTHING\n RETURNING ${TASK_SELECT_COLUMNS}`,\n [\n tenant,\n input.taskId,\n input.deviceId,\n input.agentRef?.agentId ?? null,\n input.agentRef?.profileRevision ?? null,\n this.#now(),\n ],\n );\n const created = inserted.rows[0];\n if (created !== undefined) return taskRowToAttempt(created);\n\n const existing = await this.get(tenant, input.taskId);\n // Unreachable in practice: the insert only declines when the row exists.\n if (existing === undefined) throw new Error(`task ${input.taskId} vanished during open`);\n return existing;\n }\n\n async reserveAgentOffer(\n tenant: TenantId,\n input: { readonly taskId: string; readonly deviceId: string; readonly agentRef: AgentRef },\n ): Promise<{ readonly attempt: TaskAttempt; readonly created: boolean }> {\n const inserted = await this.#pool.query<TaskRow>(\n `INSERT INTO task (\n tenant_id, task_id, device_id, agent_id, agent_profile_revision,\n owner_device_id, status, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, NULL, 'offered', $6)\n ON CONFLICT (tenant_id, task_id) DO NOTHING\n RETURNING ${TASK_SELECT_COLUMNS}`,\n [tenant, input.taskId, input.deviceId, input.agentRef.agentId, input.agentRef.profileRevision, this.#now()],\n );\n const created = inserted.rows[0];\n if (created !== undefined) return { attempt: taskRowToAttempt(created), created: true };\n const existing = await this.get(tenant, input.taskId);\n if (existing === undefined) throw new Error(`task ${input.taskId} vanished during Agent offer reservation`);\n return { attempt: existing, created: false };\n }\n\n async get(tenant: TenantId, taskId: string): Promise<TaskAttempt | undefined> {\n const result = await this.#pool.query<TaskRow>(\n `SELECT ${TASK_SELECT_COLUMNS} FROM task WHERE tenant_id = $1 AND task_id = $2`,\n [tenant, taskId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : taskRowToAttempt(row);\n }\n\n async getMany(tenant: TenantId, taskIds: readonly string[]): Promise<readonly TaskAttempt[]> {\n if (taskIds.length === 0) return [];\n const result = await this.#pool.query<TaskRow>(\n `SELECT ${TASK_SELECT_COLUMNS} FROM task WHERE tenant_id = $1 AND task_id = ANY($2::text[])`,\n [tenant, [...new Set(taskIds)]],\n );\n return result.rows.map(taskRowToAttempt);\n }\n\n async claim(\n tenant: TenantId,\n input: { readonly taskId: string; readonly deviceId: string },\n ): Promise<TaskAttempt | undefined> {\n const claimed = await this.#pool.query<TaskRow>(\n `UPDATE task\n SET owner_device_id = $3, status = 'claimed', updated_at = $4\n WHERE tenant_id = $1 AND task_id = $2 AND owner_device_id IS NULL\n AND cancel_requested_at IS NULL AND status = 'offered'\n RETURNING ${TASK_SELECT_COLUMNS}`,\n [tenant, input.taskId, input.deviceId, this.#now()],\n );\n const won = claimed.rows[0];\n if (won !== undefined) return taskRowToAttempt(won);\n\n // Either the task is already owned, or this tenant never offered it. The\n // re-read tells those apart without a second guard, and returns\n // `undefined` for the guess.\n return this.get(tenant, input.taskId);\n }\n\n async recordStatus(\n tenant: TenantId,\n input: {\n readonly taskId: string;\n readonly status: TaskAttemptStatus;\n readonly agentRef?: AgentRef;\n readonly terminalCause?: string;\n },\n ): Promise<TaskAttempt | undefined> {\n const result = await this.#pool.query<TaskRow>(\n `UPDATE task\n SET status = $3,\n terminal_cause = COALESCE($7, terminal_cause),\n updated_at = $4\n WHERE tenant_id = $1 AND task_id = $2\n AND (\n (agent_id IS NULL AND agent_profile_revision IS NULL AND $5::text IS NULL AND $6::text IS NULL)\n OR (agent_id = $5 AND agent_profile_revision = $6)\n )\n AND (\n (cancel_requested_at IS NULL AND status NOT IN ('complete', 'failed', 'cancelled'))\n OR (cancel_requested_at IS NOT NULL AND $3 = 'cancelled' AND status <> 'cancelled')\n )\n RETURNING ${TASK_SELECT_COLUMNS}`,\n [\n tenant,\n input.taskId,\n input.status,\n this.#now(),\n input.agentRef?.agentId ?? null,\n input.agentRef?.profileRevision ?? null,\n input.terminalCause ?? null,\n ],\n );\n const row = result.rows[0];\n return row === undefined ? this.get(tenant, input.taskId) : taskRowToAttempt(row);\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * The one Postgres mailbox sequence allocator.\n *\n * The caller must already be in a transaction and must keep that transaction\n * open until its outbox row is inserted. The returned row lock is what makes a\n * lower sequence commit before any higher sequence for the same device.\n */\nimport type { TenantId } from '@byok-sdk/core';\nimport type { PoolClient } from 'pg';\n\nexport async function allocateMailboxSequence(\n client: PoolClient,\n tenant: TenantId,\n deviceId: string,\n now: string,\n): Promise<number> {\n const allocation = await client.query<{ readonly seq: bigint }>(\n `INSERT INTO device_stream (tenant_id, device_id, next_seq, acked_seq, acked_at)\n VALUES ($1, $2, 2, 0, $3)\n ON CONFLICT (tenant_id, device_id) DO UPDATE\n SET next_seq = device_stream.next_seq + 1\n RETURNING next_seq - 1 AS seq`,\n [tenant, deviceId, now],\n );\n return Number(allocation.rows[0]!.seq);\n}\n","/**\n * Postgres {@link MailboxStore} (§12.7.3).\n *\n * The load-bearing rule, and the one a composition can break silently:\n * **reading is not acknowledging.** `readAfter` is a `SELECT` and nothing else.\n * The only ack is `advanceCursor`, which the daemon calls after it has durably\n * journaled the envelope, and it is monotonic — a lower cursor is refused with\n * the cursor it lost to rather than quietly re-delivering work the device has\n * already run.\n *\n * `collectRetired` deletes acked rows and **marks** unacked ones `expired`. It\n * never deletes an unacked row. §12.7.5 requires an envelope that aged out\n * before anyone consumed it to stay visible; deleting it would make \"we dropped\n * work\" indistinguishable from \"there was no work\", and dead-lettering those\n * rows is S4B's job (O-009), not this one's.\n *\n * Every row lives under `(tenant_id, device_id, seq)`, so a cross-tenant read\n * is not denied — it addresses a different key space and finds nothing. That is\n * the SQL expression of §12.6.2 layer 3: there is no bare device index to\n * accidentally query.\n */\nimport {\n ByokCoreError,\n CoreConflictError,\n assertCanonicalTimestamp,\n type Clock,\n type ContentHash,\n type MailboxAdvanceCursorInput,\n type MailboxAppendInput,\n type MailboxCursorState,\n type MailboxMessage,\n type MailboxMessageState,\n type MailboxPage,\n type MailboxReadQuery,\n type MailboxRetentionInput,\n type MailboxRetentionResult,\n type MailboxStore,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { Pool } from 'pg';\nimport { allocateMailboxSequence } from './mailbox-sequence';\n\nconst DEFAULT_READ_LIMIT = 50;\n\nexport const OUTBOX_COLUMNS =\n 'tenant_id, device_id, seq, message_id, body, body_hash, byte_size, state, appended_at';\n\nexport interface OutboxRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly seq: bigint;\n readonly message_id: string;\n readonly body: string;\n readonly body_hash: string;\n readonly byte_size: bigint;\n readonly state: string;\n readonly appended_at: string;\n}\n\ninterface CursorRow {\n readonly acked_seq: bigint;\n readonly acked_at: string | null;\n}\n\ninterface RetentionRow {\n readonly deleted_count: bigint;\n readonly expired_count: bigint;\n readonly released_bytes: bigint;\n}\n\nexport function toMailboxMessage(row: OutboxRow): MailboxMessage {\n return {\n tenantId: row.tenant_id as TenantId,\n deviceId: row.device_id,\n // `seq` is bigint in the column and `number` on the port, because it is the\n // envelope `seq` on the wire. The column is wide so the counter cannot wrap\n // into a redelivery bug; the narrowing happens once, here.\n seq: Number(row.seq),\n messageId: row.message_id,\n body: row.body,\n bodyHash: row.body_hash as ContentHash,\n byteSize: row.byte_size,\n state: row.state as MailboxMessageState,\n appendedAt: row.appended_at,\n };\n}\n\nexport class PostgresMailboxStore implements MailboxStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async append(tenant: TenantId, input: MailboxAppendInput): Promise<MailboxMessage> {\n this.#requireDeviceId(input.deviceId);\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n\n const existing = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.messageId],\n );\n const replayed = existing.rows[0];\n if (replayed !== undefined) {\n await client.query('COMMIT');\n return toMailboxMessage(replayed);\n }\n\n // The device_stream row lock serializes the whole allocate -> materialize\n // -> insert unit. Releasing it before insertion would let seq N+1 become\n // visible before N; a daemon could then ack N+1 and permanently skip the\n // late N row.\n const seq = await allocateMailboxSequence(client, tenant, input.deviceId, this.#now());\n const serializedExisting = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.messageId],\n );\n const winnerAfterLock = serializedExisting.rows[0];\n if (winnerAfterLock !== undefined) {\n await client.query('ROLLBACK');\n return toMailboxMessage(winnerAfterLock);\n }\n const materialized = await input.materialize(seq);\n const now = this.#now();\n const inserted = await client.query<OutboxRow>(\n `INSERT INTO outbox (${OUTBOX_COLUMNS})\n VALUES ($1, $2, $3::bigint, $4, $5, $6, $7::bigint, 'pending', $8)\n ON CONFLICT (tenant_id, device_id, message_id) DO NOTHING\n RETURNING ${OUTBOX_COLUMNS}`,\n [\n tenant,\n input.deviceId,\n seq,\n input.messageId,\n materialized.body,\n materialized.bodyHash,\n materialized.byteSize,\n now,\n ],\n );\n const row = inserted.rows[0];\n if (row !== undefined) {\n await client.query('COMMIT');\n return toMailboxMessage(row);\n }\n\n // A concurrent append with the same idempotency key won while this\n // transaction waited on the per-device allocator. Roll back our sequence\n // bump so an idempotent retry consumes neither a row nor a number.\n const winner = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.messageId],\n );\n await client.query('ROLLBACK');\n const won = winner.rows[0];\n if (won === undefined) {\n throw new ByokCoreError(\n 'mailbox_message_not_found',\n `Message ${input.messageId} vanished during an idempotent append.`,\n );\n }\n return toMailboxMessage(won);\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n } finally {\n client.release();\n }\n }\n\n async readAfter(tenant: TenantId, query: MailboxReadQuery): Promise<MailboxPage> {\n const limit = query.limit ?? DEFAULT_READ_LIMIT;\n // One row past the page answers `hasMore` without a second count query, and\n // without the count and the page disagreeing about which snapshot they saw.\n const result = await this.#pool.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND state = 'pending' AND seq > $3::bigint\n ORDER BY seq\n LIMIT $4`,\n [tenant, query.deviceId, query.afterSeq, limit + 1],\n );\n\n const page = result.rows.slice(0, limit).map(toMailboxMessage);\n return {\n messages: page,\n // Nothing above was mutated, so an identical call replays the same page.\n // The returned position is a READ cursor and moves no ack.\n nextSeq: page.at(-1)?.seq ?? query.afterSeq,\n hasMore: result.rows.length > page.length,\n };\n }\n\n async advanceCursor(\n tenant: TenantId,\n input: MailboxAdvanceCursorInput,\n ): Promise<MailboxCursorState> {\n this.#requireDeviceId(input.deviceId);\n const now = this.#now();\n\n // The monotonic guard lives in `WHERE device_stream.acked_seq <=\n // EXCLUDED.acked_seq`, so a stale ack updates nothing rather than winning a\n // last-write race and re-opening envelopes the device already journaled.\n //\n // Marking the rows is folded into the same statement on purpose. Split\n // across two round trips, a crash between them would leave the cursor ahead\n // of the rows it acked, and `readAfter` would re-serve work the device has\n // run. When the guard rejects, `(SELECT acked_seq FROM moved)` is NULL and\n // `seq <= NULL` marks nothing — the rejection is total, not partial.\n const moved = await this.#pool.query<CursorRow>(\n `WITH moved AS (\n INSERT INTO device_stream (tenant_id, device_id, next_seq, acked_seq, acked_at)\n VALUES ($1, $2, 1, $3::bigint, $4)\n ON CONFLICT (tenant_id, device_id) DO UPDATE\n SET acked_seq = EXCLUDED.acked_seq, acked_at = EXCLUDED.acked_at\n WHERE device_stream.acked_seq <= EXCLUDED.acked_seq\n RETURNING acked_seq, acked_at\n ), marked AS (\n UPDATE outbox\n SET state = 'acked'\n WHERE tenant_id = $1 AND device_id = $2 AND state = 'pending'\n AND seq <= (SELECT acked_seq FROM moved)\n RETURNING 1\n )\n SELECT acked_seq, acked_at FROM moved`,\n [tenant, input.deviceId, input.ackedSeq, now],\n );\n\n const row = moved.rows[0];\n if (row !== undefined) {\n return {\n tenantId: tenant,\n deviceId: input.deviceId,\n ackedSeq: Number(row.acked_seq),\n updatedAt: row.acked_at ?? now,\n };\n }\n\n const current = await this.readCursor(tenant, input.deviceId);\n throw new CoreConflictError(\n 'mailbox_cursor_regression',\n `Cursor for device ${input.deviceId} is at ${current.ackedSeq}; refusing to move it back to ${input.ackedSeq}.`,\n current,\n this.#now(),\n );\n }\n\n async readCursor(tenant: TenantId, deviceId: string): Promise<MailboxCursorState> {\n const result = await this.#pool.query<CursorRow>(\n `SELECT acked_seq, acked_at FROM device_stream\n WHERE tenant_id = $1 AND device_id = $2`,\n [tenant, deviceId],\n );\n const row = result.rows[0];\n // No row, or a row the mailbox created without ever moving its cursor: the\n // position is 0 and there is no recorded ack instant to report, so the\n // read's own clock stands in.\n return {\n tenantId: tenant,\n deviceId,\n ackedSeq: row === undefined ? 0 : Number(row.acked_seq),\n updatedAt: row?.acked_at ?? this.#now(),\n };\n }\n\n async collectRetired(\n tenant: TenantId,\n input: MailboxRetentionInput,\n ): Promise<MailboxRetentionResult> {\n // Both cutoffs are compared against `appended_at` as text; the canonical\n // form is what makes that a time comparison rather than an arbitrary one.\n // Validate before the sweep so a malformed cutoff deletes nothing at all\n // rather than a wrong prefix of history.\n assertCanonicalTimestamp(input.ackedBefore, 'ackedBefore');\n assertCanonicalTimestamp(input.expireUnackedBefore, 'expireUnackedBefore');\n\n // Delete and dead-letter in one statement, so a sweep is all or nothing and\n // the two counts an operator reads describe the same moment. The two CTEs\n // select disjoint sets — one `acked`, one `pending` — so no row can be both\n // counted and marked.\n const swept = await this.#pool.query<RetentionRow>(\n `WITH deleted AS (\n DELETE FROM outbox\n WHERE tenant_id = $1\n AND ($2::text IS NULL OR device_id = $2::text)\n AND state = 'acked'\n AND appended_at < $3\n RETURNING byte_size\n ), expired AS (\n UPDATE outbox\n SET state = 'expired'\n WHERE tenant_id = $1\n AND ($2::text IS NULL OR device_id = $2::text)\n AND state = 'pending'\n AND appended_at < $4\n RETURNING 1\n )\n SELECT (SELECT count(*) FROM deleted) AS deleted_count,\n (SELECT count(*) FROM expired) AS expired_count,\n (SELECT COALESCE(SUM(byte_size), 0) FROM deleted)::bigint AS released_bytes`,\n [tenant, input.deviceId ?? null, input.ackedBefore, input.expireUnackedBefore],\n );\n\n const row = swept.rows[0]!;\n return {\n deletedCount: Number(row.deleted_count),\n expiredCount: Number(row.expired_count),\n releasedBytes: row.released_bytes,\n };\n }\n\n /**\n * The in-memory reference refuses an empty device id rather than opening a\n * mailbox nothing can address. Kept here so the two compositions answer the\n * same way; the table itself would happily store the row.\n */\n #requireDeviceId(deviceId: string): void {\n if (deviceId.length === 0) {\n throw new ByokCoreError('mailbox_message_not_found', 'Device id must not be empty.');\n }\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","import type {\n TaskCancellationMutation,\n TaskCancellationRequest,\n TaskCancellationStore,\n} from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\nimport {\n OUTBOX_COLUMNS,\n type OutboxRow,\n toMailboxMessage,\n} from './core/mailbox';\nimport { allocateMailboxSequence } from './core/mailbox-sequence';\nimport {\n TASK_SELECT_COLUMNS,\n type TaskRow,\n taskRowToAttempt,\n} from './task-attempts';\n\n/** PostgreSQL atomic authority for host cancellation state plus mailbox delivery. */\nexport class PostgresTaskCancellationStore implements TaskCancellationStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async request(\n tenant: TenantId,\n input: TaskCancellationRequest,\n ): Promise<TaskCancellationMutation | undefined> {\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n const selected = await client.query<TaskRow>(\n `SELECT ${TASK_SELECT_COLUMNS} FROM task\n WHERE tenant_id = $1 AND task_id = $2\n FOR UPDATE`,\n [tenant, input.taskId],\n );\n const current = selected.rows[0];\n if (current === undefined) {\n await client.query('ROLLBACK');\n return undefined;\n }\n\n if (\n current.cancel_requested_at === null &&\n (current.status === 'complete' || current.status === 'failed' || current.status === 'cancelled')\n ) {\n await client.query('COMMIT');\n return { attempt: taskRowToAttempt(current) };\n }\n\n if (current.cancel_message_id !== null) {\n const replayed = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, current.device_id, current.cancel_message_id],\n );\n const message = replayed.rows[0];\n if (message === undefined) {\n // Acked mailbox rows are retention-deletable. Once the attempt is\n // cancelled, the tombstone remains the durable idempotency outcome\n // even after that delivery evidence ages out. A still-requested\n // attempt with no row is corruption and must continue to fail closed.\n if (current.status === 'cancelled') {\n await client.query('COMMIT');\n return { attempt: taskRowToAttempt(current) };\n }\n throw new Error(`Cancellation delivery ${current.cancel_message_id} is missing for task ${input.taskId}`);\n }\n await client.query('COMMIT');\n return { attempt: taskRowToAttempt(current), message: toMailboxMessage(message) };\n }\n\n const now = this.#clock.now().toISOString();\n const messageId = input.proposedMessageId;\n const seq = await allocateMailboxSequence(client, tenant, current.device_id, now);\n const materialized = await input.materialize(seq, messageId);\n const insertedMessage = await client.query<OutboxRow>(\n `INSERT INTO outbox (${OUTBOX_COLUMNS})\n VALUES ($1, $2, $3::bigint, $4, $5, $6, $7::bigint, 'pending', $8)\n RETURNING ${OUTBOX_COLUMNS}`,\n [\n tenant,\n current.device_id,\n seq,\n messageId,\n materialized.body,\n materialized.bodyHash,\n materialized.byteSize,\n now,\n ],\n );\n const updated = await client.query<TaskRow>(\n `UPDATE task\n SET status = CASE WHEN owner_device_id IS NULL THEN 'cancelled' ELSE 'cancel_requested' END,\n cancel_requested_at = $3,\n cancel_reason = $4,\n cancel_message_id = $5,\n updated_at = $3\n WHERE tenant_id = $1 AND task_id = $2\n RETURNING ${TASK_SELECT_COLUMNS}`,\n [tenant, input.taskId, now, input.reason ?? null, messageId],\n );\n await client.query('COMMIT');\n return {\n attempt: taskRowToAttempt(updated.rows[0]!),\n message: toMailboxMessage(insertedMessage.rows[0]!),\n };\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n } finally {\n client.release();\n }\n }\n}\n","import {\n ByokCloudError,\n activityCursor,\n parseTimelineEvents,\n projectTimelineEvents,\n validateActivityAppend,\n type ActivityAppendInput,\n type ActivityStore,\n type ActivityTail,\n} from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\ninterface TailRow {\n readonly tenant_id: string;\n readonly task_id: string;\n readonly entries: unknown;\n readonly dropped: number;\n readonly capacity: number;\n readonly expires_at: string;\n}\n\nfunction toTail(row: TailRow): ActivityTail {\n const entries = parseTimelineEvents(row.entries);\n const cursor = activityCursor(entries);\n return {\n tenantId: row.tenant_id as TenantId,\n taskId: row.task_id,\n entries,\n ...(cursor === undefined ? {} : { cursor }),\n dropped: row.dropped,\n capacity: row.capacity,\n expiresAt: row.expires_at,\n };\n}\n\nexport class PostgresActivityStore implements ActivityStore {\n constructor(\n private readonly pool: Pool,\n private readonly clock: Clock,\n ) {}\n\n async append(tenant: TenantId, input: ActivityAppendInput): Promise<ActivityTail> {\n const capacity = validateActivityAppend(input);\n const now = this.clock.now();\n const receivedAt = now.toISOString();\n const incoming = projectTimelineEvents(input, receivedAt);\n const expiresAt = new Date(now.getTime() + input.ttlMs).toISOString();\n\n // The conflict arm reads activity_tail only after Postgres acquires the row\n // lock. It sorts the combined typed DTOs by the stable order key before\n // trimming, so concurrent or delayed batches have the same observable tail\n // as the in-memory reference.\n const result = await this.pool.query<TailRow>(\n `WITH incoming AS (\n SELECT entry\n FROM jsonb_array_elements($4::jsonb) AS element(entry)\n ), trimmed AS (\n SELECT COALESCE(jsonb_agg(entry ORDER BY\n (entry->>'batchSeq')::bigint,\n (entry->>'eventIndex')::bigint), '[]'::jsonb) AS entries,\n $5::integer + GREATEST(jsonb_array_length($4::jsonb) - $6, 0) AS dropped\n FROM (\n SELECT entry\n FROM incoming\n ORDER BY (entry->>'batchSeq')::bigint DESC,\n (entry->>'eventIndex')::bigint DESC\n LIMIT $6\n ) retained\n )\n INSERT INTO activity_tail (tenant_id, task_id, entries, dropped, capacity, expires_at)\n SELECT $1, $2, trimmed.entries, trimmed.dropped, $6, $7 FROM trimmed\n ON CONFLICT (tenant_id, task_id) DO UPDATE\n SET entries = (\n SELECT COALESCE(jsonb_agg(entry ORDER BY\n (entry->>'batchSeq')::bigint,\n (entry->>'eventIndex')::bigint), '[]'::jsonb)\n FROM (\n SELECT entry\n FROM jsonb_array_elements(\n (CASE WHEN activity_tail.expires_at > $3\n THEN activity_tail.entries ELSE '[]'::jsonb END) || $4::jsonb\n ) AS element(entry)\n ORDER BY (entry->>'batchSeq')::bigint DESC,\n (entry->>'eventIndex')::bigint DESC\n LIMIT $6\n ) retained\n ),\n dropped = (CASE WHEN activity_tail.expires_at > $3\n THEN activity_tail.dropped ELSE 0 END)\n + $5::integer\n + GREATEST(\n jsonb_array_length(\n (CASE WHEN activity_tail.expires_at > $3\n THEN activity_tail.entries ELSE '[]'::jsonb END) || $4::jsonb\n ) - $6,\n 0\n ),\n capacity = EXCLUDED.capacity,\n expires_at = EXCLUDED.expires_at\n WHERE activity_tail.expires_at <= $3\n OR (\n NOT EXISTS (\n SELECT 1\n FROM jsonb_array_elements(activity_tail.entries) AS stored(entry)\n WHERE jsonb_typeof(entry) <> 'object'\n OR NOT (entry ?& ARRAY[\n 'taskId', 'sourceEnvelopeId', 'batchSeq',\n 'eventIndex', 'receivedAt', 'event'\n ])\n )\n AND NOT EXISTS (\n SELECT 1\n FROM jsonb_array_elements(activity_tail.entries) AS old_element(entry)\n CROSS JOIN jsonb_array_elements($4::jsonb) AS new_element(candidate)\n WHERE (entry->>'batchSeq')::bigint = (candidate->>'batchSeq')::bigint\n AND (entry->>'eventIndex')::bigint = (candidate->>'eventIndex')::bigint\n AND entry->>'sourceEnvelopeId' <> candidate->>'sourceEnvelopeId'\n )\n )\n RETURNING tenant_id, task_id, entries, dropped, capacity, expires_at`,\n [tenant, input.taskId, receivedAt, JSON.stringify(incoming), input.dropped, capacity, expiresAt],\n );\n const row = result.rows[0];\n if (row === undefined) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Activity batch ${input.batchSeq} conflicts with the existing typed tail authority.`,\n );\n }\n return toTail(row);\n }\n\n async read(tenant: TenantId, taskId: string): Promise<ActivityTail | undefined> {\n const result = await this.pool.query<TailRow>(\n `SELECT tenant_id, task_id, entries, dropped, capacity, expires_at\n FROM activity_tail\n WHERE tenant_id = $1 AND task_id = $2 AND expires_at > $3`,\n [tenant, taskId, this.clock.now().toISOString()],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toTail(row);\n }\n}\n","import {\n ApprovalObservationSchema,\n ByokCloudError,\n approvalTimelineCursor,\n parseApprovalObservations,\n validateApprovalTimelineAppend,\n type ApprovalTimelineAppendInput,\n type ApprovalTimelineStore,\n type ApprovalTimelineTail,\n} from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool, PoolClient } from 'pg';\n\ninterface TailRow {\n readonly tenant_id: string;\n readonly task_id: string;\n readonly entries: unknown;\n readonly next_revision: string | number | bigint;\n readonly dropped: number;\n readonly capacity: number;\n readonly expires_at: string;\n}\n\nfunction toTail(row: TailRow): ApprovalTimelineTail {\n const entries = parseApprovalObservations(row.entries);\n const cursor = approvalTimelineCursor(entries);\n return {\n tenantId: row.tenant_id as TenantId,\n taskId: row.task_id,\n entries,\n ...(cursor === undefined ? {} : { cursor }),\n dropped: row.dropped,\n capacity: row.capacity,\n expiresAt: row.expires_at,\n };\n}\n\nasync function readLocked(\n client: PoolClient,\n tenant: TenantId,\n taskId: string,\n): Promise<TailRow | undefined> {\n const result = await client.query<TailRow>(\n `SELECT tenant_id, task_id, entries, next_revision, dropped, capacity, expires_at\n FROM approval_timeline_tail\n WHERE tenant_id = $1 AND task_id = $2\n FOR UPDATE`,\n [tenant, taskId],\n );\n return result.rows[0];\n}\n\nexport class PostgresApprovalTimelineStore implements ApprovalTimelineStore {\n constructor(\n private readonly pool: Pool,\n private readonly clock: Clock,\n ) {}\n\n async append(\n tenant: TenantId,\n input: ApprovalTimelineAppendInput,\n ): Promise<ApprovalTimelineTail> {\n const { capacity, ttlMs, event } = validateApprovalTimelineAppend(input);\n const now = this.clock.now();\n const receivedAt = now.toISOString();\n const expiresAt = new Date(now.getTime() + ttlMs).toISOString();\n const client = await this.pool.connect();\n try {\n await client.query('BEGIN');\n await client.query(\n `SELECT pg_advisory_xact_lock(hashtextextended($1 || E'\\\\x1f' || $2, 0))`,\n [tenant, input.taskId],\n );\n const stored = await readLocked(client, tenant, input.taskId);\n const live = stored !== undefined && receivedAt < stored.expires_at ? toTail(stored) : undefined;\n const duplicate = live?.entries.find(\n (entry) => entry.sourceEnvelopeId === input.sourceEnvelopeId,\n );\n if (duplicate !== undefined) {\n if (JSON.stringify(duplicate.event) !== JSON.stringify(event)) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Approval source envelope identity already belongs to another lifecycle event.',\n );\n }\n await client.query('COMMIT');\n return live!;\n }\n\n const revision = live === undefined ? 1 : Number(stored!.next_revision);\n const expectedRevision = (live?.cursor ?? 0) + 1;\n if (\n !Number.isSafeInteger(revision) ||\n revision <= 0 ||\n revision !== expectedRevision\n ) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Approval timeline revision authority is malformed.',\n );\n }\n const observation = ApprovalObservationSchema.parse({\n taskId: input.taskId,\n sourceEnvelopeId: input.sourceEnvelopeId,\n revision,\n receivedAt,\n event,\n });\n const allEntries = [...(live?.entries ?? []), observation];\n const evicted = Math.max(allEntries.length - capacity, 0);\n const entries = allEntries.slice(evicted);\n const dropped = (live?.dropped ?? 0) + evicted;\n const result = await client.query<TailRow>(\n `INSERT INTO approval_timeline_tail\n (tenant_id, task_id, entries, next_revision, dropped, capacity, expires_at)\n VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)\n ON CONFLICT (tenant_id, task_id) DO UPDATE\n SET entries = EXCLUDED.entries,\n next_revision = EXCLUDED.next_revision,\n dropped = EXCLUDED.dropped,\n capacity = EXCLUDED.capacity,\n expires_at = EXCLUDED.expires_at\n RETURNING tenant_id, task_id, entries, next_revision, dropped, capacity, expires_at`,\n [\n tenant,\n input.taskId,\n JSON.stringify(entries),\n revision + 1,\n dropped,\n capacity,\n expiresAt,\n ],\n );\n await client.query('COMMIT');\n return toTail(result.rows[0]!);\n } catch (caught) {\n await client.query('ROLLBACK');\n throw caught;\n } finally {\n client.release();\n }\n }\n\n async read(tenant: TenantId, taskId: string): Promise<ApprovalTimelineTail | undefined> {\n const result = await this.pool.query<TailRow>(\n `SELECT tenant_id, task_id, entries, next_revision, dropped, capacity, expires_at\n FROM approval_timeline_tail\n WHERE tenant_id = $1 AND task_id = $2 AND expires_at > $3`,\n [tenant, taskId, this.clock.now().toISOString()],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toTail(row);\n }\n}\n","import {\n AgentEgressReliablePayloadSchema,\n type AgentEgressReliablePayload,\n} from '@byok-sdk/protocol';\nimport type { AgentEgressRecord, AgentEgressStore } from '@byok-sdk/cloud';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\ninterface AgentEgressRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly event_id: string;\n readonly agent_id: string;\n readonly agent_profile_revision: string;\n readonly session_ref: string;\n readonly policy_revision: string;\n readonly cursor: string;\n readonly payload_json: unknown;\n readonly content_hash: string;\n readonly byte_count: number;\n readonly receipt_id: string;\n readonly recorded_at: Date;\n}\n\nconst SELECT_COLUMNS = [\n 'tenant_id',\n 'device_id',\n 'event_id',\n 'agent_id',\n 'agent_profile_revision',\n 'session_ref',\n 'policy_revision',\n 'cursor',\n 'payload_json',\n 'content_hash',\n 'byte_count',\n 'receipt_id',\n 'recorded_at',\n].join(', ');\n\nfunction toRecord(row: AgentEgressRow): AgentEgressRecord {\n const payload: AgentEgressReliablePayload = AgentEgressReliablePayloadSchema.parse({\n agentRef: { agentId: row.agent_id, profileRevision: row.agent_profile_revision },\n sessionRef: row.session_ref,\n policyRevision: row.policy_revision,\n eventId: row.event_id,\n cursor: Number(row.cursor),\n payload: row.payload_json,\n contentHash: row.content_hash,\n byteCount: row.byte_count,\n });\n return {\n tenantId: row.tenant_id as TenantId,\n deviceId: row.device_id,\n payload,\n receiptId: row.receipt_id,\n recordedAt: row.recorded_at.toISOString(),\n };\n}\n\n/** Postgres implementation of the immutable reliable Agent egress receipt fact. */\nexport class PostgresAgentEgressStore implements AgentEgressStore {\n constructor(\n private readonly pool: Pool,\n private readonly clock: Clock,\n ) {}\n\n async record(\n tenant: TenantId,\n input: Omit<AgentEgressRecord, 'tenantId' | 'recordedAt'>,\n ): Promise<{ readonly record: AgentEgressRecord; readonly created: boolean }> {\n const payload = AgentEgressReliablePayloadSchema.parse(input.payload);\n const inserted = await this.pool.query<AgentEgressRow>(\n `INSERT INTO agent_egress_event (${SELECT_COLUMNS})\n VALUES ($1, $2, $3::uuid, $4, $5, $6, $7, $8::bigint, $9::jsonb, $10, $11::integer, $12::uuid, $13)\n ON CONFLICT (tenant_id, device_id, event_id) DO NOTHING\n RETURNING ${SELECT_COLUMNS}`,\n [\n tenant,\n input.deviceId,\n payload.eventId,\n payload.agentRef.agentId,\n payload.agentRef.profileRevision,\n payload.sessionRef,\n payload.policyRevision,\n payload.cursor,\n JSON.stringify(payload.payload),\n payload.contentHash,\n payload.byteCount,\n input.receiptId,\n this.clock.now().toISOString(),\n ],\n );\n const row = inserted.rows[0];\n if (row !== undefined) return { record: toRecord(row), created: true };\n const existing = await this.get(tenant, input.deviceId, payload.eventId);\n if (existing === undefined) throw new Error(`Agent egress ${payload.eventId} vanished during first-write record.`);\n return { record: existing, created: false };\n }\n\n async get(tenant: TenantId, deviceId: string, eventId: string): Promise<AgentEgressRecord | undefined> {\n const result = await this.pool.query<AgentEgressRow>(\n `SELECT ${SELECT_COLUMNS}\n FROM agent_egress_event\n WHERE tenant_id = $1 AND device_id = $2 AND event_id = $3::uuid`,\n [tenant, deviceId, eventId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toRecord(row);\n }\n}\n","import type {\n DeviceAssertionReplayAuthority,\n DeviceAssertionReplayConsumeInput,\n} from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\n/** Durable atomic replay authority for hosted device-assertion exchange. */\nexport class PostgresDeviceAssertionReplayAuthority implements DeviceAssertionReplayAuthority {\n readonly #pool: Pool;\n\n constructor(pool: Pool) {\n this.#pool = pool;\n }\n\n async consume(input: DeviceAssertionReplayConsumeInput): Promise<boolean> {\n if (!Number.isFinite(Date.parse(input.expiresAt))) {\n throw new Error('device assertion replay expiry is invalid');\n }\n const result = await this.#pool.query(\n `INSERT INTO device_assertion_replay (\n tenant_id, issuer, product_id, device_id, audience, jti, expires_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (tenant_id, issuer, product_id, device_id, audience, jti) DO NOTHING\n RETURNING jti`,\n [\n input.tenantId,\n input.issuer,\n input.productId,\n input.deviceId,\n input.audience,\n input.jti,\n input.expiresAt,\n ],\n );\n return result.rowCount === 1;\n }\n\n /** Bounded retention cleanup; callers choose cadence and batch size. */\n async deleteExpired(before: Date, limit: number): Promise<number> {\n if (!Number.isFinite(before.getTime()) || !Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error('device assertion replay cleanup bounds are invalid');\n }\n const result = await this.#pool.query(\n `DELETE FROM device_assertion_replay\n WHERE ctid IN (\n SELECT ctid\n FROM device_assertion_replay\n WHERE expires_at <= $1\n ORDER BY expires_at\n LIMIT $2\n )`,\n [before.toISOString(), limit],\n );\n return result.rowCount ?? 0;\n }\n}\n","/**\n * The Postgres composition of the cloud-local ports.\n *\n * Nine durable stores, one object-storage blob store, one in-memory limiter:\n *\n * - Six durable ones have rows in `deploy/sql/0001_cloud_local.sql`; S6's\n * proof receipt authority is the seventh, in `0004_device_proof_truth.sql`;\n * typed activity uses the JSONB tail row in `0002_core_domain.sql`; approval\n * lifecycle observations use `0007_approval_timeline.sql`.\n * - `blobs` is the R2 adapter over the `object_manifest` row the core store\n * already owns: metadata in Postgres, bytes in the object store, one\n * reserve/verify protocol binding them (design §6). It supplies grants only,\n * and this composition deliberately hands `createByokCloud` NO\n * `BlobContentProxy` — a device uploading straight to R2 is what having no\n * byte-proxy path means, and saying so by absence is what keeps the two\n * `/content` routes from mounting on a deployment that cannot serve them.\n * - `rateLimiter` gets the allow-all reference and NO table, by design\n * (docs/researches/s4a-dataplane-design.md §5). Persisting an allow-all would\n * create a table that is always empty, and a real limiter is edge/infra work\n * whose implementation would not be a per-request Postgres write either.\n */\nimport { AllowAllRateLimiter, type CloudStores } from '@byok-sdk/cloud';\nimport type { CloudCrypto } from '@byok-sdk/cloud';\nimport type { Clock } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\nimport { PostgresObjectStore } from './core/objects';\nimport { R2CloudBlobStore, type R2BlobStoreOptions } from './r2-blobs';\nimport { PostgresDeviceDirectory } from './devices';\nimport { PostgresInboundDedupStore } from './dedup';\nimport { PostgresNonceStore } from './nonces';\nimport { PostgresPairingCodeStore } from './pairing-codes';\nimport { PostgresRequestReceiptStore } from './receipts';\nimport { PostgresProofRequestReceiptStore } from './proof-receipts';\nimport { PostgresTaskAttemptStore } from './task-attempts';\nimport { PostgresTaskCancellationStore } from './task-cancellations';\nimport { PostgresActivityStore } from './activity';\nimport { PostgresApprovalTimelineStore } from './approval-timeline';\nimport { PostgresAgentEgressStore } from './agent-egress';\n\nexport { PostgresDeviceDirectory } from './devices';\nexport { PostgresInboundDedupStore } from './dedup';\nexport { PostgresNonceStore } from './nonces';\nexport { PostgresPairingCodeStore } from './pairing-codes';\nexport { PostgresRequestReceiptStore } from './receipts';\nexport { PostgresProofRequestReceiptStore } from './proof-receipts';\nexport { PostgresTaskAttemptStore } from './task-attempts';\nexport { PostgresTaskCancellationStore } from './task-cancellations';\nexport { PostgresActivityStore } from './activity';\nexport { PostgresApprovalTimelineStore } from './approval-timeline';\nexport { PostgresAgentEgressStore } from './agent-egress';\nexport { PostgresDeviceAssertionReplayAuthority } from './device-assertion-replay';\nexport {\n DEFAULT_MAX_ATTEMPTS,\n DEFAULT_PRESIGN_TTL_SECONDS,\n DEFAULT_RETRY_DELAY_MS,\n MAX_PRESIGN_TTL_SECONDS,\n MIN_PRESIGN_TTL_SECONDS,\n ObjectStoreRequestError,\n R2_BLOB_ERROR_CODES,\n R2BlobStoreError,\n R2CloudBlobStore,\n R2ObjectMaintenanceStore,\n} from './r2-blobs';\nexport type { ObjectStoreFetch, R2BlobErrorCode, R2BlobStoreOptions } from './r2-blobs';\nexport type {\n R2DeleteResult,\n R2ListedObject,\n R2ObjectMaintenance,\n R2ObjectMaintenanceOptions,\n R2ObjectPage,\n} from './r2-blobs';\n\n/** Every cloud-local port. All twelve, or it is not a composition. */\nexport type PostgresCloudStores = CloudStores;\n\n/** Everything the blob store needs that is not already a composition-wide input. */\nexport type PostgresObjectStorageOptions = Omit<R2BlobStoreOptions, 'objects'>;\n\nexport interface PostgresCloudStoreOptions {\n readonly pool: Pool;\n /**\n * The clock every TTL and timestamp in this composition reads. Injected, not\n * the database's own: expiry has to be assertable under a test clock, and a\n * store that asks the server for the time cannot be.\n */\n readonly clock: Clock;\n readonly crypto: CloudCrypto;\n /**\n * Where the bytes go. Required, because a composition that cannot say where\n * its objects live cannot honestly claim the `blobs` port — and the\n * conformance suite certifies compositions whole, never in parts.\n */\n readonly objectStorage: PostgresObjectStorageOptions;\n}\n\nexport function createPostgresCloudStores(\n options: PostgresCloudStoreOptions,\n): PostgresCloudStores {\n const { pool, clock, crypto } = options;\n return {\n activity: new PostgresActivityStore(pool, clock),\n approvals: new PostgresApprovalTimelineStore(pool, clock),\n devices: new PostgresDeviceDirectory(pool, clock),\n pairingCodes: new PostgresPairingCodeStore(pool, clock),\n nonces: new PostgresNonceStore(pool, clock, crypto),\n dedup: new PostgresInboundDedupStore(pool),\n tasks: new PostgresTaskAttemptStore(pool, clock),\n cancellations: new PostgresTaskCancellationStore(pool, clock),\n receipts: new PostgresRequestReceiptStore(pool, clock),\n egress: new PostgresAgentEgressStore(pool, clock),\n proofReceipts: new PostgresProofRequestReceiptStore(pool, clock),\n // A second `PostgresObjectStore` instance, not a shared one: it is a\n // stateless wrapper over the pool, so the two read and write the same rows\n // under the same locks, and requiring the caller to build the core\n // composition first would be an ordering dependency bought for nothing.\n blobs: new R2CloudBlobStore({\n ...options.objectStorage,\n objects: new PostgresObjectStore(pool, clock),\n }),\n rateLimiter: new AllowAllRateLimiter(),\n };\n}\n","/**\n * Postgres {@link PresenceStore} (§12.3).\n *\n * Presence is lossy, TTL-bounded, unsigned, and never authoritative. It is a\n * bounded upsert with one row per device. Nothing here may be\n * used to derive coordination state, execution state, authorization, billing or\n * recovery — which is why this file shares no vocabulary with `board.ts` and\n * none with the frozen wire states.\n *\n * **Expiry is absence, and it is expressed as a read filter.** A hint past its\n * `expiresAt` is invisible to every read, so no reader can observe a stale\n * level and mistake it for a live one. The in-memory reference deletes the\n * entry lazily on read; here the row stays and the predicate excludes it. Same\n * observable answer, and a `SELECT` that does not write to answer itself.\n *\n * Every instant is the injected clock's. Asserting TTL behavior against a wall\n * clock means sleeping or accepting flakes, which is why the port takes `ttlMs`\n * and the composition supplies the clock.\n */\nimport {\n ByokCoreError,\n type Clock,\n type PresenceHint,\n type PresenceHintInput,\n type PresenceLevel,\n type PresenceRuntimeFact,\n type PresenceStore,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\nconst PRESENCE_COLUMNS =\n 'tenant_id, device_id, level, detail, configured_toolsets, client_version, protocol_versions, runtimes, observed_at, expires_at';\n\ninterface PresenceRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly level: string;\n readonly detail: string | null;\n readonly configured_toolsets: readonly string[] | null;\n readonly client_version: string | null;\n readonly protocol_versions: readonly number[] | null;\n readonly runtimes: readonly PresenceRuntimeFact[] | null;\n readonly observed_at: string;\n readonly expires_at: string;\n}\n\nfunction toHint(row: PresenceRow): PresenceHint {\n return {\n tenantId: row.tenant_id as TenantId,\n deviceId: row.device_id,\n level: row.level as PresenceLevel,\n ...(row.detail === null ? {} : { detail: row.detail }),\n ...(row.configured_toolsets === null\n ? {}\n : { configuredToolsets: Object.freeze([...row.configured_toolsets]) }),\n ...(row.client_version === null ? {} : { clientVersion: row.client_version }),\n ...(row.protocol_versions === null\n ? {}\n : { protocolVersions: Object.freeze([...row.protocol_versions]) }),\n ...(row.runtimes === null\n ? {}\n : {\n runtimes: Object.freeze(\n row.runtimes.map((runtime) =>\n Object.freeze({\n id: runtime.id,\n ...(runtime.version === undefined ? {} : { version: runtime.version }),\n ...(runtime.authPresent === undefined ? {} : { authPresent: runtime.authPresent }),\n }),\n ),\n ),\n }),\n observedAt: row.observed_at,\n expiresAt: row.expires_at,\n };\n}\n\nfunction assertTtl(ttlMs: number): void {\n if (!Number.isFinite(ttlMs) || ttlMs <= 0) {\n throw new ByokCoreError(\n 'hint_ttl_invalid',\n `Hint ttl must be a positive number of milliseconds, received ${String(ttlMs)}.`,\n );\n }\n}\n\nfunction assertMinimumInterval(minimumIntervalMs: number): void {\n if (!Number.isFinite(minimumIntervalMs) || minimumIntervalMs < 0) {\n throw new ByokCoreError(\n 'hint_ttl_invalid',\n `Hint minimum interval must be a non-negative number of milliseconds, received ${String(minimumIntervalMs)}.`,\n );\n }\n}\n\nexport class PostgresPresenceStore implements PresenceStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async publish(tenant: TenantId, input: PresenceHintInput): Promise<PresenceHint> {\n assertTtl(input.ttlMs);\n assertMinimumInterval(input.minimumIntervalMs);\n const now = this.#clock.now();\n const observedAt = now.toISOString();\n const allowedBefore = new Date(now.getTime() - input.minimumIntervalMs).toISOString();\n const result = await this.#pool.query<PresenceRow>(\n `INSERT INTO device_presence (${PRESENCE_COLUMNS})\n VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7::jsonb, $8::jsonb, $9, $10)\n ON CONFLICT (tenant_id, device_id) DO UPDATE\n SET level = EXCLUDED.level,\n detail = EXCLUDED.detail,\n configured_toolsets = EXCLUDED.configured_toolsets,\n client_version = EXCLUDED.client_version,\n protocol_versions = EXCLUDED.protocol_versions,\n runtimes = EXCLUDED.runtimes,\n observed_at = EXCLUDED.observed_at,\n expires_at = EXCLUDED.expires_at\n WHERE device_presence.expires_at <= EXCLUDED.observed_at\n OR device_presence.observed_at <= $11\n RETURNING ${PRESENCE_COLUMNS}`,\n [\n tenant,\n input.deviceId,\n input.level,\n input.detail ?? null,\n input.configuredToolsets === undefined ? null : JSON.stringify(input.configuredToolsets),\n input.clientVersion ?? null,\n input.protocolVersions === undefined ? null : JSON.stringify(input.protocolVersions),\n input.runtimes === undefined ? null : JSON.stringify(input.runtimes),\n observedAt,\n new Date(now.getTime() + input.ttlMs).toISOString(),\n allowedBefore,\n ],\n );\n const row = result.rows[0];\n if (row === undefined) {\n throw new ByokCoreError(\n 'hint_rate_limited',\n `Presence for ${input.deviceId} was published more recently than the configured minimum interval.`,\n );\n }\n return toHint(row);\n }\n\n async read(tenant: TenantId, deviceId: string): Promise<PresenceHint | undefined> {\n const result = await this.#pool.query<PresenceRow>(\n `SELECT ${PRESENCE_COLUMNS} FROM device_presence\n WHERE tenant_id = $1 AND device_id = $2 AND expires_at > $3`,\n [tenant, deviceId, this.#now()],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toHint(row);\n }\n\n async list(tenant: TenantId): Promise<readonly PresenceHint[]> {\n const result = await this.#pool.query<PresenceRow>(\n `SELECT ${PRESENCE_COLUMNS} FROM device_presence\n WHERE tenant_id = $1 AND expires_at > $2\n ORDER BY device_id COLLATE \"C\"`,\n [tenant, this.#now()],\n );\n return result.rows.map(toHint);\n }\n\n #expiry(ttlMs: number): string {\n return new Date(this.#clock.now().getTime() + ttlMs).toISOString();\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * Postgres {@link BoardStore} (§12.3).\n *\n * Every mutation is one guarded `UPDATE ... WHERE`, and the guard carries the\n * caller's whole expectation: who holds the item, what status it is in, and —\n * for `claim` — that it is claimable at all. Zero rows is the rejection, and\n * the store then re-reads the item to say WHICH rejection and to hand the\n * caller the snapshot it lost to. A conflict that reports only \"conflict\"\n * forces a second round trip and invites a retry loop that eventually\n * overwrites the winner (§12.3: no silent last-write-wins).\n *\n * The concurrent-claim property comes out of Postgres' own re-check: three\n * sessions issue the same `UPDATE ... WHERE holder_id IS NULL`, one wins, and\n * the other two re-evaluate the qual against the winner's committed row and\n * match nothing. The suite asserts the outcome, not the mechanism — the\n * in-memory reference gets the same outcome from its `await` boundaries.\n *\n * **`board_seq` is allocated in its own statement, before the guarded write.**\n * Folding the allocator into a data-modifying CTE would let one session lock\n * `tenant_stream` then `board_item` while another locks them in the order the\n * planner picked for it, which is a deadlock rather than a conflict. Allocating\n * first, in an autocommitted statement that releases immediately, gives every\n * writer one lock order. A rejected write therefore burns a sequence number:\n * `boardSeq` is contractually monotonic, never contractually gapless, and the\n * incremental feed reads `> afterSeq` either way.\n */\nimport {\n ByokCoreError,\n CoreConflictError,\n isLegalBoardTransition,\n type BoardClaimInput,\n type BoardItem,\n type BoardItemInput,\n type BoardListQuery,\n type BoardPage,\n type BoardStatus,\n type BoardStatusUpdateInput,\n type BoardStore,\n type BoardUnclaimInput,\n type Clock,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\nconst DEFAULT_LIST_LIMIT = 50;\n\nconst BOARD_COLUMNS =\n 'tenant_id, item_id, channel, title, status, holder_id, held_since, board_seq, created_at, updated_at';\n\ninterface BoardRow {\n readonly tenant_id: string;\n readonly item_id: string;\n readonly channel: string;\n readonly title: string;\n readonly status: string;\n readonly holder_id: string | null;\n readonly held_since: string | null;\n readonly board_seq: bigint;\n readonly created_at: string;\n readonly updated_at: string;\n}\n\nfunction toItem(row: BoardRow): BoardItem {\n return {\n tenantId: row.tenant_id as TenantId,\n itemId: row.item_id,\n channel: row.channel,\n title: row.title,\n status: row.status as BoardStatus,\n // An unheld item has NO assignee rather than an assignee with an empty\n // holder, which is what lets `expect(item.assignee).toBeUndefined()` mean\n // \"nobody holds this\" in both compositions.\n ...(row.holder_id === null || row.held_since === null\n ? {}\n : { assignee: { holderId: row.holder_id, heldSince: row.held_since } }),\n boardSeq: Number(row.board_seq),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nexport class PostgresBoardStore implements BoardStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async create(tenant: TenantId, input: BoardItemInput): Promise<BoardItem> {\n const now = this.#now();\n const boardSeq = await this.#allocateSeq(tenant);\n const inserted = await this.#pool.query<BoardRow>(\n `INSERT INTO board_item (${BOARD_COLUMNS})\n VALUES ($1, $2, $3, $4, $5, NULL, NULL, $6::bigint, $7, $7)\n ON CONFLICT (tenant_id, item_id) DO NOTHING\n RETURNING ${BOARD_COLUMNS}`,\n [tenant, input.itemId, input.channel, input.title, input.status ?? 'todo', boardSeq, now],\n );\n const row = inserted.rows[0];\n if (row === undefined) {\n throw new ByokCoreError(\n 'board_item_exists',\n `Board item ${input.itemId} already exists in this tenant.`,\n );\n }\n return toItem(row);\n }\n\n async get(tenant: TenantId, itemId: string): Promise<BoardItem | undefined> {\n const result = await this.#pool.query<BoardRow>(\n `SELECT ${BOARD_COLUMNS} FROM board_item WHERE tenant_id = $1 AND item_id = $2`,\n [tenant, itemId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toItem(row);\n }\n\n async list(tenant: TenantId, query: BoardListQuery): Promise<BoardPage> {\n const afterSeq = query.afterSeq ?? 0;\n const limit = query.limit ?? DEFAULT_LIST_LIMIT;\n const result = await this.#pool.query<BoardRow>(\n `SELECT ${BOARD_COLUMNS} FROM board_item\n WHERE tenant_id = $1\n AND board_seq > $2::bigint\n AND ($3::text IS NULL OR channel = $3::text)\n AND ($4::text IS NULL OR status = $4::text)\n ORDER BY board_seq\n LIMIT $5`,\n [tenant, afterSeq, query.channel ?? null, query.status ?? null, limit + 1],\n );\n\n const page = result.rows.slice(0, limit).map(toItem);\n return {\n items: page,\n nextSeq: page.at(-1)?.boardSeq ?? afterSeq,\n hasMore: result.rows.length > page.length,\n };\n }\n\n async claim(tenant: TenantId, input: BoardClaimInput): Promise<BoardItem> {\n const expectedStatus = input.expectedStatus ?? 'todo';\n const now = this.#now();\n const boardSeq = await this.#allocateSeq(tenant);\n\n // `holder_id IS NULL` is the CAS on \"unheld\"; `status = $4` is the caller's\n // status expectation; `status IN ('todo','in_progress')` is the claimability\n // rule. All three in one guard, so exactly one concurrent caller wins.\n const claimed = await this.#pool.query<BoardRow>(\n `UPDATE board_item\n SET status = CASE WHEN status = 'todo' THEN 'in_progress' ELSE status END,\n holder_id = $3,\n held_since = $5,\n board_seq = $6::bigint,\n updated_at = $5\n WHERE tenant_id = $1 AND item_id = $2\n AND holder_id IS NULL\n AND status = $4::text\n AND status IN ('todo', 'in_progress')\n RETURNING ${BOARD_COLUMNS}`,\n [tenant, input.itemId, input.holderId, expectedStatus, now, boardSeq],\n );\n const won = claimed.rows[0];\n if (won !== undefined) return toItem(won);\n\n const current = await this.get(tenant, input.itemId);\n if (current === undefined) throw this.#itemNotFound(input.itemId);\n\n if (current.assignee !== undefined) {\n if (current.assignee.holderId === input.holderId) {\n // The same holder retrying is not a second winner. But an EXPLICIT\n // `expectedStatus` is a full CAS by contract, and short-circuiting past\n // it here would let the holder's retry confirm a status it no longer\n // believes in. The `todo` default is deliberately not applied on this\n // path: a retry of a successful claim legitimately observes\n // `in_progress`.\n if (input.expectedStatus !== undefined && current.status !== input.expectedStatus) {\n throw this.#statusConflict(input.itemId, current, input.expectedStatus);\n }\n return current;\n }\n throw new CoreConflictError(\n 'board_claim_conflict',\n `Board item ${input.itemId} is held by ${current.assignee.holderId}.`,\n current,\n this.#now(),\n );\n }\n if (current.status !== expectedStatus) {\n throw this.#statusConflict(input.itemId, current, expectedStatus);\n }\n throw new CoreConflictError(\n 'board_transition_invalid',\n `Board item ${input.itemId} cannot be claimed from ${current.status}.`,\n current,\n this.#now(),\n );\n }\n\n async unclaim(tenant: TenantId, input: BoardUnclaimInput): Promise<BoardItem> {\n const now = this.#now();\n const boardSeq = await this.#allocateSeq(tenant);\n\n // Releasing someone else's item is not a legal move, so the holder is part\n // of the guard rather than a comparison the caller is trusted to have made.\n const released = await this.#pool.query<BoardRow>(\n `UPDATE board_item\n SET status = CASE WHEN status = 'in_progress' THEN 'todo' ELSE status END,\n holder_id = NULL,\n held_since = NULL,\n board_seq = $4::bigint,\n updated_at = $5\n WHERE tenant_id = $1 AND item_id = $2 AND holder_id = $3\n RETURNING ${BOARD_COLUMNS}`,\n [tenant, input.itemId, input.holderId, boardSeq, now],\n );\n const row = released.rows[0];\n if (row !== undefined) return toItem(row);\n\n const current = await this.get(tenant, input.itemId);\n if (current === undefined) throw this.#itemNotFound(input.itemId);\n if (current.assignee === undefined) {\n throw new ByokCoreError(\n 'board_not_held',\n `Board item ${input.itemId} is not held by anyone.`,\n );\n }\n throw new CoreConflictError(\n 'board_claim_conflict',\n `Board item ${input.itemId} is held by ${current.assignee.holderId}, not ${input.holderId}.`,\n current,\n this.#now(),\n );\n }\n\n async updateStatus(tenant: TenantId, input: BoardStatusUpdateInput): Promise<BoardItem> {\n // Legality is a pure function of two caller-supplied values, so it is\n // decided before the statement rather than smuggled into the guard as a\n // boolean parameter. An illegal move skips the write entirely and falls\n // straight to the rejection ladder below, whose order is the contract's:\n // a missed `expectedStatus` outranks a holder mismatch, which outranks an\n // illegal transition.\n if (isLegalBoardTransition(input.expectedStatus, input.status)) {\n const now = this.#now();\n const boardSeq = await this.#allocateSeq(tenant);\n const updated = await this.#pool.query<BoardRow>(\n `UPDATE board_item\n SET status = $4::text, board_seq = $6::bigint, updated_at = $7\n WHERE tenant_id = $1 AND item_id = $2\n AND status = $3::text\n AND ($5::text IS NULL OR holder_id = $5::text)\n RETURNING ${BOARD_COLUMNS}`,\n [\n tenant,\n input.itemId,\n input.expectedStatus,\n input.status,\n input.holderId ?? null,\n boardSeq,\n now,\n ],\n );\n const row = updated.rows[0];\n if (row !== undefined) return toItem(row);\n }\n\n const current = await this.get(tenant, input.itemId);\n if (current === undefined) throw this.#itemNotFound(input.itemId);\n if (current.status !== input.expectedStatus) {\n throw this.#statusConflict(input.itemId, current, input.expectedStatus);\n }\n if (input.holderId !== undefined && current.assignee?.holderId !== input.holderId) {\n throw new CoreConflictError(\n 'board_claim_conflict',\n `Board item ${input.itemId} is not held by ${input.holderId}.`,\n current,\n this.#now(),\n );\n }\n if (!isLegalBoardTransition(input.expectedStatus, input.status)) {\n throw new CoreConflictError(\n 'board_transition_invalid',\n `${input.expectedStatus} to ${input.status} is not a legal board transition.`,\n current,\n this.#now(),\n );\n }\n // Every guard the CAS checked reads as satisfied now, so the row moved and\n // moved back between the write and this read. The caller lost a race, and\n // saying so with the current snapshot is more useful than retrying into it.\n throw this.#statusConflict(input.itemId, current, input.expectedStatus);\n }\n\n /**\n * One statement, its own transaction, lock released immediately. See the file\n * header for why this is not a CTE inside the write it feeds.\n */\n async #allocateSeq(tenant: TenantId): Promise<bigint> {\n const result = await this.#pool.query<{ board_seq: bigint }>(\n `INSERT INTO tenant_stream (tenant_id, board_seq)\n VALUES ($1, 1)\n ON CONFLICT (tenant_id) DO UPDATE SET board_seq = tenant_stream.board_seq + 1\n RETURNING board_seq`,\n [tenant],\n );\n return result.rows[0]!.board_seq;\n }\n\n #itemNotFound(itemId: string): ByokCoreError {\n return new ByokCoreError(\n 'board_item_not_found',\n `Board item ${itemId} does not exist in this tenant.`,\n );\n }\n\n #statusConflict(\n itemId: string,\n current: BoardItem,\n expected: BoardStatus,\n ): CoreConflictError<BoardItem> {\n return new CoreConflictError(\n 'board_status_conflict',\n `Board item ${itemId} is ${current.status}, not ${expected}.`,\n current,\n this.#now(),\n );\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * Postgres {@link QuotaStore} — entitlement, usage, reservation (§12.7.6-12.7.7).\n *\n * The invariant this file exists to hold is\n * `committed + reserved + expected <= hardLimitBytes`, and the reason it is the\n * hardest statement in the slice is that the obvious shapes all get it wrong in\n * a way nothing throws about.\n *\n * **Why `reserve` opens a transaction.** Admission is one guarded\n * `INSERT ... SELECT ... WHERE`, exactly as every other CAS in this package is\n * one guarded statement. But the guard's operand is an AGGREGATE over the\n * tenant's live reservations, and under READ COMMITTED a statement's snapshot\n * is taken when the statement starts. Two concurrent reservers therefore both\n * read a pre-insert world and both pass — the classic oversell. Postgres'\n * EvalPlanQual re-check, which is what makes `UPDATE ... WHERE status = $x` a\n * genuine CAS elsewhere in this package, re-evaluates the qual only against the\n * updated TARGET row; a subquery over another table keeps the original\n * snapshot. So no single statement over this shape can serialize reservers.\n *\n * The two ways out are a counter column CAS'd in place, or a lock. The counter\n * loses: it has to be decremented on all three of finalize / abort / expire,\n * and a path that settles without decrementing leaves a tenant permanently\n * short of quota it actually released — durable drift, invisible until someone\n * audits. So `storage_usage` has NO `reserved_bytes` column and\n * `TenantStorageUsage.reservedBytes` is a `SUM` over live reservations, which\n * cannot drift, and admission takes `FOR UPDATE` on the tenant's entitlement\n * row first. The next statement in that transaction takes a FRESH snapshot,\n * acquired behind the lock, so it sees every committed reservation. This is the\n * \"row-locked transaction\" `packages/core/src/in-memory/quota.ts` names as the\n * Postgres shape.\n *\n * What is NOT happening here: a read whose result is compared in TypeScript and\n * then written. Every admission decision lives in the SQL guard. The reads on\n * the rejection path exist only to answer \"which of the five typed rejections\n * is this\", after the write has already been refused.\n *\n * Nothing in this file calls SQL `now()`. Every instant is the injected clock's,\n * so reservation expiry is assertable under a test clock — and\n * `__tests__/constraints.test.ts` scans this directory to keep it that way.\n */\nimport {\n ByokCoreError,\n CoreConflictError,\n assertCanonicalTimestamp,\n type Clock,\n type ContentHash,\n type MailboxUsageDeltaInput,\n type QuotaStore,\n type StorageFinalizeInput,\n type StorageFinalizeResult,\n type StorageReservation,\n type StorageReservationInput,\n type StorageReservationState,\n type StorageStatus,\n type StorageWriteKind,\n type StorageWritePosture,\n type TenantId,\n type TenantStorageEntitlement,\n type TenantStorageEntitlementInput,\n type TenantStorageUsage,\n} from '@byok-sdk/core';\nimport type { Pool, PoolClient } from 'pg';\n\n/** Warning threshold from §12.7.8: 80% of the hard limit. */\nconst WARNING_NUMERATOR = 80n;\nconst WARNING_DENOMINATOR = 100n;\n\nconst ENTITLEMENT_COLUMNS =\n 'tenant_id, version, hard_limit_bytes, max_object_bytes, max_inline_bytes, mailbox_limit_bytes, retention_policy_id, downgrade_grace_until';\n\nconst RESERVATION_COLUMNS =\n 'tenant_id, reservation_id, state, kind, expected_bytes, content_hash, content_type, created_at, expires_at, settled_at, deduplicated';\nconst QUALIFIED_RESERVATION_COLUMNS = RESERVATION_COLUMNS.split(', ')\n .map((column) => `r.${column}`)\n .join(', ');\n\ninterface EntitlementRow {\n readonly tenant_id: string;\n readonly version: bigint;\n readonly hard_limit_bytes: bigint;\n readonly max_object_bytes: bigint;\n readonly max_inline_bytes: bigint;\n readonly mailbox_limit_bytes: bigint;\n readonly retention_policy_id: string;\n readonly downgrade_grace_until: string | null;\n}\n\ninterface ReservationRow {\n readonly tenant_id: string;\n readonly reservation_id: string;\n readonly state: string;\n readonly kind: string;\n readonly expected_bytes: bigint;\n readonly content_hash: string;\n readonly content_type: string;\n readonly created_at: string;\n readonly expires_at: string;\n readonly settled_at: string | null;\n readonly deduplicated: boolean;\n}\n\ninterface UsageRow {\n readonly committed_object_bytes: bigint;\n readonly committed_inline_bytes: bigint;\n readonly reserved_bytes: bigint;\n readonly mailbox_bytes: bigint;\n readonly object_count: bigint;\n readonly updated_at: string;\n}\n\nfunction toEntitlement(row: EntitlementRow): TenantStorageEntitlement {\n return {\n tenantId: row.tenant_id as TenantId,\n version: row.version,\n hardLimitBytes: row.hard_limit_bytes,\n maxObjectBytes: row.max_object_bytes,\n maxInlineBytes: row.max_inline_bytes,\n mailboxLimitBytes: row.mailbox_limit_bytes,\n retentionPolicyId: row.retention_policy_id,\n ...(row.downgrade_grace_until === null\n ? {}\n : { downgradeGraceUntil: row.downgrade_grace_until }),\n };\n}\n\nfunction toReservation(row: ReservationRow): StorageReservation {\n return {\n tenantId: row.tenant_id as TenantId,\n reservationId: row.reservation_id,\n state: row.state as StorageReservationState,\n kind: row.kind as StorageWriteKind,\n expectedBytes: row.expected_bytes,\n contentHash: row.content_hash as ContentHash,\n contentType: row.content_type,\n createdAt: row.created_at,\n expiresAt: row.expires_at,\n ...(row.settled_at === null ? {} : { settledAt: row.settled_at }),\n };\n}\n\nfunction toUsage(row: UsageRow): TenantStorageUsage {\n return {\n committedObjectBytes: row.committed_object_bytes,\n committedInlineBytes: row.committed_inline_bytes,\n reservedBytes: row.reserved_bytes,\n mailboxBytes: row.mailbox_bytes,\n objectCount: row.object_count,\n updatedAt: row.updated_at,\n };\n}\n\n/**\n * `reservedBytes` is derived here, not stored — see the file header. The\n * `LEFT JOIN` is what lets a tenant with no usage row read as all zeros without\n * a write happening on a read path.\n */\nconst USAGE_SQL = `\n SELECT\n COALESCE(u.committed_object_bytes, 0)::bigint AS committed_object_bytes,\n COALESCE(u.committed_inline_bytes, 0)::bigint AS committed_inline_bytes,\n COALESCE(u.mailbox_bytes, 0)::bigint AS mailbox_bytes,\n COALESCE(u.object_count, 0)::bigint AS object_count,\n COALESCE(u.updated_at, $2) AS updated_at,\n COALESCE((SELECT SUM(r.expected_bytes) FROM storage_reservation r\n WHERE r.tenant_id = $1 AND r.state = 'reserved'), 0)::bigint AS reserved_bytes\n FROM (SELECT $1::text AS tenant_id) AS scope\n LEFT JOIN storage_usage u ON u.tenant_id = scope.tenant_id`;\n\nexport class PostgresQuotaStore implements QuotaStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async readEntitlement(tenant: TenantId): Promise<TenantStorageEntitlement | undefined> {\n const result = await this.#pool.query<EntitlementRow>(\n `SELECT ${ENTITLEMENT_COLUMNS} FROM storage_entitlement WHERE tenant_id = $1`,\n [tenant],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toEntitlement(row);\n }\n\n async writeEntitlement(\n tenant: TenantId,\n input: TenantStorageEntitlementInput,\n ): Promise<TenantStorageEntitlement> {\n // Validated before the version CAS and before any statement runs: an\n // unusable deadline is a bad write regardless of which version wins, and a\n // rejected entitlement must not be a partially written one.\n if (input.downgradeGraceUntil !== undefined) {\n assertCanonicalTimestamp(input.downgradeGraceUntil, 'downgradeGraceUntil');\n }\n\n // The `seeded` CTE is what establishes this composition's standing\n // invariant: a `storage_usage` row exists whenever a `storage_entitlement`\n // row does. Every later accounting write is then a guarded `UPDATE` rather\n // than an upsert that would have to restate its guard in two places.\n const applied = await this.#pool.query<EntitlementRow>(\n `WITH applied AS (\n INSERT INTO storage_entitlement (${ENTITLEMENT_COLUMNS})\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (tenant_id) DO UPDATE\n SET version = EXCLUDED.version,\n hard_limit_bytes = EXCLUDED.hard_limit_bytes,\n max_object_bytes = EXCLUDED.max_object_bytes,\n max_inline_bytes = EXCLUDED.max_inline_bytes,\n mailbox_limit_bytes = EXCLUDED.mailbox_limit_bytes,\n retention_policy_id = EXCLUDED.retention_policy_id,\n downgrade_grace_until = EXCLUDED.downgrade_grace_until\n WHERE storage_entitlement.version < EXCLUDED.version\n RETURNING ${ENTITLEMENT_COLUMNS}\n ), seeded AS (\n INSERT INTO storage_usage (tenant_id, updated_at)\n SELECT $1, $9 FROM applied\n ON CONFLICT (tenant_id) DO NOTHING\n RETURNING 1\n )\n SELECT ${ENTITLEMENT_COLUMNS} FROM applied`,\n [\n tenant,\n input.version,\n input.hardLimitBytes,\n input.maxObjectBytes,\n input.maxInlineBytes,\n input.mailboxLimitBytes,\n input.retentionPolicyId,\n input.downgradeGraceUntil ?? null,\n this.#now(),\n ],\n );\n const row = applied.rows[0];\n if (row !== undefined) return toEntitlement(row);\n\n // The guard rejected: the stored version is at or above the one offered.\n // Version is monotonic, not merely different, so an equal version is stale\n // too — and the caller gets the row it lost to rather than a bare failure.\n const current = await this.readEntitlement(tenant);\n if (current === undefined) {\n throw new Error(`entitlement for ${tenant} vanished during a version CAS`);\n }\n throw new CoreConflictError(\n 'storage_entitlement_version_conflict',\n `Entitlement is at version ${String(current.version)}; refusing to apply version ${String(input.version)}.`,\n current,\n this.#now(),\n );\n }\n\n async readUsage(tenant: TenantId): Promise<TenantStorageUsage> {\n const result = await this.#pool.query<UsageRow>(USAGE_SQL, [tenant, this.#now()]);\n return toUsage(result.rows[0]!);\n }\n\n async readStatus(tenant: TenantId): Promise<StorageStatus> {\n const entitlement = await this.readEntitlement(tenant);\n if (entitlement === undefined) throw this.#entitlementMissing();\n const usage = await this.readUsage(tenant);\n const used = usedBytes(usage);\n const graceActive = this.#graceActive(entitlement);\n return {\n entitlement,\n usage,\n posture: posture(entitlement, usage, graceActive),\n availableBytes:\n used >= entitlement.hardLimitBytes ? 0n : entitlement.hardLimitBytes - used,\n graceActive,\n };\n }\n\n async readReservation(\n tenant: TenantId,\n reservationId: string,\n ): Promise<StorageReservation | undefined> {\n return (await this.#readReservation(tenant, reservationId))?.reservation;\n }\n\n async reserve(\n tenant: TenantId,\n input: StorageReservationInput,\n ): Promise<StorageReservation> {\n const client = await this.#pool.connect();\n let admitted: StorageReservation | undefined;\n let rejection: ByokCoreError | undefined;\n try {\n await client.query('BEGIN');\n\n // The serialization point. Every reserver for this tenant queues here,\n // and the guarded insert below runs on a snapshot taken AFTER the lock is\n // held — which is the only way its aggregate sees a competitor's row.\n const entitlement = await this.#lockEntitlement(client, tenant);\n if (entitlement === undefined) {\n rejection = this.#entitlementMissing();\n } else {\n const now = this.#now();\n // The tenant entitlement lock also serializes this bounded reap with\n // admission. A client can disappear after PUT grant issuance; stale\n // reservations must not remain in the aggregate and permanently\n // consume the tenant's hard limit until an external scheduler runs.\n await client.query(\n `UPDATE storage_reservation\n SET state = 'expired', settled_at = $2\n WHERE tenant_id = $1 AND state = 'reserved' AND expires_at <= $2`,\n [tenant, now],\n );\n const inserted = await client.query<ReservationRow>(\n `WITH ent AS (\n SELECT hard_limit_bytes, max_object_bytes, max_inline_bytes, downgrade_grace_until\n FROM storage_entitlement WHERE tenant_id = $1\n ), used AS (\n SELECT COALESCE((SELECT committed_object_bytes + committed_inline_bytes\n FROM storage_usage WHERE tenant_id = $1), 0)::bigint\n + COALESCE((SELECT SUM(expected_bytes) FROM storage_reservation\n WHERE tenant_id = $1 AND state = 'reserved'), 0)::bigint\n AS used_bytes\n )\n INSERT INTO storage_reservation\n (tenant_id, reservation_id, state, kind, expected_bytes,\n content_hash, content_type, created_at, expires_at)\n SELECT $1, $2, 'reserved', $3::text, $4::bigint, $5, $6, $7, $8\n FROM ent, used\n WHERE $4::bigint <= (CASE WHEN $3::text = 'object'\n THEN ent.max_object_bytes\n ELSE ent.max_inline_bytes END)\n AND used.used_bytes + $4::bigint <= ent.hard_limit_bytes\n AND ($3::text <> 'object' OR NOT EXISTS (\n SELECT 1 FROM object_manifest m\n WHERE m.tenant_id = $1 AND m.hash = $5\n AND m.state = 'delete_pending'\n ))\n AND NOT (used.used_bytes >= ent.hard_limit_bytes\n AND ent.downgrade_grace_until IS NOT NULL\n AND ent.downgrade_grace_until <= $9)\n ON CONFLICT (tenant_id, reservation_id) DO NOTHING\n RETURNING ${RESERVATION_COLUMNS}`,\n [\n tenant,\n input.reservationId,\n input.kind,\n input.expectedBytes,\n input.contentHash,\n input.contentType,\n now,\n this.#expiry(input.ttlMs),\n now,\n ],\n );\n const row = inserted.rows[0];\n if (row !== undefined) {\n admitted = toReservation(row);\n } else {\n const outcome = await this.#explainRefusedReservation(\n client,\n tenant,\n input,\n entitlement,\n );\n if (outcome instanceof ByokCoreError) rejection = outcome;\n else admitted = outcome;\n }\n }\n\n await client.query('COMMIT');\n } catch (error) {\n // Best-effort, for the same reason the migration runner's is: a rollback\n // that throws must not replace the failure the caller needs to see.\n await client.query('ROLLBACK').catch(() => {});\n throw error;\n } finally {\n client.release();\n }\n\n // Thrown outside the transaction block so the catch above stays reserved\n // for genuine faults rather than for this store's own typed rejections.\n if (rejection !== undefined) throw rejection;\n return admitted!;\n }\n\n async finalizeReservation(\n tenant: TenantId,\n input: StorageFinalizeInput,\n ): Promise<StorageFinalizeResult> {\n const existing = await this.#readReservation(tenant, input.reservationId);\n if (existing === undefined) throw this.#reservationMissing(input.reservationId);\n\n if (existing.reservation.state === 'committed') {\n // A replayed finalize answers the same way the original did, including\n // `deduplicated` — which is why that flag is stored rather than\n // recomputed against a set this row is now a member of.\n return {\n reservation: existing.reservation,\n usage: await this.readUsage(tenant),\n deduplicated: existing.deduplicated,\n };\n }\n if (existing.reservation.state !== 'reserved') {\n throw new ByokCoreError(\n 'storage_reservation_expired',\n `Reservation ${input.reservationId} is ${existing.reservation.state}.`,\n );\n }\n if (this.#now() >= existing.reservation.expiresAt) {\n await this.#settle(tenant, input.reservationId, 'expired');\n throw new ByokCoreError(\n 'storage_reservation_expired',\n `Reservation ${input.reservationId} expired at ${existing.reservation.expiresAt}.`,\n );\n }\n if (\n input.observedByteSize !== existing.reservation.expectedBytes ||\n input.observedContentType !== existing.reservation.contentType\n ) {\n // §12.7.7 step 6: a failed finalize releases the bytes and the uploaded\n // object becomes an orphan candidate for the GC worker. Releasing is the\n // state transition itself — nothing decrements a counter.\n await this.#settle(tenant, input.reservationId, 'aborted');\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Observed object does not match reservation ${input.reservationId}.`,\n );\n }\n\n // One statement owns all three durable facts: object manifest, reservation,\n // and usage. `candidate` reads the pre-transition manifest state so object\n // deduplication is defined by manifest authority, not by a second shadow\n // set of committed reservation rows. A missing or mismatched manifest\n // aborts the reservation in this same statement and is surfaced below.\n // Hash identity comes from the reservation row: HEAD observes only\n // size/type (ADR-024), so there is no second digest to compare or persist.\n const settled = await this.#pool.query<ReservationRow>(\n `WITH candidate AS MATERIALIZED (\n SELECT r.tenant_id,\n r.reservation_id,\n r.kind,\n r.content_hash,\n r.expected_bytes,\n r.content_type,\n m.state AS manifest_state,\n (m.tenant_id IS NOT NULL\n AND m.state IN ('pending', 'committed')\n AND m.byte_size = $4::bigint\n AND m.content_type = $5) AS manifest_valid,\n EXISTS (\n SELECT 1 FROM storage_reservation p\n WHERE p.tenant_id = r.tenant_id\n AND p.content_hash = r.content_hash\n AND p.state = 'committed'\n ) AS inline_deduplicated\n FROM storage_reservation r\n LEFT JOIN object_manifest m\n ON m.tenant_id = r.tenant_id AND m.hash = r.content_hash\n WHERE r.tenant_id = $1\n AND r.reservation_id = $2\n AND r.state = 'reserved'\n ), committed_manifest AS (\n UPDATE object_manifest m\n SET state = 'committed', updated_at = $3\n FROM candidate c\n WHERE c.kind = 'object'\n AND c.manifest_valid\n AND m.state = 'pending'\n AND m.tenant_id = c.tenant_id\n AND m.hash = c.content_hash\n RETURNING 1\n ), settled AS (\n UPDATE storage_reservation r\n SET state = CASE\n WHEN c.kind = 'object' AND NOT c.manifest_valid\n THEN 'aborted'\n ELSE 'committed'\n END,\n settled_at = $3,\n deduplicated = CASE\n WHEN c.kind = 'object'\n THEN NOT EXISTS (SELECT 1 FROM committed_manifest)\n ELSE c.inline_deduplicated\n END\n FROM candidate c,\n (SELECT COUNT(*) FROM committed_manifest) AS manifest_barrier\n WHERE r.tenant_id = c.tenant_id\n AND r.reservation_id = c.reservation_id\n AND r.state = 'reserved'\n RETURNING ${QUALIFIED_RESERVATION_COLUMNS}\n ), accounted AS (\n UPDATE storage_usage u\n SET committed_object_bytes = u.committed_object_bytes\n + CASE WHEN s.kind = 'object' AND NOT s.deduplicated\n THEN s.expected_bytes ELSE 0 END,\n committed_inline_bytes = u.committed_inline_bytes\n + CASE WHEN s.kind = 'inline' AND NOT s.deduplicated\n THEN s.expected_bytes ELSE 0 END,\n object_count = u.object_count\n + CASE WHEN s.kind = 'object' AND NOT s.deduplicated THEN 1 ELSE 0 END,\n updated_at = $3\n FROM settled s\n WHERE u.tenant_id = $1 AND s.state = 'committed'\n RETURNING 1\n )\n SELECT ${RESERVATION_COLUMNS} FROM settled`,\n [\n tenant,\n input.reservationId,\n this.#now(),\n input.observedByteSize,\n input.observedContentType,\n ],\n );\n\n const row = settled.rows[0];\n if (row === undefined) {\n // Lost the transition to a concurrent settle between the read above and\n // this statement. Report whatever actually happened rather than retrying\n // into it.\n const raced = await this.#readReservation(tenant, input.reservationId);\n if (raced !== undefined && raced.reservation.state === 'committed') {\n return {\n reservation: raced.reservation,\n usage: await this.readUsage(tenant),\n deduplicated: raced.deduplicated,\n };\n }\n throw new ByokCoreError(\n 'storage_reservation_expired',\n `Reservation ${input.reservationId} was settled concurrently.`,\n );\n }\n\n const reservation = toReservation(row);\n if (reservation.state === 'aborted') {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Reservation ${input.reservationId} has no matching committable object manifest.`,\n );\n }\n\n return {\n reservation,\n usage: await this.readUsage(tenant),\n deduplicated: row.deduplicated,\n };\n }\n\n async abortReservation(\n tenant: TenantId,\n reservationId: string,\n ): Promise<StorageReservation> {\n const existing = await this.#readReservation(tenant, reservationId);\n if (existing === undefined) throw this.#reservationMissing(reservationId);\n // Idempotent by contract: an already-settled reservation returns its\n // settled row instead of failing a retry that has nothing left to release.\n if (existing.reservation.state !== 'reserved') return existing.reservation;\n\n const settled = await this.#settle(tenant, reservationId, 'aborted');\n if (settled !== undefined) return settled;\n const raced = await this.#readReservation(tenant, reservationId);\n if (raced === undefined) throw this.#reservationMissing(reservationId);\n return raced.reservation;\n }\n\n async expireReservations(tenant: TenantId): Promise<readonly StorageReservation[]> {\n // The cutoff is the injected clock's instant, passed as a parameter. A SQL\n // `now()` here would make reservation expiry unassertable without sleeping,\n // and the suite advances a test clock instead.\n const expired = await this.#pool.query<ReservationRow>(\n `UPDATE storage_reservation\n SET state = 'expired', settled_at = $2\n WHERE tenant_id = $1 AND state = 'reserved' AND expires_at <= $2\n RETURNING ${RESERVATION_COLUMNS}`,\n [tenant, this.#now()],\n );\n return expired.rows\n .map(toReservation)\n .sort((left, right) => left.reservationId.localeCompare(right.reservationId));\n }\n\n async applyMailboxDelta(\n tenant: TenantId,\n input: MailboxUsageDeltaInput,\n ): Promise<TenantStorageUsage> {\n // Mailbox bytes are platform-protection accounting, not user capacity: the\n // bound is its own entitlement field. A release (negative delta) is never\n // refused and clamps at zero, so a retention sweep that double-reports\n // cannot drive the counter negative.\n const applied = await this.#pool.query(\n `WITH ent AS (\n SELECT mailbox_limit_bytes FROM storage_entitlement WHERE tenant_id = $1\n )\n UPDATE storage_usage u\n SET mailbox_bytes = GREATEST(u.mailbox_bytes + $2::bigint, 0::bigint),\n updated_at = $3\n FROM ent\n WHERE u.tenant_id = $1\n AND ($2::bigint <= 0 OR u.mailbox_bytes + $2::bigint <= ent.mailbox_limit_bytes)\n RETURNING 1`,\n [tenant, input.deltaBytes, this.#now()],\n );\n\n if (applied.rowCount === 0) {\n const entitlement = await this.readEntitlement(tenant);\n if (entitlement === undefined) throw this.#entitlementMissing();\n const usage = await this.readUsage(tenant);\n throw new ByokCoreError(\n 'storage_quota_exceeded',\n `Mailbox would reach ${String(usage.mailboxBytes + input.deltaBytes)} bytes, over the limit of ${String(entitlement.mailboxLimitBytes)} bytes.`,\n );\n }\n return this.readUsage(tenant);\n }\n\n async #lockEntitlement(\n client: PoolClient,\n tenant: TenantId,\n ): Promise<TenantStorageEntitlement | undefined> {\n const result = await client.query<EntitlementRow>(\n `SELECT ${ENTITLEMENT_COLUMNS} FROM storage_entitlement WHERE tenant_id = $1 FOR UPDATE`,\n [tenant],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toEntitlement(row);\n }\n\n /**\n * Names the refusal. Runs only after the guarded insert has already declined,\n * inside the same locked transaction, so the state it reads is the state that\n * refused. The order matches the contract's precedence: an existing\n * reservation is an idempotent answer, not a rejection; a suspended tenant is\n * read-only (423) before it is over-quota (507); a single oversized write is\n * 413 regardless of how much room is left.\n */\n async #explainRefusedReservation(\n client: PoolClient,\n tenant: TenantId,\n input: StorageReservationInput,\n entitlement: TenantStorageEntitlement,\n ): Promise<StorageReservation | ByokCoreError> {\n const existing = await client.query<ReservationRow>(\n `SELECT ${RESERVATION_COLUMNS} FROM storage_reservation\n WHERE tenant_id = $1 AND reservation_id = $2`,\n [tenant, input.reservationId],\n );\n const held = existing.rows[0];\n if (held !== undefined) {\n if (held.state === 'reserved') {\n if (\n held.kind !== input.kind ||\n held.expected_bytes !== input.expectedBytes ||\n held.content_hash !== input.contentHash ||\n held.content_type !== input.contentType\n ) {\n return new ByokCoreError(\n 'storage_integrity_mismatch',\n `Reservation ${input.reservationId} already binds a different storage declaration.`,\n );\n }\n return toReservation(held);\n }\n return new ByokCoreError(\n 'storage_reservation_expired',\n `Reservation ${input.reservationId} is already ${held.state}.`,\n );\n }\n\n if (input.kind === 'object') {\n const tombstone = await client.query<{ readonly state: string }>(\n `SELECT state FROM object_manifest\n WHERE tenant_id = $1 AND hash = $2 AND state = 'delete_pending'`,\n [tenant, input.contentHash],\n );\n if (tombstone.rows[0] !== undefined) {\n return new ByokCoreError(\n 'object_state_invalid',\n `Object ${input.contentHash} is pending deletion and cannot accept a new reservation.`,\n );\n }\n }\n\n const usageResult = await client.query<UsageRow>(USAGE_SQL, [tenant, this.#now()]);\n const usage = toUsage(usageResult.rows[0]!);\n if (posture(entitlement, usage, this.#graceActive(entitlement)) === 'suspended') {\n return new ByokCoreError(\n 'storage_write_suspended',\n 'Tenant is over its hard limit and its downgrade grace has ended; durable writes are suspended.',\n );\n }\n\n const perWriteLimit =\n input.kind === 'object' ? entitlement.maxObjectBytes : entitlement.maxInlineBytes;\n if (input.expectedBytes > perWriteLimit) {\n return new ByokCoreError(\n 'storage_object_too_large',\n `${String(input.expectedBytes)} bytes exceeds the ${input.kind} limit of ${String(perWriteLimit)} bytes.`,\n );\n }\n return new ByokCoreError(\n 'storage_quota_exceeded',\n `Reserving ${String(input.expectedBytes)} bytes would exceed the hard limit of ${String(entitlement.hardLimitBytes)} bytes.`,\n );\n }\n\n async #readReservation(\n tenant: TenantId,\n reservationId: string,\n ): Promise<{ reservation: StorageReservation; deduplicated: boolean } | undefined> {\n const result = await this.#pool.query<ReservationRow>(\n `SELECT ${RESERVATION_COLUMNS} FROM storage_reservation\n WHERE tenant_id = $1 AND reservation_id = $2`,\n [tenant, reservationId],\n );\n const row = result.rows[0];\n if (row === undefined) return undefined;\n return { reservation: toReservation(row), deduplicated: row.deduplicated };\n }\n\n /**\n * The settle guard. `WHERE state = 'reserved'` is what makes two settlements\n * of the same reservation produce one winner; the loser gets zero rows and\n * re-reads rather than stamping a second `settled_at` over the first.\n * Releasing the reserved bytes needs no second write: they were never a\n * counter, only the sum of rows in this state.\n */\n async #settle(\n tenant: TenantId,\n reservationId: string,\n state: Exclude<StorageReservationState, 'reserved'>,\n ): Promise<StorageReservation | undefined> {\n const result = await this.#pool.query<ReservationRow>(\n `UPDATE storage_reservation\n SET state = $3, settled_at = $4\n WHERE tenant_id = $1 AND reservation_id = $2 AND state = 'reserved'\n RETURNING ${RESERVATION_COLUMNS}`,\n [tenant, reservationId, state, this.#now()],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toReservation(row);\n }\n\n #graceActive(entitlement: TenantStorageEntitlement): boolean {\n return (\n entitlement.downgradeGraceUntil !== undefined &&\n this.#now() < entitlement.downgradeGraceUntil\n );\n }\n\n #entitlementMissing(): ByokCoreError {\n return new ByokCoreError(\n 'storage_entitlement_missing',\n 'No storage entitlement has been issued for this tenant.',\n );\n }\n\n #reservationMissing(reservationId: string): ByokCoreError {\n return new ByokCoreError(\n 'storage_reservation_not_found',\n `Reservation ${reservationId} does not exist in this tenant.`,\n );\n }\n\n #expiry(ttlMs: number): string {\n return new Date(this.#clock.now().getTime() + ttlMs).toISOString();\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n\nfunction usedBytes(usage: TenantStorageUsage): bigint {\n return usage.committedObjectBytes + usage.committedInlineBytes + usage.reservedBytes;\n}\n\n/**\n * Effective write posture (§12.7.8). A tenant that was downgraded gets its\n * configured grace window; once it ends and usage is still over the limit, the\n * tenant is read-only (423) rather than merely unable to add bytes (507).\n */\nfunction posture(\n entitlement: TenantStorageEntitlement,\n usage: TenantStorageUsage,\n graceActive: boolean,\n): StorageWritePosture {\n const used = usedBytes(usage);\n if (used >= entitlement.hardLimitBytes) {\n const graceConfigured = entitlement.downgradeGraceUntil !== undefined;\n return graceConfigured && !graceActive ? 'suspended' : 'blocked';\n }\n if (\n entitlement.hardLimitBytes > 0n &&\n used * WARNING_DENOMINATOR >= entitlement.hardLimitBytes * WARNING_NUMERATOR\n ) {\n return 'warning';\n }\n return 'normal';\n}\n","/**\n * Postgres {@link SkillPackStore} (plan `skill-pack-delivery-channel`, Phase 2).\n *\n * A faithful projection of {@link InMemorySkillPackStore}: same validators, same\n * refusals, same read shape. What `publish` checks and what it rejects is core's\n * decision, not this store's — it reuses `checkSkillPackManifest` /\n * `checkSkillPackEntry` and the manifest/file cross-checks the reference\n * performs, because this store cannot hash (integrity is the installing device's\n * job) but it CAN refuse to persist a pack whose declared path set or byte sizes\n * already disagree with the bytes it was handed. Storing that pair unchecked\n * would hand a device a corrupt publication it could not tell from a tampered\n * response.\n *\n * Two tables, one per level of the manifest (`deploy/sql/0005_skill_packs.sql`):\n * `skill_pack` carries the pack-level fields a `SkillPackManifest` needs to be\n * reconstructed (version, description, the pack content hash), and\n * `skill_pack_file` carries one row per declared file with its content hash,\n * byte size, and the UTF-8 text itself. A publish is a single transaction that\n * upserts the pack row and REPLACES its file set, so a re-publish of a changed\n * pack under the same name never leaves a stale file behind.\n *\n * `byte_size` is `integer`, not `bigint`: `SkillPackFile.byteSize` is a core\n * `number` bounded by `SKILL_PACK_FILE_MAX_BYTES` (256 KiB), unlike the quota\n * and truth byte fields the contract declares as `bigint`. `integer` is the\n * type that round-trips a `number` without a cast at the boundary — the same\n * call `object_manifest.ref_count` makes for a small count.\n *\n * No injected clock: a manifest carries no timestamp, so this store writes none\n * and asks the database for none. That mirrors the reference, which takes no\n * clock either.\n */\nimport {\n ByokCoreError,\n SKILL_PACK_ENTRY_PATH,\n SKILL_PACK_MANIFEST_SCHEMA_ID,\n checkSkillPackEntry,\n checkSkillPackManifest,\n type ContentHash,\n type SkillPackFile,\n type SkillPackFileContent,\n type SkillPackListQuery,\n type SkillPackManifest,\n type SkillPackPublishInput,\n type SkillPackStore,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { Pool, PoolClient } from 'pg';\n\nconst DEFAULT_LIST_LIMIT = 50;\n\ninterface PackRow {\n readonly name: string;\n readonly version: string;\n readonly description: string;\n readonly content_hash: string;\n}\n\ninterface FileRow {\n readonly pack_name: string;\n readonly path: string;\n readonly content_hash: string;\n readonly byte_size: number;\n readonly content: string;\n}\n\n/** Reassembles the manifest a `publish` validated, from its two-level row set. */\nfunction toManifest(pack: PackRow, files: readonly FileRow[]): SkillPackManifest {\n return {\n schema: SKILL_PACK_MANIFEST_SCHEMA_ID,\n name: pack.name,\n version: pack.version,\n description: pack.description,\n files: files.map(toFile),\n contentHash: pack.content_hash as ContentHash,\n };\n}\n\nfunction toFile(row: FileRow): SkillPackFile {\n return {\n path: row.path,\n contentHash: row.content_hash as ContentHash,\n byteSize: row.byte_size,\n };\n}\n\nexport class PostgresSkillPackStore implements SkillPackStore {\n readonly #pool: Pool;\n\n constructor(pool: Pool) {\n this.#pool = pool;\n }\n\n async publish(tenant: TenantId, input: SkillPackPublishInput): Promise<SkillPackManifest> {\n const { manifest } = input;\n const structural = checkSkillPackManifest(manifest);\n if (!structural.ok) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${structural.reason} — ${structural.detail}`,\n );\n }\n\n // The delivered path set and the declared path set must be exactly equal,\n // and every delivered file's UTF-8 byte length must equal its declared\n // size. Same checks the reference performs, in the same order, so a pack\n // rejected against one composition is rejected against the other.\n const contents = new Map<string, string>();\n for (const file of input.files) {\n if (contents.has(file.path)) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(file.path)} was supplied twice.`,\n );\n }\n contents.set(file.path, file.content);\n }\n\n for (const declared of manifest.files) {\n const content = contents.get(declared.path);\n if (content === undefined) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(declared.path)} is declared but was not supplied.`,\n );\n }\n const bytes = new TextEncoder().encode(content).length;\n if (bytes !== declared.byteSize) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(declared.path)} declares ${declared.byteSize} bytes and supplies ${bytes}.`,\n );\n }\n }\n if (contents.size !== manifest.files.length) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${contents.size} files were supplied for ${manifest.files.length} declared rows.`,\n );\n }\n\n const entry = checkSkillPackEntry(manifest, contents.get(SKILL_PACK_ENTRY_PATH)!);\n if (!entry.ok) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${entry.reason} — ${entry.detail}`,\n );\n }\n\n await this.#inTransaction(async (client) => {\n await client.query(\n `INSERT INTO skill_pack (tenant_id, name, version, description, content_hash)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (tenant_id, name) DO UPDATE\n SET version = EXCLUDED.version,\n description = EXCLUDED.description,\n content_hash = EXCLUDED.content_hash`,\n [tenant, manifest.name, manifest.version, manifest.description, manifest.contentHash],\n );\n // Replace, never merge: a re-publish under the same name is a full\n // overwrite, so a file dropped from the new manifest must not linger.\n await client.query(`DELETE FROM skill_pack_file WHERE tenant_id = $1 AND pack_name = $2`, [\n tenant,\n manifest.name,\n ]);\n for (const declared of manifest.files) {\n await client.query(\n `INSERT INTO skill_pack_file (tenant_id, pack_name, path, content_hash, byte_size, content)\n VALUES ($1, $2, $3, $4, $5, $6)`,\n [\n tenant,\n manifest.name,\n declared.path,\n declared.contentHash,\n declared.byteSize,\n contents.get(declared.path)!,\n ],\n );\n }\n });\n\n return manifest;\n }\n\n async get(tenant: TenantId, name: string): Promise<SkillPackManifest | undefined> {\n const packResult = await this.#pool.query<PackRow>(\n `SELECT name, version, description, content_hash\n FROM skill_pack WHERE tenant_id = $1 AND name = $2`,\n [tenant, name],\n );\n const pack = packResult.rows[0];\n if (pack === undefined) return undefined;\n\n const files = await this.#filesFor(tenant, [name]);\n return toManifest(pack, files);\n }\n\n async list(tenant: TenantId, query: SkillPackListQuery): Promise<readonly SkillPackManifest[]> {\n // Byte-order name sort, capped — the same order and default limit the\n // reference produces. `COLLATE \"C\"` pins it to code-point order rather than\n // the server's initialized collation.\n const packs = await this.#pool.query<PackRow>(\n `SELECT name, version, description, content_hash\n FROM skill_pack WHERE tenant_id = $1\n ORDER BY name COLLATE \"C\"\n LIMIT $2`,\n [tenant, query.limit ?? DEFAULT_LIST_LIMIT],\n );\n if (packs.rows.length === 0) return [];\n\n const files = await this.#filesFor(\n tenant,\n packs.rows.map((row) => row.name),\n );\n const byPack = new Map<string, FileRow[]>();\n for (const file of files) {\n const bucket = byPack.get(file.pack_name);\n if (bucket === undefined) byPack.set(file.pack_name, [file]);\n else bucket.push(file);\n }\n return packs.rows.map((pack) => toManifest(pack, byPack.get(pack.name) ?? []));\n }\n\n async readFile(\n tenant: TenantId,\n name: string,\n path: string,\n ): Promise<SkillPackFileContent | undefined> {\n const result = await this.#pool.query<FileRow>(\n `SELECT pack_name, path, content_hash, byte_size, content\n FROM skill_pack_file\n WHERE tenant_id = $1 AND pack_name = $2 AND path = $3`,\n [tenant, name, path],\n );\n const row = result.rows[0];\n if (row === undefined) return undefined;\n return {\n path: row.path,\n contentHash: row.content_hash as ContentHash,\n byteSize: row.byte_size,\n content: row.content,\n };\n }\n\n /** Every file row for the named packs, in byte order of (pack_name, path). */\n async #filesFor(tenant: TenantId, names: readonly string[]): Promise<FileRow[]> {\n const result = await this.#pool.query<FileRow>(\n `SELECT pack_name, path, content_hash, byte_size, content\n FROM skill_pack_file\n WHERE tenant_id = $1 AND pack_name = ANY($2::text[])\n ORDER BY pack_name COLLATE \"C\", path COLLATE \"C\"`,\n [tenant, names],\n );\n return result.rows;\n }\n\n async #inTransaction(run: (client: PoolClient) => Promise<void>): Promise<void> {\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n await run(client);\n await client.query('COMMIT');\n } catch (error) {\n // Best-effort rollback, for the same reason the object store's is: a\n // rollback that itself throws must not replace the failure the caller\n // needs to see.\n await client.query('ROLLBACK').catch(() => {});\n throw error;\n } finally {\n client.release();\n }\n }\n}\n","/**\n * Postgres {@link TruthStore} (§12.3, §12.6.4).\n *\n * Two write models over one table, and the primary key does the deciding for\n * both.\n *\n * - `task.terminal` is first-write-wins: `INSERT ... ON CONFLICT DO NOTHING`\n * plus an equality re-read. A replay of the identical hash returns the\n * ORIGINAL row — same `rev`, same `writtenAt`, same `requestId` — and a\n * different hash for the same task is refused with the record already\n * committed attached. An upsert would pass a naive \"write it twice\" check\n * while quietly restamping the first fact, which §12.6.4 forbids outright.\n * - `profile` / `memory` are per-key snapshots under an `expectedRev` CAS:\n * `UPDATE ... WHERE rev = $expectedRev`, with `expectedRev = 0` expressed as\n * the insert. Zero rows is the conflict, and the caller gets the current\n * record — or `undefined` when it claimed a revision of a record that does\n * not exist.\n *\n * The store never merges bodies. A conflict hands back what it lost to and\n * stops, because the device holding the context is the only party that can\n * decide what the merged truth should be (§12.3).\n */\nimport {\n CoreConflictError,\n type Clock,\n type ContentHash,\n type SnapshotWriteInput,\n type TenantId,\n type TerminalWriteInput,\n type TruthBodyRef,\n type TruthManifestEntry,\n type TruthManifestQuery,\n type TruthRecord,\n type TruthRecordKind,\n type TruthRecordSelector,\n type TruthStore,\n} from '@byok-sdk/core';\nimport type { Pool } from 'pg';\n\nconst DEFAULT_MANIFEST_LIMIT = 100;\n\nconst RECORD_COLUMNS =\n 'tenant_id, kind, subject_id, rev, content_hash, byte_size, body_kind, body_inline, body_object_hash, label, request_id, written_at';\n\ninterface RecordRow {\n readonly tenant_id: string;\n readonly kind: string;\n readonly subject_id: string;\n readonly rev: number;\n readonly content_hash: string;\n readonly byte_size: bigint;\n readonly body_kind: string;\n readonly body_inline: string | null;\n readonly body_object_hash: string | null;\n readonly label: string | null;\n readonly request_id: string | null;\n readonly written_at: string;\n}\n\ninterface ManifestRow {\n readonly kind: string;\n readonly subject_id: string;\n readonly rev: number;\n readonly content_hash: string;\n readonly byte_size: bigint;\n readonly label: string | null;\n readonly written_at: string;\n}\n\nfunction toBody(row: RecordRow): TruthBodyRef {\n return row.body_kind === 'inline'\n ? { kind: 'inline', body: row.body_inline ?? '' }\n : { kind: 'object', hash: (row.body_object_hash ?? '') as ContentHash };\n}\n\nfunction toRecord(row: RecordRow): TruthRecord {\n return {\n tenantId: row.tenant_id as TenantId,\n kind: row.kind as TruthRecordKind,\n recordKey: row.subject_id,\n rev: row.rev,\n contentHash: row.content_hash as ContentHash,\n byteSize: row.byte_size,\n body: toBody(row),\n ...(row.label === null ? {} : { label: row.label }),\n ...(row.request_id === null ? {} : { requestId: row.request_id }),\n writtenAt: row.written_at,\n };\n}\n\n/** Splits the two-case `TruthBodyRef` union into the two nullable columns. */\nfunction bodyColumns(body: TruthBodyRef): readonly [string, string | null, string | null] {\n return body.kind === 'inline'\n ? ['inline', body.body, null]\n : ['object', null, body.hash as string];\n}\n\nexport class PostgresTruthStore implements TruthStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n\n constructor(pool: Pool, clock: Clock) {\n this.#pool = pool;\n this.#clock = clock;\n }\n\n async writeTerminal(tenant: TenantId, input: TerminalWriteInput): Promise<TruthRecord> {\n const [bodyKind, bodyInline, bodyObjectHash] = bodyColumns(input.body);\n const inserted = await this.#pool.query<RecordRow>(\n `INSERT INTO attested_record (${RECORD_COLUMNS})\n VALUES ($1, 'task.terminal', $2, 1, $3, $4::bigint, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (tenant_id, kind, subject_id) DO NOTHING\n RETURNING ${RECORD_COLUMNS}`,\n [\n tenant,\n input.taskId,\n input.contentHash,\n input.byteSize,\n bodyKind,\n bodyInline,\n bodyObjectHash,\n input.label ?? null,\n input.requestId ?? null,\n this.#now(),\n ],\n );\n const row = inserted.rows[0];\n if (row !== undefined) return toRecord(row);\n\n const existing = await this.getRecord(tenant, {\n kind: 'task.terminal',\n recordKey: input.taskId,\n });\n if (existing === undefined) {\n throw new Error(`terminal record for ${input.taskId} vanished during a first write`);\n }\n // Exact replay of a committed fact: the original, unchanged. A retry after\n // a lost response is therefore safe and observably a no-op.\n if (existing.contentHash === input.contentHash) return existing;\n throw new CoreConflictError(\n 'terminal_conflict',\n `Task ${input.taskId} already has an immutable terminal record with a different hash.`,\n existing,\n this.#now(),\n );\n }\n\n async writeSnapshot(tenant: TenantId, input: SnapshotWriteInput): Promise<TruthRecord> {\n const [bodyKind, bodyInline, bodyObjectHash] = bodyColumns(input.body);\n const now = this.#now();\n\n // `expectedRev = 0` asserts \"no record yet\", which in SQL is the insert\n // itself: the primary key rejects a caller whose assertion is stale. Every\n // other expected revision is the `rev = $expectedRev` guard on the update.\n // Both are one statement, and both report zero rows as the same conflict.\n const written =\n input.expectedRev === 0\n ? await this.#pool.query<RecordRow>(\n `INSERT INTO attested_record (${RECORD_COLUMNS})\n VALUES ($1, $2, $3, 1, $4, $5::bigint, $6, $7, $8, $9, $10, $11)\n ON CONFLICT (tenant_id, kind, subject_id) DO NOTHING\n RETURNING ${RECORD_COLUMNS}`,\n [\n tenant,\n input.kind,\n input.recordKey,\n input.contentHash,\n input.byteSize,\n bodyKind,\n bodyInline,\n bodyObjectHash,\n input.label ?? null,\n input.requestId ?? null,\n now,\n ],\n )\n : await this.#pool.query<RecordRow>(\n `UPDATE attested_record\n SET rev = rev + 1,\n content_hash = $4,\n byte_size = $5::bigint,\n body_kind = $6,\n body_inline = $7,\n body_object_hash = $8,\n label = $9,\n request_id = $10,\n written_at = $11\n WHERE tenant_id = $1 AND kind = $2 AND subject_id = $3 AND rev = $12\n RETURNING ${RECORD_COLUMNS}`,\n [\n tenant,\n input.kind,\n input.recordKey,\n input.contentHash,\n input.byteSize,\n bodyKind,\n bodyInline,\n bodyObjectHash,\n input.label ?? null,\n input.requestId ?? null,\n now,\n input.expectedRev,\n ],\n );\n\n const row = written.rows[0];\n if (row !== undefined) return toRecord(row);\n\n const current = await this.getRecord(tenant, {\n kind: input.kind,\n recordKey: input.recordKey,\n });\n throw new CoreConflictError<TruthRecord | undefined>(\n 'truth_revision_conflict',\n `Record ${input.kind}/${input.recordKey} is at rev ${current?.rev ?? 0}, not ${input.expectedRev}.`,\n current,\n this.#now(),\n );\n }\n\n async getRecord(\n tenant: TenantId,\n selector: TruthRecordSelector,\n ): Promise<TruthRecord | undefined> {\n const result = await this.#pool.query<RecordRow>(\n `SELECT ${RECORD_COLUMNS} FROM attested_record\n WHERE tenant_id = $1 AND kind = $2 AND subject_id = $3`,\n [tenant, selector.kind, selector.recordKey],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toRecord(row);\n }\n\n async listManifest(\n tenant: TenantId,\n query: TruthManifestQuery,\n ): Promise<readonly TruthManifestEntry[]> {\n // Metadata only — the body columns are not in the projection at all, so a\n // manifest listing cannot accidentally ship payloads. Selecting which\n // bodies to fetch is a local decision (§S6.4), and an unbounded response\n // would defeat it.\n //\n // `COLLATE \"C\"` pins the order to byte order, which is what the in-memory\n // reference's `localeCompare` produces for these keys and, unlike the\n // database's default collation, does not depend on how the server was\n // initialized.\n const result = await this.#pool.query<ManifestRow>(\n `SELECT kind, subject_id, rev, content_hash, byte_size, label, written_at\n FROM attested_record\n WHERE tenant_id = $1\n AND ($2::text IS NULL OR kind = $2::text)\n AND ($3::text IS NULL OR starts_with(subject_id, $3::text))\n ORDER BY kind COLLATE \"C\", subject_id COLLATE \"C\"\n LIMIT $4`,\n [tenant, query.kind ?? null, query.keyPrefix ?? null, query.limit ?? DEFAULT_MANIFEST_LIMIT],\n );\n\n return result.rows.map((row) => ({\n kind: row.kind as TruthRecordKind,\n recordKey: row.subject_id,\n rev: row.rev,\n contentHash: row.content_hash as ContentHash,\n byteSize: row.byte_size,\n ...(row.label === null ? {} : { label: row.label }),\n updatedAt: row.written_at,\n }));\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * The Postgres composition of the seven `@byok-sdk/core` ports.\n *\n * All seven, or none: `runCoreConformance`'s port-inventory dimension asserts a\n * composition supplies exactly `CORE_STORE_NAMES` and exactly the methods\n * `CORE_PORT_METHODS` declares, so there is no such thing as a partial core\n * composition to certify. The original seven landed in one slice (design §11);\n * `skillPacks` joined in Phase 2 of `skill-pack-delivery-channel`\n * when it graduated from a bridge port to a mandatory `CoreStores` member. This\n * function returns a full `CoreStores` where the cloud-local sibling returns a\n * named subset.\n *\n * Everything that reads time reads the injected clock. Nothing calls SQL\n * `now()` — presence expiry and reservation expiry are both\n * contract behavior the suite asserts by moving a test clock, and a store that\n * asked the database for the time would make every one of those assertions\n * either a sleep or a flake.\n */\nimport type { Clock, CoreStores } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\nimport { PostgresPresenceStore } from './presence';\nimport { PostgresBoardStore } from './board';\nimport { PostgresMailboxStore } from './mailbox';\nimport { PostgresObjectStore } from './objects';\nimport { PostgresQuotaStore } from './quota';\nimport { PostgresSkillPackStore } from './skill-pack';\nimport { PostgresTruthStore } from './truth';\n\nexport { PostgresMailboxStore } from './mailbox';\nexport { PostgresBoardStore } from './board';\nexport { PostgresTruthStore } from './truth';\nexport { PostgresPresenceStore } from './presence';\nexport { PostgresObjectStore } from './objects';\nexport { PostgresQuotaStore } from './quota';\nexport { PostgresSkillPackStore } from './skill-pack';\n\nexport interface PostgresCoreStoreOptions {\n readonly pool: Pool;\n /**\n * The clock every TTL and timestamp in this composition reads. Injected, not\n * the database's `now()`: expiry has to be assertable under a test clock, and\n * a store that asks the server for the time cannot be.\n */\n readonly clock: Clock;\n}\n\nexport function createPostgresCoreStores(options: PostgresCoreStoreOptions): CoreStores {\n const { pool, clock } = options;\n return {\n mailbox: new PostgresMailboxStore(pool, clock),\n board: new PostgresBoardStore(pool, clock),\n truth: new PostgresTruthStore(pool, clock),\n presence: new PostgresPresenceStore(pool, clock),\n objects: new PostgresObjectStore(pool, clock),\n quota: new PostgresQuotaStore(pool, clock),\n // No clock: a skill-pack manifest carries no timestamp, so this store reads\n // none — the same shape as the cloud-local `devices` directory.\n skillPacks: new PostgresSkillPackStore(pool),\n };\n}\n","import {\n TRUTH_REQUEST_ID_MAX_LENGTH,\n TruthCommitResponseSchema,\n TruthCommitError,\n truthRecordMetadata,\n type CloudCrypto,\n type PreparedTruthWrite,\n type ProofRequestReceipt,\n type TruthCommitInput,\n type TruthCommitResponse,\n type TruthCommitResult,\n type TruthCommitter,\n} from '@byok-sdk/cloud';\nimport {\n ByokCoreError,\n CoreConflictError,\n type Clock,\n type ContentHash,\n type TenantId,\n type TruthBodyRef,\n type TruthRecord,\n type TruthRecordKind,\n} from '@byok-sdk/core';\nimport type { Pool, PoolClient } from 'pg';\nimport { PostgresTruthStore } from './stores/core/truth';\n\nconst RECORD_COLUMNS =\n 'tenant_id, kind, subject_id, rev, content_hash, byte_size, body_kind, body_inline, body_object_hash, label, request_id, written_at';\nconst RECEIPT_COLUMNS =\n 'tenant_id, device_id, request_id, operation, resource, body_sha256, body_size, response_status, response_body, recorded_at';\n\ninterface RecordRow {\n readonly tenant_id: string;\n readonly kind: string;\n readonly subject_id: string;\n readonly rev: number;\n readonly content_hash: string;\n readonly byte_size: bigint;\n readonly body_kind: string;\n readonly body_inline: string | null;\n readonly body_object_hash: string | null;\n readonly label: string | null;\n readonly request_id: string | null;\n readonly written_at: string;\n}\n\ninterface ReceiptRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly request_id: string;\n readonly operation: string;\n readonly resource: string;\n readonly body_sha256: string;\n readonly body_size: bigint;\n readonly response_status: number;\n readonly response_body: string;\n readonly recorded_at: Date;\n}\n\ninterface EntitlementRow {\n readonly hard_limit_bytes: bigint;\n readonly max_inline_bytes: bigint;\n readonly downgrade_grace_until: string | null;\n}\n\ninterface UsageRow {\n readonly committed_object_bytes: bigint;\n readonly committed_inline_bytes: bigint;\n readonly reserved_bytes: bigint;\n}\n\ninterface ManifestRow {\n readonly hash: string;\n readonly byte_size: bigint;\n readonly state: string;\n}\n\ninterface InlineHashRow {\n readonly content_hash: string;\n readonly byte_size: bigint;\n readonly ref_count: bigint;\n}\n\ninterface AppliedWrite {\n readonly input: PreparedTruthWrite;\n readonly before: TruthRecord | undefined;\n readonly record: TruthRecord;\n readonly mutated: boolean;\n}\n\nexport interface PostgresTruthCommitterOptions {\n readonly pool: Pool;\n readonly clock: Clock;\n readonly crypto: Pick<CloudCrypto, 'sha256'>;\n}\n\nfunction toBody(row: RecordRow): TruthBodyRef {\n return row.body_kind === 'inline'\n ? { kind: 'inline', body: row.body_inline ?? '' }\n : { kind: 'object', hash: (row.body_object_hash ?? '') as ContentHash };\n}\n\nfunction toRecord(tenant: TenantId, row: RecordRow): TruthRecord {\n return {\n tenantId: tenant,\n kind: row.kind as TruthRecordKind,\n recordKey: row.subject_id,\n rev: row.rev,\n contentHash: row.content_hash as ContentHash,\n byteSize: row.byte_size,\n body: toBody(row),\n ...(row.label === null ? {} : { label: row.label }),\n ...(row.request_id === null ? {} : { requestId: row.request_id }),\n writtenAt: row.written_at,\n };\n}\n\nfunction toReceipt(tenant: TenantId, row: ReceiptRow): ProofRequestReceipt {\n return {\n tenantId: tenant,\n deviceId: row.device_id,\n requestId: row.request_id,\n operation: row.operation,\n resource: row.resource,\n bodySha256: row.body_sha256,\n bodySize: row.body_size,\n responseStatus: row.response_status,\n responseBody: row.response_body,\n recordedAt: row.recorded_at.toISOString(),\n };\n}\n\nfunction sameBinding(receipt: ProofRequestReceipt, input: TruthCommitInput): boolean {\n return (\n receipt.operation === input.operation &&\n receipt.resource === input.resource &&\n receipt.bodySha256 === input.proofBodySha256 &&\n receipt.bodySize === input.proofBodySize\n );\n}\n\nfunction bodyColumns(body: TruthBodyRef): readonly [string, string | null, string | null] {\n return body.kind === 'inline'\n ? ['inline', body.body, null]\n : ['object', null, body.hash];\n}\n\nfunction writeKey(write: PreparedTruthWrite): string {\n return `${write.kind}\\u0000${write.recordKey}`;\n}\n\nfunction referenceId(write: PreparedTruthWrite): string {\n return `${write.kind}:${write.recordKey}`;\n}\n\nexport class PostgresTruthCommitter implements TruthCommitter {\n readonly #pool: Pool;\n readonly #clock: Clock;\n readonly #crypto: Pick<CloudCrypto, 'sha256'>;\n readonly #truth: PostgresTruthStore;\n\n constructor(options: PostgresTruthCommitterOptions) {\n this.#pool = options.pool;\n this.#clock = options.clock;\n this.#crypto = options.crypto;\n this.#truth = new PostgresTruthStore(options.pool, options.clock);\n }\n\n getRecord(tenant: TenantId, selector: Parameters<TruthCommitter['getRecord']>[1]) {\n return this.#truth.getRecord(tenant, selector);\n }\n\n listManifest(tenant: TenantId, query: Parameters<TruthCommitter['listManifest']>[1]) {\n return this.#truth.listManifest(tenant, query);\n }\n\n async commit(tenant: TenantId, input: TruthCommitInput): Promise<TruthCommitResult> {\n await this.#validateInput(input);\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n // Serializes the absence case too. A row lock cannot lock a receipt that\n // does not exist; without this, two first deliveries could both mutate\n // truth before one loses the receipt PK race.\n await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [\n JSON.stringify(['truth-receipt', tenant, input.deviceId, input.requestId]),\n ]);\n\n const replay = await this.#readReceipt(client, tenant, input.deviceId, input.requestId);\n if (replay !== undefined) {\n if (!sameBinding(replay, input)) {\n throw new TruthCommitError(\n 'proof_request_conflict',\n `Request ${input.requestId} was already used with a different binding.`,\n );\n }\n const response = TruthCommitResponseSchema.parse(JSON.parse(replay.responseBody));\n await client.query('COMMIT');\n return { response, replayed: true };\n }\n\n const before = await this.#lockCurrentRecords(client, tenant, input.writes);\n this.#assertWritePreconditions(input.writes, before);\n await this.#lockAndVerifyObjects(client, tenant, input.writes, before);\n\n const inlineAffected = input.writes.some((write) => {\n const current = before.get(writeKey(write));\n if (write.kind === 'task.terminal' && current !== undefined) return false;\n return current?.body.kind === 'inline' || write.body.kind === 'inline';\n });\n const inlineDelta = inlineAffected\n ? await this.#prepareInlineAccounting(client, tenant, input.writes, before)\n : 0n;\n\n const applied = await this.#applyWrites(client, tenant, input, before);\n await this.#replaceObjectReferences(client, tenant, applied);\n await this.#settleInlineAccounting(client, tenant, inlineDelta);\n\n const response: TruthCommitResponse = {\n primary: truthRecordMetadata(applied[0]!.record),\n snapshots: applied.slice(1).map((entry) => truthRecordMetadata(entry.record)),\n };\n await client.query(\n `INSERT INTO proof_request_receipt (${RECEIPT_COLUMNS})\n VALUES ($1, $2, $3, $4, $5, $6, $7::bigint, 200, $8, $9)`,\n [\n tenant,\n input.deviceId,\n input.requestId,\n input.operation,\n input.resource,\n input.proofBodySha256,\n input.proofBodySize,\n JSON.stringify(response),\n this.#now(),\n ],\n );\n await client.query('COMMIT');\n return { response, replayed: false };\n } catch (error) {\n await client.query('ROLLBACK').catch(() => undefined);\n throw error;\n } finally {\n client.release();\n }\n }\n\n async #validateInput(input: TruthCommitInput): Promise<void> {\n if (input.requestId.length === 0 || input.requestId.length > TRUTH_REQUEST_ID_MAX_LENGTH) {\n throw new TruthCommitError('proof_request_conflict', 'Request id is outside the record contract.');\n }\n const seen = new Set<string>();\n const objectSizes = new Map<string, bigint>();\n for (const write of input.writes) {\n const key = writeKey(write);\n if (seen.has(key)) {\n throw new TruthCommitError('proof_request_conflict', `Duplicate truth write ${key}.`);\n }\n seen.add(key);\n if (write.body.kind === 'inline') {\n const bytes = new TextEncoder().encode(write.body.body);\n if (BigInt(bytes.byteLength) !== write.byteSize) {\n throw new ByokCoreError('storage_integrity_mismatch', 'Inline byte size disagrees with its content.');\n }\n if ((await this.#crypto.sha256(bytes)) !== write.contentHash) {\n throw new ByokCoreError('storage_integrity_mismatch', 'Inline hash disagrees with its content.');\n }\n } else if (write.body.hash !== write.contentHash) {\n throw new ByokCoreError('storage_integrity_mismatch', 'Object body hash disagrees with record hash.');\n } else {\n const priorSize = objectSizes.get(write.body.hash);\n if (priorSize !== undefined && priorSize !== write.byteSize) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Object ${write.body.hash} was declared with inconsistent byte sizes.`,\n );\n }\n objectSizes.set(write.body.hash, write.byteSize);\n }\n }\n }\n\n async #readReceipt(\n client: PoolClient,\n tenant: TenantId,\n deviceId: string,\n requestId: string,\n ): Promise<ProofRequestReceipt | undefined> {\n const result = await client.query<ReceiptRow>(\n `SELECT ${RECEIPT_COLUMNS} FROM proof_request_receipt\n WHERE tenant_id = $1 AND device_id = $2 AND request_id = $3`,\n [tenant, deviceId, requestId],\n );\n const row = result.rows[0];\n return row === undefined ? undefined : toReceipt(tenant, row);\n }\n\n async #lockCurrentRecords(\n client: PoolClient,\n tenant: TenantId,\n writes: readonly PreparedTruthWrite[],\n ): Promise<Map<string, TruthRecord | undefined>> {\n const current = new Map<string, TruthRecord | undefined>();\n const ordered = [...writes].sort((a, b) => writeKey(a).localeCompare(writeKey(b)));\n // Row locks cannot protect a missing snapshot. Per-key advisory locks make\n // expectedRev=0 deterministic: the waiter observes the winner and raises a\n // typed revision conflict instead of leaking a unique-constraint error.\n for (const write of ordered) {\n await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [\n JSON.stringify(['truth-record', tenant, write.kind, write.recordKey]),\n ]);\n }\n for (const write of ordered) {\n const result = await client.query<RecordRow>(\n `SELECT ${RECORD_COLUMNS} FROM attested_record\n WHERE tenant_id = $1 AND kind = $2 AND subject_id = $3\n FOR UPDATE`,\n [tenant, write.kind, write.recordKey],\n );\n current.set(\n writeKey(write),\n result.rows[0] === undefined ? undefined : toRecord(tenant, result.rows[0]),\n );\n }\n return current;\n }\n\n #assertWritePreconditions(\n writes: readonly PreparedTruthWrite[],\n current: ReadonlyMap<string, TruthRecord | undefined>,\n ): void {\n for (const write of writes) {\n const before = current.get(writeKey(write));\n if (write.kind === 'task.terminal') {\n if (before !== undefined && before.contentHash !== write.contentHash) {\n throw new CoreConflictError(\n 'terminal_conflict',\n `Task ${write.recordKey} already has a different immutable terminal.`,\n before,\n this.#now(),\n );\n }\n } else if ((before?.rev ?? 0) !== write.expectedRev) {\n throw new CoreConflictError(\n 'truth_revision_conflict',\n `${write.kind}/${write.recordKey} is at rev ${before?.rev ?? 0}, not ${write.expectedRev}.`,\n before,\n this.#now(),\n );\n }\n }\n }\n\n async #lockAndVerifyObjects(\n client: PoolClient,\n tenant: TenantId,\n writes: readonly PreparedTruthWrite[],\n current: ReadonlyMap<string, TruthRecord | undefined>,\n ): Promise<void> {\n const requested = new Map<string, bigint>();\n const affected = new Set<string>();\n for (const write of writes) {\n const before = current.get(writeKey(write));\n if (write.kind === 'task.terminal' && before !== undefined) continue;\n if (before?.body.kind === 'object') affected.add(before.body.hash);\n if (write.body.kind === 'object') {\n const existing = requested.get(write.body.hash);\n if (existing !== undefined && existing !== write.byteSize) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Object ${write.body.hash} was declared with inconsistent byte sizes.`,\n );\n }\n requested.set(write.body.hash, write.byteSize);\n affected.add(write.body.hash);\n }\n }\n // Lock both the old and new manifests in one global order. Locking only\n // the new side lets two snapshots swapping A/B each hold its destination\n // and deadlock while recounting the other's source reference.\n for (const hash of [...affected].sort()) {\n const result = await client.query<ManifestRow>(\n `SELECT hash, byte_size, state FROM object_manifest\n WHERE tenant_id = $1 AND hash = $2 FOR UPDATE`,\n [tenant, hash],\n );\n const manifest = result.rows[0];\n const byteSize = requested.get(hash);\n if (\n manifest === undefined ||\n (byteSize !== undefined &&\n (manifest.state !== 'committed' || manifest.byte_size !== byteSize))\n ) {\n throw new TruthCommitError(\n 'truth_object_not_committed',\n `Object ${hash} is not a committed matching manifest.`,\n );\n }\n }\n }\n\n async #prepareInlineAccounting(\n client: PoolClient,\n tenant: TenantId,\n writes: readonly PreparedTruthWrite[],\n current: ReadonlyMap<string, TruthRecord | undefined>,\n ): Promise<bigint> {\n const entitlementResult = await client.query<EntitlementRow>(\n `SELECT hard_limit_bytes, max_inline_bytes, downgrade_grace_until\n FROM storage_entitlement WHERE tenant_id = $1 FOR UPDATE`,\n [tenant],\n );\n const entitlement = entitlementResult.rows[0];\n if (entitlement === undefined) {\n throw new ByokCoreError('storage_entitlement_missing', 'Tenant has no storage entitlement.');\n }\n const now = this.#now();\n await client.query(\n `UPDATE storage_reservation SET state = 'expired', settled_at = $2\n WHERE tenant_id = $1 AND state = 'reserved' AND expires_at <= $2`,\n [tenant, now],\n );\n const usageResult = await client.query<UsageRow>(\n `SELECT u.committed_object_bytes, u.committed_inline_bytes,\n COALESCE((SELECT SUM(expected_bytes) FROM storage_reservation r\n WHERE r.tenant_id = $1 AND r.state = 'reserved'), 0)::bigint AS reserved_bytes\n FROM storage_usage u WHERE u.tenant_id = $1 FOR UPDATE`,\n [tenant],\n );\n const usage = usageResult.rows[0];\n if (usage === undefined) throw new Error(`storage usage for ${tenant} is missing`);\n\n const affectedHashes = new Set<string>();\n const sizes = new Map<string, bigint>();\n for (const write of writes) {\n const before = current.get(writeKey(write));\n if (write.kind === 'task.terminal' && before !== undefined) continue;\n if (before?.body.kind === 'inline') {\n affectedHashes.add(before.contentHash);\n sizes.set(before.contentHash, before.byteSize);\n }\n if (write.body.kind !== 'inline') continue;\n if (write.byteSize > entitlement.max_inline_bytes) {\n throw new ByokCoreError(\n 'storage_object_too_large',\n `Inline truth ${write.kind}/${write.recordKey} exceeds maxInlineBytes.`,\n );\n }\n const knownSize = sizes.get(write.contentHash);\n if (knownSize !== undefined && knownSize !== write.byteSize) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Inline hash ${write.contentHash} was declared with inconsistent byte sizes.`,\n );\n }\n affectedHashes.add(write.contentHash);\n sizes.set(write.contentHash, write.byteSize);\n }\n\n const hashes = [...affectedHashes].sort();\n const baseline = new Map<string, bigint>(hashes.map((hash) => [hash, 0n]));\n const existing = await client.query<InlineHashRow>(\n `SELECT content_hash, byte_size, count(*)::bigint AS ref_count\n FROM attested_record\n WHERE tenant_id = $1 AND body_kind = 'inline' AND content_hash = ANY($2::text[])\n GROUP BY content_hash, byte_size`,\n [tenant, hashes],\n );\n for (const row of existing.rows) {\n const knownSize = sizes.get(row.content_hash);\n if (knownSize !== undefined && knownSize !== row.byte_size) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Stored inline hash ${row.content_hash} disagrees on byte size.`,\n );\n }\n if ((baseline.get(row.content_hash) ?? 0n) !== 0n) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Stored inline hash ${row.content_hash} has multiple byte sizes.`,\n );\n }\n baseline.set(row.content_hash, row.ref_count);\n sizes.set(row.content_hash, row.byte_size);\n }\n\n const projected = new Map(baseline);\n for (const write of writes) {\n const before = current.get(writeKey(write));\n if (write.kind === 'task.terminal' && before !== undefined) continue;\n if (before?.body.kind === 'inline') {\n projected.set(before.contentHash, (projected.get(before.contentHash) ?? 0n) - 1n);\n }\n if (write.body.kind === 'inline') {\n projected.set(write.contentHash, (projected.get(write.contentHash) ?? 0n) + 1n);\n }\n }\n\n let delta = 0n;\n let newlyCommitted = 0n;\n for (const hash of hashes) {\n const before = baseline.get(hash) ?? 0n;\n const after = projected.get(hash) ?? 0n;\n if (after < 0n) throw new Error(`inline reference count for ${hash} would become negative`);\n const byteSize = sizes.get(hash);\n if (byteSize === undefined) throw new Error(`inline byte size for ${hash} is missing`);\n if (before === 0n && after > 0n) {\n delta += byteSize;\n newlyCommitted += byteSize;\n } else if (before > 0n && after === 0n) {\n delta -= byteSize;\n }\n }\n\n const used = usage.committed_object_bytes + usage.committed_inline_bytes + usage.reserved_bytes;\n if (\n newlyCommitted > 0n &&\n used >= entitlement.hard_limit_bytes &&\n entitlement.downgrade_grace_until !== null &&\n entitlement.downgrade_grace_until <= now\n ) {\n throw new ByokCoreError('storage_write_suspended', 'Durable writes are suspended.');\n }\n if (used + delta > entitlement.hard_limit_bytes) {\n throw new ByokCoreError('storage_quota_exceeded', 'Final inline truth usage exceeds quota.');\n }\n return delta;\n }\n\n async #applyWrites(\n client: PoolClient,\n tenant: TenantId,\n input: TruthCommitInput,\n current: ReadonlyMap<string, TruthRecord | undefined>,\n ): Promise<AppliedWrite[]> {\n const applied: AppliedWrite[] = [];\n for (const write of input.writes) {\n const before = current.get(writeKey(write));\n if (write.kind === 'task.terminal' && before !== undefined) {\n applied.push({ input: write, before, record: before, mutated: false });\n continue;\n }\n const [bodyKind, bodyInline, bodyObjectHash] = bodyColumns(write.body);\n const values = [\n tenant,\n write.kind,\n write.recordKey,\n write.contentHash,\n write.byteSize,\n bodyKind,\n bodyInline,\n bodyObjectHash,\n write.label ?? null,\n input.requestId,\n this.#now(),\n ];\n const result =\n before === undefined\n ? await client.query<RecordRow>(\n `INSERT INTO attested_record (${RECORD_COLUMNS})\n VALUES ($1, $2, $3, 1, $4, $5, $6, $7, $8, $9, $10, $11)\n RETURNING ${RECORD_COLUMNS}`,\n values,\n )\n : await client.query<RecordRow>(\n `UPDATE attested_record\n SET rev = rev + 1, content_hash = $4, byte_size = $5,\n body_kind = $6, body_inline = $7, body_object_hash = $8,\n label = $9, request_id = $10, written_at = $11\n WHERE tenant_id = $1 AND kind = $2 AND subject_id = $3\n RETURNING ${RECORD_COLUMNS}`,\n values,\n );\n applied.push({\n input: write,\n before,\n record: toRecord(tenant, result.rows[0]!),\n mutated: true,\n });\n }\n return applied;\n }\n\n async #replaceObjectReferences(\n client: PoolClient,\n tenant: TenantId,\n applied: readonly AppliedWrite[],\n ): Promise<void> {\n const affected = new Set<string>();\n for (const entry of applied) {\n if (!entry.mutated) continue;\n const refId = referenceId(entry.input);\n if (entry.input.body.kind === 'object') {\n affected.add(entry.input.body.hash);\n await client.query(\n `INSERT INTO object_reference (tenant_id, hash, ref_kind, ref_id, created_at)\n VALUES ($1, $2, 'truth', $3, $4)\n ON CONFLICT (tenant_id, hash, ref_kind, ref_id) DO NOTHING`,\n [tenant, entry.input.body.hash, refId, this.#now()],\n );\n }\n if (\n entry.before?.body.kind === 'object' &&\n (entry.input.body.kind !== 'object' || entry.input.body.hash !== entry.before.body.hash)\n ) {\n affected.add(entry.before.body.hash);\n await client.query(\n `DELETE FROM object_reference\n WHERE tenant_id = $1 AND hash = $2 AND ref_kind = 'truth' AND ref_id = $3`,\n [tenant, entry.before.body.hash, refId],\n );\n }\n }\n for (const hash of [...affected].sort()) {\n await client.query(\n `UPDATE object_manifest\n SET ref_count = (SELECT count(*) FROM object_reference r\n WHERE r.tenant_id = $1 AND r.hash = $2),\n updated_at = $3\n WHERE tenant_id = $1 AND hash = $2`,\n [tenant, hash, this.#now()],\n );\n }\n }\n\n async #settleInlineAccounting(\n client: PoolClient,\n tenant: TenantId,\n delta: bigint,\n ): Promise<void> {\n if (delta !== 0n) {\n const updated = await client.query(\n `UPDATE storage_usage\n SET committed_inline_bytes = committed_inline_bytes + $2::bigint,\n updated_at = $3\n WHERE tenant_id = $1 AND committed_inline_bytes + $2::bigint >= 0\n RETURNING 1`,\n [tenant, delta, this.#now()],\n );\n if (updated.rowCount !== 1) throw new Error('inline accounting would become negative');\n }\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * Where this package's own migration files are.\n *\n * `migrate(pool, directory)` takes a directory rather than defaulting to one,\n * because a runner that guesses where a host keeps deployment assets can\n * silently migrate nothing. That contract is unchanged — this function just\n * means the answer no longer has to come from a git checkout the installed\n * package cannot see. The build copies `deploy/sql/*.sql` into `dist/sql/`\n * (`scripts/copy-migrations.mjs`), so the files sit next to the compiled entry\n * point and resolve relative to it.\n *\n * Resolution is relative to THIS module's own URL, never to `process.cwd()` or\n * a `require.resolve` of the package name: an installed copy is the only thing\n * in reach, and `fileURLToPath` is what turns a `file:///C:/...` URL into a path\n * Windows can open.\n */\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Absolute path to the migration directory shipped inside this package, ready\n * to hand to {@link migrate}. The directory exists in an installed package and\n * in this repository after a build; it does not exist in an unbuilt checkout,\n * where `deploy/sql/` is the thing to read.\n */\nexport function migrationsDir(): string {\n return fileURLToPath(new URL('./sql', import.meta.url));\n}\n","/**\n * The forward-only migration runner.\n *\n * Six rules, and each one exists because the alternative is a schema incident\n * (docs/researches/s4a-dataplane-design.md §2):\n *\n * 1. **Ordering comes from filenames.** `deploy/sql/NNNN_*.sql`, sorted by the\n * four-digit prefix — the same constraint `check-deploy-sql-order` already\n * enforces in CI. Two ordering authorities cannot coexist, which is the\n * whole reason this is a hand-written runner instead of a migration\n * framework with its own directory convention.\n * 2. **One runner at a time**, via a session-level `pg_advisory_lock` held on a\n * single checked-out client for the entire run. Two deploy jobs starting\n * together is normal; two of them applying the same file is not.\n * 3. **The ledger bootstraps itself.** `byok_schema_migration` is the ONLY DDL\n * outside `deploy/sql/`. Putting it in `0001` would force the runner to\n * special-case \"the ledger does not exist yet\" before it can read the\n * ledger — two sources of truth for one table.\n * 4. **One transaction per file**, covering the file's statements AND its\n * ledger row. A crash leaves a migration entirely applied or entirely\n * absent, never applied-but-unrecorded (which the next run would replay).\n * 5. **Checksums are verified, not recorded and forgotten.** An already-applied\n * file whose sha256 no longer matches the ledger raises\n * {@link MigrationChecksumMismatchError} and the run STOPS. \"Forward-only\"\n * means published files are immutable; without this check that is a slogan.\n * 6. **There is no down path.** Not \"unimplemented\" — absent. Rollback is\n * \"revert the application, leave the tables\" (sprint S4A.6), and a\n * destructive path that exists is a destructive path that eventually runs.\n *\n * Known boundary of rule 4: a statement that cannot run inside a transaction\n * (`CREATE INDEX CONCURRENTLY`, and `ALTER TYPE ... ADD VALUE` on older\n * servers) cannot appear in a migration file. That is a deliberate trade —\n * per-file atomicity is worth more here than building an index without a lock,\n * and the day it is not, it needs its own reviewed mechanism rather than a\n * quiet exception.\n */\nimport { createHash } from 'node:crypto';\nimport { readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Pool, PoolClient } from 'pg';\nimport { migrationsDir } from './migrations-dir';\n\n/**\n * An arbitrary but permanently fixed advisory-lock key. Its only requirement is\n * that every runner in every process picks the same one; changing it would let\n * an old and a new deployment migrate concurrently exactly once.\n */\nconst MIGRATION_ADVISORY_LOCK_KEY = '4021960801';\n\n/** `NNNN_name.sql` — the same shape `scripts/check-deploy-sql-order.sh` enforces. */\nconst MIGRATION_FILENAME_PATTERN = /^(\\d{4})[_-].+\\.sql$/;\n\n/**\n * The migration ledger, and the sole DDL statement in this package: every other\n * table a deployment owns is created by a file under `deploy/sql/`.\n */\nconst LEDGER_DDL = `\nCREATE TABLE IF NOT EXISTS byok_schema_migration (\n version text PRIMARY KEY,\n checksum text NOT NULL,\n applied_at timestamptz NOT NULL\n)`;\n\nconst MIGRATION_LEDGER_TABLE = 'byok_schema_migration';\nconst LEDGER_READ_SQL = 'SELECT version, checksum FROM byok_schema_migration';\n\n/** One file on disk, already ordered and checksummed. */\nexport interface MigrationFile {\n /** The filename, e.g. `0001_cloud_local.sql`. This is the ledger's `version`. */\n readonly version: string;\n /** The four-digit prefix as a number, used for ordering only. */\n readonly ordinal: number;\n readonly checksum: string;\n readonly sql: string;\n}\n\n/** What a run did. `applied` is empty when the database was already up to date. */\nexport interface MigrationResult {\n readonly applied: readonly string[];\n readonly alreadyApplied: readonly string[];\n}\n\n/** The exact package-owned row returned after a successful ledger readback. */\nexport interface MigrationVerificationRow {\n readonly version: string;\n readonly checksum: string;\n}\n\nexport type MigrationStateIssue =\n | {\n readonly kind: 'missing';\n readonly version: string;\n readonly expectedChecksum: string;\n }\n | {\n readonly kind: 'unexpected';\n readonly version: string;\n readonly actualChecksum: string;\n }\n | {\n readonly kind: 'checksum_mismatch';\n readonly version: string;\n readonly expectedChecksum: string;\n readonly actualChecksum: string;\n }\n | {\n readonly kind: 'ledger_missing';\n readonly table: 'byok_schema_migration';\n };\n\n/**\n * The database's migration state does not exactly match this package's files.\n *\n * This is deliberately aggregate and fail-closed: a host can report every\n * drift fact in one readiness result, but it cannot continue as though a\n * partially matching schema were usable.\n */\nexport class MigrationStateMismatchError extends Error {\n readonly issues: readonly MigrationStateIssue[];\n\n constructor(issues: readonly MigrationStateIssue[], options?: ErrorOptions) {\n const detail = issues\n .map((issue) => {\n switch (issue.kind) {\n case 'missing':\n return `missing ${issue.version}`;\n case 'unexpected':\n return `unexpected ${issue.version}`;\n case 'checksum_mismatch':\n return `checksum mismatch ${issue.version}`;\n case 'ledger_missing':\n return `ledger table missing ${issue.table}`;\n }\n })\n .join('; ');\n super(`Migration state does not match package files: ${detail}`, options);\n this.name = 'MigrationStateMismatchError';\n this.issues = Object.freeze([...issues]);\n }\n}\n\n/**\n * A published migration file changed after it was applied.\n *\n * Fail-closed by design: the runner cannot know whether the edit was a harmless\n * comment or a dropped column, and a deployment that guesses wrong corrupts a\n * schema. The fix is a NEW migration file, never an edit to an old one.\n */\nexport class MigrationChecksumMismatchError extends Error {\n readonly version: string;\n readonly expectedChecksum: string;\n readonly actualChecksum: string;\n\n constructor(version: string, expectedChecksum: string, actualChecksum: string) {\n super(\n `Migration ${version} was already applied with checksum ${expectedChecksum}, but the file on disk hashes to ${actualChecksum}. ` +\n 'Published migrations are immutable: add a new file instead of editing this one.',\n );\n this.name = 'MigrationChecksumMismatchError';\n this.version = version;\n this.expectedChecksum = expectedChecksum;\n this.actualChecksum = actualChecksum;\n }\n}\n\n/** A file in the migration directory that the naming contract does not admit. */\nexport class MigrationFilenameError extends Error {\n readonly filename: string;\n\n constructor(filename: string, reason: string) {\n super(`Migration file ${filename} is not usable: ${reason}`);\n this.name = 'MigrationFilenameError';\n this.filename = filename;\n }\n}\n\nfunction sha256(text: string): string {\n return createHash('sha256').update(text, 'utf8').digest('hex');\n}\n\n/**\n * Reads and orders the migration files in `directory`.\n *\n * Ordering is by the four-digit prefix, not by whatever order the filesystem\n * hands back — `readdir` makes no promise, and on some filesystems it is\n * effectively insertion order. A non-conforming filename or a duplicated prefix\n * is an error rather than a skip: silently ignoring a `.sql` file someone\n * dropped in this directory is how a migration goes missing.\n */\nexport async function readMigrationFiles(directory: string): Promise<readonly MigrationFile[]> {\n const entries = await readdir(directory, { withFileTypes: true });\n const files: MigrationFile[] = [];\n\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith('.sql')) continue;\n const match = MIGRATION_FILENAME_PATTERN.exec(entry.name);\n if (match === null) {\n throw new MigrationFilenameError(\n entry.name,\n 'expected a four-digit prefix, e.g. 0001_cloud_local.sql',\n );\n }\n const sql = await readFile(join(directory, entry.name), 'utf8');\n files.push({\n version: entry.name,\n ordinal: Number.parseInt(match[1]!, 10),\n checksum: sha256(sql),\n sql,\n });\n }\n\n files.sort((left, right) => left.ordinal - right.ordinal);\n\n for (let index = 1; index < files.length; index += 1) {\n const previous = files[index - 1]!;\n const current = files[index]!;\n if (previous.ordinal === current.ordinal) {\n throw new MigrationFilenameError(\n current.version,\n `duplicate prefix ${String(current.ordinal).padStart(4, '0')}, already used by ${previous.version}`,\n );\n }\n }\n\n return files;\n}\n\ninterface MigrationLedgerRow {\n readonly version: string;\n readonly checksum: string;\n}\n\nasync function readLedgerRows(client: PoolClient): Promise<readonly MigrationLedgerRow[]> {\n const result = await client.query<MigrationLedgerRow>(LEDGER_READ_SQL);\n return result.rows;\n}\n\nasync function readLedger(client: PoolClient): Promise<Map<string, string>> {\n const rows = await readLedgerRows(client);\n return new Map(rows.map((row) => [row.version, row.checksum]));\n}\n\nfunction isMissingLedgerTable(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n error.code === '42P01'\n );\n}\n\nfunction compareVersions(left: string, right: string): number {\n if (left < right) return -1;\n if (left > right) return 1;\n return 0;\n}\n\n/**\n * Reads the package migration files and the existing ledger, then requires an\n * exact version/checksum match.\n *\n * The default directory is the migration projection shipped by this package.\n * This function only reads state: it never creates the ledger, applies a\n * migration, or synthesizes a compatible result for a missing/changed row.\n */\nexport async function verifyMigrations(\n pool: Pool,\n directory: string = migrationsDir(),\n): Promise<readonly MigrationVerificationRow[]> {\n const files = await readMigrationFiles(directory);\n const client = await pool.connect();\n\n try {\n let ledgerRows: readonly MigrationLedgerRow[];\n try {\n ledgerRows = await readLedgerRows(client);\n } catch (error) {\n if (!isMissingLedgerTable(error)) throw error;\n throw new MigrationStateMismatchError(\n [{ kind: 'ledger_missing', table: MIGRATION_LEDGER_TABLE }],\n { cause: error },\n );\n }\n\n const ledger = new Map(ledgerRows.map((row) => [row.version, row.checksum]));\n const expectedVersions = new Set(files.map((file) => file.version));\n const issues: MigrationStateIssue[] = [];\n\n for (const file of files) {\n const actualChecksum = ledger.get(file.version);\n if (actualChecksum === undefined) {\n issues.push({\n kind: 'missing',\n version: file.version,\n expectedChecksum: file.checksum,\n });\n } else if (actualChecksum !== file.checksum) {\n issues.push({\n kind: 'checksum_mismatch',\n version: file.version,\n expectedChecksum: file.checksum,\n actualChecksum,\n });\n }\n }\n\n const unexpectedRows = ledgerRows\n .filter((row) => !expectedVersions.has(row.version))\n .slice()\n .sort((left, right) => compareVersions(left.version, right.version));\n for (const row of unexpectedRows) {\n issues.push({ kind: 'unexpected', version: row.version, actualChecksum: row.checksum });\n }\n\n if (issues.length > 0) throw new MigrationStateMismatchError(issues);\n\n return files.map(({ version, checksum }) => ({ version, checksum }));\n } finally {\n client.release();\n }\n}\n\n/**\n * Applies every pending migration in `directory`, in prefix order.\n *\n * @param pool The pool to migrate. One client is checked out for the whole run\n * because the advisory lock is session-scoped.\n * @param directory Absolute path to the migration directory (this repo's\n * `deploy/sql/`). Required rather than defaulted: a published package cannot\n * guess where its consumer keeps deployment assets, and guessing wrong would\n * mean silently migrating nothing.\n */\nexport async function migrate(pool: Pool, directory: string): Promise<MigrationResult> {\n // Read the files BEFORE taking the lock: a filename error is a mistake in the\n // repository, and there is no reason to make a second runner queue behind it.\n const files = await readMigrationFiles(directory);\n\n const client = await pool.connect();\n try {\n await client.query('SELECT pg_advisory_lock($1)', [MIGRATION_ADVISORY_LOCK_KEY]);\n try {\n await client.query(LEDGER_DDL);\n const ledger = await readLedger(client);\n\n const applied: string[] = [];\n const alreadyApplied: string[] = [];\n\n for (const file of files) {\n const recordedChecksum = ledger.get(file.version);\n if (recordedChecksum !== undefined) {\n if (recordedChecksum !== file.checksum) {\n throw new MigrationChecksumMismatchError(file.version, recordedChecksum, file.checksum);\n }\n alreadyApplied.push(file.version);\n continue;\n }\n\n // One transaction: the file's statements and its ledger row land or\n // vanish together. A multi-statement string goes over the simple\n // protocol, which runs inside the transaction opened here.\n await client.query('BEGIN');\n try {\n await client.query(file.sql);\n await client.query(\n 'INSERT INTO byok_schema_migration (version, checksum, applied_at) VALUES ($1, $2, now())',\n [file.version, file.checksum],\n );\n await client.query('COMMIT');\n } catch (error) {\n // The rollback is best-effort on purpose. When the failure was a lost\n // connection, `ROLLBACK` rejects too — and an unguarded await here\n // would replace the migration error with a transport error, hiding\n // the one fact an operator needs: which file failed and why. The\n // server discards an abandoned transaction on disconnect anyway, so\n // swallowing this rejection loses nothing and rethrowing the original\n // keeps the diagnosis intact.\n await client.query('ROLLBACK').catch(() => {});\n throw error;\n }\n applied.push(file.version);\n }\n\n return { applied, alreadyApplied };\n } finally {\n await client.query('SELECT pg_advisory_unlock($1)', [MIGRATION_ADVISORY_LOCK_KEY]);\n }\n } finally {\n client.release();\n }\n}\n","/**\n * Host-owned S4B-c maintenance for the Postgres + R2 composition.\n *\n * Postgres remains the manifest/accounting authority. R2 is touched only after\n * a durable `delete_pending` tombstone, and a missing object is an idempotent\n * DELETE replay — never evidence that a committed manifest was truthful.\n */\nimport { createHash } from 'node:crypto';\nimport {\n ByokCoreError,\n contentHash,\n tenantId,\n type Clock,\n type ContentHash,\n type MailboxMessage,\n type MailboxMessageState,\n type TenantId,\n} from '@byok-sdk/core';\nimport { decodeEnvelope, encodeEnvelope, EnvelopeSchema, isServerToDaemonType } from '@byok-sdk/protocol';\nimport type { Pool, PoolClient } from 'pg';\nimport {\n R2ObjectMaintenanceStore,\n type R2BlobStoreOptions,\n type R2ObjectMaintenance,\n} from './stores/r2-blobs';\nimport { allocateMailboxSequence } from './stores/core/mailbox-sequence';\n\nconst DEFAULT_BATCH_SIZE = 100;\nconst MAX_BATCH_SIZE = 1000;\nconst ADVISORY_LOCK_NAMESPACE = 1_106_736_963;\nconst OUTBOX_COLUMNS =\n 'tenant_id, device_id, seq, message_id, body, body_hash, byte_size, state, appended_at, replay_source_seq';\n\nexport const CLOUD_CLEANUP_ERROR_CODES = {\n cleanup_invalid_input: 'cleanup_invalid_input',\n cleanup_policy_missing: 'cleanup_policy_missing',\n cleanup_job_running: 'cleanup_job_running',\n cleanup_dead_letter_not_found: 'cleanup_dead_letter_not_found',\n cleanup_accounting_drift: 'cleanup_accounting_drift',\n} as const;\n\nexport type CloudCleanupErrorCode =\n (typeof CLOUD_CLEANUP_ERROR_CODES)[keyof typeof CLOUD_CLEANUP_ERROR_CODES];\n\nexport class CloudCleanupError extends Error {\n readonly code: CloudCleanupErrorCode;\n\n constructor(code: CloudCleanupErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'CloudCleanupError';\n this.code = code;\n }\n}\n\nexport interface TenantRetentionPolicyInput {\n readonly policyId: string;\n readonly mailboxAckedRetentionMs: bigint;\n readonly mailboxUnackedRetentionMs: bigint;\n readonly requestReceiptRetentionMs: bigint;\n readonly objectOrphanGraceMs: bigint;\n}\n\nexport interface TenantRetentionPolicy extends TenantRetentionPolicyInput {\n readonly tenantId: TenantId;\n readonly updatedAt: string;\n}\n\nexport type CleanupJobState = 'running' | 'completed' | 'completed_with_errors' | 'failed';\n\nexport interface CloudCleanupResult {\n readonly tenantId: TenantId;\n readonly jobId: string;\n readonly state: CleanupJobState;\n readonly startedAt: string;\n readonly finishedAt?: string;\n readonly mailboxDeletedCount: bigint;\n readonly mailboxExpiredCount: bigint;\n readonly mailboxReleasedBytes: bigint;\n readonly reservationsExpired: bigint;\n readonly ttlRowsDeleted: bigint;\n readonly objectsTombstoned: bigint;\n readonly objectsDeleted: bigint;\n readonly objectReleasedBytes: bigint;\n readonly orphanWitnessesCreated: bigint;\n readonly missingObjects: bigint;\n readonly shapeDrift: bigint;\n readonly invalidObjectKeys: bigint;\n readonly operationErrors: bigint;\n readonly errorMessage?: string;\n}\n\nexport interface DeadLetterQuery {\n readonly deviceId?: string;\n /** Exclusive composite cursor; use the last message from the prior page. */\n readonly after?: DeadLetterRef;\n readonly limit?: number;\n}\n\nexport interface DeadLetterPage {\n readonly messages: readonly MailboxMessage[];\n readonly hasMore: boolean;\n}\n\nexport interface DeadLetterReplayInput {\n readonly deviceId: string;\n readonly seq: number;\n /** Operator-issued idempotency key for the new delivery. */\n readonly replayMessageId: string;\n}\n\nexport interface DeadLetterRef {\n readonly deviceId: string;\n readonly seq: number;\n}\n\nexport interface ObjectUsageRebuildResult {\n readonly committedObjectBytes: bigint;\n readonly objectCount: bigint;\n readonly updatedAt: string;\n}\n\nexport interface PostgresCloudCleanupOptions {\n readonly pool: Pool;\n readonly clock: Clock;\n readonly objectStorage: R2ObjectMaintenance;\n readonly batchSize?: number;\n}\n\nexport interface PostgresCloudMaintenanceOptions {\n readonly pool: Pool;\n readonly clock: Clock;\n readonly objectStorage: Omit<R2BlobStoreOptions, 'objects'>;\n readonly batchSize?: number;\n}\n\ninterface RetentionPolicyRow {\n readonly tenant_id: string;\n readonly policy_id: string;\n readonly mailbox_acked_retention_ms: bigint;\n readonly mailbox_unacked_retention_ms: bigint;\n readonly request_receipt_retention_ms: bigint;\n readonly object_orphan_grace_ms: bigint;\n readonly updated_at: string;\n}\n\ninterface CleanupJobRow {\n readonly tenant_id: string;\n readonly job_id: string;\n readonly state: string;\n readonly started_at: string;\n readonly finished_at: string | null;\n readonly mailbox_deleted_count: bigint;\n readonly mailbox_expired_count: bigint;\n readonly mailbox_released_bytes: bigint;\n readonly reservations_expired: bigint;\n readonly ttl_rows_deleted: bigint;\n readonly objects_tombstoned: bigint;\n readonly objects_deleted: bigint;\n readonly object_released_bytes: bigint;\n readonly orphan_witnesses_created: bigint;\n readonly missing_objects: bigint;\n readonly shape_drift: bigint;\n readonly invalid_object_keys: bigint;\n readonly operation_errors: bigint;\n readonly error_message: string | null;\n}\n\ninterface RetentionResultRow {\n readonly mailbox_deleted_count: bigint;\n readonly mailbox_expired_count: bigint;\n readonly mailbox_released_bytes: bigint;\n readonly usage_accounted: bigint;\n readonly reservations_expired: bigint;\n readonly ttl_rows_deleted: bigint;\n}\n\ninterface ManifestMaintenanceRow {\n readonly hash: string;\n readonly byte_size: bigint;\n readonly content_type: string;\n readonly state: string;\n readonly gc_accounted_bytes: bigint | null;\n readonly gc_accounted_object: boolean | null;\n}\n\ninterface OutboxRow {\n readonly tenant_id: string;\n readonly device_id: string;\n readonly seq: bigint;\n readonly message_id: string;\n readonly body: string;\n readonly body_hash: string;\n readonly byte_size: bigint;\n readonly state: string;\n readonly appended_at: string;\n readonly replay_source_seq: bigint | null;\n}\n\ninterface MutableCounts {\n mailboxDeletedCount: bigint;\n mailboxExpiredCount: bigint;\n mailboxReleasedBytes: bigint;\n reservationsExpired: bigint;\n ttlRowsDeleted: bigint;\n objectsTombstoned: bigint;\n objectsDeleted: bigint;\n objectReleasedBytes: bigint;\n orphanWitnessesCreated: bigint;\n missingObjects: bigint;\n shapeDrift: bigint;\n invalidObjectKeys: bigint;\n operationErrors: bigint;\n}\n\nexport class PostgresCloudCleanup {\n readonly #pool: Pool;\n readonly #clock: Clock;\n readonly #objectStorage: R2ObjectMaintenance;\n readonly #batchSize: number;\n\n constructor(options: PostgresCloudCleanupOptions) {\n this.#pool = options.pool;\n this.#clock = options.clock;\n this.#objectStorage = options.objectStorage;\n this.#batchSize = assertBatchSize(options.batchSize ?? DEFAULT_BATCH_SIZE);\n }\n\n async writeRetentionPolicy(\n tenant: TenantId,\n input: TenantRetentionPolicyInput,\n ): Promise<TenantRetentionPolicy> {\n assertPolicy(input);\n const written = await this.#pool.query<RetentionPolicyRow>(\n `INSERT INTO tenant_retention_policy (\n tenant_id, policy_id, mailbox_acked_retention_ms,\n mailbox_unacked_retention_ms, request_receipt_retention_ms,\n object_orphan_grace_ms, updated_at\n ) VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (tenant_id, policy_id) DO UPDATE\n SET mailbox_acked_retention_ms = EXCLUDED.mailbox_acked_retention_ms,\n mailbox_unacked_retention_ms = EXCLUDED.mailbox_unacked_retention_ms,\n request_receipt_retention_ms = EXCLUDED.request_receipt_retention_ms,\n object_orphan_grace_ms = EXCLUDED.object_orphan_grace_ms,\n updated_at = EXCLUDED.updated_at\n RETURNING tenant_id, policy_id, mailbox_acked_retention_ms,\n mailbox_unacked_retention_ms, request_receipt_retention_ms,\n object_orphan_grace_ms, updated_at`,\n [\n tenant,\n input.policyId,\n input.mailboxAckedRetentionMs,\n input.mailboxUnackedRetentionMs,\n input.requestReceiptRetentionMs,\n input.objectOrphanGraceMs,\n this.#now(),\n ],\n );\n return toPolicy(written.rows[0]!);\n }\n\n async readRetentionPolicy(tenant: TenantId): Promise<TenantRetentionPolicy> {\n return this.#readRetentionPolicy(this.#pool, tenant);\n }\n\n /** Run one bounded tenant maintenance cycle. Completed job ids are replay-safe. */\n async runTenant(tenant: TenantId, jobId: string): Promise<CloudCleanupResult> {\n assertIdentifier(jobId, 'jobId');\n const client = await this.#pool.connect();\n let jobStarted = false;\n try {\n const lock = await client.query<{ readonly locked: boolean }>(\n 'SELECT pg_try_advisory_lock(hashtextextended($1, $2)) AS locked',\n [tenant, ADVISORY_LOCK_NAMESPACE],\n );\n if (lock.rows[0]?.locked !== true) {\n throw new CloudCleanupError(\n 'cleanup_job_running',\n `A cleanup job is already running for tenant ${tenant}.`,\n );\n }\n\n const replay = await this.#startJob(client, tenant, jobId);\n if (replay !== undefined) return replay;\n jobStarted = true;\n\n const policy = await this.#readRetentionPolicy(client, tenant);\n const counts = emptyCounts();\n const retention = await this.#runRetention(client, tenant, policy);\n counts.mailboxDeletedCount = retention.mailbox_deleted_count;\n counts.mailboxExpiredCount = retention.mailbox_expired_count;\n counts.mailboxReleasedBytes = retention.mailbox_released_bytes;\n counts.reservationsExpired = retention.reservations_expired;\n counts.ttlRowsDeleted = retention.ttl_rows_deleted;\n\n const orphanCutoff = cutoff(this.#clock.now(), policy.objectOrphanGraceMs);\n counts.objectsTombstoned = await this.#markTombstones(client, tenant, orphanCutoff);\n\n const deleteCursor = await this.#readCursor(client, tenant, 'delete');\n const pending = await client.query<ManifestMaintenanceRow>(\n `SELECT hash, byte_size, content_type, state,\n gc_accounted_bytes, gc_accounted_object\n FROM object_manifest\n WHERE tenant_id = $1\n AND state = 'delete_pending'\n AND gc_accounted_bytes IS NOT NULL\n AND gc_accounted_object IS NOT NULL\n AND hash > $2\n ORDER BY hash\n LIMIT $3`,\n [tenant, deleteCursor ?? '', this.#batchSize],\n );\n for (const manifest of pending.rows) {\n try {\n await this.#objectStorage.deleteObject(tenant, manifest.hash as ContentHash);\n const released = await this.#settleDeleted(client, tenant, manifest.hash as ContentHash);\n if (released !== undefined) {\n counts.objectsDeleted += 1n;\n counts.objectReleasedBytes += released;\n }\n } catch {\n // The tombstone is the retry record. Preserve it and expose the\n // failure count; a later run repeats DELETE and settlement.\n counts.operationErrors += 1n;\n }\n }\n await this.#advanceLexicalCursor(\n client,\n tenant,\n 'delete',\n pending.rows.at(-1)?.hash,\n pending.rows.length,\n );\n\n await this.#reconcileManifests(client, tenant, counts);\n await this.#reconcileR2(client, tenant, counts);\n\n const state: CleanupJobState =\n counts.operationErrors === 0n ? 'completed' : 'completed_with_errors';\n return this.#finishJob(client, tenant, jobId, state, counts);\n } catch (cause) {\n if (jobStarted) {\n await this.#failJob(client, tenant, jobId, cause).catch(() => {});\n }\n throw cause;\n } finally {\n await client\n .query('SELECT pg_advisory_unlock(hashtextextended($1, $2))', [\n tenant,\n ADVISORY_LOCK_NAMESPACE,\n ])\n .catch(() => {});\n client.release();\n }\n }\n\n async listDeadLetters(tenant: TenantId, query: DeadLetterQuery = {}): Promise<DeadLetterPage> {\n const limit = assertBatchSize(query.limit ?? DEFAULT_BATCH_SIZE);\n if (query.deviceId !== undefined) assertIdentifier(query.deviceId, 'deviceId');\n if (query.after !== undefined) assertDeadLetterRef(query.after);\n if (\n query.deviceId !== undefined &&\n query.after !== undefined &&\n query.deviceId !== query.after.deviceId\n ) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n 'A device-scoped dead-letter cursor must belong to the same device.',\n );\n }\n const listed = await this.#pool.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1\n AND state = 'expired'\n AND ($2::text IS NULL OR device_id = $2::text)\n AND (device_id > $3 OR (device_id = $3 AND seq > $4::bigint))\n ORDER BY device_id, seq\n LIMIT $5`,\n [\n tenant,\n query.deviceId ?? null,\n query.after?.deviceId ?? '',\n query.after?.seq ?? 0,\n limit + 1,\n ],\n );\n return {\n messages: listed.rows.slice(0, limit).map(toMailboxMessage),\n hasMore: listed.rows.length > limit,\n };\n }\n\n /** Clone an expired row to a new monotonic seq. The original remains evidence. */\n async replayDeadLetter(\n tenant: TenantId,\n input: DeadLetterReplayInput,\n ): Promise<MailboxMessage> {\n assertDeadLetterRef(input);\n assertIdentifier(input.replayMessageId, 'replayMessageId');\n const client = await this.#pool.connect();\n let result: MailboxMessage | undefined;\n let rejection: Error | undefined;\n let rollbackAllocation = false;\n try {\n await client.query('BEGIN');\n const originalResult = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND seq = $3::bigint\n AND state = 'expired'\n FOR UPDATE`,\n [tenant, input.deviceId, input.seq],\n );\n const original = originalResult.rows[0];\n if (original === undefined) {\n rejection = deadLetterMissing(input);\n } else {\n const existingResult = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.replayMessageId],\n );\n const existing = existingResult.rows[0];\n if (existing !== undefined) {\n if (!replayMatches(existing, original)) {\n rejection = new CloudCleanupError(\n 'cleanup_invalid_input',\n `Replay id ${input.replayMessageId} already binds a different replay delivery.`,\n );\n } else {\n result = toMailboxMessage(existing);\n }\n } else {\n const entitlement = await client.query<{\n readonly mailbox_limit_bytes: bigint;\n readonly mailbox_bytes: bigint;\n }>(\n `SELECT e.mailbox_limit_bytes, u.mailbox_bytes\n FROM storage_entitlement e\n JOIN storage_usage u ON u.tenant_id = e.tenant_id\n WHERE e.tenant_id = $1\n FOR UPDATE OF e, u`,\n [tenant],\n );\n const capacity = entitlement.rows[0];\n // A different dead-letter row may race on the same operator-issued\n // replay id. The usage lock above is the serialization point; read\n // the idempotency key again after acquiring it so the loser returns\n // the winner instead of surfacing a raw unique violation.\n const serializedExisting = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.replayMessageId],\n );\n const winner = serializedExisting.rows[0];\n if (winner !== undefined) {\n if (!replayMatches(winner, original)) {\n rejection = new CloudCleanupError(\n 'cleanup_invalid_input',\n `Replay id ${input.replayMessageId} already binds a different replay delivery.`,\n );\n } else {\n result = toMailboxMessage(winner);\n }\n } else if (capacity === undefined) {\n rejection = new CloudCleanupError(\n 'cleanup_policy_missing',\n `Tenant ${tenant} has no storage entitlement/usage row.`,\n );\n } else {\n // Hold the same per-device allocator lock as normal mailbox append\n // until the rebound envelope row is inserted. This keeps replay\n // commits ordered with live offers.\n const seq = await allocateMailboxSequence(\n client,\n tenant,\n input.deviceId,\n this.#now(),\n );\n // Normal mailbox append uses this same device lock. Recheck after\n // acquiring it so an append that won between the usage check and\n // allocation resolves through typed idempotency rather than a raw\n // unique violation. Roll back the unused allocation either way.\n const afterAllocation = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND message_id = $3`,\n [tenant, input.deviceId, input.replayMessageId],\n );\n const appendWinner = afterAllocation.rows[0];\n if (appendWinner !== undefined) {\n rollbackAllocation = true;\n if (!replayMatches(appendWinner, original)) {\n rejection = new CloudCleanupError(\n 'cleanup_invalid_input',\n `Replay id ${input.replayMessageId} already binds a different replay delivery.`,\n );\n } else {\n result = toMailboxMessage(appendWinner);\n }\n } else {\n const rebound = materializeReplayBody(original, seq);\n if (capacity.mailbox_bytes + rebound.byteSize > capacity.mailbox_limit_bytes) {\n rejection = new ByokCoreError(\n 'storage_quota_exceeded',\n `Replaying the dead letter would exceed tenant ${tenant}'s mailbox limit.`,\n );\n } else {\n const inserted = await client.query<OutboxRow>(\n `INSERT INTO outbox (${OUTBOX_COLUMNS})\n VALUES ($1, $2, $3::bigint, $4, $5, $6, $7::bigint, 'pending', $8, $9)\n RETURNING ${OUTBOX_COLUMNS}`,\n [\n tenant,\n input.deviceId,\n seq,\n input.replayMessageId,\n rebound.body,\n rebound.bodyHash,\n rebound.byteSize,\n this.#now(),\n original.seq,\n ],\n );\n await client.query(\n `UPDATE storage_usage\n SET mailbox_bytes = mailbox_bytes + $2::bigint, updated_at = $3\n WHERE tenant_id = $1`,\n [tenant, rebound.byteSize, this.#now()],\n );\n result = toMailboxMessage(inserted.rows[0]!);\n }\n }\n }\n }\n }\n if (rejection === undefined && !rollbackAllocation) await client.query('COMMIT');\n else await client.query('ROLLBACK');\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n } finally {\n client.release();\n }\n if (rejection !== undefined) throw rejection;\n return result!;\n }\n\n /** Explicit operator discard. Automatic retention never deletes dead letters. */\n async discardDeadLetter(tenant: TenantId, ref: DeadLetterRef): Promise<MailboxMessage> {\n assertDeadLetterRef(ref);\n const client = await this.#pool.connect();\n let row: OutboxRow | undefined;\n let rejection: Error | undefined;\n try {\n await client.query('BEGIN');\n const existing = await client.query<OutboxRow>(\n `SELECT ${OUTBOX_COLUMNS} FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND seq = $3::bigint\n AND state = 'expired'\n FOR UPDATE`,\n [tenant, ref.deviceId, ref.seq],\n );\n const deadLetter = existing.rows[0];\n const usage = await client.query<{ readonly mailbox_bytes: bigint }>(\n 'SELECT mailbox_bytes FROM storage_usage WHERE tenant_id = $1 FOR UPDATE',\n [tenant],\n );\n if (deadLetter === undefined) {\n rejection = deadLetterMissing(ref);\n } else if (usage.rows[0] === undefined || usage.rows[0].mailbox_bytes < deadLetter.byte_size) {\n rejection = new CloudCleanupError(\n 'cleanup_accounting_drift',\n `Mailbox accounting cannot release dead letter ${ref.deviceId}/${String(ref.seq)}.`,\n );\n } else {\n const removed = await client.query<OutboxRow>(\n `DELETE FROM outbox\n WHERE tenant_id = $1 AND device_id = $2 AND seq = $3::bigint\n AND state = 'expired'\n RETURNING ${OUTBOX_COLUMNS}`,\n [tenant, ref.deviceId, ref.seq],\n );\n await client.query(\n `UPDATE storage_usage\n SET mailbox_bytes = mailbox_bytes - $2::bigint, updated_at = $3\n WHERE tenant_id = $1`,\n [tenant, deadLetter.byte_size, this.#now()],\n );\n row = removed.rows[0];\n }\n if (rejection === undefined) await client.query('COMMIT');\n else await client.query('ROLLBACK');\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n } finally {\n client.release();\n }\n if (rejection !== undefined) throw rejection;\n return toMailboxMessage(row!);\n }\n\n /**\n * Explicit recovery operation: rebuild object accounting from committed\n * Postgres manifests. Reconciliation must run first; R2 LIST is never used as\n * billing authority and inline/mailbox usage is left untouched.\n */\n async rebuildObjectUsage(tenant: TenantId): Promise<ObjectUsageRebuildResult> {\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n const locked = await client.query(\n 'SELECT 1 FROM storage_usage WHERE tenant_id = $1 FOR UPDATE',\n [tenant],\n );\n if (locked.rowCount === 0) {\n throw new CloudCleanupError(\n 'cleanup_policy_missing',\n `Tenant ${tenant} has no storage usage row to rebuild.`,\n );\n }\n const rebuilt = await client.query<{\n readonly committed_object_bytes: bigint;\n readonly object_count: bigint;\n readonly updated_at: string;\n }>(\n `WITH authority AS MATERIALIZED (\n SELECT COALESCE(SUM(byte_size), 0)::bigint AS committed_object_bytes,\n count(*)::bigint AS object_count\n FROM object_manifest\n WHERE tenant_id = $1 AND state = 'committed'\n )\n UPDATE storage_usage u\n SET committed_object_bytes = authority.committed_object_bytes,\n object_count = authority.object_count,\n updated_at = $2\n FROM authority\n WHERE u.tenant_id = $1\n RETURNING u.committed_object_bytes, u.object_count, u.updated_at`,\n [tenant, this.#now()],\n );\n await client.query('COMMIT');\n const row = rebuilt.rows[0]!;\n return {\n committedObjectBytes: row.committed_object_bytes,\n objectCount: row.object_count,\n updatedAt: row.updated_at,\n };\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n } finally {\n client.release();\n }\n }\n\n async #readRetentionPolicy(\n queryable: Pick<Pool, 'query'> | Pick<PoolClient, 'query'>,\n tenant: TenantId,\n ): Promise<TenantRetentionPolicy> {\n const result = await queryable.query<RetentionPolicyRow>(\n `SELECT p.tenant_id, p.policy_id, p.mailbox_acked_retention_ms,\n p.mailbox_unacked_retention_ms, p.request_receipt_retention_ms,\n p.object_orphan_grace_ms, p.updated_at\n FROM storage_entitlement e\n JOIN tenant_retention_policy p\n ON p.tenant_id = e.tenant_id AND p.policy_id = e.retention_policy_id\n WHERE e.tenant_id = $1`,\n [tenant],\n );\n const row = result.rows[0];\n if (row === undefined) {\n throw new CloudCleanupError(\n 'cleanup_policy_missing',\n `Tenant ${tenant} has no retention policy matching its entitlement.`,\n );\n }\n const policy = toPolicy(row);\n assertPolicy(policy);\n return policy;\n }\n\n async #startJob(\n client: PoolClient,\n tenant: TenantId,\n jobId: string,\n ): Promise<CloudCleanupResult | undefined> {\n const now = this.#now();\n const started = await client.query<CleanupJobRow>(\n `INSERT INTO cleanup_job (tenant_id, job_id, kind, state, started_at)\n VALUES ($1, $2, 'tenant_cleanup', 'running', $3)\n ON CONFLICT (tenant_id, job_id) DO UPDATE\n SET state = 'running', started_at = EXCLUDED.started_at,\n finished_at = NULL, error_message = NULL\n WHERE cleanup_job.state IN ('running', 'failed')\n RETURNING ${JOB_COLUMNS}`,\n [tenant, jobId, now],\n );\n if (started.rows[0] !== undefined) return undefined;\n const existing = await this.#readJob(client, tenant, jobId);\n return toCleanupResult(existing);\n }\n\n async #runRetention(\n client: PoolClient,\n tenant: TenantId,\n policy: TenantRetentionPolicy,\n ): Promise<RetentionResultRow> {\n const ackedBefore = cutoff(this.#clock.now(), policy.mailboxAckedRetentionMs);\n const expireBefore = cutoff(this.#clock.now(), policy.mailboxUnackedRetentionMs);\n const receiptBefore = cutoff(this.#clock.now(), policy.requestReceiptRetentionMs);\n const now = this.#now();\n try {\n await client.query('BEGIN');\n const swept = await client.query<RetentionResultRow>(\n `WITH deleted AS (\n DELETE FROM outbox\n WHERE tenant_id = $1 AND state = 'acked' AND appended_at < $2\n RETURNING byte_size\n ), released AS MATERIALIZED (\n SELECT COALESCE(SUM(byte_size), 0)::bigint AS bytes FROM deleted\n ), expired AS (\n UPDATE outbox SET state = 'expired'\n WHERE tenant_id = $1 AND state = 'pending' AND appended_at < $3\n RETURNING 1\n ), reservations AS (\n UPDATE storage_reservation SET state = 'expired', settled_at = $4\n WHERE tenant_id = $1 AND state = 'reserved' AND expires_at <= $4\n RETURNING 1\n ), nonces AS (\n DELETE FROM auth_nonce\n WHERE tenant_id = $1 AND (used OR expires_at <= $4::timestamptz)\n RETURNING 1\n ), pairing_codes AS (\n DELETE FROM pairing_code\n WHERE tenant_id = $1\n AND (redeemed_at IS NOT NULL OR expires_at <= $4::timestamptz)\n RETURNING 1\n ), receipts AS (\n DELETE FROM device_request_receipts\n WHERE tenant_id = $1 AND recorded_at < $5::timestamptz\n RETURNING 1\n ), presence AS (\n DELETE FROM device_presence\n WHERE tenant_id = $1 AND expires_at <= $4\n RETURNING 1\n ), activity AS (\n DELETE FROM activity_tail\n WHERE tenant_id = $1 AND expires_at <= $4\n RETURNING 1\n ), approvals AS (\n DELETE FROM approval_timeline_tail\n WHERE tenant_id = $1 AND expires_at <= $4\n RETURNING 1\n ), accounted AS (\n UPDATE storage_usage u\n SET mailbox_bytes = u.mailbox_bytes - released.bytes, updated_at = $4\n FROM released\n WHERE u.tenant_id = $1 AND u.mailbox_bytes >= released.bytes\n RETURNING released.bytes\n )\n SELECT (SELECT count(*) FROM deleted)::bigint AS mailbox_deleted_count,\n (SELECT count(*) FROM expired)::bigint AS mailbox_expired_count,\n (SELECT bytes FROM released)::bigint AS mailbox_released_bytes,\n (SELECT count(*) FROM accounted)::bigint AS usage_accounted,\n (SELECT count(*) FROM reservations)::bigint AS reservations_expired,\n ((SELECT count(*) FROM nonces)\n + (SELECT count(*) FROM pairing_codes)\n + (SELECT count(*) FROM receipts)\n + (SELECT count(*) FROM presence)\n + (SELECT count(*) FROM activity)\n + (SELECT count(*) FROM approvals))::bigint AS ttl_rows_deleted`,\n [tenant, ackedBefore, expireBefore, now, receiptBefore],\n );\n const result = swept.rows[0]!;\n if (result.usage_accounted !== 1n) {\n throw new CloudCleanupError(\n 'cleanup_accounting_drift',\n `Mailbox accounting cannot release ${String(result.mailbox_released_bytes)} deleted bytes for tenant ${tenant}.`,\n );\n }\n await client.query('COMMIT');\n return result;\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n }\n }\n\n async #markTombstones(\n client: PoolClient,\n tenant: TenantId,\n orphanCutoff: string,\n ): Promise<bigint> {\n try {\n await client.query('BEGIN');\n // Reservation admission uses this same tenant row as its serialization\n // point. Acquiring it before the candidate statement gives that\n // statement a fresh snapshot after every already-started reservation,\n // while later reservations see `delete_pending` and fail closed.\n await client.query(\n 'SELECT 1 FROM storage_entitlement WHERE tenant_id = $1 FOR UPDATE',\n [tenant],\n );\n const marked = await client.query<{ readonly hash: string }>(\n `WITH candidates AS MATERIALIZED (\n SELECT m.tenant_id, m.hash\n FROM object_manifest m\n WHERE m.tenant_id = $1\n AND m.state IN ('pending', 'committed')\n AND m.ref_count = 0\n AND m.updated_at < $2\n AND NOT EXISTS (\n SELECT 1 FROM object_reference r\n WHERE r.tenant_id = m.tenant_id AND r.hash = m.hash\n )\n AND NOT EXISTS (\n SELECT 1 FROM storage_reservation s\n WHERE s.tenant_id = m.tenant_id AND s.content_hash = m.hash\n AND s.state = 'reserved'\n )\n ORDER BY m.updated_at, m.hash\n LIMIT $3\n FOR UPDATE OF m SKIP LOCKED\n )\n UPDATE object_manifest m\n SET gc_accounted_bytes = CASE WHEN m.state = 'committed' THEN m.byte_size ELSE 0 END,\n gc_accounted_object = (m.state = 'committed'),\n state = 'delete_pending', delete_pending_at = $4, updated_at = $4\n FROM candidates c\n WHERE m.tenant_id = c.tenant_id AND m.hash = c.hash\n RETURNING m.hash`,\n [tenant, orphanCutoff, this.#batchSize, this.#now()],\n );\n await client.query('COMMIT');\n return BigInt(marked.rowCount ?? 0);\n } catch (cause) {\n await client.query('ROLLBACK').catch(() => {});\n throw cause;\n }\n }\n\n async #settleDeleted(\n client: PoolClient,\n tenant: TenantId,\n hash: ContentHash,\n ): Promise<bigint | undefined> {\n const settled = await client.query<{\n readonly gc_accounted_bytes: bigint;\n }>(\n `WITH candidate AS MATERIALIZED (\n SELECT m.gc_accounted_bytes, m.gc_accounted_object\n FROM object_manifest m\n JOIN storage_usage u ON u.tenant_id = m.tenant_id\n WHERE m.tenant_id = $1 AND m.hash = $2\n AND m.state = 'delete_pending'\n AND m.ref_count = 0\n AND m.gc_accounted_bytes IS NOT NULL\n AND m.gc_accounted_object IS NOT NULL\n AND NOT EXISTS (\n SELECT 1 FROM object_reference r\n WHERE r.tenant_id = m.tenant_id AND r.hash = m.hash\n )\n AND u.committed_object_bytes >= m.gc_accounted_bytes\n AND u.object_count >= CASE WHEN m.gc_accounted_object THEN 1 ELSE 0 END\n FOR UPDATE OF m, u\n ), moved AS (\n UPDATE object_manifest m\n SET state = 'deleted', updated_at = $3\n FROM candidate c\n WHERE m.tenant_id = $1 AND m.hash = $2 AND m.state = 'delete_pending'\n RETURNING c.gc_accounted_bytes, c.gc_accounted_object\n ), accounted AS (\n UPDATE storage_usage u\n SET committed_object_bytes = u.committed_object_bytes - moved.gc_accounted_bytes,\n object_count = u.object_count - CASE WHEN moved.gc_accounted_object THEN 1 ELSE 0 END,\n updated_at = $3\n FROM moved\n WHERE u.tenant_id = $1\n RETURNING moved.gc_accounted_bytes\n )\n SELECT gc_accounted_bytes FROM accounted`,\n [tenant, hash, this.#now()],\n );\n const row = settled.rows[0];\n if (row !== undefined) return row.gc_accounted_bytes;\n const current = await client.query<{ readonly state: string }>(\n 'SELECT state FROM object_manifest WHERE tenant_id = $1 AND hash = $2',\n [tenant, hash],\n );\n if (current.rows[0]?.state === 'deleted') return undefined;\n throw new CloudCleanupError(\n 'cleanup_accounting_drift',\n `Object ${hash} could not settle its delete tombstone against storage usage.`,\n );\n }\n\n async #reconcileManifests(\n client: PoolClient,\n tenant: TenantId,\n counts: MutableCounts,\n ): Promise<void> {\n const cursor = await this.#readCursor(client, tenant, 'manifest');\n const page = await client.query<ManifestMaintenanceRow>(\n `SELECT hash, byte_size, content_type, state,\n gc_accounted_bytes, gc_accounted_object\n FROM object_manifest\n WHERE tenant_id = $1\n AND state IN ('committed', 'delete_pending')\n AND hash > $2\n ORDER BY hash\n LIMIT $3`,\n [tenant, cursor ?? '', this.#batchSize],\n );\n for (const manifest of page.rows) {\n const observed = await this.#objectStorage.inspectObject(\n tenant,\n manifest.hash as ContentHash,\n );\n if (manifest.state === 'delete_pending') {\n if (observed === undefined) {\n try {\n const released = await this.#settleDeleted(\n client,\n tenant,\n manifest.hash as ContentHash,\n );\n if (released !== undefined) {\n counts.objectsDeleted += 1n;\n counts.objectReleasedBytes += released;\n }\n } catch {\n counts.operationErrors += 1n;\n }\n }\n continue;\n }\n if (observed === undefined) {\n counts.missingObjects += 1n;\n } else if (\n observed.observedByteSize !== manifest.byte_size ||\n observed.observedContentType !== manifest.content_type\n ) {\n counts.shapeDrift += 1n;\n }\n }\n await this.#advanceLexicalCursor(\n client,\n tenant,\n 'manifest',\n page.rows.at(-1)?.hash,\n page.rows.length,\n );\n }\n\n async #reconcileR2(\n client: PoolClient,\n tenant: TenantId,\n counts: MutableCounts,\n ): Promise<void> {\n const cursor = await this.#readCursor(client, tenant, 'r2');\n const page = await this.#objectStorage.listTenantObjects(\n tenant,\n cursor ?? undefined,\n this.#batchSize,\n );\n for (const object of page.objects) {\n if (object.hash === undefined) {\n counts.invalidObjectKeys += 1n;\n continue;\n }\n const manifest = await client.query<{ readonly state: string }>(\n 'SELECT state FROM object_manifest WHERE tenant_id = $1 AND hash = $2',\n [tenant, object.hash],\n );\n const state = manifest.rows[0]?.state;\n if (state !== undefined && state !== 'deleted') continue;\n const observed = await this.#objectStorage.inspectObject(tenant, object.hash);\n if (observed === undefined) continue;\n const witnessed = await client.query(\n `INSERT INTO object_manifest (\n tenant_id, hash, byte_size, content_type, state, ref_count,\n created_at, updated_at, delete_pending_at,\n gc_accounted_bytes, gc_accounted_object\n ) VALUES ($1, $2, $3, $4, 'pending', 0, $5, $5, NULL, NULL, NULL)\n ON CONFLICT (tenant_id, hash) DO UPDATE\n SET byte_size = EXCLUDED.byte_size,\n content_type = EXCLUDED.content_type,\n state = 'pending', ref_count = 0,\n created_at = EXCLUDED.created_at,\n updated_at = EXCLUDED.updated_at,\n delete_pending_at = NULL,\n gc_accounted_bytes = NULL,\n gc_accounted_object = NULL\n WHERE object_manifest.state = 'deleted'\n RETURNING 1`,\n [\n tenant,\n object.hash,\n observed.observedByteSize,\n observed.observedContentType,\n this.#now(),\n ],\n );\n counts.orphanWitnessesCreated += BigInt(witnessed.rowCount ?? 0);\n }\n if (page.nextContinuationToken === undefined) {\n await this.#clearCursor(client, tenant, 'r2');\n } else {\n await this.#writeCursor(client, tenant, 'r2', page.nextContinuationToken);\n }\n }\n\n async #advanceLexicalCursor(\n client: PoolClient,\n tenant: TenantId,\n kind: string,\n lastValue: string | undefined,\n rowCount: number,\n ): Promise<void> {\n if (lastValue === undefined || rowCount < this.#batchSize) {\n await this.#clearCursor(client, tenant, kind);\n } else {\n await this.#writeCursor(client, tenant, kind, lastValue);\n }\n }\n\n async #readCursor(\n client: PoolClient,\n tenant: TenantId,\n kind: string,\n ): Promise<string | null> {\n const result = await client.query<{ readonly cursor_value: string | null }>(\n 'SELECT cursor_value FROM gc_cursor WHERE tenant_id = $1 AND cursor_kind = $2',\n [tenant, kind],\n );\n return result.rows[0]?.cursor_value ?? null;\n }\n\n async #writeCursor(\n client: PoolClient,\n tenant: TenantId,\n kind: string,\n value: string,\n ): Promise<void> {\n await client.query(\n `INSERT INTO gc_cursor (tenant_id, cursor_kind, cursor_value, updated_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (tenant_id, cursor_kind) DO UPDATE\n SET cursor_value = EXCLUDED.cursor_value, updated_at = EXCLUDED.updated_at`,\n [tenant, kind, value, this.#now()],\n );\n }\n\n async #clearCursor(client: PoolClient, tenant: TenantId, kind: string): Promise<void> {\n await client.query(\n 'DELETE FROM gc_cursor WHERE tenant_id = $1 AND cursor_kind = $2',\n [tenant, kind],\n );\n }\n\n async #finishJob(\n client: PoolClient,\n tenant: TenantId,\n jobId: string,\n state: CleanupJobState,\n counts: MutableCounts,\n ): Promise<CloudCleanupResult> {\n const finished = await client.query<CleanupJobRow>(\n `UPDATE cleanup_job SET\n state = $3, finished_at = $4,\n mailbox_deleted_count = $5, mailbox_expired_count = $6,\n mailbox_released_bytes = $7, reservations_expired = $8,\n ttl_rows_deleted = $9,\n objects_tombstoned = $10, objects_deleted = $11,\n object_released_bytes = $12, orphan_witnesses_created = $13,\n missing_objects = $14, shape_drift = $15,\n invalid_object_keys = $16, operation_errors = $17,\n error_message = NULL\n WHERE tenant_id = $1 AND job_id = $2\n RETURNING ${JOB_COLUMNS}`,\n [\n tenant,\n jobId,\n state,\n this.#now(),\n counts.mailboxDeletedCount,\n counts.mailboxExpiredCount,\n counts.mailboxReleasedBytes,\n counts.reservationsExpired,\n counts.ttlRowsDeleted,\n counts.objectsTombstoned,\n counts.objectsDeleted,\n counts.objectReleasedBytes,\n counts.orphanWitnessesCreated,\n counts.missingObjects,\n counts.shapeDrift,\n counts.invalidObjectKeys,\n counts.operationErrors,\n ],\n );\n return toCleanupResult(finished.rows[0]!);\n }\n\n async #failJob(\n client: PoolClient,\n tenant: TenantId,\n jobId: string,\n cause: unknown,\n ): Promise<void> {\n const message = (cause instanceof Error ? cause.message : String(cause)).slice(0, 2000);\n await client.query(\n `UPDATE cleanup_job\n SET state = 'failed', finished_at = $3, error_message = $4\n WHERE tenant_id = $1 AND job_id = $2`,\n [tenant, jobId, this.#now(), message],\n );\n }\n\n async #readJob(client: PoolClient, tenant: TenantId, jobId: string): Promise<CleanupJobRow> {\n const result = await client.query<CleanupJobRow>(\n `SELECT ${JOB_COLUMNS} FROM cleanup_job WHERE tenant_id = $1 AND job_id = $2`,\n [tenant, jobId],\n );\n return result.rows[0]!;\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n\n/** Build the maintenance composition against the same Postgres/R2 authority. */\nexport function createPostgresCloudMaintenance(\n options: PostgresCloudMaintenanceOptions,\n): PostgresCloudCleanup {\n const objectStorage = new R2ObjectMaintenanceStore(options.objectStorage);\n return new PostgresCloudCleanup({\n pool: options.pool,\n clock: options.clock,\n objectStorage,\n ...(options.batchSize === undefined ? {} : { batchSize: options.batchSize }),\n });\n}\n\nconst JOB_COLUMNS = [\n 'tenant_id',\n 'job_id',\n 'state',\n 'started_at',\n 'finished_at',\n 'mailbox_deleted_count',\n 'mailbox_expired_count',\n 'mailbox_released_bytes',\n 'reservations_expired',\n 'ttl_rows_deleted',\n 'objects_tombstoned',\n 'objects_deleted',\n 'object_released_bytes',\n 'orphan_witnesses_created',\n 'missing_objects',\n 'shape_drift',\n 'invalid_object_keys',\n 'operation_errors',\n 'error_message',\n].join(', ');\n\nfunction emptyCounts(): MutableCounts {\n return {\n mailboxDeletedCount: 0n,\n mailboxExpiredCount: 0n,\n mailboxReleasedBytes: 0n,\n reservationsExpired: 0n,\n ttlRowsDeleted: 0n,\n objectsTombstoned: 0n,\n objectsDeleted: 0n,\n objectReleasedBytes: 0n,\n orphanWitnessesCreated: 0n,\n missingObjects: 0n,\n shapeDrift: 0n,\n invalidObjectKeys: 0n,\n operationErrors: 0n,\n };\n}\n\nfunction toPolicy(row: RetentionPolicyRow): TenantRetentionPolicy {\n return {\n tenantId: tenantId(row.tenant_id),\n policyId: row.policy_id,\n mailboxAckedRetentionMs: row.mailbox_acked_retention_ms,\n mailboxUnackedRetentionMs: row.mailbox_unacked_retention_ms,\n requestReceiptRetentionMs: row.request_receipt_retention_ms,\n objectOrphanGraceMs: row.object_orphan_grace_ms,\n updatedAt: row.updated_at,\n };\n}\n\nfunction toCleanupResult(row: CleanupJobRow): CloudCleanupResult {\n return {\n tenantId: tenantId(row.tenant_id),\n jobId: row.job_id,\n state: row.state as CleanupJobState,\n startedAt: row.started_at,\n ...(row.finished_at === null ? {} : { finishedAt: row.finished_at }),\n mailboxDeletedCount: row.mailbox_deleted_count,\n mailboxExpiredCount: row.mailbox_expired_count,\n mailboxReleasedBytes: row.mailbox_released_bytes,\n reservationsExpired: row.reservations_expired,\n ttlRowsDeleted: row.ttl_rows_deleted,\n objectsTombstoned: row.objects_tombstoned,\n objectsDeleted: row.objects_deleted,\n objectReleasedBytes: row.object_released_bytes,\n orphanWitnessesCreated: row.orphan_witnesses_created,\n missingObjects: row.missing_objects,\n shapeDrift: row.shape_drift,\n invalidObjectKeys: row.invalid_object_keys,\n operationErrors: row.operation_errors,\n ...(row.error_message === null ? {} : { errorMessage: row.error_message }),\n };\n}\n\nfunction toMailboxMessage(row: OutboxRow): MailboxMessage {\n return {\n tenantId: tenantId(row.tenant_id),\n deviceId: row.device_id,\n seq: Number(row.seq),\n messageId: row.message_id,\n body: row.body,\n bodyHash: row.body_hash as ContentHash,\n byteSize: row.byte_size,\n state: row.state as MailboxMessageState,\n appendedAt: row.appended_at,\n };\n}\n\ninterface ReplayBody {\n readonly body: string;\n readonly bodyHash: ContentHash;\n readonly byteSize: bigint;\n}\n\nfunction materializeReplayBody(original: OutboxRow, seq: number): ReplayBody {\n try {\n const envelope = decodeEnvelope(original.body);\n if (!isServerToDaemonType(envelope.type)) {\n throw new Error(`Envelope type ${envelope.type} is not server-to-daemon.`);\n }\n const rebound = EnvelopeSchema.parse({ ...envelope, seq });\n const body = encodeEnvelope(rebound);\n const bytes = new TextEncoder().encode(body);\n return {\n body,\n bodyHash: contentHash(`sha256:${createHash('sha256').update(bytes).digest('hex')}`),\n byteSize: BigInt(bytes.length),\n };\n } catch (cause) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n `Dead letter ${original.device_id}/${String(original.seq)} is not a replayable server-to-daemon envelope.`,\n { cause },\n );\n }\n}\n\nfunction replayMatches(row: OutboxRow, original: OutboxRow): boolean {\n if (row.replay_source_seq !== original.seq) return false;\n const expected = materializeReplayBody(original, Number(row.seq));\n return (\n row.body === expected.body &&\n row.body_hash === expected.bodyHash &&\n row.byte_size === expected.byteSize\n );\n}\n\nfunction assertPolicy(input: TenantRetentionPolicyInput): void {\n assertIdentifier(input.policyId, 'policyId');\n for (const [field, value] of [\n ['mailboxAckedRetentionMs', input.mailboxAckedRetentionMs],\n ['mailboxUnackedRetentionMs', input.mailboxUnackedRetentionMs],\n ['requestReceiptRetentionMs', input.requestReceiptRetentionMs],\n ['objectOrphanGraceMs', input.objectOrphanGraceMs],\n ] as const) {\n if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n `${field} must be a non-negative duration no larger than Number.MAX_SAFE_INTEGER milliseconds.`,\n );\n }\n }\n}\n\nfunction assertBatchSize(value: number): number {\n if (!Number.isInteger(value) || value < 1 || value > MAX_BATCH_SIZE) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n `batchSize/limit must be a whole number in [1, ${String(MAX_BATCH_SIZE)}].`,\n );\n }\n return value;\n}\n\nfunction assertIdentifier(value: string, field: string): void {\n if (value.length === 0 || value.length > 256 || value.trim() !== value) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n `${field} must be a non-empty, unpadded string no longer than 256 characters.`,\n );\n }\n}\n\nfunction assertDeadLetterRef(ref: DeadLetterRef): void {\n assertIdentifier(ref.deviceId, 'deviceId');\n if (!Number.isSafeInteger(ref.seq) || ref.seq < 1) {\n throw new CloudCleanupError(\n 'cleanup_invalid_input',\n 'A dead-letter seq must be a positive safe integer.',\n );\n }\n}\n\nfunction cutoff(now: Date, durationMs: bigint): string {\n return new Date(now.getTime() - Number(durationMs)).toISOString();\n}\n\nfunction deadLetterMissing(ref: DeadLetterRef): CloudCleanupError {\n return new CloudCleanupError(\n 'cleanup_dead_letter_not_found',\n `Expired mailbox row ${ref.deviceId}/${String(ref.seq)} was not found.`,\n );\n}\n","/**\n * Package-owned, resumable tenant erasure for the Node maintenance surface.\n *\n * Cleanup's policy/cursor/accounting lifecycle is intentionally not reused.\n * Here the durable operation receipt is the authority: it records the opaque\n * R2 cursor before any SQL is touched, carries a short CAS lease while one\n * caller advances bounded work, and survives every product-data deletion.\n */\nimport { randomUUID } from 'node:crypto';\nimport { tenantId, type Clock, type TenantId } from '@byok-sdk/core';\nimport type { Pool } from 'pg';\nimport {\n R2ObjectMaintenanceStore,\n type R2BlobStoreOptions,\n type R2ObjectMaintenance,\n} from './stores/r2-blobs';\n\nconst DEFAULT_BATCH_SIZE = 100;\nconst DEFAULT_MAX_PAGES_PER_RUN = 10;\nconst DEFAULT_LEASE_MS = 30_000;\nconst MAX_BATCH_SIZE = 1_000;\nconst MAX_PAGES_PER_RUN = 100;\nconst MAX_LEASE_MS = 5 * 60_000;\n\n/** Every tenant-owned table as of 0013, in child-before-parent deletion order. */\nexport const TENANT_ERASURE_TABLES = [\n 'object_reference',\n 'object_manifest',\n 'storage_reservation',\n 'storage_usage',\n 'storage_entitlement',\n 'gc_cursor',\n 'cleanup_job',\n 'tenant_retention_policy',\n 'skill_pack_file',\n 'skill_pack',\n 'approval_timeline_tail',\n 'activity_tail',\n 'attested_record',\n 'board_item',\n 'tenant_stream',\n 'outbox',\n 'agent_egress_event',\n 'device_request_receipts',\n 'proof_request_receipt',\n 'task',\n 'device_presence',\n 'device_assertion_replay',\n 'device_stream',\n 'inbound_dedup',\n 'auth_nonce',\n 'pairing_code',\n 'device',\n] as const;\n\nconst TENANT_ERASURE_TABLE_SET = new Set<string>(TENANT_ERASURE_TABLES);\n\nexport const TENANT_ERASURE_ERROR_CODES = {\n tenant_erasure_invalid_input: 'tenant_erasure_invalid_input',\n tenant_erasure_schema_drift: 'tenant_erasure_schema_drift',\n tenant_erasure_object_key_invalid: 'tenant_erasure_object_key_invalid',\n tenant_erasure_storage_failure: 'tenant_erasure_storage_failure',\n tenant_erasure_database_failure: 'tenant_erasure_database_failure',\n tenant_erasure_cas_lost: 'tenant_erasure_cas_lost',\n} as const;\n\nexport type TenantErasureErrorCode =\n (typeof TENANT_ERASURE_ERROR_CODES)[keyof typeof TENANT_ERASURE_ERROR_CODES];\n\nexport class TenantErasureError extends Error {\n readonly code: TenantErasureErrorCode;\n\n constructor(code: TenantErasureErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'TenantErasureError';\n this.code = code;\n }\n}\n\nexport type TenantErasureStatus = 'outstanding' | 'partial' | 'completed';\n\nexport interface TenantErasureReadback {\n readonly status: TenantErasureStatus;\n readonly tenantId: TenantId;\n readonly operationId: string;\n readonly startedAt: string;\n readonly updatedAt: string;\n readonly completedAt?: string;\n readonly r2Complete: boolean;\n readonly sqlTableIndex: number;\n readonly r2ObjectsDeleted: bigint;\n readonly sqlRowsDeleted: bigint;\n /** A closed, audit-safe class. Remote messages and object names are never retained. */\n readonly errorCode?: TenantErasureErrorCode;\n}\n\nexport interface TenantErasureConflict {\n readonly status: 'conflict';\n readonly tenantId: TenantId;\n readonly operationId: string;\n readonly activeOperationId: string;\n}\n\nexport type TenantErasureResult = TenantErasureReadback | TenantErasureConflict;\n\nexport interface PostgresTenantErasureOptions {\n /** A Node direct-DSN pool. The host owns pool lifetime and write quiescence. */\n readonly pool: Pool;\n readonly clock: Clock;\n readonly objectStorage: R2ObjectMaintenance;\n /** ListObjectsV2 and one SQL DELETE use this bound; valid range is 1..1000. */\n readonly batchSize?: number;\n /** Maximum R2/SQL pages one operator invocation may advance; valid range is 1..100. */\n readonly maxPagesPerRun?: number;\n /** Crash-recovery lease; a retry may take an expired lease using the operation CAS. */\n readonly leaseMs?: number;\n}\n\nexport interface PostgresTenantErasureCompositionOptions {\n readonly pool: Pool;\n readonly clock: Clock;\n readonly objectStorage: Omit<R2BlobStoreOptions, 'objects'>;\n readonly batchSize?: number;\n readonly maxPagesPerRun?: number;\n readonly leaseMs?: number;\n}\n\ninterface OperationRow {\n readonly tenant_id: string;\n readonly operation_id: string;\n readonly state: 'running' | 'completed';\n readonly revision: bigint;\n readonly lease_token: string | null;\n readonly lease_expires_at: Date | null;\n readonly r2_cursor: string | null;\n readonly r2_complete: boolean;\n readonly sql_table_index: number;\n readonly r2_objects_deleted: bigint;\n readonly sql_rows_deleted: bigint;\n readonly started_at: Date;\n readonly updated_at: Date;\n readonly completed_at: Date | null;\n readonly last_error_code: string | null;\n}\n\nconst OPERATION_COLUMNS = [\n 'tenant_id',\n 'operation_id',\n 'state',\n 'revision',\n 'lease_token',\n 'lease_expires_at',\n 'r2_cursor',\n 'r2_complete',\n 'sql_table_index',\n 'r2_objects_deleted',\n 'sql_rows_deleted',\n 'started_at',\n 'updated_at',\n 'completed_at',\n 'last_error_code',\n].join(', ');\n\n/**\n * The Node-only erasure authority. It has no raw-table or raw-key API: the\n * static inventory and canonical R2 adapter are the only deletion authority.\n */\nexport class PostgresTenantErasure {\n readonly #pool: Pool;\n readonly #clock: Clock;\n readonly #objectStorage: R2ObjectMaintenance;\n readonly #batchSize: number;\n readonly #maxPagesPerRun: number;\n readonly #leaseMs: number;\n\n constructor(options: PostgresTenantErasureOptions) {\n this.#pool = options.pool;\n this.#clock = options.clock;\n this.#objectStorage = options.objectStorage;\n this.#batchSize = assertBoundedWhole(options.batchSize ?? DEFAULT_BATCH_SIZE, 'batchSize', MAX_BATCH_SIZE);\n this.#maxPagesPerRun = assertBoundedWhole(\n options.maxPagesPerRun ?? DEFAULT_MAX_PAGES_PER_RUN,\n 'maxPagesPerRun',\n MAX_PAGES_PER_RUN,\n );\n this.#leaseMs = assertBoundedWhole(options.leaseMs ?? DEFAULT_LEASE_MS, 'leaseMs', MAX_LEASE_MS);\n }\n\n /** Read a durable operation receipt without advancing it. */\n async readTenantErasure(tenant: TenantId, operationId: string): Promise<TenantErasureReadback | undefined> {\n assertOperationId(operationId);\n const row = await this.#readOperation(tenant, operationId);\n return row === undefined ? undefined : toReadback(row);\n }\n\n /**\n * Advance one bounded operation slice. Calls with a completed id replay its\n * receipt; another running id for the same tenant gets a typed conflict.\n */\n async eraseTenant(tenant: TenantId, operationId: string): Promise<TenantErasureResult> {\n assertOperationId(operationId);\n\n // A completed receipt is frozen operator evidence, not tenant product\n // data. Replay must therefore remain stable even when a later migration\n // makes the product-table inventory unsafe for every new/running erase.\n // No running or absent operation passes this branch: those still assert\n // the exact live inventory before acquiring or advancing a lease.\n let existing: OperationRow | undefined;\n try {\n existing = await this.#readOperation(tenant, operationId);\n } catch (cause) {\n throw databaseFailure('reading tenant erasure operation', cause);\n }\n if (existing?.state === 'completed') return toReadback(existing);\n\n await this.#assertSchemaInventory();\n\n let row: OperationRow;\n try {\n const opened = await this.#openOperation(tenant, operationId);\n if ('status' in opened) return opened;\n row = opened;\n } catch (cause) {\n throw databaseFailure('opening tenant erasure operation', cause);\n }\n\n if (row.state === 'completed') return toReadback(row);\n\n const leaseToken = randomUUID();\n let claimed: OperationRow | undefined;\n try {\n claimed = await this.#claim(tenant, operationId, row.revision, leaseToken);\n if (claimed === undefined) return await this.#readConflictOrReceipt(tenant, operationId);\n\n for (let page = 0; page < this.#maxPagesPerRun; page += 1) {\n if (!claimed.r2_complete) {\n claimed = await this.#eraseR2Page(tenant, claimed, leaseToken);\n continue;\n }\n if (claimed.sql_table_index < TENANT_ERASURE_TABLES.length) {\n claimed = await this.#eraseSqlPage(tenant, claimed, leaseToken);\n continue;\n }\n claimed = await this.#verifyAndComplete(tenant, claimed, leaseToken);\n if (claimed.state === 'completed') return toReadback(claimed);\n }\n\n return toReadback(await this.#release(tenant, operationId, claimed.revision, leaseToken));\n } catch (cause) {\n if (claimed === undefined) throw databaseFailure('claiming tenant erasure operation', cause);\n const code = cause instanceof TenantErasureError\n ? cause.code\n : TENANT_ERASURE_ERROR_CODES.tenant_erasure_database_failure;\n try {\n return toReadback(await this.#recordPartial(tenant, operationId, claimed.revision, leaseToken, code));\n } catch (recordCause) {\n throw databaseFailure('recording tenant erasure partial outcome', recordCause);\n }\n }\n }\n\n async #assertSchemaInventory(): Promise<void> {\n const found = await this.#pool.query<{ readonly relname: string }>(\n `SELECT t.relname\n FROM pg_class t\n JOIN pg_namespace n ON n.oid = t.relnamespace\n WHERE n.nspname = current_schema()\n AND t.relkind = 'r'\n AND t.relname NOT IN ('byok_schema_migration', 'tenant_erasure_operation')\n ORDER BY t.relname`,\n );\n const actual = new Set(found.rows.map((row) => row.relname));\n const missing = TENANT_ERASURE_TABLES.filter((name) => !actual.has(name));\n const unexpected = [...actual].filter((name) => !TENANT_ERASURE_TABLE_SET.has(name));\n if (missing.length === 0 && unexpected.length === 0 && actual.size === TENANT_ERASURE_TABLES.length) return;\n throw new TenantErasureError(\n 'tenant_erasure_schema_drift',\n `Tenant erasure inventory drift: missing=[${missing.join(',')}], unexpected=[${unexpected.join(',')}].`,\n );\n }\n\n async #openOperation(\n tenant: TenantId,\n operationId: string,\n ): Promise<OperationRow | TenantErasureConflict> {\n const now = this.#clock.now();\n try {\n await this.#pool.query(\n `INSERT INTO tenant_erasure_operation (\n tenant_id, operation_id, state, started_at, updated_at\n ) VALUES ($1, $2, 'running', $3, $3)\n ON CONFLICT (tenant_id, operation_id) DO NOTHING`,\n [tenant, operationId, now],\n );\n } catch (cause) {\n if (postgresCode(cause) !== '23505') throw cause;\n return this.#conflict(tenant, operationId);\n }\n\n const own = await this.#readOperation(tenant, operationId);\n if (own !== undefined) return own;\n // The only possible winner is another active operation. If it finished in\n // the intervening instant, retrying is an operator decision, not a silent\n // second erase under an id that never acquired a receipt.\n return this.#conflict(tenant, operationId);\n }\n\n async #claim(\n tenant: TenantId,\n operationId: string,\n revision: bigint,\n leaseToken: string,\n ): Promise<OperationRow | undefined> {\n const now = this.#clock.now();\n const leaseExpiresAt = new Date(now.getTime() + this.#leaseMs);\n const result = await this.#pool.query<OperationRow>(\n `UPDATE tenant_erasure_operation\n SET lease_token = $1,\n lease_expires_at = $2,\n revision = revision + 1,\n updated_at = $3,\n last_error_code = NULL\n WHERE tenant_id = $4\n AND operation_id = $5\n AND state = 'running'\n AND revision = $6::bigint\n AND (lease_token IS NULL OR lease_expires_at <= $3)\n RETURNING ${OPERATION_COLUMNS}`,\n [leaseToken, leaseExpiresAt, now, tenant, operationId, revision],\n );\n return result.rows[0];\n }\n\n async #eraseR2Page(tenant: TenantId, row: OperationRow, leaseToken: string): Promise<OperationRow> {\n let page;\n try {\n page = await this.#objectStorage.listTenantObjects(\n tenant,\n row.r2_cursor ?? undefined,\n this.#batchSize,\n );\n } catch (cause) {\n throw storageFailure('listing the tenant R2 namespace', cause);\n }\n\n for (const object of page.objects) {\n if (object.hash === undefined) {\n throw new TenantErasureError(\n 'tenant_erasure_object_key_invalid',\n 'Tenant R2 namespace contains a non-canonical object key; erasure refused before SQL deletion.',\n );\n }\n try {\n await this.#objectStorage.deleteObject(tenant, object.hash);\n } catch (cause) {\n throw storageFailure('deleting a tenant R2 object', cause);\n }\n }\n\n return this.#casUpdate(tenant, row.operation_id, row.revision, leaseToken,\n `r2_cursor = $1,\n r2_complete = $2,\n r2_objects_deleted = r2_objects_deleted + $3::bigint`,\n [page.nextContinuationToken ?? null, page.nextContinuationToken === undefined, page.objects.length],\n );\n }\n\n async #eraseSqlPage(tenant: TenantId, row: OperationRow, leaseToken: string): Promise<OperationRow> {\n const table = TENANT_ERASURE_TABLES[row.sql_table_index];\n if (table === undefined) {\n throw new TenantErasureError('tenant_erasure_cas_lost', 'Tenant erasure SQL progress escaped its static inventory.');\n }\n let deleted: bigint;\n try {\n const result = await this.#pool.query<{ readonly deleted: bigint }>(\n `WITH deleted AS (\n DELETE FROM ${table}\n WHERE ctid IN (\n SELECT ctid FROM ${table}\n WHERE tenant_id = $1\n LIMIT $2\n )\n RETURNING 1\n )\n SELECT count(*)::bigint AS deleted FROM deleted`,\n [tenant, this.#batchSize],\n );\n deleted = result.rows[0]!.deleted;\n } catch (cause) {\n throw databaseFailure(`deleting tenant rows from ${table}`, cause);\n }\n\n const nextTableIndex = deleted < BigInt(this.#batchSize)\n ? row.sql_table_index + 1\n : row.sql_table_index;\n return this.#casUpdate(tenant, row.operation_id, row.revision, leaseToken,\n `sql_table_index = $1,\n sql_rows_deleted = sql_rows_deleted + $2::bigint`,\n [nextTableIndex, deleted],\n );\n }\n\n async #verifyAndComplete(tenant: TenantId, row: OperationRow, leaseToken: string): Promise<OperationRow> {\n try {\n const r2 = await this.#objectStorage.listTenantObjects(tenant, undefined, 1);\n if (r2.objects.length > 0) {\n return this.#casUpdate(tenant, row.operation_id, row.revision, leaseToken,\n 'r2_cursor = NULL, r2_complete = false',\n [],\n );\n }\n } catch (cause) {\n throw storageFailure('verifying the tenant R2 namespace is empty', cause);\n }\n\n for (const table of TENANT_ERASURE_TABLES) {\n let present: boolean;\n try {\n const result = await this.#pool.query<{ readonly present: boolean }>(\n `SELECT EXISTS (SELECT 1 FROM ${table} WHERE tenant_id = $1) AS present`,\n [tenant],\n );\n present = result.rows[0]!.present;\n } catch (cause) {\n throw databaseFailure(`verifying tenant rows in ${table}`, cause);\n }\n if (present) {\n return this.#casUpdate(tenant, row.operation_id, row.revision, leaseToken,\n 'sql_table_index = 0',\n [],\n );\n }\n }\n\n const now = this.#clock.now();\n return this.#casUpdate(tenant, row.operation_id, row.revision, leaseToken,\n `state = 'completed',\n completed_at = $1,\n lease_token = NULL,\n lease_expires_at = NULL,\n last_error_code = NULL`,\n [now],\n false,\n );\n }\n\n async #release(tenant: TenantId, operationId: string, revision: bigint, leaseToken: string): Promise<OperationRow> {\n return this.#casUpdate(tenant, operationId, revision, leaseToken,\n 'lease_token = NULL, lease_expires_at = NULL',\n [],\n false,\n );\n }\n\n async #recordPartial(\n tenant: TenantId,\n operationId: string,\n revision: bigint,\n leaseToken: string,\n errorCode: TenantErasureErrorCode,\n ): Promise<OperationRow> {\n return this.#casUpdate(tenant, operationId, revision, leaseToken,\n `lease_token = NULL,\n lease_expires_at = NULL,\n last_error_code = $1`,\n [errorCode],\n false,\n );\n }\n\n async #casUpdate(\n tenant: TenantId,\n operationId: string,\n revision: bigint,\n leaseToken: string,\n setClause: string,\n setValues: readonly unknown[],\n refreshLease = true,\n ): Promise<OperationRow> {\n const now = this.#clock.now();\n const values = [...setValues];\n let refreshClause = '';\n if (refreshLease) {\n values.push(new Date(now.getTime() + this.#leaseMs));\n refreshClause = `, lease_expires_at = $${String(values.length)}`;\n }\n values.push(now, tenant, operationId, revision, leaseToken);\n const updatedAtIndex = values.length - 4;\n const tenantIndex = values.length - 3;\n const operationIndex = values.length - 2;\n const revisionIndex = values.length - 1;\n const leaseIndex = values.length;\n const result = await this.#pool.query<OperationRow>(\n `UPDATE tenant_erasure_operation\n SET ${setClause}${refreshClause},\n revision = revision + 1,\n updated_at = $${String(updatedAtIndex)}\n WHERE tenant_id = $${String(tenantIndex)}\n AND operation_id = $${String(operationIndex)}\n AND state = 'running'\n AND revision = $${String(revisionIndex)}::bigint\n AND lease_token = $${String(leaseIndex)}\n RETURNING ${OPERATION_COLUMNS}`,\n values,\n );\n const row = result.rows[0];\n if (row !== undefined) return row;\n throw new TenantErasureError(\n 'tenant_erasure_cas_lost',\n 'Tenant erasure operation no longer owns its durable progress lease.',\n );\n }\n\n async #readOperation(tenant: TenantId, operationId: string): Promise<OperationRow | undefined> {\n const result = await this.#pool.query<OperationRow>(\n `SELECT ${OPERATION_COLUMNS}\n FROM tenant_erasure_operation\n WHERE tenant_id = $1 AND operation_id = $2`,\n [tenant, operationId],\n );\n return result.rows[0];\n }\n\n async #readConflictOrReceipt(tenant: TenantId, operationId: string): Promise<TenantErasureResult> {\n const own = await this.#readOperation(tenant, operationId);\n if (own?.state === 'completed') return toReadback(own);\n // The same id is idempotent only after its receipt is terminal. While a\n // caller holds the CAS lease, a second concurrent caller receives the\n // same typed conflict a distinct operation id receives; it must not be\n // handed an \"outstanding\" result that suggests it owns progress.\n if (\n own !== undefined &&\n own.lease_token !== null &&\n own.lease_expires_at !== null &&\n own.lease_expires_at > this.#clock.now()\n ) {\n return { status: 'conflict', tenantId: tenant, operationId, activeOperationId: own.operation_id };\n }\n if (own !== undefined) return toReadback(own);\n return this.#conflict(tenant, operationId);\n }\n\n async #conflict(tenant: TenantId, operationId: string): Promise<TenantErasureConflict> {\n const active = await this.#pool.query<{ readonly operation_id: string }>(\n `SELECT operation_id\n FROM tenant_erasure_operation\n WHERE tenant_id = $1 AND state = 'running'`,\n [tenant],\n );\n const winner = active.rows[0];\n if (winner === undefined) {\n throw new TenantErasureError(\n 'tenant_erasure_cas_lost',\n 'Tenant erasure operation changed while acquiring its receipt; retry with the same operation id.',\n );\n }\n return { status: 'conflict', tenantId: tenant, operationId, activeOperationId: winner.operation_id };\n }\n}\n\n/** Build the Node maintenance composition against the same direct Postgres/R2 authorities. */\nexport function createPostgresTenantErasure(\n options: PostgresTenantErasureCompositionOptions,\n): PostgresTenantErasure {\n return new PostgresTenantErasure({\n pool: options.pool,\n clock: options.clock,\n objectStorage: new R2ObjectMaintenanceStore(options.objectStorage),\n ...(options.batchSize === undefined ? {} : { batchSize: options.batchSize }),\n ...(options.maxPagesPerRun === undefined ? {} : { maxPagesPerRun: options.maxPagesPerRun }),\n ...(options.leaseMs === undefined ? {} : { leaseMs: options.leaseMs }),\n });\n}\n\nfunction toReadback(row: OperationRow): TenantErasureReadback {\n const status: TenantErasureStatus = row.state === 'completed'\n ? 'completed'\n : row.last_error_code === null\n ? 'outstanding'\n : 'partial';\n return {\n status,\n tenantId: tenantId(row.tenant_id),\n operationId: row.operation_id,\n startedAt: row.started_at.toISOString(),\n updatedAt: row.updated_at.toISOString(),\n ...(row.completed_at === null ? {} : { completedAt: row.completed_at.toISOString() }),\n r2Complete: row.r2_complete,\n sqlTableIndex: row.sql_table_index,\n r2ObjectsDeleted: row.r2_objects_deleted,\n sqlRowsDeleted: row.sql_rows_deleted,\n ...(row.last_error_code === null ? {} : { errorCode: row.last_error_code as TenantErasureErrorCode }),\n };\n}\n\nfunction assertOperationId(operationId: string): void {\n if (operationId.length === 0 || operationId.length > 256 || operationId.trim() !== operationId) {\n throw new TenantErasureError(\n 'tenant_erasure_invalid_input',\n 'operationId must be a non-empty, unpadded string no longer than 256 characters.',\n );\n }\n}\n\nfunction assertBoundedWhole(value: number, field: string, max: number): number {\n if (!Number.isSafeInteger(value) || value < 1 || value > max) {\n throw new TenantErasureError(\n 'tenant_erasure_invalid_input',\n `${field} must be a whole number in [1, ${String(max)}].`,\n );\n }\n return value;\n}\n\nfunction postgresCode(cause: unknown): string | undefined {\n return typeof cause === 'object' && cause !== null && 'code' in cause && typeof cause.code === 'string'\n ? cause.code\n : undefined;\n}\n\nfunction storageFailure(action: string, cause: unknown): TenantErasureError {\n return new TenantErasureError(\n 'tenant_erasure_storage_failure',\n `Tenant erasure could not finish ${action}; no SQL progress was advanced.`,\n { cause },\n );\n}\n\nfunction databaseFailure(action: string, cause: unknown): TenantErasureError {\n return cause instanceof TenantErasureError\n ? cause\n : new TenantErasureError(\n 'tenant_erasure_database_failure',\n `Tenant erasure could not finish ${action}; retry with the same operation id.`,\n { cause },\n );\n}\n"]}
|