@byok-sdk/cloud-dataplane 0.8.0 → 0.9.0-rc.1
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 +341 -7
- package/dist/index.js.map +1 -1
- package/dist/runtime.d.ts +2 -2
- package/dist/runtime.js +338 -7
- package/dist/runtime.js.map +1 -1
- package/dist/sql/0014_agent_memory_projection.sql +134 -0
- package/dist/stores/agent-memory-projection.d.ts +34 -0
- package/dist/stores/index.d.ts +2 -0
- package/dist/tenant-erasure.d.ts +2 -2
- package/package.json +4 -4
package/dist/runtime.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/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"],"names":["ByokCoreError","SELECT_COLUMNS","toReceipt","assertCanonicalTimestamp","toTail","ByokCloudError","toRecord","DEFAULT_LIST_LIMIT","CoreConflictError","RECORD_COLUMNS","toBody","bodyColumns","response"],"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,M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AAK,EAAG;AACvC,MAAA,MAAM,MAAA,CAAO,KAAA;AAAA,QACX,CAAA;AAAA;AAAA;AAAA;AAAA,4CAAA,CAAA;AAAA,QAKA,CAAC,MAAA,EAAQ,IAAA,EAAM,IAAA,CAAK,MAAM;AAAA,OAC5B;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,uBAAA,CACJ,MAAA,EACA,MAAA,EACA,KAAA,EACe;AACf,IAAA,IAAI,UAAU,EAAA,EAAI;AAChB,MAAA,MAAM,OAAA,GAAU,MAAM,MAAA,CAAO,KAAA;AAAA,QAC3B,CAAA;AAAA;AAAA;AAAA;AAAA,oBAAA,CAAA;AAAA,QAKA,CAAC,MAAA,EAAQ,KAAA,EAAO,IAAA,CAAK,MAAM;AAAA,OAC7B;AACA,MAAA,IAAI,QAAQ,QAAA,KAAa,CAAA,EAAG,MAAM,IAAI,MAAM,yCAAyC,CAAA;AAAA,IACvF;AAAA,EACF;AAAA,EAEA,IAAA,GAAe;AACb,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,EAAI,CAAE,WAAA,EAAY;AAAA,EACvC;AACF","file":"runtime.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"]}
|
|
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/agent-memory-projection.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"],"names":["ByokCoreError","SELECT_COLUMNS","toReceipt","assertCanonicalTimestamp","toTail","ByokCloudError","toRecord","DEFAULT_LIST_LIMIT","CoreConflictError","RECORD_COLUMNS","RECEIPT_COLUMNS","toBody","bodyColumns","response"],"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,EA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,UACX,CAAA;AAAA,qFAAA,CAAA;AAAA,UAEA,CAAC,MAAA,EAAQ,KAAA,CAAM,MAAA,CAAO,IAAA,CAAK,MAAM,KAAK;AAAA,SACxC;AAAA,MACF;AAAA,IACF;AACA,IAAA,KAAA,MAAW,QAAQ,CAAC,GAAG,QAAQ,CAAA,CAAE,MAAK,EAAG;AACvC,MAAA,MAAM,MAAA,CAAO,KAAA;AAAA,QACX,CAAA;AAAA;AAAA;AAAA;AAAA,4CAAA,CAAA;AAAA,QAKA,CAAC,MAAA,EAAQ,IAAA,EAAM,IAAA,CAAK,MAAM;AAAA,OAC5B;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,uBAAA,CACJ,MAAA,EACA,MAAA,EACA,KAAA,EACe;AACf,IAAA,IAAI,UAAU,EAAA,EAAI;AAChB,MAAA,MAAM,OAAA,GAAU,MAAM,MAAA,CAAO,KAAA;AAAA,QAC3B,CAAA;AAAA;AAAA;AAAA;AAAA,oBAAA,CAAA;AAAA,QAKA,CAAC,MAAA,EAAQ,KAAA,EAAO,IAAA,CAAK,MAAM;AAAA,OAC7B;AACA,MAAA,IAAI,QAAQ,QAAA,KAAa,CAAA,EAAG,MAAM,IAAI,MAAM,yCAAyC,CAAA;AAAA,IACvF;AAAA,EACF;AAAA,EAEA,IAAA,GAAe;AACb,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,EAAI,CAAE,WAAA,EAAY;AAAA,EACvC;AACF","file":"runtime.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","/**\n * Postgres authority for the optional, one-way hosted Agent-memory projection.\n *\n * The only stored body is the latest accepted redacted snapshot. Immutable\n * receipt rows retain the complete non-body replay binding and byte metering so\n * an old exact retry is still provable after the head advances or an epoch is\n * superseded. Neither table has a raw-source hash, cwd, path, or audit body.\n */\nimport {\n type AgentMemoryProjectionCommitInput,\n type AgentMemoryProjectionEraseResult,\n type AgentMemoryProjectionReceipt,\n type AgentMemoryProjectionStore,\n ByokCloudError,\n type CloudCrypto,\n} from '@byok-sdk/cloud';\nimport {\n AgentMemoryProjectionMutationSchema,\n AgentMemoryProjectionEraseResultSchema,\n AgentMemoryProjectionReceiptSchema,\n AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE,\n AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES,\n} from '@byok-sdk/protocol';\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { Pool, PoolClient } from 'pg';\n\nexport interface PostgresAgentMemoryProjectionStoreOptions {\n readonly pool: Pool;\n readonly clock: Clock;\n /** The same Worker-safe crypto authority used by the hosting cloud composition. */\n readonly crypto: Pick<CloudCrypto, 'randomUuid' | 'sha256'>;\n}\n\ninterface ProjectionHeadRow {\n readonly tenant_id: string;\n readonly agent_id: string;\n readonly writer_epoch: number;\n readonly source_seq: number;\n}\ninterface EraseFenceRow { readonly next_writer_epoch: number; }\n\ninterface MeteringReceiptRow {\n readonly tenant_id: string;\n readonly agent_id: string;\n readonly writer_epoch: number;\n readonly source_seq: number;\n readonly mutation_id: string;\n readonly device_id: string;\n readonly task_id: string;\n readonly agent_profile_revision: string;\n readonly session_ref: string;\n readonly runtime_id: string;\n readonly grant_ref: string;\n readonly policy_revision: string;\n readonly redacted_hash: string;\n readonly redacted_byte_count: number;\n readonly metering_receipt_id: string;\n readonly recorded_at: Date;\n}\n\nconst RECEIPT_COLUMNS = [\n 'tenant_id',\n 'agent_id',\n 'writer_epoch',\n 'source_seq',\n 'mutation_id',\n 'device_id',\n 'task_id',\n 'agent_profile_revision',\n 'session_ref',\n 'runtime_id',\n 'grant_ref',\n 'policy_revision',\n 'redacted_hash',\n 'redacted_byte_count',\n 'metering_receipt_id',\n 'recorded_at',\n].join(', ');\n\n/**\n * A transaction-scoped Postgres projection store. The per-source advisory lock\n * closes the empty-head race without creating a separate lock row or making a\n * tenant-wide writer bottleneck; erase takes the identical lock.\n */\nexport class PostgresAgentMemoryProjectionStore implements AgentMemoryProjectionStore {\n readonly #pool: Pool;\n readonly #clock: Clock;\n readonly #crypto: Pick<CloudCrypto, 'randomUuid' | 'sha256'>;\n\n constructor(options: PostgresAgentMemoryProjectionStoreOptions) {\n this.#pool = options.pool;\n this.#clock = options.clock;\n this.#crypto = options.crypto;\n }\n\n async commit(input: AgentMemoryProjectionCommitInput): Promise<AgentMemoryProjectionReceipt> {\n const mutation = AgentMemoryProjectionMutationSchema.parse(input.mutation);\n await this.#assertRedactedSnapshot(\n input.redactedBytes,\n mutation.snapshot.redactedBytes,\n mutation.snapshot.redactedByteCount,\n mutation.snapshot.redactedHash,\n );\n\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n await lockAgentMutation(client, input.tenantId, mutation.agentRef.agentId);\n\n const receipt = await this.#readReceipt(client, input.tenantId, mutation.agentRef.agentId, mutation.writerEpoch, mutation.sourceSeq);\n if (receipt !== undefined) {\n if (!sameReceiptBinding(receipt, input, mutation)) {\n throw replayMismatch();\n }\n await client.query('COMMIT');\n return toReceipt(receipt, 'idempotent');\n }\n\n // A mutation id is a distinct immutable identity within one epoch. Check\n // it before sequence acceptance so SQL uniqueness is never the behavior\n // oracle and a reused id cannot masquerade as a database failure.\n const existingMutation = await this.#readReceiptByMutationId(\n client,\n input.tenantId,\n mutation.agentRef.agentId,\n mutation.writerEpoch,\n mutation.mutationId,\n );\n if (existingMutation !== undefined) throw replayMismatch();\n\n const head = await this.#readHeadForUpdate(client, input.tenantId, mutation.agentRef.agentId);\n const fence = await this.#readEraseFenceForUpdate(client, input.tenantId, mutation.agentRef.agentId);\n assertNextMutation(head, fence, mutation.writerEpoch, mutation.sourceSeq);\n\n const now = this.#clock.now();\n const meteringReceiptId = this.#crypto.randomUuid();\n await client.query(\n `INSERT INTO agent_memory_projection_metering_receipt (${RECEIPT_COLUMNS})\n VALUES ($1, $2, $3, $4, $5::uuid, $6, $7, $8, $9, $10, $11, $12, $13, $14::integer, $15::uuid, $16)`,\n [\n input.tenantId,\n mutation.agentRef.agentId,\n mutation.writerEpoch,\n mutation.sourceSeq,\n mutation.mutationId,\n input.deviceId,\n mutation.taskId,\n mutation.agentRef.profileRevision,\n mutation.sessionRef,\n mutation.runtimeId,\n mutation.grantRef,\n mutation.policyRevision,\n mutation.snapshot.redactedHash,\n mutation.snapshot.redactedByteCount,\n meteringReceiptId,\n now,\n ],\n );\n\n await client.query(\n `INSERT INTO agent_memory_projection_head (\n tenant_id, agent_id, writer_epoch, source_seq, mutation_id,\n device_id, task_id, agent_profile_revision, session_ref, runtime_id,\n grant_ref, policy_revision, redacted_hash, redacted_snapshot,\n redacted_byte_count, committed_at\n ) VALUES (\n $1, $2, $3, $4, $5::uuid,\n $6, $7, $8, $9, $10,\n $11, $12, $13, decode($14, 'base64'),\n $15::integer, $16\n )\n ON CONFLICT (tenant_id, agent_id) DO UPDATE SET\n writer_epoch = EXCLUDED.writer_epoch,\n source_seq = EXCLUDED.source_seq,\n mutation_id = EXCLUDED.mutation_id,\n device_id = EXCLUDED.device_id,\n task_id = EXCLUDED.task_id,\n agent_profile_revision = EXCLUDED.agent_profile_revision,\n session_ref = EXCLUDED.session_ref,\n runtime_id = EXCLUDED.runtime_id,\n grant_ref = EXCLUDED.grant_ref,\n policy_revision = EXCLUDED.policy_revision,\n redacted_hash = EXCLUDED.redacted_hash,\n redacted_snapshot = EXCLUDED.redacted_snapshot,\n redacted_byte_count = EXCLUDED.redacted_byte_count,\n committed_at = EXCLUDED.committed_at`,\n [\n input.tenantId,\n mutation.agentRef.agentId,\n mutation.writerEpoch,\n mutation.sourceSeq,\n mutation.mutationId,\n input.deviceId,\n mutation.taskId,\n mutation.agentRef.profileRevision,\n mutation.sessionRef,\n mutation.runtimeId,\n mutation.grantRef,\n mutation.policyRevision,\n mutation.snapshot.redactedHash,\n toBase64(input.redactedBytes),\n mutation.snapshot.redactedByteCount,\n now,\n ],\n );\n\n await client.query('COMMIT');\n return AgentMemoryProjectionReceiptSchema.parse({\n outcome: 'accepted',\n tenantId: input.tenantId,\n deviceId: input.deviceId,\n taskId: mutation.taskId,\n agentRef: mutation.agentRef,\n sessionRef: mutation.sessionRef,\n runtimeId: mutation.runtimeId,\n grantRef: mutation.grantRef,\n writerEpoch: mutation.writerEpoch,\n sourceSeq: mutation.sourceSeq,\n mutationId: mutation.mutationId,\n policyRevision: mutation.policyRevision,\n redactedHash: mutation.snapshot.redactedHash,\n redactedByteCount: mutation.snapshot.redactedByteCount,\n metering: {\n meteringReceiptId,\n acceptedRedactedBytes: mutation.snapshot.redactedByteCount,\n recordedAt: now.toISOString(),\n },\n });\n } catch (cause) {\n await rollback(client);\n throw cause;\n } finally {\n client.release();\n }\n }\n\n /** Delete body/receipts but retain a body-free epoch fence under one source lock. */\n async erase(input: { readonly tenantId: TenantId; readonly agentId: string }): Promise<AgentMemoryProjectionEraseResult> {\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n await lockAgentMutation(client, input.tenantId, input.agentId);\n const head = await this.#readHeadForUpdate(client, input.tenantId, input.agentId);\n const fence = await this.#readEraseFenceForUpdate(client, input.tenantId, input.agentId);\n const nextWriterEpoch = Math.max(fence?.next_writer_epoch ?? 1, (head?.writer_epoch ?? 0) + 1);\n if (nextWriterEpoch > AGENT_MEMORY_PROJECTION_MAX_ORDERING_VALUE) {\n throw new ByokCloudError('agent_memory_projection_epoch_exhausted', 'The memory projection writerEpoch cannot advance after erase.');\n }\n await client.query(\n 'DELETE FROM agent_memory_projection_metering_receipt WHERE tenant_id = $1 AND agent_id = $2',\n [input.tenantId, input.agentId],\n );\n await client.query(\n 'DELETE FROM agent_memory_projection_head WHERE tenant_id = $1 AND agent_id = $2',\n [input.tenantId, input.agentId],\n );\n await client.query(\n `INSERT INTO agent_memory_projection_erase_fence (tenant_id, agent_id, next_writer_epoch, erased_at)\n VALUES ($1, $2, $3::integer, $4)\n ON CONFLICT (tenant_id, agent_id) DO UPDATE SET\n next_writer_epoch = GREATEST(agent_memory_projection_erase_fence.next_writer_epoch, EXCLUDED.next_writer_epoch),\n erased_at = EXCLUDED.erased_at`,\n [input.tenantId, input.agentId, nextWriterEpoch, this.#clock.now()],\n );\n await client.query('COMMIT');\n return AgentMemoryProjectionEraseResultSchema.parse({ nextWriterEpoch });\n } catch (cause) {\n await rollback(client);\n throw cause;\n } finally {\n client.release();\n }\n }\n\n async #assertRedactedSnapshot(\n bytes: Uint8Array,\n portableBody: string,\n byteCount: number,\n expectedHash: string,\n ): Promise<void> {\n if (bytes.byteLength !== byteCount || bytes.byteLength > AGENT_MEMORY_PROJECTION_MAX_REDACTED_BYTES) {\n throw hashMismatch('Decoded redacted snapshot bytes do not match redactedByteCount.');\n }\n if (portableBody !== toBase64Url(bytes)) {\n throw hashMismatch('Decoded redacted snapshot bytes do not match the portable redactedBytes body.');\n }\n if (await this.#crypto.sha256(bytes) !== expectedHash) {\n throw hashMismatch('Decoded redacted snapshot bytes do not match redactedHash.');\n }\n }\n\n async #readHeadForUpdate(client: PoolClient, tenant: TenantId, agentId: string): Promise<ProjectionHeadRow | undefined> {\n const result = await client.query<ProjectionHeadRow>(\n `SELECT tenant_id, agent_id, writer_epoch, source_seq\n FROM agent_memory_projection_head\n WHERE tenant_id = $1 AND agent_id = $2\n FOR UPDATE`,\n [tenant, agentId],\n );\n return result.rows[0];\n }\n\n async #readEraseFenceForUpdate(client: PoolClient, tenant: TenantId, agentId: string): Promise<EraseFenceRow | undefined> {\n const result = await client.query<EraseFenceRow>(\n `SELECT next_writer_epoch\n FROM agent_memory_projection_erase_fence\n WHERE tenant_id = $1 AND agent_id = $2\n FOR UPDATE`,\n [tenant, agentId],\n );\n return result.rows[0];\n }\n\n async #readReceipt(\n client: PoolClient,\n tenant: TenantId,\n agentId: string,\n writerEpoch: number,\n sourceSeq: number,\n ): Promise<MeteringReceiptRow | undefined> {\n const result = await client.query<MeteringReceiptRow>(\n `SELECT ${RECEIPT_COLUMNS}\n FROM agent_memory_projection_metering_receipt\n WHERE tenant_id = $1 AND agent_id = $2 AND writer_epoch = $3 AND source_seq = $4`,\n [tenant, agentId, writerEpoch, sourceSeq],\n );\n return result.rows[0];\n }\n\n async #readReceiptByMutationId(\n client: PoolClient,\n tenant: TenantId,\n agentId: string,\n writerEpoch: number,\n mutationId: string,\n ): Promise<MeteringReceiptRow | undefined> {\n const result = await client.query<MeteringReceiptRow>(\n `SELECT ${RECEIPT_COLUMNS}\n FROM agent_memory_projection_metering_receipt\n WHERE tenant_id = $1 AND agent_id = $2 AND writer_epoch = $3 AND mutation_id = $4::uuid`,\n [tenant, agentId, writerEpoch, mutationId],\n );\n return result.rows[0];\n }\n}\n\n/** Build the runtime-safe Postgres implementation of the optional cloud port. */\nexport function createPostgresAgentMemoryProjectionStore(\n options: PostgresAgentMemoryProjectionStoreOptions,\n): AgentMemoryProjectionStore {\n return new PostgresAgentMemoryProjectionStore(options);\n}\n\nfunction assertNextMutation(\n head: ProjectionHeadRow | undefined,\n fence: EraseFenceRow | undefined,\n writerEpoch: number,\n sourceSeq: number,\n): void {\n if (fence !== undefined && writerEpoch < fence.next_writer_epoch) {\n throw erasedEpoch();\n }\n if (head === undefined) {\n if (sourceSeq !== 1) throw sequenceGap('The first memory projection mutation must use sourceSeq 1.');\n return;\n }\n if (writerEpoch < head.writer_epoch) {\n throw new ByokCloudError('agent_memory_projection_stale_epoch', 'The memory projection writerEpoch is stale.');\n }\n if (writerEpoch > head.writer_epoch) {\n if (sourceSeq !== 1) throw sequenceGap('A new memory projection writerEpoch must start at sourceSeq 1.');\n return;\n }\n if (sourceSeq !== head.source_seq + 1) {\n throw sequenceGap('A memory projection mutation must advance sourceSeq exactly by one.');\n }\n}\n\nfunction sameReceiptBinding(\n receipt: MeteringReceiptRow,\n input: AgentMemoryProjectionCommitInput,\n mutation: ReturnType<typeof AgentMemoryProjectionMutationSchema.parse>,\n): boolean {\n return (\n receipt.tenant_id === input.tenantId &&\n receipt.agent_id === mutation.agentRef.agentId &&\n receipt.device_id === input.deviceId &&\n receipt.task_id === mutation.taskId &&\n receipt.agent_profile_revision === mutation.agentRef.profileRevision &&\n receipt.session_ref === mutation.sessionRef &&\n receipt.runtime_id === mutation.runtimeId &&\n receipt.grant_ref === mutation.grantRef &&\n receipt.writer_epoch === mutation.writerEpoch &&\n receipt.source_seq === mutation.sourceSeq &&\n receipt.mutation_id === mutation.mutationId &&\n receipt.policy_revision === mutation.policyRevision &&\n receipt.redacted_hash === mutation.snapshot.redactedHash &&\n receipt.redacted_byte_count === mutation.snapshot.redactedByteCount\n );\n}\n\nfunction toReceipt(row: MeteringReceiptRow, outcome: 'accepted' | 'idempotent'): AgentMemoryProjectionReceipt {\n return AgentMemoryProjectionReceiptSchema.parse({\n outcome,\n tenantId: row.tenant_id,\n deviceId: row.device_id,\n taskId: row.task_id,\n agentRef: { agentId: row.agent_id, profileRevision: row.agent_profile_revision },\n sessionRef: row.session_ref,\n runtimeId: row.runtime_id,\n grantRef: row.grant_ref,\n writerEpoch: row.writer_epoch,\n sourceSeq: row.source_seq,\n mutationId: row.mutation_id,\n policyRevision: row.policy_revision,\n redactedHash: row.redacted_hash,\n redactedByteCount: row.redacted_byte_count,\n metering: {\n meteringReceiptId: row.metering_receipt_id,\n acceptedRedactedBytes: row.redacted_byte_count,\n recordedAt: row.recorded_at.toISOString(),\n },\n });\n}\n\nasync function lockAgentMutation(client: PoolClient, tenant: TenantId, agentId: string): Promise<void> {\n await client.query(\n `SELECT pg_advisory_xact_lock(\n hashtextextended(length($1)::text || ':' || $1 || length($2)::text || ':' || $2, 0)\n )`,\n [tenant, agentId],\n );\n}\n\nfunction hashMismatch(message: string): ByokCloudError {\n return new ByokCloudError('agent_memory_projection_hash_mismatch', message);\n}\n\nfunction sequenceGap(message: string): ByokCloudError {\n return new ByokCloudError('agent_memory_projection_sequence_gap', message);\n}\n\nfunction erasedEpoch(): ByokCloudError {\n return new ByokCloudError('agent_memory_projection_erased_epoch', 'The memory projection writerEpoch was erased and cannot be replayed.');\n}\n\nfunction replayMismatch(): ByokCloudError {\n return new ByokCloudError(\n 'agent_memory_projection_replay_mismatch',\n 'A memory projection epoch and source sequence already names a different immutable mutation.',\n );\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n const chunks: string[] = [];\n for (let offset = 0; offset < bytes.length; offset += 32 * 1024) {\n chunks.push(String.fromCharCode(...bytes.subarray(offset, offset + 32 * 1024)));\n }\n return btoa(chunks.join(''));\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n return toBase64(bytes).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');\n}\n\nasync function rollback(client: PoolClient): Promise<void> {\n try {\n await client.query('ROLLBACK');\n } catch {}\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 {\n PostgresAgentMemoryProjectionStore,\n createPostgresAgentMemoryProjectionStore,\n} from './agent-memory-projection';\nexport type { PostgresAgentMemoryProjectionStoreOptions } from './agent-memory-projection';\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"]}
|