@byok-sdk/core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +11 -0
- package/dist/attestation.d.ts +153 -0
- package/dist/blob.d.ts +116 -0
- package/dist/board.d.ts +120 -0
- package/dist/capabilities.d.ts +38 -0
- package/dist/errors.d.ts +87 -0
- package/dist/in-memory/blob.d.ts +24 -0
- package/dist/in-memory/board.d.ts +26 -0
- package/dist/in-memory/clock.d.ts +12 -0
- package/dist/in-memory/index.d.ts +23 -0
- package/dist/in-memory/mailbox.d.ts +12 -0
- package/dist/in-memory/presence.d.ts +16 -0
- package/dist/in-memory/quota.d.ts +18 -0
- package/dist/in-memory/truth.d.ts +11 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.js +1498 -0
- package/dist/index.js.map +1 -0
- package/dist/mailbox.d.ts +115 -0
- package/dist/ports-contract.d.ts +26 -0
- package/dist/presence.d.ts +95 -0
- package/dist/principals.d.ts +54 -0
- package/dist/quota.d.ts +189 -0
- package/dist/stores.d.ts +54 -0
- package/dist/tenant.d.ts +48 -0
- package/dist/time.d.ts +24 -0
- package/dist/truth.d.ts +109 -0
- package/package.json +49 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/tenant.ts","../src/principals.ts","../src/time.ts","../src/mailbox.ts","../src/board.ts","../src/truth.ts","../src/presence.ts","../src/blob.ts","../src/quota.ts","../src/capabilities.ts","../src/stores.ts","../src/ports-contract.ts","../src/attestation.ts","../src/in-memory/presence.ts","../src/in-memory/board.ts","../src/in-memory/mailbox.ts","../src/in-memory/blob.ts","../src/in-memory/quota.ts","../src/in-memory/truth.ts","../src/in-memory/clock.ts","../src/in-memory/index.ts"],"names":["parts","z","DEFAULT_LIST_LIMIT"],"mappings":";;;AA+BO,IAAM,gBAAA,GAAmB;AAAA;AAAA,EAE9B,iBAAA,EAAmB,mBAAA;AAAA,EACn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,kBAAA,CAAmB,KAAK,CAAA;AAAA,IACnC,QAAA,EAAU,IAAI,qBAAA,CAAsB,KAAK,CAAA;AAAA,IACzC,QAAA,EAAU,IAAI,qBAAA,CAAsB,KAAK,CAAA;AAAA,IACzC,OAAA;AAAA,IACA,KAAA,EAAO,IAAI,kBAAA,CAAmB,KAAA,EAAO,OAAO;AAAA,GAC9C;AACA,EAAA,OAAO,EAAE,QAAQ,KAAA,EAAM;AACzB;AAGO,SAAS,sCAAA,GAGd;AACA,EAAA,MAAM,QAAQ,kBAAA,EAAmB;AACjC,EAAA,OAAO,EAAE,QAAQ,wBAAA,CAAyB,EAAE,OAAO,CAAA,CAAE,QAAQ,KAAA,EAAM;AACrE","file":"index.js","sourcesContent":["/**\n * The one error taxonomy for `@byok-sdk/core`.\n *\n * Two rules the rest of the package is built around:\n *\n * 1. **One class, code-based branching.** Consumers switch on `error.code`, not\n * on class identity — the same idiom `@byok-sdk/keys` uses. A composition that\n * maps core errors onto HTTP does it with a code table, so adding a code is\n * an additive change instead of a new `instanceof` chain everywhere.\n * 2. **Every conflict carries the current snapshot.** A CAS failure that\n * reports only \"conflict\" forces the caller into a second round trip and\n * invites last-write-wins retries. {@link CoreConflictError} therefore\n * carries `current` — the authoritative state the caller lost to — plus the\n * `observedAt` instant it was read at.\n *\n * This module imports nothing. It is the graph sink: `quota.ts` narrows\n * {@link StorageErrorCode} out of this union and maps it to HTTP status, and\n * every port module documents which codes it can raise. That keeps the code\n * list in one place while letting each domain own its own status mapping.\n */\n\n/**\n * Every error code this package can raise.\n *\n * Codes are stable strings. Two groups are additionally **wire-stable** — a\n * composition is expected to surface them verbatim to clients, so renaming one\n * is a breaking change:\n *\n * - `terminal_conflict` (§12.6.4, HTTP 409)\n * - the five `storage_*` codes (§12.7.7, see `quota.ts`)\n */\nexport const CORE_ERROR_CODES = {\n // identity + content addressing\n tenant_id_invalid: 'tenant_id_invalid',\n content_hash_invalid: 'content_hash_invalid',\n\n // caller-supplied instants (see `time.ts`)\n timestamp_not_canonical: 'timestamp_not_canonical',\n\n // capability declaration (ADR-010)\n capability_declaration_invalid: 'capability_declaration_invalid',\n capability_unavailable: 'capability_unavailable',\n\n // device proof (§12.6.3)\n proof_envelope_invalid: 'proof_envelope_invalid',\n proof_canonicalization_failed: 'proof_canonicalization_failed',\n\n // mailbox (§12.7.3)\n mailbox_message_not_found: 'mailbox_message_not_found',\n mailbox_cursor_regression: 'mailbox_cursor_regression',\n\n // board coordination (§12.3)\n board_item_not_found: 'board_item_not_found',\n board_item_exists: 'board_item_exists',\n board_transition_invalid: 'board_transition_invalid',\n board_status_conflict: 'board_status_conflict',\n board_claim_conflict: 'board_claim_conflict',\n board_not_held: 'board_not_held',\n\n // truth records (§12.3, §12.6.4)\n truth_record_not_found: 'truth_record_not_found',\n terminal_conflict: 'terminal_conflict',\n truth_revision_conflict: 'truth_revision_conflict',\n\n // presence + activity hints (§12.3)\n activity_capacity_invalid: 'activity_capacity_invalid',\n activity_batch_invalid: 'activity_batch_invalid',\n hint_ttl_invalid: 'hint_ttl_invalid',\n hint_rate_limited: 'hint_rate_limited',\n\n // object manifest (§12.7.4, §12.7.8)\n object_not_found: 'object_not_found',\n object_state_invalid: 'object_state_invalid',\n\n // storage entitlement / usage / reservation (§12.7.6-12.7.7)\n storage_entitlement_missing: 'storage_entitlement_missing',\n storage_entitlement_version_conflict: 'storage_entitlement_version_conflict',\n storage_reservation_not_found: 'storage_reservation_not_found',\n storage_object_too_large: 'storage_object_too_large',\n storage_quota_exceeded: 'storage_quota_exceeded',\n storage_reservation_expired: 'storage_reservation_expired',\n storage_integrity_mismatch: 'storage_integrity_mismatch',\n storage_write_suspended: 'storage_write_suspended',\n} as const;\n\nexport type CoreErrorCode = (typeof CORE_ERROR_CODES)[keyof typeof CORE_ERROR_CODES];\n\n/** Base error for every failure this package raises. */\nexport class ByokCoreError extends Error {\n public readonly code: CoreErrorCode;\n\n constructor(code: CoreErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ByokCoreError';\n this.code = code;\n }\n}\n\n/**\n * A compare-and-set failure.\n *\n * `current` is the authoritative state at the moment the write was rejected —\n * the board item whose status moved, the terminal record already committed, the\n * entitlement row at a newer version. The caller re-decides against it; the\n * store never merges (§12.3: \"不做 silent last-write-wins\", §12.6.4: 不覆写第一份事实).\n */\nexport class CoreConflictError<TCurrent> extends ByokCoreError {\n public readonly current: TCurrent;\n public readonly observedAt: string;\n\n constructor(\n code: CoreErrorCode,\n message: string,\n current: TCurrent,\n observedAt: string,\n options?: ErrorOptions,\n ) {\n super(code, message, options);\n this.name = 'CoreConflictError';\n this.current = current;\n this.observedAt = observedAt;\n }\n}\n\n/** Narrows an unknown thrown value to a core error, optionally to one code. */\nexport function isCoreError(value: unknown, code?: CoreErrorCode): value is ByokCoreError {\n if (!(value instanceof ByokCoreError)) return false;\n return code === undefined || value.code === code;\n}\n\n/** Narrows an unknown thrown value to a conflict error carrying a snapshot. */\nexport function isCoreConflictError<TCurrent>(\n value: unknown,\n code?: CoreErrorCode,\n): value is CoreConflictError<TCurrent> {\n if (!(value instanceof CoreConflictError)) return false;\n return code === undefined || value.code === code;\n}\n","/**\n * Tenant identity — layer 1 of the six-layer isolation model\n * (`docs/architecture/sdk-architecture.md` §12.6.2).\n *\n * `TenantId` is a branded string and this module is the **only** place that may\n * produce one: every other module receives a `TenantId` it cannot forge without\n * calling {@link tenantId}. The brand carries no runtime value — it exists so a\n * bare `string` (a path segment, a claim from an unverified proof, a\n * device-supplied query parameter) can never silently slide into a store port's\n * first parameter.\n *\n * `src/__tests__/constraints.test.ts` greps the package for `as TenantId`: this\n * file and test fixtures are the only allowed sites. A module that needs a\n * `TenantId` takes one as a parameter or mints it here.\n */\nimport { ByokCoreError } from './errors';\n\n/**\n * A validated tenant identifier.\n *\n * Nominal by construction: structurally a `string`, but the phantom brand makes\n * it unassignable from an arbitrary string. Assignment the other way\n * (`TenantId` → `string`) stays legal on purpose, so composition code can pass\n * it as a SQL parameter or key prefix without a cast.\n */\nexport type TenantId = string & { readonly __byokTenantId: unique symbol };\n\n/**\n * Upper bound on tenant id length. Not a security boundary — a bound so a\n * pathological id cannot become an unbounded key prefix inside a store.\n */\nexport const TENANT_ID_MAX_LENGTH = 200;\n\n/**\n * Separator for flat composite keys. `NUL` cannot appear in a tenant id that a\n * control plane can express in a URL, a header, or a SQL identifier, and\n * {@link tenantId} rejects it outright — so a composite key is never ambiguous\n * between `(a, bc)` and `(ab, c)`.\n */\nexport const TENANT_KEY_SEPARATOR = '\\u0000';\n\n/**\n * The single mint point for {@link TenantId}.\n *\n * Fail-closed: empty, whitespace-padded, over-long, non-string, or\n * `NUL`-bearing values are rejected rather than normalized. Normalizing here\n * would create a second source of truth for \"which tenant is this\", because the\n * control plane that issued the id would then disagree with the SDK about its\n * canonical form.\n *\n * @throws {ByokCoreError} code `tenant_id_invalid`.\n */\nexport function tenantId(value: string): TenantId {\n const candidate: unknown = value;\n if (typeof candidate !== 'string') {\n throw new ByokCoreError(\n 'tenant_id_invalid',\n `Tenant id must be a string, received ${typeof candidate}.`,\n );\n }\n if (candidate.length === 0) {\n throw new ByokCoreError('tenant_id_invalid', 'Tenant id must not be empty.');\n }\n if (candidate.trim() !== candidate) {\n throw new ByokCoreError(\n 'tenant_id_invalid',\n 'Tenant id must not have leading or trailing whitespace.',\n );\n }\n if (candidate.length > TENANT_ID_MAX_LENGTH) {\n throw new ByokCoreError(\n 'tenant_id_invalid',\n `Tenant id must be at most ${TENANT_ID_MAX_LENGTH} characters.`,\n );\n }\n if (candidate.includes(TENANT_KEY_SEPARATOR)) {\n throw new ByokCoreError('tenant_id_invalid', 'Tenant id must not contain a NUL character.');\n }\n return candidate as TenantId;\n}\n\n/**\n * Non-throwing form of {@link tenantId}, for surfaces that must answer \"is this\n * a tenant id?\" without building an error (route matching, log redaction).\n * Accepts exactly what {@link tenantId} accepts, never more.\n */\nexport function isTenantId(value: unknown): value is TenantId {\n if (typeof value !== 'string') return false;\n return (\n value.length > 0 &&\n value.trim() === value &&\n value.length <= TENANT_ID_MAX_LENGTH &&\n !value.includes(TENANT_KEY_SEPARATOR)\n );\n}\n\n/**\n * Composite key helper for compositions that need a flat key space (in-memory\n * maps, KV namespaces). SQL compositions use a tenant-prefixed composite\n * primary key instead — §12.6.2 layer 3 forbids a bare device/task index\n * regardless of which representation a composition picks.\n */\nexport function tenantKey(tenant: TenantId, ...parts: readonly string[]): string {\n return [tenant as string, ...parts].join(TENANT_KEY_SEPARATOR);\n}\n","/**\n * Authenticated principals — layer 2 of the isolation model (§12.6.2).\n *\n * A handler never receives a raw tenant string; it receives a principal that\n * already carries a minted {@link TenantId}. The two principal shapes are\n * deliberately not one type with an optional `deviceId`: a control-plane caller\n * that can write entitlements and a device that can write truth records have\n * different authority, and a discriminated union makes a handler state which\n * one it accepts.\n *\n * `keyId`/`keyEpoch` are **not** here. They are device-proof semantics\n * (`plans/sprints/…sprint.md` §S6.2): the signing key's identity and rotation\n * generation, resolved by looking up the device row during proof verification.\n * Putting them on the principal would create permanently-empty fields on every\n * principal minted by a non-proof path.\n */\nimport type { TenantId } from './tenant';\n\n/** Principal kinds. A composition may not invent a third without a contract change. */\nexport const PRINCIPAL_KINDS = ['device', 'control-plane'] as const;\nexport type PrincipalKind = (typeof PRINCIPAL_KINDS)[number];\n\n/**\n * A paired device acting inside one tenant/product.\n *\n * Built only from a device row loaded with the tenant as part of the lookup key\n * (§12.6.2 layer 5) — never from claims a device asserted about itself.\n */\nexport interface DevicePrincipal {\n readonly kind: 'device';\n readonly tenantId: TenantId;\n readonly productId: string;\n readonly deviceId: string;\n}\n\n/**\n * The host's control plane acting on a tenant: entitlement writes, retention\n * policy, administrative reads. Carries the operator identity for audit, which\n * is opaque to the SDK.\n */\nexport interface ControlPlanePrincipal {\n readonly kind: 'control-plane';\n readonly tenantId: TenantId;\n readonly operatorId: string;\n}\n\n/** Anything that can address a tenant-scoped store. */\nexport type Principal = DevicePrincipal | ControlPlanePrincipal;\n\nexport function isDevicePrincipal(principal: Principal): principal is DevicePrincipal {\n return principal.kind === 'device';\n}\n\nexport function isControlPlanePrincipal(\n principal: Principal,\n): principal is ControlPlanePrincipal {\n return principal.kind === 'control-plane';\n}\n\n/**\n * The tenant every store call must be scoped to.\n *\n * Exists so a handler cannot accidentally read `principal.tenantId` off one\n * principal and pass a different tenant to a store: the facade that binds\n * stores to a tenant takes this, not a loose string.\n */\nexport function principalTenant(principal: Principal): TenantId {\n return principal.tenantId;\n}\n","/**\n * The one timestamp format this package accepts across every composition.\n *\n * Every instant that crosses a store port is an ISO-8601 UTC string, and the\n * in-memory reference compares those strings with `<` / `>=` — a downgrade\n * grace deadline, a retention cutoff, a reservation expiry. Lexicographic\n * order equals chronological order **only** for the canonical\n * `YYYY-MM-DDTHH:mm:ss.sssZ` shape that `Date.prototype.toISOString` emits.\n * Feed the same store `2026-08-08T00:00:00+08:00` and the string comparison\n * silently answers a different question than a SQL `timestamptz` comparison\n * would, so the in-memory and Postgres compositions would diverge on an input\n * the conformance suite never sees.\n *\n * The fix is a format contract rather than a normalizer: a caller-supplied\n * timestamp that is not already canonical is **rejected**, not rewritten.\n * Rewriting would make this module a second authority on what instant the\n * caller meant, and an offset-bearing or second-precision string is exactly the\n * case where that guess is worth refusing.\n *\n * Store-produced timestamps are canonical by construction (they come from\n * `Clock.now().toISOString()`); this module guards the *inbound* direction —\n * `downgradeGraceUntil`, `deletePendingBefore`, `ackedBefore`,\n * `expireUnackedBefore`.\n *\n * No `node:` import and no clock read: validation is pure, so a Workers\n * composition and the constraint test (`Date.now()` is banned package-wide)\n * both stay happy. `Date.parse` is used for *calendar validity only* — the\n * pattern is what pins the shape.\n */\nimport { ByokCoreError } from './errors';\n\n/**\n * Exactly what `toISOString()` produces: four-digit year, `T` separator,\n * millisecond precision, literal `Z`. No offsets, no omitted milliseconds, no\n * expanded-year form — each of those breaks the lexicographic-order property.\n */\nexport const CANONICAL_TIMESTAMP_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/;\n\n/**\n * True when `value` is a canonical ISO-8601 UTC instant.\n *\n * Two checks, in order: the pattern pins the *shape*, then a round trip\n * through `Date` pins *calendar validity* — `2026-02-30T00:00:00.000Z` matches\n * the pattern and is not an instant.\n */\nexport function isCanonicalTimestamp(value: unknown): value is string {\n if (typeof value !== 'string') return false;\n if (!CANONICAL_TIMESTAMP_PATTERN.test(value)) return false;\n const parsed = Date.parse(value);\n if (!Number.isFinite(parsed)) return false;\n return new Date(parsed).toISOString() === value;\n}\n\n/**\n * Fail-closed gate for a caller-supplied instant.\n *\n * @param value The timestamp as received from the caller.\n * @param field Field name, so the failure names the contract that was missed\n * rather than just the bad string.\n * @returns The same string, so call sites can validate and assign in one step.\n * @throws {ByokCoreError} code `timestamp_not_canonical`.\n */\nexport function assertCanonicalTimestamp(value: string, field: string): string {\n if (!isCanonicalTimestamp(value)) {\n throw new ByokCoreError(\n 'timestamp_not_canonical',\n `${field} must be a canonical ISO-8601 UTC instant (YYYY-MM-DDTHH:mm:ss.sssZ), received ${JSON.stringify(value)}.`,\n );\n }\n return value;\n}\n","/**\n * Hosted mailbox contract (§12.7.3).\n *\n * The load-bearing rule of this file: **reading is not acknowledging.**\n * `readAfter` never mutates the cursor. The only ack is the cursor the daemon\n * brings back on its next poll, after it has durably appended the envelope to\n * its local journal. \"领走即弃\" means *cursor-advanced-then-deleted*, not\n * *read-then-deleted* — read-deletes would break the frozen at-least-once\n * semantics the client's stall recovery is built on (§8.3).\n *\n * The mailbox transports opaque envelope bytes and is **not** an\n * execution-state authority. `body` is a string here rather than a parsed\n * message because core is protocol-free: the frozen v1 shape lives in\n * `@byok-sdk/protocol`, and core must not grow an edge to it (§12.1 invariant).\n */\nimport type { ContentHash } from './blob';\nimport type { TenantId } from './tenant';\n\n/**\n * Row lifecycle. `pending` and `acked` are derived from the device cursor;\n * `expired` is the dead-letter state for rows that aged out before ever being\n * acked — §12.7.5 requires those to be visible, not silently dropped.\n */\nexport const MAILBOX_MESSAGE_STATES = ['pending', 'acked', 'expired'] as const;\nexport type MailboxMessageState = (typeof MAILBOX_MESSAGE_STATES)[number];\n\n/** One mailbox row. `seq` is monotonic per (tenant, device) — never global. */\nexport interface MailboxMessage {\n readonly tenantId: TenantId;\n readonly deviceId: string;\n readonly seq: number;\n readonly messageId: string;\n /** Opaque encoded envelope. Core never parses it. */\n readonly body: string;\n readonly bodyHash: ContentHash;\n readonly byteSize: bigint;\n readonly state: MailboxMessageState;\n readonly appendedAt: string;\n}\n\nexport interface MailboxAppendInput {\n readonly deviceId: string;\n readonly body: string;\n readonly bodyHash: ContentHash;\n readonly byteSize: bigint;\n /**\n * Producer-supplied idempotency key. A second append with the same\n * `messageId` returns the existing row instead of enqueuing a duplicate.\n */\n readonly messageId: string;\n}\n\nexport interface MailboxReadQuery {\n readonly deviceId: string;\n /** Exclusive lower bound. `0` reads from the beginning of the retained window. */\n readonly afterSeq: number;\n readonly limit?: number;\n}\n\nexport interface MailboxPage {\n readonly messages: readonly MailboxMessage[];\n /**\n * The seq to poll after next. Equal to `afterSeq` when the page is empty —\n * reading never moves the ack cursor, so a caller that only reads can replay\n * the same page forever without losing anything.\n */\n readonly nextSeq: number;\n readonly hasMore: boolean;\n}\n\nexport interface MailboxAdvanceCursorInput {\n readonly deviceId: string;\n /** Highest seq the device has durably journaled. */\n readonly ackedSeq: number;\n}\n\n/** The device's durable acknowledgement position. */\nexport interface MailboxCursorState {\n readonly tenantId: TenantId;\n readonly deviceId: string;\n readonly ackedSeq: number;\n readonly updatedAt: string;\n}\n\n/**\n * Retention cutoffs.\n *\n * Both instants must be **canonical ISO-8601 UTC** (`YYYY-MM-DDTHH:mm:ss.sssZ`);\n * anything else is rejected with `timestamp_not_canonical`. A retention sweep\n * deletes rows, so an offset-bearing string that a string comparison and a SQL\n * `timestamptz` comparison read differently is the worst place to guess — see\n * `time.ts`.\n */\nexport interface MailboxRetentionInput {\n readonly deviceId?: string;\n /** Acked rows appended before this instant are deleted. */\n readonly ackedBefore: string;\n /** Unacked rows appended before this instant move to `expired`, never deleted here. */\n readonly expireUnackedBefore: string;\n}\n\nexport interface MailboxRetentionResult {\n readonly deletedCount: number;\n readonly expiredCount: number;\n readonly releasedBytes: bigint;\n}\n\n/**\n * Mailbox port. Tenant-first, async.\n *\n * Raises: `mailbox_cursor_regression` (an ack that moves the cursor backwards,\n * which would silently re-deliver already-journaled work),\n * `timestamp_not_canonical` (a retention cutoff that is not a canonical\n * ISO-8601 UTC instant).\n */\nexport interface MailboxStore {\n append(tenant: TenantId, input: MailboxAppendInput): Promise<MailboxMessage>;\n /** Pure read. Never advances the cursor, never deletes, never marks acked. */\n readAfter(tenant: TenantId, query: MailboxReadQuery): Promise<MailboxPage>;\n /** The one and only ack. Monotonic; a lower `ackedSeq` is rejected. */\n advanceCursor(\n tenant: TenantId,\n input: MailboxAdvanceCursorInput,\n ): Promise<MailboxCursorState>;\n readCursor(tenant: TenantId, deviceId: string): Promise<MailboxCursorState>;\n /** Retention hook: delete acked rows, dead-letter unacked ones. */\n collectRetired(\n tenant: TenantId,\n input: MailboxRetentionInput,\n ): Promise<MailboxRetentionResult>;\n}\n","/**\n * Board coordination state (§12.3).\n *\n * This is the *human and multi-device* collaboration lifecycle, and it is a\n * separate vocabulary from the frozen wire execution vocabulary on purpose. One\n * run attempt is not one work item: an item can outlive several attempts, and a\n * finished attempt does not mean a human accepted the result. The constraint\n * test asserts that no wire execution state name appears in this file — if the\n * two vocabularies ever merge, status sniffing comes back and the board becomes\n * a second, unreliable execution authority.\n *\n * Three invariants the ports below encode:\n *\n * - **assignee and status are two fields**, not one enum. \"Who holds it\" and\n * \"where it is\" change independently.\n * - **every mutation is a CAS.** `claim` compares against \"unheld\"; every status\n * move carries `expectedStatus`. There is no last-write-wins path.\n * - **conflicts return the snapshot they lost to**, so the caller re-decides\n * against real state instead of retrying blind.\n */\nimport type { TenantId } from './tenant';\n\n/** The five board statuses. `closed` means \"terminated, unaccepted\" (§12.3). */\nexport const BOARD_STATUSES = ['todo', 'in_progress', 'in_review', 'done', 'closed'] as const;\nexport type BoardStatus = (typeof BOARD_STATUSES)[number];\n\n/**\n * Legal transitions, transcribed from the §12.3 state diagram.\n *\n * `in_review → done` is the human acceptance step: a device reporting a\n * terminal record can push an item to `in_review`, never straight to `done`.\n * `done` and `closed` are sinks — if archival semantics are ever needed, §12.3\n * pins the answer to an `archivedAt` field, not a sixth status.\n */\nexport const BOARD_TRANSITIONS: Readonly<Record<BoardStatus, readonly BoardStatus[]>> = {\n todo: ['in_progress', 'closed'],\n in_progress: ['todo', 'in_review', 'closed'],\n in_review: ['in_progress', 'done', 'closed'],\n done: [],\n closed: [],\n};\n\nexport function isLegalBoardTransition(from: BoardStatus, to: BoardStatus): boolean {\n return BOARD_TRANSITIONS[from].includes(to);\n}\n\n/** Who currently holds the item. Separate from {@link BoardItem.status}. */\nexport interface BoardAssignee {\n readonly holderId: string;\n readonly heldSince: string;\n}\n\n/**\n * One work item.\n *\n * `boardSeq` is monotonic **per tenant** and bumps on every mutation, which is\n * what makes incremental list polling possible without a cross-tenant sequence\n * (a global sequence would leak other tenants' write rate).\n */\nexport interface BoardItem {\n readonly tenantId: TenantId;\n readonly itemId: string;\n readonly channel: string;\n readonly title: string;\n readonly status: BoardStatus;\n readonly assignee?: BoardAssignee;\n readonly boardSeq: number;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\nexport interface BoardItemInput {\n readonly itemId: string;\n readonly channel: string;\n readonly title: string;\n /** Defaults to `todo`. Creating directly into a sink status is legal but explicit. */\n readonly status?: BoardStatus;\n}\n\nexport interface BoardListQuery {\n /** Exclusive lower bound on `boardSeq`, for incremental polling. */\n readonly afterSeq?: number;\n readonly channel?: string;\n readonly status?: BoardStatus;\n readonly limit?: number;\n}\n\nexport interface BoardPage {\n readonly items: readonly BoardItem[];\n /** Highest `boardSeq` in this page, or the requested `afterSeq` when empty. */\n readonly nextSeq: number;\n readonly hasMore: boolean;\n}\n\nexport interface BoardClaimInput {\n readonly itemId: string;\n readonly holderId: string;\n /**\n * Status the claimer believes the item is in. Defaults to `todo`; supplying\n * it explicitly makes the claim a full CAS rather than an assignee-only one.\n *\n * The CAS holds on the idempotent path too: a re-claim by the current holder\n * that supplies a stale `expectedStatus` fails with `board_status_conflict`\n * and the current item. The default is *not* applied there — a retry of a\n * successful claim legitimately observes `in_progress`.\n */\n readonly expectedStatus?: BoardStatus;\n}\n\nexport interface BoardUnclaimInput {\n readonly itemId: string;\n /** Must match the current holder — releasing someone else's item is not a legal move. */\n readonly holderId: string;\n}\n\nexport interface BoardStatusUpdateInput {\n readonly itemId: string;\n readonly expectedStatus: BoardStatus;\n readonly status: BoardStatus;\n /** Optional holder assertion, for transitions only the holder may make. */\n readonly holderId?: string;\n}\n\n/**\n * Board port. Tenant-first, async.\n *\n * Raises: `board_item_not_found`, `board_claim_conflict` (loser gets the\n * winner's holder snapshot), `board_status_conflict` (`expectedStatus` missed —\n * carries the current item), `board_transition_invalid` (move not in\n * {@link BOARD_TRANSITIONS} — also carries the current item), `board_not_held`.\n */\nexport interface BoardStore {\n create(tenant: TenantId, input: BoardItemInput): Promise<BoardItem>;\n get(tenant: TenantId, itemId: string): Promise<BoardItem | undefined>;\n list(tenant: TenantId, query: BoardListQuery): Promise<BoardPage>;\n /** CAS on \"unheld\". Exactly one concurrent caller wins; losers get the holder snapshot. */\n claim(tenant: TenantId, input: BoardClaimInput): Promise<BoardItem>;\n unclaim(tenant: TenantId, input: BoardUnclaimInput): Promise<BoardItem>;\n updateStatus(tenant: TenantId, input: BoardStatusUpdateInput): Promise<BoardItem>;\n}\n","/**\n * Truth records: attested metadata with two different write models (§12.3, §12.6.4).\n *\n * | kind | write model | conflict model |\n * | --------------- | ------------------------------ | --------------------------------------- |\n * | `task.terminal` | first write per task, immutable | different hash → `terminal_conflict` |\n * | `profile` | per-key snapshot | `expectedRev` CAS |\n * | `memory` | per-key snapshot | `expectedRev` CAS |\n *\n * The store is deliberately dumb about content. It can match, sort, and return\n * by tenant/kind/key/rev/hash, and that is the whole of its authority: no\n * summarizing, no merging, no relevance ranking (§12.3). Merge decisions belong\n * to the device that holds the context, which is why a conflict hands back the\n * current snapshot and stops.\n *\n * The manifest listing returns metadata only — never bodies. Selecting which\n * bodies to fetch is a local decision (§S6.4), so shipping bodies in the list\n * response would both defeat that and make the response unbounded.\n */\nimport type { ContentHash } from './blob';\nimport type { TenantId } from './tenant';\n\nexport const TRUTH_RECORD_KINDS = ['task.terminal', 'profile', 'memory'] as const;\nexport type TruthRecordKind = (typeof TRUTH_RECORD_KINDS)[number];\n\n/**\n * Where the record body lives. Small payloads may be inline and still count\n * against tenant usage (§12.7.6); larger ones are an object reference.\n */\nexport type TruthBodyRef =\n | { readonly kind: 'inline'; readonly body: string }\n | { readonly kind: 'object'; readonly hash: ContentHash };\n\nexport interface TruthRecord {\n readonly tenantId: TenantId;\n readonly kind: TruthRecordKind;\n /** For `task.terminal` this is the task id; for snapshots, the host's key. */\n readonly recordKey: string;\n /** `1` for the first write. Terminal records never advance past `1`. */\n readonly rev: number;\n readonly contentHash: ContentHash;\n readonly byteSize: bigint;\n readonly body: TruthBodyRef;\n readonly label?: string;\n /** Idempotency key of the accepted write, for replay detection. */\n readonly requestId?: string;\n readonly writtenAt: string;\n}\n\n/** Manifest projection: everything needed to decide *whether* to fetch a body. */\nexport interface TruthManifestEntry {\n readonly kind: TruthRecordKind;\n readonly recordKey: string;\n readonly rev: number;\n readonly contentHash: ContentHash;\n readonly byteSize: bigint;\n readonly label?: string;\n readonly updatedAt: string;\n}\n\nexport interface TerminalWriteInput {\n readonly taskId: string;\n readonly contentHash: ContentHash;\n readonly byteSize: bigint;\n readonly body: TruthBodyRef;\n readonly label?: string;\n readonly requestId?: string;\n}\n\nexport interface SnapshotWriteInput {\n readonly kind: 'profile' | 'memory';\n readonly recordKey: string;\n /** `0` asserts \"no record yet\". Any other value must equal the stored `rev`. */\n readonly expectedRev: number;\n readonly contentHash: ContentHash;\n readonly byteSize: bigint;\n readonly body: TruthBodyRef;\n readonly label?: string;\n readonly requestId?: string;\n}\n\nexport interface TruthRecordSelector {\n readonly kind: TruthRecordKind;\n readonly recordKey: string;\n}\n\nexport interface TruthManifestQuery {\n readonly kind?: TruthRecordKind;\n readonly keyPrefix?: string;\n readonly limit?: number;\n}\n\n/**\n * Truth port. Tenant-first, async.\n *\n * Raises: `terminal_conflict` (same task, different hash — carries the record\n * already committed), `truth_revision_conflict` (`expectedRev` missed — carries\n * the current record), `truth_record_not_found`.\n */\nexport interface TruthStore {\n /**\n * Writes the first terminal record for a task.\n *\n * Replaying the identical hash returns the original record unchanged, so a\n * retry after a lost response is safe. A different hash for the same task is\n * a conflict: the first fact is never overwritten.\n */\n writeTerminal(tenant: TenantId, input: TerminalWriteInput): Promise<TruthRecord>;\n /** Per-key snapshot write under `expectedRev` CAS. The store never merges bodies. */\n writeSnapshot(tenant: TenantId, input: SnapshotWriteInput): Promise<TruthRecord>;\n getRecord(tenant: TenantId, selector: TruthRecordSelector): Promise<TruthRecord | undefined>;\n /** Metadata only — key/rev/hash/size/label, no bodies. */\n listManifest(\n tenant: TenantId,\n query: TruthManifestQuery,\n ): Promise<readonly TruthManifestEntry[]>;\n}\n","/**\n * Presence and activity hints (§12.3).\n *\n * Both are lossy, TTL-bounded, unsigned, and never authoritative. Expiry means\n * *absence*, not a stale value: a hint past its TTL is invisible to readers, so\n * nothing downstream can mistake an old level for a live one.\n *\n * These hints must never be used to derive coordination state, execution state,\n * authorization, billing, or recovery — which is why this module shares no\n * vocabulary with `board.ts` and no vocabulary with the frozen wire states. The\n * constraint test enforces that separation by scanning this file for those\n * names. A device that looks busy is not evidence that any particular work item\n * moved anywhere.\n *\n * The activity tail is bounded by count and carries an explicit `dropped`\n * counter: lossiness is written into the data instead of being hidden behind a\n * stream that pretends to be complete.\n */\nimport type { TenantId } from './tenant';\n\n/** The five presence levels. */\nexport const PRESENCE_LEVELS = ['online', 'thinking', 'working', 'error', 'offline'] as const;\nexport type PresenceLevel = (typeof PRESENCE_LEVELS)[number];\n\n/** A device-level hint. `expiresAt` is authoritative: past it, the hint does not exist. */\nexport interface PresenceHint {\n readonly tenantId: TenantId;\n readonly deviceId: string;\n readonly level: PresenceLevel;\n /** Free-form host label, bounded by the composition. Never parsed by core. */\n readonly detail?: string;\n readonly observedAt: string;\n readonly expiresAt: string;\n}\n\nexport interface PresenceHintInput {\n readonly deviceId: string;\n readonly level: PresenceLevel;\n readonly detail?: string;\n /** Hint lifetime. §12.7.5 suggests 60-120s for presence. */\n readonly ttlMs: number;\n /** Minimum time between accepted publications for this device. `0` explicitly disables throttling. */\n readonly minimumIntervalMs: number;\n}\n\n/** One entry of a task's lossy tail. */\nexport interface ActivityEntry {\n readonly at: string;\n readonly detail: string;\n}\n\n/**\n * A task's bounded tail.\n *\n * `dropped` counts entries evicted by `capacity`, so a reader can tell the\n * difference between \"nothing happened\" and \"we lost the middle\".\n */\nexport interface ActivityTail {\n readonly tenantId: TenantId;\n readonly taskId: string;\n readonly entries: readonly ActivityEntry[];\n readonly dropped: number;\n readonly capacity: number;\n readonly expiresAt: string;\n}\n\nexport interface ActivityAppendInput {\n readonly taskId: string;\n /** One ProgressBatcher-shaped batch. Empty batches are rejected. */\n readonly details: readonly string[];\n /** Events the producer dropped before this batch reached the store. */\n readonly dropped: number;\n /** Tail lifetime. §12.7.5 suggests 5-15 minutes for activity. */\n readonly ttlMs: number;\n /** Maximum retained entries. Must be a positive integer. */\n readonly capacity?: number;\n}\n\n/**\n * Presence port. Tenant-first, async.\n *\n * Reads filter expired hints out rather than returning them with a flag: an\n * expired hint is indistinguishable from one that was never written.\n */\nexport interface PresenceStore {\n publish(tenant: TenantId, input: PresenceHintInput): Promise<PresenceHint>;\n read(tenant: TenantId, deviceId: string): Promise<PresenceHint | undefined>;\n list(tenant: TenantId): Promise<readonly PresenceHint[]>;\n}\n\n/**\n * Activity port. Tenant-first, async.\n *\n * Raises: `activity_capacity_invalid` (non-positive or non-integer capacity —\n * an unbounded tail is exactly what this contract exists to prevent),\n * `activity_batch_invalid` (empty batch or invalid producer drop count).\n */\nexport interface ActivityStore {\n append(tenant: TenantId, input: ActivityAppendInput): Promise<ActivityTail>;\n read(tenant: TenantId, taskId: string): Promise<ActivityTail | undefined>;\n}\n\n/** Default tail capacity when an append does not specify one. */\nexport const DEFAULT_ACTIVITY_CAPACITY = 50;\n","/**\n * Content addressing and the object manifest (§12.7.4, §12.7.8).\n *\n * This module is **metadata only**. No byte transport, no presigning, no\n * hashing: R2/S3 URL signing and digest computation are composition concerns\n * that need platform crypto, and core stays Node-free. What core owns is the\n * shape everyone must agree on — the hash format, the manifest state machine,\n * and reference counting — so that Postgres, D1, and the in-memory reference\n * cannot disagree about when an object is safe to delete.\n *\n * Object keys are tenant-scoped by construction ({@link tenantObjectKey}).\n * A global `sha256/<hex>` key space would turn object existence into a\n * cross-tenant oracle, which is why §12.7.4 forbids it even though it would\n * deduplicate better.\n */\nimport { ByokCoreError } from './errors';\nimport type { TenantId } from './tenant';\n\n/** `sha256:<64 lowercase hex>`. The only content-address form core accepts. */\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/** A validated content address. Branded so an unvalidated digest cannot stand in for one. */\nexport type ContentHash = string & { readonly __byokContentHash: unique symbol };\n\n/**\n * The single mint point for {@link ContentHash}.\n *\n * Fail-closed on uppercase hex: accepting both cases would make the same bytes\n * addressable under two keys, which breaks per-tenant deduplication and the\n * \"count each hash once\" billing rule (§12.7.6).\n *\n * @throws {ByokCoreError} code `content_hash_invalid`.\n */\nexport function contentHash(value: string): ContentHash {\n if (!CONTENT_HASH_PATTERN.test(value)) {\n throw new ByokCoreError(\n 'content_hash_invalid',\n `Content hash must match ${CONTENT_HASH_PATTERN.source}, received ${JSON.stringify(value)}.`,\n );\n }\n return value as ContentHash;\n}\n\n/** Non-throwing form of {@link contentHash}. */\nexport function isContentHash(value: unknown): value is ContentHash {\n return typeof value === 'string' && CONTENT_HASH_PATTERN.test(value);\n}\n\n/**\n * Tenant-scoped object key, e.g.\n * `tenants/<tenantId>/objects/sha256/<hex>` (§12.7.4).\n */\nexport function tenantObjectKey(tenant: TenantId, hash: ContentHash): string {\n const hex = hash.slice('sha256:'.length);\n return `tenants/${tenant as string}/objects/sha256/${hex}`;\n}\n\n/**\n * Object manifest lifecycle (§12.7.8).\n *\n * `pending` exists because Postgres and R2 have no shared transaction: the row\n * is written before the bytes land, and only `committed` rows may be referenced\n * by a truth record. `delete_pending` is the tombstone the GC worker drives, so\n * a failed R2 delete is retryable instead of leaving usage silently wrong.\n */\nexport const OBJECT_STATES = ['pending', 'committed', 'delete_pending', 'deleted'] as const;\nexport type ObjectState = (typeof OBJECT_STATES)[number];\n\n/** Legal manifest transitions. Anything else raises `object_state_invalid`. */\nexport const OBJECT_STATE_TRANSITIONS: Readonly<Record<ObjectState, readonly ObjectState[]>> = {\n pending: ['committed', 'delete_pending'],\n committed: ['delete_pending'],\n delete_pending: ['deleted', 'committed'],\n deleted: [],\n};\n\nexport function isLegalObjectTransition(from: ObjectState, to: ObjectState): boolean {\n return OBJECT_STATE_TRANSITIONS[from].includes(to);\n}\n\n/** One row of `object_manifest` (§12.7.6). */\nexport interface ObjectManifestEntry {\n readonly tenantId: TenantId;\n readonly hash: ContentHash;\n /** Declared at reservation time, re-verified at commit against the store's `HEAD`. */\n readonly byteSize: bigint;\n readonly contentType: string;\n readonly state: ObjectState;\n /** Number of live {@link ObjectReference} rows. `0` makes the object GC-eligible after grace. */\n readonly refCount: number;\n readonly createdAt: string;\n readonly updatedAt: string;\n /** Set when the row entered `delete_pending`; the grace window is measured from here. */\n readonly deletePendingAt?: string;\n}\n\n/** What references an object. `refKind`/`refId` are opaque to core. */\nexport interface ObjectReference {\n readonly tenantId: TenantId;\n readonly hash: ContentHash;\n readonly refKind: string;\n readonly refId: string;\n readonly createdAt: string;\n}\n\nexport interface ObjectManifestInput {\n readonly hash: ContentHash;\n readonly byteSize: bigint;\n readonly contentType: string;\n}\n\n/**\n * Finalize input. `byteSize`/`contentType` are what the composition actually\n * observed on the object store, not what the client declared — the whole point\n * of the check is that the two can differ (§12.7.7 step 4).\n */\nexport interface ObjectCommitInput {\n readonly hash: ContentHash;\n readonly observedByteSize: bigint;\n readonly observedContentType: string;\n}\n\nexport interface ObjectReferenceInput {\n readonly hash: ContentHash;\n readonly refKind: string;\n readonly refId: string;\n}\n\nexport interface ObjectListQuery {\n readonly state?: ObjectState;\n /**\n * Only rows whose `deletePendingAt` is at or before this instant.\n *\n * Must be a **canonical ISO-8601 UTC instant** (`YYYY-MM-DDTHH:mm:ss.sssZ`);\n * anything else is rejected with `timestamp_not_canonical`, because the\n * in-memory composition compares it as a string and a SQL composition\n * compares it as a `timestamptz` — see `time.ts`.\n */\n readonly deletePendingBefore?: string;\n readonly limit?: number;\n}\n\n/**\n * Object manifest port. Tenant-first, async, metadata only.\n *\n * Raises: `object_not_found`, `object_state_invalid`,\n * `storage_integrity_mismatch` (commit observed size/type disagreeing with the\n * declared manifest row), `timestamp_not_canonical` (a `list` query whose\n * `deletePendingBefore` is not a canonical ISO-8601 UTC instant).\n */\nexport interface ObjectStore {\n /** Creates or returns the `pending` row for `hash`. Idempotent per (tenant, hash). */\n putManifest(tenant: TenantId, input: ObjectManifestInput): Promise<ObjectManifestEntry>;\n /** `pending` → `committed` after verifying observed size/type. */\n commit(tenant: TenantId, input: ObjectCommitInput): Promise<ObjectManifestEntry>;\n get(tenant: TenantId, hash: ContentHash): Promise<ObjectManifestEntry | undefined>;\n list(tenant: TenantId, query: ObjectListQuery): Promise<readonly ObjectManifestEntry[]>;\n /** Idempotent per (tenant, hash, refKind, refId) — re-adding does not double-count. */\n addReference(tenant: TenantId, input: ObjectReferenceInput): Promise<ObjectManifestEntry>;\n removeReference(tenant: TenantId, input: ObjectReferenceInput): Promise<ObjectManifestEntry>;\n /** Tombstone step 1: only legal at `refCount === 0`. */\n markDeletePending(tenant: TenantId, hash: ContentHash): Promise<ObjectManifestEntry>;\n /** Tombstone step 3: the object store delete succeeded. */\n markDeleted(tenant: TenantId, hash: ContentHash): Promise<ObjectManifestEntry>;\n}\n","/**\n * Tenant storage entitlement, usage, reservation and retention (§12.7.6-12.7.7).\n *\n * The SDK does not know what a plan is. It never sees `free`, `pro`, a price, a\n * currency, or a purchase flow — those belong to the host SaaS. What crosses\n * this boundary is a *numeric, versioned* entitlement the host issues, and the\n * constraint test asserts this file contains no plan-name or price vocabulary.\n * The moment the SDK hardcodes a tier, every host is stuck with the SDK's\n * commercial model.\n *\n * Byte counts are `bigint`. Serialization is a composition concern: JSON has no\n * bigint, so a cloud handler renders them as decimal strings on the wire. Using\n * `number` here would put a silent 2^53 ceiling into a storage quota contract.\n *\n * Reservation exists because Postgres and R2 have no shared transaction\n * (§12.7.7). Every durable write reserves first, uploads second, finalizes\n * third; the invariant `committed + reserved + expected <= hardLimit` is\n * checked under the reservation lock, which is what makes concurrent uploads\n * unable to oversell the tenant.\n */\nimport type { ContentHash } from './blob';\nimport type { CoreErrorCode } from './errors';\nimport type { TenantId } from './tenant';\n\n/**\n * The host-issued numeric entitlement (§12.7.6, verbatim).\n *\n * `version` is monotonic and CAS-checked on write: a delayed control-plane\n * update must not resurrect an older plan over a newer one.\n */\nexport interface TenantStorageEntitlement {\n tenantId: TenantId;\n version: bigint;\n hardLimitBytes: bigint;\n maxObjectBytes: bigint;\n maxInlineBytes: bigint;\n mailboxLimitBytes: bigint;\n retentionPolicyId: string;\n /** Canonical ISO-8601 UTC instant — see {@link TenantStorageEntitlementInput}. */\n downgradeGraceUntil?: string;\n}\n\n/**\n * Measured tenant usage (§12.7.6, verbatim).\n *\n * Carries no `tenantId` because it is always read through a tenant-scoped port\n * call — the tenant is the query, not a field of the answer.\n */\nexport interface TenantStorageUsage {\n committedObjectBytes: bigint;\n committedInlineBytes: bigint;\n reservedBytes: bigint;\n mailboxBytes: bigint;\n objectCount: bigint;\n updatedAt: string;\n}\n\n/** Entitlement write payload. `tenantId` comes from the port's first parameter. */\nexport interface TenantStorageEntitlementInput {\n readonly version: bigint;\n readonly hardLimitBytes: bigint;\n readonly maxObjectBytes: bigint;\n readonly maxInlineBytes: bigint;\n readonly mailboxLimitBytes: bigint;\n readonly retentionPolicyId: string;\n /**\n * Deadline after which an over-limit tenant is suspended rather than blocked.\n *\n * Must be a **canonical ISO-8601 UTC instant** (`YYYY-MM-DDTHH:mm:ss.sssZ`);\n * anything else is rejected with `timestamp_not_canonical`. The in-memory\n * composition compares this deadline as a string and a SQL composition\n * compares it as a `timestamptz`, and those two agree only on the canonical\n * form — see `time.ts`.\n */\n readonly downgradeGraceUntil?: string;\n}\n\n/** Durable write classes a reservation can cover. */\nexport const STORAGE_WRITE_KINDS = ['object', 'inline'] as const;\nexport type StorageWriteKind = (typeof STORAGE_WRITE_KINDS)[number];\n\nexport const STORAGE_RESERVATION_STATES = [\n 'reserved',\n 'committed',\n 'aborted',\n 'expired',\n] as const;\nexport type StorageReservationState = (typeof STORAGE_RESERVATION_STATES)[number];\n\nexport interface StorageReservation {\n readonly tenantId: TenantId;\n readonly reservationId: string;\n readonly state: StorageReservationState;\n readonly kind: StorageWriteKind;\n readonly expectedBytes: bigint;\n readonly contentHash: ContentHash;\n readonly contentType: string;\n readonly createdAt: string;\n readonly expiresAt: string;\n readonly settledAt?: string;\n}\n\nexport interface StorageReservationInput {\n readonly reservationId: string;\n readonly kind: StorageWriteKind;\n readonly expectedBytes: bigint;\n readonly contentHash: ContentHash;\n readonly contentType: string;\n readonly ttlMs: number;\n}\n\n/**\n * Finalize payload. Size/type are what the composition observed on the object\n * store, not what the client promised — disagreement is\n * `storage_integrity_mismatch`.\n *\n * Hash identity stays on the reservation as the authenticated daemon's\n * declaration (ADR-024). Object-store HEAD does not independently observe a\n * SHA-256 digest, so accepting one here would turn a copied declaration into a\n * false verification claim.\n */\nexport interface StorageFinalizeInput {\n readonly reservationId: string;\n readonly observedByteSize: bigint;\n readonly observedContentType: string;\n}\n\nexport interface StorageFinalizeResult {\n readonly reservation: StorageReservation;\n readonly usage: TenantStorageUsage;\n /**\n * True when this tenant already had the same content hash committed. The\n * reserved bytes are released and nothing is added: same tenant, same hash,\n * counted once (§12.7.6). Cross-tenant sharing never happens — usage is\n * per-tenant even when the bytes are identical.\n */\n readonly deduplicated: boolean;\n}\n\n/** Effective write posture derived from entitlement + usage + clock (§12.7.8). */\nexport const STORAGE_WRITE_POSTURES = ['normal', 'warning', 'blocked', 'suspended'] as const;\nexport type StorageWritePosture = (typeof STORAGE_WRITE_POSTURES)[number];\n\nexport interface StorageStatus {\n readonly entitlement: TenantStorageEntitlement;\n readonly usage: TenantStorageUsage;\n readonly posture: StorageWritePosture;\n /** `committed + reserved` against `hardLimitBytes`, for host UI. */\n readonly availableBytes: bigint;\n readonly graceActive: boolean;\n}\n\n/**\n * The five wire-stable storage error codes (§12.7.7). Renaming one is a\n * breaking change for every host that branches on them.\n */\nexport const STORAGE_ERROR_CODES = [\n 'storage_object_too_large',\n 'storage_quota_exceeded',\n 'storage_reservation_expired',\n 'storage_integrity_mismatch',\n 'storage_write_suspended',\n] as const satisfies readonly CoreErrorCode[];\n\nexport type StorageErrorCode = (typeof STORAGE_ERROR_CODES)[number];\n\n/** HTTP status mapping from §12.7.7. Compositions render these verbatim. */\nexport const STORAGE_ERROR_HTTP_STATUS = {\n storage_object_too_large: 413,\n storage_quota_exceeded: 507,\n storage_reservation_expired: 409,\n storage_integrity_mismatch: 422,\n storage_write_suspended: 423,\n} as const satisfies Record<StorageErrorCode, number>;\n\nexport interface MailboxUsageDeltaInput {\n /** Signed. Negative deltas release bytes after retention deletes rows. */\n readonly deltaBytes: bigint;\n}\n\n/**\n * Quota port. Tenant-first, async.\n *\n * Raises: `storage_entitlement_missing`,\n * `storage_entitlement_version_conflict` (carries the current entitlement),\n * `storage_reservation_not_found`, and the five wire-stable codes above.\n */\nexport interface QuotaStore {\n readEntitlement(tenant: TenantId): Promise<TenantStorageEntitlement | undefined>;\n /**\n * Version CAS: a write at or below the stored version is rejected with the\n * current row. Raises `timestamp_not_canonical` when `downgradeGraceUntil` is\n * not a canonical ISO-8601 UTC instant.\n */\n writeEntitlement(\n tenant: TenantId,\n input: TenantStorageEntitlementInput,\n ): Promise<TenantStorageEntitlement>;\n readUsage(tenant: TenantId): Promise<TenantStorageUsage>;\n readStatus(tenant: TenantId): Promise<StorageStatus>;\n /** Tenant-scoped lookup used to bind a finalize request to its reservation. */\n readReservation(tenant: TenantId, reservationId: string): Promise<StorageReservation | undefined>;\n /**\n * Atomically checks `committed + reserved + expected <= hardLimitBytes` and,\n * on success, adds `expectedBytes` to `reservedBytes`.\n */\n reserve(tenant: TenantId, input: StorageReservationInput): Promise<StorageReservation>;\n /**\n * Moves reserved bytes to committed after verifying the observed object.\n * For object reservations, the composition commits the matching manifest in\n * the same authority step as reservation/accounting settlement.\n */\n finalizeReservation(\n tenant: TenantId,\n input: StorageFinalizeInput,\n ): Promise<StorageFinalizeResult>;\n /** Idempotent release. Already-settled reservations return their settled row. */\n abortReservation(tenant: TenantId, reservationId: string): Promise<StorageReservation>;\n /** Cleanup hook: expires reservations past their TTL and releases their bytes. */\n expireReservations(tenant: TenantId): Promise<readonly StorageReservation[]>;\n /** Mailbox bytes are platform-protection accounting, bounded by `mailboxLimitBytes`. */\n applyMailboxDelta(\n tenant: TenantId,\n input: MailboxUsageDeltaInput,\n ): Promise<TenantStorageUsage>;\n}\n","/**\n * Capability declaration (ADR-010).\n *\n * A client learns what a deployment supports by reading a declaration, never by\n * probing endpoints and interpreting 404/405/501. Status-code sniffing conflates\n * \"this build does not have that feature\" with \"that request was wrong\" and\n * with \"a proxy ate it\", and every consumer ends up with its own guess.\n *\n * The schema is intentionally the minimum that supports that rule: an opaque\n * string set plus a monotonic declaration version. Capability names are host and\n * deployment vocabulary — core validates their shape, never their meaning, so a\n * new capability never requires a core release.\n */\nimport { z } from 'zod';\nimport { ByokCoreError } from './errors';\n\nexport const CAPABILITY_DECLARATION_SCHEMA_ID = 'byok-capabilities-v1';\n\n/** Capability names: lowercase dotted segments, e.g. `board.sse`, `storage.reservations`. */\nexport const CAPABILITY_NAME_PATTERN = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;\n\nexport const CapabilityDeclarationSchema = z\n .object({\n schema: z.literal(CAPABILITY_DECLARATION_SCHEMA_ID),\n /** Monotonic per deployment. Lets a client cache and detect a rollout. */\n version: z.number().int().nonnegative(),\n capabilities: z.array(z.string().regex(CAPABILITY_NAME_PATTERN)),\n })\n .superRefine((declaration, ctx) => {\n const seen = new Set<string>();\n for (const [index, name] of declaration.capabilities.entries()) {\n if (seen.has(name)) {\n ctx.addIssue({\n code: 'custom',\n path: ['capabilities', index],\n message: `Duplicate capability ${JSON.stringify(name)}.`,\n });\n }\n seen.add(name);\n }\n });\n\nexport type CapabilityDeclaration = z.infer<typeof CapabilityDeclarationSchema>;\n\n/**\n * Parses a declaration fail-closed.\n *\n * @throws {ByokCoreError} code `capability_declaration_invalid`.\n */\nexport function parseCapabilityDeclaration(input: unknown): CapabilityDeclaration {\n const result = CapabilityDeclarationSchema.safeParse(input);\n if (!result.success) {\n throw new ByokCoreError(\n 'capability_declaration_invalid',\n `Invalid capability declaration: ${result.error.issues\n .map((issue) => `${issue.path.join('.') || '<root>'}: ${issue.message}`)\n .join('; ')}`,\n { cause: result.error },\n );\n }\n return result.data;\n}\n\nexport function hasCapability(\n declaration: CapabilityDeclaration,\n capability: string,\n): boolean {\n return declaration.capabilities.includes(capability);\n}\n\n/**\n * The enforcement point ADR-010 exists for: a caller asserts the capability up\n * front and gets a named failure, instead of issuing the request and guessing\n * what the status code meant.\n *\n * @throws {ByokCoreError} code `capability_unavailable`.\n */\nexport function assertCapability(\n declaration: CapabilityDeclaration,\n capability: string,\n): void {\n if (!hasCapability(declaration, capability)) {\n throw new ByokCoreError(\n 'capability_unavailable',\n `Capability ${JSON.stringify(capability)} is not declared by this deployment.`,\n );\n }\n}\n","/**\n * The composition contract: the full set of store ports, plus the clock seam.\n *\n * Every method on every port in this package obeys two rules, and\n * `src/__tests__/constraints.test.ts` enumerates them method by method to prove\n * it (sprint I7):\n *\n * 1. **Async.** Every method returns a `Promise`. A synchronous port would\n * silently exclude SQL and object-store compositions from the contract.\n * 2. **Tenant-first.** Every method's first parameter is a required\n * {@link TenantId}. There is no bare `deviceId`/`taskId` lookup anywhere —\n * §12.6.2 layer 3 forbids the index such a lookup would need, and layer 5\n * requires the tenant to be part of the lookup key rather than a second\n * comparison step that can be forgotten.\n *\n * No port method can change the tenant of an existing row. That is not an\n * omission: \"move this to another tenant\" is the one operation that would make\n * every cross-tenant assertion in the conformance suite unfalsifiable.\n */\nimport type { ActivityStore, PresenceStore } from './presence';\nimport type { BoardStore } from './board';\nimport type { MailboxStore } from './mailbox';\nimport type { ObjectStore } from './blob';\nimport type { QuotaStore } from './quota';\nimport type { TenantId } from './tenant';\nimport type { TruthStore } from './truth';\n\n/**\n * Injected time.\n *\n * TTL semantics (presence expiry, activity expiry, reservation expiry) are\n * behavior the conformance suite has to assert deterministically, which is\n * impossible against a wall clock. Compositions inject one; nothing in core\n * calls `Date.now()` directly.\n */\nexport interface Clock {\n now(): Date;\n}\n\n/** A clock pinned to a fixed instant, advanced explicitly. Used by tests and the in-memory reference. */\nexport interface MutableClock extends Clock {\n advance(ms: number): void;\n set(instant: Date): void;\n}\n\n/** Every port a composition must supply. */\nexport interface CoreStores {\n readonly mailbox: MailboxStore;\n readonly board: BoardStore;\n readonly truth: TruthStore;\n readonly presence: PresenceStore;\n readonly activity: ActivityStore;\n readonly objects: ObjectStore;\n readonly quota: QuotaStore;\n}\n\n/** Names of the ports in {@link CoreStores}, in contract order. */\nexport const CORE_STORE_NAMES = [\n 'mailbox',\n 'board',\n 'truth',\n 'presence',\n 'activity',\n 'objects',\n 'quota',\n] as const;\n\nexport type CoreStoreName = (typeof CORE_STORE_NAMES)[number];\n\n// Layer 2 of §12.6.2 — the tenant-closed facade a handler actually receives —\n// is deliberately not here. It is shaped by how handlers are written, and the\n// first handlers land in `@byok-sdk/cloud` (S3). Defining it now would mean\n// guessing that shape and freezing the guess into the contract package that\n// every later sprint depends on. The tenant-first ports below are what make\n// that facade a thin binding rather than a new authority.\n","/**\n * The declared method inventory of every core port (sprint I7).\n *\n * This table is contract data, not test data — it says what a port IS, and it\n * is enforced from two directions that must read the same table:\n *\n * - `__tests__/constraints.test.ts` scans the *source interfaces* in this\n * package and asserts each listed method exists, is async, and takes a\n * required `TenantId` first.\n * - `@byok-sdk/conformance`'s port-inventory dimension asserts every *composition\n * under test* implements exactly these methods — no missing method, and no\n * extra one that the contract has not pinned down and that therefore no\n * other composition would implement.\n *\n * It lives in shipped source rather than under `__tests__/` because the second\n * enforcer is now a separate package (S4A story O-005): a `core → conformance`\n * devDependency for a table `core` itself asserts against would be a cycle,\n * and the direction that has to hold is `conformance → core`.\n *\n * Adding a port method means editing this table, which is the point: a port\n * grows by contract, not by whichever composition needed something.\n */\nimport type { CoreStoreName } from './stores';\n\nexport const CORE_PORT_METHODS: Readonly<Record<CoreStoreName, readonly string[]>> = {\n mailbox: ['append', 'readAfter', 'advanceCursor', 'readCursor', 'collectRetired'],\n board: ['create', 'get', 'list', 'claim', 'unclaim', 'updateStatus'],\n truth: ['writeTerminal', 'writeSnapshot', 'getRecord', 'listManifest'],\n presence: ['publish', 'read', 'list'],\n activity: ['append', 'read'],\n objects: [\n 'putManifest',\n 'commit',\n 'get',\n 'list',\n 'addReference',\n 'removeReference',\n 'markDeletePending',\n 'markDeleted',\n ],\n quota: [\n 'readEntitlement',\n 'writeEntitlement',\n 'readUsage',\n 'readStatus',\n 'readReservation',\n 'reserve',\n 'finalizeReservation',\n 'abortReservation',\n 'expireReservations',\n 'applyMailboxDelta',\n ],\n};\n\n/** The interface each port name is declared as, for the source-side scan. */\nexport const CORE_PORT_INTERFACES: Readonly<Record<CoreStoreName, string>> = {\n mailbox: 'MailboxStore',\n board: 'BoardStore',\n truth: 'TruthStore',\n presence: 'PresenceStore',\n activity: 'ActivityStore',\n objects: 'ObjectStore',\n quota: 'QuotaStore',\n};\n","/**\n * Device proof envelope and canonical signing bytes (§12.6.3, sprint §S6.2).\n *\n * Three things live here and nothing else:\n *\n * 1. **The protected-claims schema.** Every field a signature must cover so the\n * proof binds a *specific request*: tenant, product, device, key + epoch,\n * request id, operation, resource, the request line (method+path or a stable\n * operation id), and the body's hash *and* size. Signing only the body is\n * forbidden — it would let a valid proof be replayed against a different\n * operation or resource.\n * 2. **A dependency-free deterministic canonicalizer.** RFC 8785 (JCS) in the\n * narrow subset the envelope allows. Node and Workers must produce\n * byte-identical output, so the accepted value space is deliberately small:\n * strings, booleans, null, safe integers, plain objects, arrays. Floats,\n * non-safe integers, `NaN`, `Infinity`, `undefined`, `bigint`, dates and\n * class instances throw instead of being coerced — a signature over a value\n * whose serialization is implementation-defined is not a signature.\n * 3. **The verify port.** An interface, never an implementation: core is\n * Node-free and Workers-safe, and `node:crypto` and WebCrypto disagree about\n * key handling. The composition brings its own verifier.\n *\n * Claims are **untrusted input**. `tenantId` here is a plain string, not a\n * branded `TenantId`, because a device asserting a tenant proves nothing: the\n * claim is a lookup key used to load the device row, and the row is the\n * authority (§12.6.2 layer 5). Branding happens after that lookup, not here.\n */\nimport { z } from 'zod';\nimport { CONTENT_HASH_PATTERN } from './blob';\nimport { ByokCoreError } from './errors';\n\n/** Envelope schema id, self-consistent with the domain prefix below. */\nexport const DEVICE_PROOF_SCHEMA_ID = 'byok-device-proof-v1';\n\n/**\n * Domain separation prefix (§12.6.3). Prepended to the canonical claim bytes\n * before signing so a device-proof signature can never be replayed as a nonce\n * signature (`byok-nonce-v1\\n`) or a record attestation.\n */\nexport const DEVICE_PROOF_DOMAIN_PREFIX = 'byok-device-proof-v1\\n';\n\nexport const DEVICE_PROOF_VERSION = 1;\n\n/** Signature algorithms this envelope version admits. */\nexport const DEVICE_PROOF_ALGORITHMS = ['ed25519'] as const;\nexport type DeviceProofAlgorithm = (typeof DEVICE_PROOF_ALGORITHMS)[number];\n\nconst BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/;\nconst HTTP_METHOD_PATTERN = /^[A-Z]+$/;\n\n// ---------------------------------------------------------------------------\n// Canonicalization (RFC 8785 subset)\n// ---------------------------------------------------------------------------\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | readonly JsonValue[] | { readonly [key: string]: JsonValue };\nexport type JsonObject = { readonly [key: string]: JsonValue };\n\nfunction canonicalizationFailure(path: string, reason: string): ByokCoreError {\n return new ByokCoreError(\n 'proof_canonicalization_failed',\n `Cannot canonicalize ${path}: ${reason}`,\n );\n}\n\nfunction isPlainObject(value: object): boolean {\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction canonicalizeValue(value: unknown, path: string, seen: Set<object>): string {\n if (value === null) return 'null';\n\n switch (typeof value) {\n case 'boolean':\n return value ? 'true' : 'false';\n case 'string':\n // JSON.stringify implements exactly the ECMAScript string serialization\n // RFC 8785 mandates, including well-formed escaping of lone surrogates.\n return JSON.stringify(value);\n case 'number': {\n if (!Number.isSafeInteger(value)) {\n throw canonicalizationFailure(\n path,\n `only safe integers are canonicalizable, received ${String(value)}`,\n );\n }\n // Normalizes -0 to 0; RFC 8785 has no signed zero.\n return String(value === 0 ? 0 : value);\n }\n case 'undefined':\n throw canonicalizationFailure(path, 'undefined has no canonical form');\n case 'bigint':\n throw canonicalizationFailure(path, 'bigint is not a JSON type');\n case 'function':\n case 'symbol':\n throw canonicalizationFailure(path, `${typeof value} is not a JSON type`);\n case 'object':\n break;\n default:\n throw canonicalizationFailure(path, `unsupported type ${typeof value}`);\n }\n\n const objectValue = value as object;\n if (seen.has(objectValue)) {\n throw canonicalizationFailure(path, 'circular reference');\n }\n seen.add(objectValue);\n try {\n if (Array.isArray(objectValue)) {\n const parts = objectValue.map((entry, index) =>\n canonicalizeValue(entry, `${path}[${index}]`, seen),\n );\n return `[${parts.join(',')}]`;\n }\n if (!isPlainObject(objectValue)) {\n throw canonicalizationFailure(\n path,\n 'only plain objects and arrays are canonicalizable',\n );\n }\n // Default string sort compares UTF-16 code units, which is what RFC 8785\n // specifies for member ordering.\n const keys = Object.keys(objectValue).sort();\n const record = objectValue as Record<string, unknown>;\n const parts = keys.map((key) => {\n const encodedKey = JSON.stringify(key);\n const encodedValue = canonicalizeValue(record[key], `${path}.${key}`, seen);\n return `${encodedKey}:${encodedValue}`;\n });\n return `{${parts.join(',')}}`;\n } finally {\n seen.delete(objectValue);\n }\n}\n\n/**\n * Canonical JSON text for `value`, per RFC 8785 restricted to the value space\n * above. Key insertion order never affects the output; anything outside the\n * accepted space throws `proof_canonicalization_failed`.\n */\nexport function canonicalizeJson(value: JsonValue): string {\n return canonicalizeValue(value, '<root>', new Set());\n}\n\n/** UTF-8 bytes of {@link canonicalizeJson}. `TextEncoder` is a platform global on Node and Workers. */\nexport function canonicalizeJsonBytes(value: JsonValue): Uint8Array {\n return new TextEncoder().encode(canonicalizeJson(value));\n}\n\n// ---------------------------------------------------------------------------\n// Protected claims\n// ---------------------------------------------------------------------------\n\n/**\n * The signed claim set (§S6.2).\n *\n * The request line is expressible two ways — `method` + `path`, or a stable\n * `operationId` — and exactly one form must be present. Allowing both at once\n * would create two different canonical byte strings for one request; allowing\n * neither would drop the operation binding the whole design rests on.\n */\nexport const DeviceProofProtectedClaimsSchema = z\n .strictObject({\n version: z.literal(DEVICE_PROOF_VERSION),\n tenantId: z.string().min(1),\n productId: z.string().min(1),\n deviceId: z.string().min(1),\n /** Identity of the signing key, resolved against the device row at verify time. */\n keyId: z.string().min(1),\n /** Rotation generation. An older epoch is rejected by the verifier, not here. */\n keyEpoch: z.number().int().nonnegative(),\n /** Idempotency key: exact replay returns the original result, reuse with a different body is a conflict. */\n requestId: z.string().min(1),\n /** Logical operation, e.g. `truth.write`. */\n operation: z.string().min(1),\n /** Tenant-scoped resource the operation targets. */\n resource: z.string().min(1),\n method: z.string().regex(HTTP_METHOD_PATTERN).optional(),\n path: z.string().startsWith('/').optional(),\n operationId: z.string().min(1).optional(),\n bodySha256: z.string().regex(CONTENT_HASH_PATTERN),\n /** Bound alongside the hash so a truncation attack cannot hide behind a hash collision claim. */\n bodySize: z.number().int().nonnegative(),\n issuedAt: z.iso.datetime(),\n expiresAt: z.iso.datetime().optional(),\n nonce: z.string().min(1).optional(),\n })\n .superRefine((claims, ctx) => {\n const hasRequestLine = claims.method !== undefined && claims.path !== undefined;\n const hasOperationId = claims.operationId !== undefined;\n if (hasRequestLine === hasOperationId) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'Claims must carry exactly one request binding: both `method` and `path`, or `operationId`.',\n });\n }\n if (!hasRequestLine && (claims.method !== undefined || claims.path !== undefined)) {\n ctx.addIssue({\n code: 'custom',\n message: '`method` and `path` must be supplied together.',\n });\n }\n });\n\nexport type DeviceProofProtectedClaims = z.infer<typeof DeviceProofProtectedClaimsSchema>;\n\nexport const DeviceProofEnvelopeV1Schema = z.strictObject({\n schema: z.literal(DEVICE_PROOF_SCHEMA_ID),\n algorithm: z.enum(DEVICE_PROOF_ALGORITHMS),\n protected: DeviceProofProtectedClaimsSchema,\n /** base64url, unpadded. */\n signature: z.string().regex(BASE64URL_PATTERN),\n});\n\nexport type DeviceProofEnvelopeV1 = z.infer<typeof DeviceProofEnvelopeV1Schema>;\n\n/**\n * Parses an envelope fail-closed.\n *\n * @throws {ByokCoreError} code `proof_envelope_invalid`.\n */\nexport function parseDeviceProofEnvelope(input: unknown): DeviceProofEnvelopeV1 {\n const result = DeviceProofEnvelopeV1Schema.safeParse(input);\n if (!result.success) {\n throw new ByokCoreError(\n 'proof_envelope_invalid',\n `Invalid device proof envelope: ${result.error.issues\n .map((issue) => `${issue.path.join('.') || '<root>'}: ${issue.message}`)\n .join('; ')}`,\n { cause: result.error },\n );\n }\n return result.data;\n}\n\n/**\n * Projects claims into the exact JSON object that gets canonicalized.\n *\n * Built field by field rather than by spreading the parsed object: an absent\n * optional must be an *absent key*, never a key holding `undefined`, or\n * `{nonce: undefined}` and `{}` would be the same request with two different\n * signatures. The canonicalizer refuses `undefined` outright, so this\n * projection is where absence is decided.\n */\nexport function deviceProofCanonicalClaims(claims: DeviceProofProtectedClaims): JsonObject {\n const canonical: Record<string, JsonValue> = {\n version: claims.version,\n tenantId: claims.tenantId,\n productId: claims.productId,\n deviceId: claims.deviceId,\n keyId: claims.keyId,\n keyEpoch: claims.keyEpoch,\n requestId: claims.requestId,\n operation: claims.operation,\n resource: claims.resource,\n bodySha256: claims.bodySha256,\n bodySize: claims.bodySize,\n issuedAt: claims.issuedAt,\n };\n if (claims.method !== undefined) canonical['method'] = claims.method;\n if (claims.path !== undefined) canonical['path'] = claims.path;\n if (claims.operationId !== undefined) canonical['operationId'] = claims.operationId;\n if (claims.expiresAt !== undefined) canonical['expiresAt'] = claims.expiresAt;\n if (claims.nonce !== undefined) canonical['nonce'] = claims.nonce;\n return canonical;\n}\n\n/** Canonical JSON text of the protected claim set, without the domain prefix. */\nexport function deviceProofCanonicalJson(claims: DeviceProofProtectedClaims): string {\n return canonicalizeJson(deviceProofCanonicalClaims(claims));\n}\n\n/**\n * The exact bytes a device signs and a verifier reconstructs:\n * `byok-device-proof-v1\\n` followed by the canonical claim JSON, UTF-8 encoded.\n *\n * Frozen by `src/__tests__/golden/device-proof-v1.canonical.json`.\n */\nexport function deviceProofSigningInput(claims: DeviceProofProtectedClaims): Uint8Array {\n return new TextEncoder().encode(\n DEVICE_PROOF_DOMAIN_PREFIX + deviceProofCanonicalJson(claims),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Verify port\n// ---------------------------------------------------------------------------\n\nexport interface DeviceProofVerifyInput {\n readonly algorithm: DeviceProofAlgorithm;\n /** Raw public key, base64url — the JWK `x` encoding the device registry stores. */\n readonly publicKey: string;\n readonly signature: string;\n readonly signingInput: Uint8Array;\n}\n\n/**\n * Injected signature verification.\n *\n * Not a store port, so it has no tenant parameter: it answers a pure\n * cryptographic question about bytes. Deciding *which* key to check against is\n * the caller's tenant-scoped device-row lookup, and keeping that out of here is\n * what stops a verifier from becoming a second authority on device identity.\n */\nexport interface DeviceProofVerifier {\n verify(input: DeviceProofVerifyInput): Promise<boolean>;\n}\n","/**\n * In-memory {@link PresenceStore} and {@link ActivityStore} reference (§12.3).\n *\n * Expiry is absence. A hint past its `expiresAt` is filtered out of every read\n * and lazily dropped, so no reader can ever observe a stale level and mistake\n * it for a live one. Both stores read time from the injected clock, which is\n * what lets the conformance suite assert expiry without sleeping.\n */\nimport { ByokCoreError } from '../errors';\nimport {\n DEFAULT_ACTIVITY_CAPACITY,\n type ActivityAppendInput,\n type ActivityEntry,\n type ActivityStore,\n type ActivityTail,\n type PresenceHint,\n type PresenceHintInput,\n type PresenceStore,\n} from '../presence';\nimport type { Clock } from '../stores';\nimport { tenantKey, type TenantId } from '../tenant';\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 InMemoryPresenceStore implements PresenceStore {\n readonly #hints = new Map<string, PresenceHint>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\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 key = tenantKey(tenant, input.deviceId);\n const existing = this.#hints.get(key);\n if (\n existing !== undefined &&\n now.toISOString() < existing.expiresAt &&\n now.getTime() - Date.parse(existing.observedAt) < input.minimumIntervalMs\n ) {\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 const hint: PresenceHint = {\n tenantId: tenant,\n deviceId: input.deviceId,\n level: input.level,\n ...(input.detail === undefined ? {} : { detail: input.detail }),\n observedAt: now.toISOString(),\n expiresAt: new Date(now.getTime() + input.ttlMs).toISOString(),\n };\n this.#hints.set(key, hint);\n return hint;\n }\n\n async read(tenant: TenantId, deviceId: string): Promise<PresenceHint | undefined> {\n const key = tenantKey(tenant, deviceId);\n const hint = this.#hints.get(key);\n if (hint === undefined) return undefined;\n if (this.#isExpired(hint.expiresAt)) {\n this.#hints.delete(key);\n return undefined;\n }\n return hint;\n }\n\n async list(tenant: TenantId): Promise<readonly PresenceHint[]> {\n const prefix = tenantKey(tenant, '');\n const live: PresenceHint[] = [];\n for (const [key, hint] of [...this.#hints.entries()]) {\n if (!key.startsWith(prefix)) continue;\n if (this.#isExpired(hint.expiresAt)) {\n this.#hints.delete(key);\n continue;\n }\n live.push(hint);\n }\n live.sort((left, right) => left.deviceId.localeCompare(right.deviceId));\n return live;\n }\n\n #isExpired(expiresAt: string): boolean {\n return this.#clock.now().toISOString() >= expiresAt;\n }\n}\n\nexport class InMemoryActivityStore implements ActivityStore {\n readonly #tails = new Map<string, ActivityTail>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async append(tenant: TenantId, input: ActivityAppendInput): Promise<ActivityTail> {\n assertTtl(input.ttlMs);\n const capacity = input.capacity ?? DEFAULT_ACTIVITY_CAPACITY;\n if (!Number.isSafeInteger(capacity) || capacity <= 0) {\n throw new ByokCoreError(\n 'activity_capacity_invalid',\n `Activity capacity must be a positive integer, received ${String(capacity)}.`,\n );\n }\n if (input.details.length === 0 || !Number.isSafeInteger(input.dropped) || input.dropped < 0) {\n throw new ByokCoreError(\n 'activity_batch_invalid',\n 'Activity batches require at least one detail and a non-negative integer dropped count.',\n );\n }\n\n const now = this.#clock.now();\n const key = tenantKey(tenant, input.taskId);\n const existing = this.#tails.get(key);\n const live =\n existing !== undefined && now.toISOString() < existing.expiresAt ? existing : undefined;\n\n const appended: ActivityEntry[] = input.details.map((detail) => ({\n at: now.toISOString(),\n detail,\n }));\n const entries = [...(live?.entries ?? []), ...appended];\n let dropped = (live?.dropped ?? 0) + input.dropped;\n while (entries.length > capacity) {\n entries.shift();\n // Lossiness is data, not an omission: a reader can tell \"nothing\n // happened\" from \"we lost the middle\".\n dropped += 1;\n }\n\n const tail: ActivityTail = {\n tenantId: tenant,\n taskId: input.taskId,\n entries,\n dropped,\n capacity,\n expiresAt: new Date(now.getTime() + input.ttlMs).toISOString(),\n };\n this.#tails.set(key, tail);\n return tail;\n }\n\n async read(tenant: TenantId, taskId: string): Promise<ActivityTail | undefined> {\n const key = tenantKey(tenant, taskId);\n const tail = this.#tails.get(key);\n if (tail === undefined) return undefined;\n if (this.#clock.now().toISOString() >= tail.expiresAt) {\n this.#tails.delete(key);\n return undefined;\n }\n return tail;\n }\n}\n","/**\n * In-memory {@link BoardStore} reference (§12.3).\n *\n * The claim path is the interesting one: because JavaScript resolves each\n * `await` boundary atomically here, N concurrent `claim` calls serialize and\n * exactly one finds `assignee === undefined`. A SQL composition gets the same\n * outcome from a conditional `UPDATE ... WHERE assignee IS NULL`; the\n * conformance suite asserts the outcome, not the mechanism.\n *\n * `boardSeq` is per tenant and bumps on every mutation, which is what makes\n * `list({ afterSeq })` an incremental feed that cannot leak another tenant's\n * write rate.\n */\nimport {\n isLegalBoardTransition,\n type BoardClaimInput,\n type BoardItem,\n type BoardItemInput,\n type BoardListQuery,\n type BoardPage,\n type BoardStatusUpdateInput,\n type BoardStore,\n type BoardUnclaimInput,\n} from '../board';\nimport { ByokCoreError, CoreConflictError } from '../errors';\nimport type { Clock } from '../stores';\nimport { tenantKey, type TenantId } from '../tenant';\n\nconst DEFAULT_LIST_LIMIT = 50;\n\nexport class InMemoryBoardStore implements BoardStore {\n readonly #items = new Map<string, BoardItem>();\n readonly #seqByTenant = new Map<string, number>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async create(tenant: TenantId, input: BoardItemInput): Promise<BoardItem> {\n const key = tenantKey(tenant, input.itemId);\n if (this.#items.has(key)) {\n throw new ByokCoreError(\n 'board_item_exists',\n `Board item ${input.itemId} already exists in this tenant.`,\n );\n }\n const now = this.#now();\n const item: BoardItem = {\n tenantId: tenant,\n itemId: input.itemId,\n channel: input.channel,\n title: input.title,\n status: input.status ?? 'todo',\n boardSeq: this.#nextSeq(tenant),\n createdAt: now,\n updatedAt: now,\n };\n this.#items.set(key, item);\n return item;\n }\n\n async get(tenant: TenantId, itemId: string): Promise<BoardItem | undefined> {\n return this.#items.get(tenantKey(tenant, itemId));\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 prefix = tenantKey(tenant, '');\n const matches: BoardItem[] = [];\n for (const [key, item] of this.#items.entries()) {\n if (!key.startsWith(prefix)) continue;\n if (item.boardSeq <= afterSeq) continue;\n if (query.channel !== undefined && item.channel !== query.channel) continue;\n if (query.status !== undefined && item.status !== query.status) continue;\n matches.push(item);\n }\n matches.sort((left, right) => left.boardSeq - right.boardSeq);\n const page = matches.slice(0, limit);\n return {\n items: page,\n nextSeq: page.at(-1)?.boardSeq ?? afterSeq,\n hasMore: matches.length > page.length,\n };\n }\n\n async claim(tenant: TenantId, input: BoardClaimInput): Promise<BoardItem> {\n const item = this.#require(tenant, input.itemId);\n const expectedStatus = input.expectedStatus ?? 'todo';\n\n if (item.assignee !== undefined) {\n if (item.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 skipping it here would\n // let the holder's retry succeed against a status it no longer believes\n // in — a CAS in name only. The default is not applied on this path: a\n // retry of a successful claim legitimately observes `in_progress`.\n if (input.expectedStatus !== undefined && item.status !== input.expectedStatus) {\n throw new CoreConflictError(\n 'board_status_conflict',\n `Board item ${input.itemId} is ${item.status}, not ${input.expectedStatus}.`,\n item,\n this.#now(),\n );\n }\n return item;\n }\n throw new CoreConflictError(\n 'board_claim_conflict',\n `Board item ${input.itemId} is held by ${item.assignee.holderId}.`,\n item,\n this.#now(),\n );\n }\n if (item.status !== expectedStatus) {\n throw new CoreConflictError(\n 'board_status_conflict',\n `Board item ${input.itemId} is ${item.status}, not ${expectedStatus}.`,\n item,\n this.#now(),\n );\n }\n if (item.status !== 'todo' && item.status !== 'in_progress') {\n throw new CoreConflictError(\n 'board_transition_invalid',\n `Board item ${input.itemId} cannot be claimed from ${item.status}.`,\n item,\n this.#now(),\n );\n }\n\n const now = this.#now();\n const claimed: BoardItem = {\n ...item,\n status: item.status === 'todo' ? 'in_progress' : item.status,\n assignee: { holderId: input.holderId, heldSince: now },\n boardSeq: this.#nextSeq(tenant),\n updatedAt: now,\n };\n this.#items.set(tenantKey(tenant, input.itemId), claimed);\n return claimed;\n }\n\n async unclaim(tenant: TenantId, input: BoardUnclaimInput): Promise<BoardItem> {\n const item = this.#require(tenant, input.itemId);\n if (item.assignee === undefined) {\n throw new ByokCoreError(\n 'board_not_held',\n `Board item ${input.itemId} is not held by anyone.`,\n );\n }\n if (item.assignee.holderId !== input.holderId) {\n throw new CoreConflictError(\n 'board_claim_conflict',\n `Board item ${input.itemId} is held by ${item.assignee.holderId}, not ${input.holderId}.`,\n item,\n this.#now(),\n );\n }\n const now = this.#now();\n const released: BoardItem = {\n tenantId: item.tenantId,\n itemId: item.itemId,\n channel: item.channel,\n title: item.title,\n status: item.status === 'in_progress' ? 'todo' : item.status,\n boardSeq: this.#nextSeq(tenant),\n createdAt: item.createdAt,\n updatedAt: now,\n };\n this.#items.set(tenantKey(tenant, input.itemId), released);\n return released;\n }\n\n async updateStatus(tenant: TenantId, input: BoardStatusUpdateInput): Promise<BoardItem> {\n const item = this.#require(tenant, input.itemId);\n if (item.status !== input.expectedStatus) {\n throw new CoreConflictError(\n 'board_status_conflict',\n `Board item ${input.itemId} is ${item.status}, not ${input.expectedStatus}.`,\n item,\n this.#now(),\n );\n }\n if (input.holderId !== undefined && item.assignee?.holderId !== input.holderId) {\n throw new CoreConflictError(\n 'board_claim_conflict',\n `Board item ${input.itemId} is not held by ${input.holderId}.`,\n item,\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 item,\n this.#now(),\n );\n }\n const now = this.#now();\n const updated: BoardItem = {\n ...item,\n status: input.status,\n boardSeq: this.#nextSeq(tenant),\n updatedAt: now,\n };\n this.#items.set(tenantKey(tenant, input.itemId), updated);\n return updated;\n }\n\n #require(tenant: TenantId, itemId: string): BoardItem {\n const item = this.#items.get(tenantKey(tenant, itemId));\n if (item === undefined) {\n throw new ByokCoreError(\n 'board_item_not_found',\n `Board item ${itemId} does not exist in this tenant.`,\n );\n }\n return item;\n }\n\n #nextSeq(tenant: TenantId): number {\n const next = (this.#seqByTenant.get(tenant) ?? 0) + 1;\n this.#seqByTenant.set(tenant, next);\n return next;\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * In-memory {@link MailboxStore} reference (§12.7.3).\n *\n * Every row lives under a `(tenant, device)` composite key, so a cross-tenant\n * read is not \"denied\" — it addresses a different key space and finds nothing.\n * That is the in-memory expression of §12.6.2 layer 3: there is no bare device\n * index to accidentally query.\n */\nimport { ByokCoreError, CoreConflictError } from '../errors';\nimport type {\n MailboxAdvanceCursorInput,\n MailboxAppendInput,\n MailboxCursorState,\n MailboxMessage,\n MailboxPage,\n MailboxReadQuery,\n MailboxRetentionInput,\n MailboxRetentionResult,\n MailboxStore,\n} from '../mailbox';\nimport type { Clock } from '../stores';\nimport { tenantKey, type TenantId } from '../tenant';\nimport { assertCanonicalTimestamp } from '../time';\n\nconst DEFAULT_READ_LIMIT = 50;\n\ninterface DeviceMailbox {\n nextSeq: number;\n ackedSeq: number;\n cursorUpdatedAt: string;\n readonly messages: MailboxMessage[];\n readonly byMessageId: Map<string, MailboxMessage>;\n}\n\nexport class InMemoryMailboxStore implements MailboxStore {\n readonly #devices = new Map<string, DeviceMailbox>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async append(tenant: TenantId, input: MailboxAppendInput): Promise<MailboxMessage> {\n const device = this.#device(tenant, input.deviceId);\n const existing = device.byMessageId.get(input.messageId);\n if (existing !== undefined) return existing;\n\n const message: MailboxMessage = {\n tenantId: tenant,\n deviceId: input.deviceId,\n seq: device.nextSeq,\n messageId: input.messageId,\n body: input.body,\n bodyHash: input.bodyHash,\n byteSize: input.byteSize,\n state: 'pending',\n appendedAt: this.#now(),\n };\n device.nextSeq += 1;\n device.messages.push(message);\n device.byMessageId.set(message.messageId, message);\n return message;\n }\n\n async readAfter(tenant: TenantId, query: MailboxReadQuery): Promise<MailboxPage> {\n const device = this.#devices.get(tenantKey(tenant, query.deviceId));\n const limit = query.limit ?? DEFAULT_READ_LIMIT;\n if (device === undefined) {\n return { messages: [], nextSeq: query.afterSeq, hasMore: false };\n }\n const pending = device.messages\n .filter((message) => message.state === 'pending' && message.seq > query.afterSeq)\n .sort((left, right) => left.seq - right.seq);\n const page = pending.slice(0, limit);\n const last = page.at(-1);\n return {\n messages: page,\n // Reading is not acknowledging: the returned position is a *read* cursor.\n // Nothing above was mutated, so an identical call replays the same page.\n nextSeq: last?.seq ?? query.afterSeq,\n hasMore: pending.length > page.length,\n };\n }\n\n async advanceCursor(\n tenant: TenantId,\n input: MailboxAdvanceCursorInput,\n ): Promise<MailboxCursorState> {\n const device = this.#device(tenant, input.deviceId);\n if (input.ackedSeq < device.ackedSeq) {\n throw new CoreConflictError(\n 'mailbox_cursor_regression',\n `Cursor for device ${input.deviceId} is at ${device.ackedSeq}; refusing to move it back to ${input.ackedSeq}.`,\n this.#cursorState(tenant, input.deviceId, device),\n this.#now(),\n );\n }\n device.ackedSeq = input.ackedSeq;\n device.cursorUpdatedAt = this.#now();\n for (const [index, message] of device.messages.entries()) {\n if (message.state === 'pending' && message.seq <= input.ackedSeq) {\n device.messages[index] = { ...message, state: 'acked' };\n device.byMessageId.set(message.messageId, device.messages[index]!);\n }\n }\n return this.#cursorState(tenant, input.deviceId, device);\n }\n\n async readCursor(tenant: TenantId, deviceId: string): Promise<MailboxCursorState> {\n const device = this.#devices.get(tenantKey(tenant, deviceId));\n if (device === undefined) {\n return { tenantId: tenant, deviceId, ackedSeq: 0, updatedAt: this.#now() };\n }\n return this.#cursorState(tenant, deviceId, device);\n }\n\n async collectRetired(\n tenant: TenantId,\n input: MailboxRetentionInput,\n ): Promise<MailboxRetentionResult> {\n // Both cutoffs are compared against `appendedAt` as strings; the canonical\n // form is what makes that a time comparison. Validate before the sweep so a\n // malformed cutoff deletes nothing rather than a wrong prefix of history.\n assertCanonicalTimestamp(input.ackedBefore, 'ackedBefore');\n assertCanonicalTimestamp(input.expireUnackedBefore, 'expireUnackedBefore');\n\n let deletedCount = 0;\n let expiredCount = 0;\n let releasedBytes = 0n;\n\n for (const [key, device] of this.#devices.entries()) {\n if (!key.startsWith(tenantKey(tenant, ''))) continue;\n if (input.deviceId !== undefined && key !== tenantKey(tenant, input.deviceId)) continue;\n\n for (let index = device.messages.length - 1; index >= 0; index -= 1) {\n const message = device.messages[index]!;\n if (message.state === 'acked' && message.appendedAt < input.ackedBefore) {\n device.messages.splice(index, 1);\n device.byMessageId.delete(message.messageId);\n deletedCount += 1;\n releasedBytes += message.byteSize;\n continue;\n }\n if (message.state === 'pending' && message.appendedAt < input.expireUnackedBefore) {\n // Dead-letter, never delete: §12.7.5 requires an unacked row that\n // aged out to stay visible instead of disappearing silently.\n const expired: MailboxMessage = { ...message, state: 'expired' };\n device.messages[index] = expired;\n device.byMessageId.set(expired.messageId, expired);\n expiredCount += 1;\n }\n }\n }\n\n return { deletedCount, expiredCount, releasedBytes };\n }\n\n #device(tenant: TenantId, deviceId: string): DeviceMailbox {\n if (deviceId.length === 0) {\n throw new ByokCoreError('mailbox_message_not_found', 'Device id must not be empty.');\n }\n const key = tenantKey(tenant, deviceId);\n const existing = this.#devices.get(key);\n if (existing !== undefined) return existing;\n const created: DeviceMailbox = {\n nextSeq: 1,\n ackedSeq: 0,\n cursorUpdatedAt: this.#now(),\n messages: [],\n byMessageId: new Map(),\n };\n this.#devices.set(key, created);\n return created;\n }\n\n #cursorState(\n tenant: TenantId,\n deviceId: string,\n device: DeviceMailbox,\n ): MailboxCursorState {\n return {\n tenantId: tenant,\n deviceId,\n ackedSeq: device.ackedSeq,\n updatedAt: device.cursorUpdatedAt,\n };\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * In-memory {@link ObjectStore} reference (§12.7.4, §12.7.8).\n *\n * Metadata only — there are no bytes here, and there are none in the Postgres\n * composition either: the manifest is the transaction authority and the object\n * store holds the payload. `refCount` is derived from the reference rows rather\n * than incremented in place, so a double `addReference` for the same\n * `(refKind, refId)` cannot inflate it and strand an object forever.\n */\nimport {\n isLegalObjectTransition,\n type ContentHash,\n type ObjectCommitInput,\n type ObjectListQuery,\n type ObjectManifestEntry,\n type ObjectManifestInput,\n type ObjectReference,\n type ObjectReferenceInput,\n type ObjectStore,\n} from '../blob';\nimport { ByokCoreError } from '../errors';\nimport type { Clock } from '../stores';\nimport { tenantKey, type TenantId } from '../tenant';\nimport { assertCanonicalTimestamp } from '../time';\n\nconst DEFAULT_LIST_LIMIT = 100;\n\nexport class InMemoryObjectStore implements ObjectStore {\n readonly #manifest = new Map<string, ObjectManifestEntry>();\n readonly #references = new Map<string, ObjectReference>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async putManifest(\n tenant: TenantId,\n input: ObjectManifestInput,\n ): Promise<ObjectManifestEntry> {\n const key = tenantKey(tenant, input.hash);\n const existing = this.#manifest.get(key);\n if (existing !== undefined && existing.state !== 'deleted') return existing;\n\n const now = this.#now();\n const entry: ObjectManifestEntry = {\n tenantId: tenant,\n hash: input.hash,\n byteSize: input.byteSize,\n contentType: input.contentType,\n state: 'pending',\n refCount: 0,\n createdAt: now,\n updatedAt: now,\n };\n this.#manifest.set(key, entry);\n return entry;\n }\n\n async commit(tenant: TenantId, input: ObjectCommitInput): Promise<ObjectManifestEntry> {\n const entry = this.#require(tenant, input.hash);\n if (\n entry.byteSize !== input.observedByteSize ||\n entry.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 (entry.state === 'committed') return entry;\n return this.#transition(tenant, entry, 'committed');\n }\n\n async get(tenant: TenantId, hash: ContentHash): Promise<ObjectManifestEntry | undefined> {\n return this.#manifest.get(tenantKey(tenant, hash));\n }\n\n async list(\n tenant: TenantId,\n query: ObjectListQuery,\n ): Promise<readonly ObjectManifestEntry[]> {\n // The cutoff is compared against `deletePendingAt` as a string below, which\n // only equals a time comparison for the canonical form. A GC sweep reading\n // a mis-parsed cutoff would either miss tombstones or take live ones.\n if (query.deletePendingBefore !== undefined) {\n assertCanonicalTimestamp(query.deletePendingBefore, 'deletePendingBefore');\n }\n const prefix = tenantKey(tenant, '');\n const matches: ObjectManifestEntry[] = [];\n for (const [key, entry] of this.#manifest.entries()) {\n if (!key.startsWith(prefix)) continue;\n if (query.state !== undefined && entry.state !== query.state) continue;\n if (query.deletePendingBefore !== undefined) {\n if (entry.deletePendingAt === undefined) continue;\n if (entry.deletePendingAt >= query.deletePendingBefore) continue;\n }\n matches.push(entry);\n }\n matches.sort((left, right) => left.hash.localeCompare(right.hash));\n return matches.slice(0, query.limit ?? DEFAULT_LIST_LIMIT);\n }\n\n async addReference(\n tenant: TenantId,\n input: ObjectReferenceInput,\n ): Promise<ObjectManifestEntry> {\n const entry = this.#require(tenant, input.hash);\n if (entry.state !== 'committed') {\n throw new ByokCoreError(\n 'object_state_invalid',\n `Only committed objects can be referenced; ${input.hash} is ${entry.state}.`,\n );\n }\n const refKey = tenantKey(tenant, input.hash, input.refKind, input.refId);\n if (!this.#references.has(refKey)) {\n this.#references.set(refKey, {\n tenantId: tenant,\n hash: input.hash,\n refKind: input.refKind,\n refId: input.refId,\n createdAt: this.#now(),\n });\n }\n return this.#recount(tenant, entry);\n }\n\n async removeReference(\n tenant: TenantId,\n input: ObjectReferenceInput,\n ): Promise<ObjectManifestEntry> {\n const entry = this.#require(tenant, input.hash);\n this.#references.delete(tenantKey(tenant, input.hash, input.refKind, input.refId));\n return this.#recount(tenant, entry);\n }\n\n async markDeletePending(\n tenant: TenantId,\n hash: ContentHash,\n ): Promise<ObjectManifestEntry> {\n const entry = this.#require(tenant, hash);\n if (entry.refCount !== 0) {\n throw new ByokCoreError(\n 'object_state_invalid',\n `Object ${hash} still has ${entry.refCount} reference(s).`,\n );\n }\n return this.#transition(tenant, entry, 'delete_pending');\n }\n\n async markDeleted(tenant: TenantId, hash: ContentHash): Promise<ObjectManifestEntry> {\n const entry = this.#require(tenant, hash);\n return this.#transition(tenant, entry, 'deleted');\n }\n\n #transition(\n tenant: TenantId,\n entry: ObjectManifestEntry,\n next: ObjectManifestEntry['state'],\n ): ObjectManifestEntry {\n if (!isLegalObjectTransition(entry.state, next)) {\n throw new ByokCoreError(\n 'object_state_invalid',\n `${entry.state} to ${next} is not a legal object manifest transition.`,\n );\n }\n const now = this.#now();\n const updated: ObjectManifestEntry = {\n ...entry,\n state: next,\n updatedAt: now,\n ...(next === 'delete_pending' ? { deletePendingAt: now } : {}),\n };\n this.#manifest.set(tenantKey(tenant, entry.hash), updated);\n return updated;\n }\n\n #recount(tenant: TenantId, entry: ObjectManifestEntry): ObjectManifestEntry {\n const refPrefix = tenantKey(tenant, entry.hash, '');\n let refCount = 0;\n for (const key of this.#references.keys()) {\n if (key.startsWith(refPrefix)) refCount += 1;\n }\n const updated: ObjectManifestEntry = { ...entry, refCount, updatedAt: this.#now() };\n this.#manifest.set(tenantKey(tenant, entry.hash), updated);\n return updated;\n }\n\n #require(tenant: TenantId, hash: ContentHash): ObjectManifestEntry {\n const entry = this.#manifest.get(tenantKey(tenant, hash));\n if (entry === undefined) {\n throw new ByokCoreError(\n 'object_not_found',\n `Object ${hash} has no manifest row in this tenant.`,\n );\n }\n return entry;\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * In-memory {@link QuotaStore} reference (§12.7.6-12.7.7).\n *\n * The invariant this file exists to hold is\n * `committed + reserved + expected <= hardLimitBytes`, checked inside\n * {@link InMemoryQuotaStore.reserve} before any bytes are handed out. A\n * Postgres composition does the same check inside a row-locked transaction;\n * both must reject the same set of concurrent reservations, which is what the\n * conformance suite asserts.\n *\n * Per-tenant hash deduplication lives here rather than in the object manifest\n * because usage accounting is what deduplication is *for* (§12.7.6: same\n * tenant, same hash, counted once). In SQL this set is a join against\n * `object_manifest`; here it is an explicit set, and the observable behavior is\n * identical: finalizing an already-committed hash releases the reservation and\n * adds nothing.\n */\nimport { ByokCoreError, CoreConflictError } from '../errors';\nimport type { ObjectStore } from '../blob';\nimport type {\n MailboxUsageDeltaInput,\n StorageFinalizeInput,\n StorageFinalizeResult,\n StorageReservation,\n StorageReservationInput,\n StorageStatus,\n StorageWritePosture,\n QuotaStore,\n TenantStorageEntitlement,\n TenantStorageEntitlementInput,\n TenantStorageUsage,\n} from '../quota';\nimport type { Clock } from '../stores';\nimport { tenantKey, type TenantId } from '../tenant';\nimport { assertCanonicalTimestamp } from '../time';\n\n/** Warning threshold from §12.7.8: 80% of the hard limit. */\nconst WARNING_NUMERATOR = 80n;\nconst WARNING_DENOMINATOR = 100n;\n\ninterface ReservationRecord {\n reservation: StorageReservation;\n deduplicated: boolean;\n}\n\nexport class InMemoryQuotaStore implements QuotaStore {\n readonly #entitlements = new Map<string, TenantStorageEntitlement>();\n readonly #usage = new Map<string, TenantStorageUsage>();\n readonly #reservations = new Map<string, ReservationRecord>();\n readonly #committedHashes = new Map<string, Set<string>>();\n readonly #clock: Clock;\n readonly #objects: ObjectStore;\n\n constructor(clock: Clock, objects: ObjectStore) {\n this.#clock = clock;\n this.#objects = objects;\n }\n\n async readEntitlement(tenant: TenantId): Promise<TenantStorageEntitlement | undefined> {\n return this.#entitlements.get(tenant);\n }\n\n async writeEntitlement(\n tenant: TenantId,\n input: TenantStorageEntitlementInput,\n ): Promise<TenantStorageEntitlement> {\n // Validated before the version CAS: an unusable deadline is a bad write\n // regardless of which version wins, and `readStatus` compares this field as\n // a string (canonical form is what makes that equal a time comparison).\n if (input.downgradeGraceUntil !== undefined) {\n assertCanonicalTimestamp(input.downgradeGraceUntil, 'downgradeGraceUntil');\n }\n const existing = this.#entitlements.get(tenant);\n if (existing !== undefined && input.version <= existing.version) {\n throw new CoreConflictError(\n 'storage_entitlement_version_conflict',\n `Entitlement is at version ${String(existing.version)}; refusing to apply version ${String(input.version)}.`,\n existing,\n this.#now(),\n );\n }\n const entitlement: TenantStorageEntitlement = {\n tenantId: tenant,\n version: input.version,\n hardLimitBytes: input.hardLimitBytes,\n maxObjectBytes: input.maxObjectBytes,\n maxInlineBytes: input.maxInlineBytes,\n mailboxLimitBytes: input.mailboxLimitBytes,\n retentionPolicyId: input.retentionPolicyId,\n ...(input.downgradeGraceUntil === undefined\n ? {}\n : { downgradeGraceUntil: input.downgradeGraceUntil }),\n };\n this.#entitlements.set(tenant, entitlement);\n return entitlement;\n }\n\n async readUsage(tenant: TenantId): Promise<TenantStorageUsage> {\n return this.#usageOf(tenant);\n }\n\n async readStatus(tenant: TenantId): Promise<StorageStatus> {\n const entitlement = this.#requireEntitlement(tenant);\n const usage = this.#usageOf(tenant);\n const used = this.#usedBytes(usage);\n const graceActive =\n entitlement.downgradeGraceUntil !== undefined &&\n this.#now() < entitlement.downgradeGraceUntil;\n return {\n entitlement,\n usage,\n posture: this.#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 this.#reservations.get(tenantKey(tenant, reservationId))?.reservation;\n }\n\n async reserve(\n tenant: TenantId,\n input: StorageReservationInput,\n ): Promise<StorageReservation> {\n const entitlement = this.#requireEntitlement(tenant);\n // Admission is the bounded product-side reap point. A daemon may die\n // after receiving a grant and never call finalize/abort; expired holds\n // therefore have to be settled before they can deny the next write.\n await this.expireReservations(tenant);\n const key = tenantKey(tenant, input.reservationId);\n const existing = this.#reservations.get(key);\n if (existing !== undefined) {\n if (existing.reservation.state === 'reserved') {\n if (\n existing.reservation.kind !== input.kind ||\n existing.reservation.expectedBytes !== input.expectedBytes ||\n existing.reservation.contentHash !== input.contentHash ||\n existing.reservation.contentType !== input.contentType\n ) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Reservation ${input.reservationId} already binds a different storage declaration.`,\n );\n }\n return existing.reservation;\n }\n throw new ByokCoreError(\n 'storage_reservation_expired',\n `Reservation ${input.reservationId} is already ${existing.reservation.state}.`,\n );\n }\n\n const usage = this.#usageOf(tenant);\n const graceActive =\n entitlement.downgradeGraceUntil !== undefined &&\n this.#now() < entitlement.downgradeGraceUntil;\n if (this.#posture(entitlement, usage, graceActive) === 'suspended') {\n throw 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 perObjectLimit =\n input.kind === 'object' ? entitlement.maxObjectBytes : entitlement.maxInlineBytes;\n if (input.expectedBytes > perObjectLimit) {\n throw new ByokCoreError(\n 'storage_object_too_large',\n `${String(input.expectedBytes)} bytes exceeds the ${input.kind} limit of ${String(perObjectLimit)} bytes.`,\n );\n }\n if (this.#usedBytes(usage) + input.expectedBytes > entitlement.hardLimitBytes) {\n throw 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 const now = this.#now();\n const reservation: StorageReservation = {\n tenantId: tenant,\n reservationId: input.reservationId,\n state: 'reserved',\n kind: input.kind,\n expectedBytes: input.expectedBytes,\n contentHash: input.contentHash,\n contentType: input.contentType,\n createdAt: now,\n expiresAt: new Date(this.#clock.now().getTime() + input.ttlMs).toISOString(),\n };\n this.#reservations.set(key, { reservation, deduplicated: false });\n this.#setUsage(tenant, { ...usage, reservedBytes: usage.reservedBytes + input.expectedBytes });\n return reservation;\n }\n\n async finalizeReservation(\n tenant: TenantId,\n input: StorageFinalizeInput,\n ): Promise<StorageFinalizeResult> {\n const key = tenantKey(tenant, input.reservationId);\n const record = this.#requireReservation(tenant, input.reservationId);\n const reservation = record.reservation;\n\n if (reservation.state === 'committed') {\n return {\n reservation,\n usage: this.#usageOf(tenant),\n deduplicated: record.deduplicated,\n };\n }\n if (reservation.state !== 'reserved') {\n throw new ByokCoreError(\n 'storage_reservation_expired',\n `Reservation ${input.reservationId} is ${reservation.state}.`,\n );\n }\n if (this.#now() >= reservation.expiresAt) {\n this.#settle(tenant, key, record, 'expired');\n throw new ByokCoreError(\n 'storage_reservation_expired',\n `Reservation ${input.reservationId} expired at ${reservation.expiresAt}.`,\n );\n }\n if (\n input.observedByteSize !== reservation.expectedBytes ||\n input.observedContentType !== reservation.contentType\n ) {\n // §12.7.7 step 6: a failed finalize releases the bytes; the uploaded\n // object becomes an orphan candidate for the GC worker.\n this.#settle(tenant, key, record, 'aborted');\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Observed object does not match reservation ${input.reservationId}.`,\n );\n }\n\n if (reservation.kind === 'object') {\n try {\n await this.#objects.commit(tenant, {\n hash: reservation.contentHash,\n observedByteSize: input.observedByteSize,\n observedContentType: input.observedContentType,\n });\n } catch (error) {\n this.#settle(tenant, key, record, 'aborted');\n if (\n error instanceof ByokCoreError &&\n (error.code === 'object_not_found' || error.code === 'object_state_invalid')\n ) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Reservation ${input.reservationId} has no committable object manifest.`,\n { cause: error },\n );\n }\n throw error;\n }\n }\n\n const hashes = this.#hashesOf(tenant);\n // Same tenant, same hash, counted once (§12.7.6). `#settle` has already\n // released the reserved bytes, so a deduplicated finalize adds nothing.\n const deduplicated = hashes.has(reservation.contentHash);\n const settled = this.#settle(tenant, key, record, 'committed', deduplicated);\n\n if (!deduplicated) {\n hashes.add(reservation.contentHash);\n const current = this.#usageOf(tenant);\n this.#setUsage(tenant, {\n ...current,\n committedObjectBytes:\n reservation.kind === 'object'\n ? current.committedObjectBytes + reservation.expectedBytes\n : current.committedObjectBytes,\n committedInlineBytes:\n reservation.kind === 'inline'\n ? current.committedInlineBytes + reservation.expectedBytes\n : current.committedInlineBytes,\n objectCount:\n reservation.kind === 'object' ? current.objectCount + 1n : current.objectCount,\n });\n }\n\n return { reservation: settled, usage: this.#usageOf(tenant), deduplicated };\n }\n\n async abortReservation(\n tenant: TenantId,\n reservationId: string,\n ): Promise<StorageReservation> {\n const key = tenantKey(tenant, reservationId);\n const record = this.#requireReservation(tenant, reservationId);\n if (record.reservation.state !== 'reserved') return record.reservation;\n return this.#settle(tenant, key, record, 'aborted');\n }\n\n async expireReservations(tenant: TenantId): Promise<readonly StorageReservation[]> {\n const prefix = tenantKey(tenant, '');\n const now = this.#now();\n const expired: StorageReservation[] = [];\n for (const [key, record] of [...this.#reservations.entries()]) {\n if (!key.startsWith(prefix)) continue;\n if (record.reservation.state !== 'reserved') continue;\n if (now < record.reservation.expiresAt) continue;\n expired.push(this.#settle(tenant, key, record, 'expired'));\n }\n return expired;\n }\n\n async applyMailboxDelta(\n tenant: TenantId,\n input: MailboxUsageDeltaInput,\n ): Promise<TenantStorageUsage> {\n const entitlement = this.#requireEntitlement(tenant);\n const usage = this.#usageOf(tenant);\n const next = usage.mailboxBytes + input.deltaBytes;\n if (input.deltaBytes > 0n && next > entitlement.mailboxLimitBytes) {\n throw new ByokCoreError(\n 'storage_quota_exceeded',\n `Mailbox would reach ${String(next)} bytes, over the limit of ${String(entitlement.mailboxLimitBytes)} bytes.`,\n );\n }\n this.#setUsage(tenant, { ...usage, mailboxBytes: next < 0n ? 0n : next });\n return this.#usageOf(tenant);\n }\n\n #settle(\n tenant: TenantId,\n key: string,\n record: ReservationRecord,\n state: Exclude<StorageReservation['state'], 'reserved'>,\n deduplicated = false,\n ): StorageReservation {\n const settled: StorageReservation = {\n ...record.reservation,\n state,\n settledAt: this.#now(),\n };\n this.#reservations.set(key, { reservation: settled, deduplicated });\n const usage = this.#usageOf(tenant);\n const released = usage.reservedBytes - record.reservation.expectedBytes;\n this.#setUsage(tenant, { ...usage, reservedBytes: released < 0n ? 0n : released });\n return settled;\n }\n\n #posture(\n entitlement: TenantStorageEntitlement,\n usage: TenantStorageUsage,\n graceActive: boolean,\n ): StorageWritePosture {\n const used = this.#usedBytes(usage);\n if (used >= entitlement.hardLimitBytes) {\n // A tenant that was downgraded gets its configured grace window; once it\n // ends and usage is still over the limit, the tenant is read-only (423)\n // rather than merely unable to add bytes (507).\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 #usedBytes(usage: TenantStorageUsage): bigint {\n return usage.committedObjectBytes + usage.committedInlineBytes + usage.reservedBytes;\n }\n\n #usageOf(tenant: TenantId): TenantStorageUsage {\n const existing = this.#usage.get(tenant);\n if (existing !== undefined) return existing;\n const empty: TenantStorageUsage = {\n committedObjectBytes: 0n,\n committedInlineBytes: 0n,\n reservedBytes: 0n,\n mailboxBytes: 0n,\n objectCount: 0n,\n updatedAt: this.#now(),\n };\n this.#usage.set(tenant, empty);\n return empty;\n }\n\n #setUsage(tenant: TenantId, usage: TenantStorageUsage): void {\n this.#usage.set(tenant, { ...usage, updatedAt: this.#now() });\n }\n\n #hashesOf(tenant: TenantId): Set<string> {\n const existing = this.#committedHashes.get(tenant);\n if (existing !== undefined) return existing;\n const created = new Set<string>();\n this.#committedHashes.set(tenant, created);\n return created;\n }\n\n #requireEntitlement(tenant: TenantId): TenantStorageEntitlement {\n const entitlement = this.#entitlements.get(tenant);\n if (entitlement === undefined) {\n throw new ByokCoreError(\n 'storage_entitlement_missing',\n 'No storage entitlement has been issued for this tenant.',\n );\n }\n return entitlement;\n }\n\n #requireReservation(tenant: TenantId, reservationId: string): ReservationRecord {\n const record = this.#reservations.get(tenantKey(tenant, reservationId));\n if (record === undefined) {\n throw new ByokCoreError(\n 'storage_reservation_not_found',\n `Reservation ${reservationId} does not exist in this tenant.`,\n );\n }\n return record;\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * In-memory {@link TruthStore} reference (§12.3, §12.6.4).\n *\n * Two write models, one storage shape. The terminal path is first-write-wins\n * with hash-equality replay; the snapshot path is `expectedRev` CAS. Neither\n * ever merges bodies — a conflict hands back the record it lost to and stops,\n * because the device holding the context is the only party that can decide what\n * the merged truth should be.\n */\nimport { CoreConflictError } from '../errors';\nimport type { Clock } from '../stores';\nimport { tenantKey, type TenantId } from '../tenant';\nimport type {\n SnapshotWriteInput,\n TerminalWriteInput,\n TruthManifestEntry,\n TruthManifestQuery,\n TruthRecord,\n TruthRecordSelector,\n TruthStore,\n} from '../truth';\n\nconst DEFAULT_MANIFEST_LIMIT = 100;\n\nexport class InMemoryTruthStore implements TruthStore {\n readonly #records = new Map<string, TruthRecord>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async writeTerminal(tenant: TenantId, input: TerminalWriteInput): Promise<TruthRecord> {\n const key = tenantKey(tenant, 'task.terminal', input.taskId);\n const existing = this.#records.get(key);\n if (existing !== undefined) {\n if (existing.contentHash === input.contentHash) {\n // Exact replay of a committed fact: return the original, unchanged.\n return existing;\n }\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 const record: TruthRecord = {\n tenantId: tenant,\n kind: 'task.terminal',\n recordKey: input.taskId,\n rev: 1,\n contentHash: input.contentHash,\n byteSize: input.byteSize,\n body: input.body,\n ...(input.label === undefined ? {} : { label: input.label }),\n ...(input.requestId === undefined ? {} : { requestId: input.requestId }),\n writtenAt: this.#now(),\n };\n this.#records.set(key, record);\n return record;\n }\n\n async writeSnapshot(tenant: TenantId, input: SnapshotWriteInput): Promise<TruthRecord> {\n const key = tenantKey(tenant, input.kind, input.recordKey);\n const existing = this.#records.get(key);\n const currentRev = existing?.rev ?? 0;\n if (input.expectedRev !== currentRev) {\n throw new CoreConflictError<TruthRecord | undefined>(\n 'truth_revision_conflict',\n `Record ${input.kind}/${input.recordKey} is at rev ${currentRev}, not ${input.expectedRev}.`,\n existing,\n this.#now(),\n );\n }\n const record: TruthRecord = {\n tenantId: tenant,\n kind: input.kind,\n recordKey: input.recordKey,\n rev: currentRev + 1,\n contentHash: input.contentHash,\n byteSize: input.byteSize,\n body: input.body,\n ...(input.label === undefined ? {} : { label: input.label }),\n ...(input.requestId === undefined ? {} : { requestId: input.requestId }),\n writtenAt: this.#now(),\n };\n this.#records.set(key, record);\n return record;\n }\n\n async getRecord(\n tenant: TenantId,\n selector: TruthRecordSelector,\n ): Promise<TruthRecord | undefined> {\n return this.#records.get(tenantKey(tenant, selector.kind, selector.recordKey));\n }\n\n async listManifest(\n tenant: TenantId,\n query: TruthManifestQuery,\n ): Promise<readonly TruthManifestEntry[]> {\n const prefix = tenantKey(tenant, '');\n const entries: TruthManifestEntry[] = [];\n for (const [key, record] of this.#records.entries()) {\n if (!key.startsWith(prefix)) continue;\n if (query.kind !== undefined && record.kind !== query.kind) continue;\n if (query.keyPrefix !== undefined && !record.recordKey.startsWith(query.keyPrefix)) {\n continue;\n }\n entries.push({\n kind: record.kind,\n recordKey: record.recordKey,\n rev: record.rev,\n contentHash: record.contentHash,\n byteSize: record.byteSize,\n ...(record.label === undefined ? {} : { label: record.label }),\n updatedAt: record.writtenAt,\n });\n }\n entries.sort(\n (left, right) =>\n left.kind.localeCompare(right.kind) || left.recordKey.localeCompare(right.recordKey),\n );\n return entries.slice(0, query.limit ?? DEFAULT_MANIFEST_LIMIT);\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","/**\n * A deterministic clock for the in-memory reference and the conformance suite.\n *\n * TTL behavior (presence expiry, activity expiry, reservation expiry) is part\n * of the contract, and asserting it against a wall clock means either sleeping\n * or accepting flakes. A composition under test injects one of these and moves\n * time explicitly.\n */\nimport type { MutableClock } from '../stores';\n\n/** Fixed start instant, so golden-ish assertions in the suite read the same on every run. */\nexport const IN_MEMORY_CLOCK_EPOCH = '2026-01-01T00:00:00.000Z';\n\nexport function createMutableClock(start: Date = new Date(IN_MEMORY_CLOCK_EPOCH)): MutableClock {\n let current = start.getTime();\n return {\n now(): Date {\n return new Date(current);\n },\n advance(ms: number): void {\n current += ms;\n },\n set(instant: Date): void {\n current = instant.getTime();\n },\n };\n}\n","/**\n * The in-memory reference composition.\n *\n * This exists to be the first thing that passes the conformance suite, and to\n * stay the cheapest way to run it. It is a reference, not a production store:\n * everything lives in process memory and nothing survives a restart. What it\n * *does* guarantee is that the behavior the suite asserts is achievable without\n * a database, which is what makes the same assertions meaningful when a\n * Postgres + R2 composition runs them later.\n */\nimport { InMemoryActivityStore, InMemoryPresenceStore } from './presence';\nimport { InMemoryBoardStore } from './board';\nimport { InMemoryMailboxStore } from './mailbox';\nimport { InMemoryObjectStore } from './blob';\nimport { InMemoryQuotaStore } from './quota';\nimport { InMemoryTruthStore } from './truth';\nimport { createMutableClock } from './clock';\nimport type { Clock, CoreStores, MutableClock } from '../stores';\n\nexport { createMutableClock, IN_MEMORY_CLOCK_EPOCH } from './clock';\nexport { InMemoryMailboxStore } from './mailbox';\nexport { InMemoryBoardStore } from './board';\nexport { InMemoryTruthStore } from './truth';\nexport { InMemoryPresenceStore, InMemoryActivityStore } from './presence';\nexport { InMemoryObjectStore } from './blob';\nexport { InMemoryQuotaStore } from './quota';\n\nexport interface InMemoryCoreOptions {\n /** Defaults to a fresh {@link createMutableClock}, so TTL behavior is deterministic. */\n readonly clock?: Clock;\n}\n\nexport interface InMemoryCoreComposition {\n readonly stores: CoreStores;\n /** The clock the stores read. Mutable only when the caller did not inject its own. */\n readonly clock: Clock;\n}\n\nexport function createInMemoryCoreStores(\n options: InMemoryCoreOptions = {},\n): InMemoryCoreComposition {\n const clock: Clock = options.clock ?? createMutableClock();\n const objects = new InMemoryObjectStore(clock);\n const stores: CoreStores = {\n mailbox: new InMemoryMailboxStore(clock),\n board: new InMemoryBoardStore(clock),\n truth: new InMemoryTruthStore(clock),\n presence: new InMemoryPresenceStore(clock),\n activity: new InMemoryActivityStore(clock),\n objects,\n quota: new InMemoryQuotaStore(clock, objects),\n };\n return { stores, clock };\n}\n\n/** Convenience for tests that need to move time: returns the composition and its mutable clock. */\nexport function createInMemoryCoreCompositionWithClock(): {\n readonly stores: CoreStores;\n readonly clock: MutableClock;\n} {\n const clock = createMutableClock();\n return { stores: createInMemoryCoreStores({ clock }).stores, clock };\n}\n"]}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hosted mailbox contract (§12.7.3).
|
|
3
|
+
*
|
|
4
|
+
* The load-bearing rule of this file: **reading is not acknowledging.**
|
|
5
|
+
* `readAfter` never mutates the cursor. The only ack is the cursor the daemon
|
|
6
|
+
* brings back on its next poll, after it has durably appended the envelope to
|
|
7
|
+
* its local journal. "领走即弃" means *cursor-advanced-then-deleted*, not
|
|
8
|
+
* *read-then-deleted* — read-deletes would break the frozen at-least-once
|
|
9
|
+
* semantics the client's stall recovery is built on (§8.3).
|
|
10
|
+
*
|
|
11
|
+
* The mailbox transports opaque envelope bytes and is **not** an
|
|
12
|
+
* execution-state authority. `body` is a string here rather than a parsed
|
|
13
|
+
* message because core is protocol-free: the frozen v1 shape lives in
|
|
14
|
+
* `@byok-sdk/protocol`, and core must not grow an edge to it (§12.1 invariant).
|
|
15
|
+
*/
|
|
16
|
+
import type { ContentHash } from './blob';
|
|
17
|
+
import type { TenantId } from './tenant';
|
|
18
|
+
/**
|
|
19
|
+
* Row lifecycle. `pending` and `acked` are derived from the device cursor;
|
|
20
|
+
* `expired` is the dead-letter state for rows that aged out before ever being
|
|
21
|
+
* acked — §12.7.5 requires those to be visible, not silently dropped.
|
|
22
|
+
*/
|
|
23
|
+
export declare const MAILBOX_MESSAGE_STATES: readonly ['pending', 'acked', 'expired'];
|
|
24
|
+
export type MailboxMessageState = (typeof MAILBOX_MESSAGE_STATES)[number];
|
|
25
|
+
/** One mailbox row. `seq` is monotonic per (tenant, device) — never global. */
|
|
26
|
+
export interface MailboxMessage {
|
|
27
|
+
readonly tenantId: TenantId;
|
|
28
|
+
readonly deviceId: string;
|
|
29
|
+
readonly seq: number;
|
|
30
|
+
readonly messageId: string;
|
|
31
|
+
/** Opaque encoded envelope. Core never parses it. */
|
|
32
|
+
readonly body: string;
|
|
33
|
+
readonly bodyHash: ContentHash;
|
|
34
|
+
readonly byteSize: bigint;
|
|
35
|
+
readonly state: MailboxMessageState;
|
|
36
|
+
readonly appendedAt: string;
|
|
37
|
+
}
|
|
38
|
+
export interface MailboxAppendInput {
|
|
39
|
+
readonly deviceId: string;
|
|
40
|
+
readonly body: string;
|
|
41
|
+
readonly bodyHash: ContentHash;
|
|
42
|
+
readonly byteSize: bigint;
|
|
43
|
+
/**
|
|
44
|
+
* Producer-supplied idempotency key. A second append with the same
|
|
45
|
+
* `messageId` returns the existing row instead of enqueuing a duplicate.
|
|
46
|
+
*/
|
|
47
|
+
readonly messageId: string;
|
|
48
|
+
}
|
|
49
|
+
export interface MailboxReadQuery {
|
|
50
|
+
readonly deviceId: string;
|
|
51
|
+
/** Exclusive lower bound. `0` reads from the beginning of the retained window. */
|
|
52
|
+
readonly afterSeq: number;
|
|
53
|
+
readonly limit?: number;
|
|
54
|
+
}
|
|
55
|
+
export interface MailboxPage {
|
|
56
|
+
readonly messages: readonly MailboxMessage[];
|
|
57
|
+
/**
|
|
58
|
+
* The seq to poll after next. Equal to `afterSeq` when the page is empty —
|
|
59
|
+
* reading never moves the ack cursor, so a caller that only reads can replay
|
|
60
|
+
* the same page forever without losing anything.
|
|
61
|
+
*/
|
|
62
|
+
readonly nextSeq: number;
|
|
63
|
+
readonly hasMore: boolean;
|
|
64
|
+
}
|
|
65
|
+
export interface MailboxAdvanceCursorInput {
|
|
66
|
+
readonly deviceId: string;
|
|
67
|
+
/** Highest seq the device has durably journaled. */
|
|
68
|
+
readonly ackedSeq: number;
|
|
69
|
+
}
|
|
70
|
+
/** The device's durable acknowledgement position. */
|
|
71
|
+
export interface MailboxCursorState {
|
|
72
|
+
readonly tenantId: TenantId;
|
|
73
|
+
readonly deviceId: string;
|
|
74
|
+
readonly ackedSeq: number;
|
|
75
|
+
readonly updatedAt: string;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Retention cutoffs.
|
|
79
|
+
*
|
|
80
|
+
* Both instants must be **canonical ISO-8601 UTC** (`YYYY-MM-DDTHH:mm:ss.sssZ`);
|
|
81
|
+
* anything else is rejected with `timestamp_not_canonical`. A retention sweep
|
|
82
|
+
* deletes rows, so an offset-bearing string that a string comparison and a SQL
|
|
83
|
+
* `timestamptz` comparison read differently is the worst place to guess — see
|
|
84
|
+
* `time.ts`.
|
|
85
|
+
*/
|
|
86
|
+
export interface MailboxRetentionInput {
|
|
87
|
+
readonly deviceId?: string;
|
|
88
|
+
/** Acked rows appended before this instant are deleted. */
|
|
89
|
+
readonly ackedBefore: string;
|
|
90
|
+
/** Unacked rows appended before this instant move to `expired`, never deleted here. */
|
|
91
|
+
readonly expireUnackedBefore: string;
|
|
92
|
+
}
|
|
93
|
+
export interface MailboxRetentionResult {
|
|
94
|
+
readonly deletedCount: number;
|
|
95
|
+
readonly expiredCount: number;
|
|
96
|
+
readonly releasedBytes: bigint;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Mailbox port. Tenant-first, async.
|
|
100
|
+
*
|
|
101
|
+
* Raises: `mailbox_cursor_regression` (an ack that moves the cursor backwards,
|
|
102
|
+
* which would silently re-deliver already-journaled work),
|
|
103
|
+
* `timestamp_not_canonical` (a retention cutoff that is not a canonical
|
|
104
|
+
* ISO-8601 UTC instant).
|
|
105
|
+
*/
|
|
106
|
+
export interface MailboxStore {
|
|
107
|
+
append(tenant: TenantId, input: MailboxAppendInput): Promise<MailboxMessage>;
|
|
108
|
+
/** Pure read. Never advances the cursor, never deletes, never marks acked. */
|
|
109
|
+
readAfter(tenant: TenantId, query: MailboxReadQuery): Promise<MailboxPage>;
|
|
110
|
+
/** The one and only ack. Monotonic; a lower `ackedSeq` is rejected. */
|
|
111
|
+
advanceCursor(tenant: TenantId, input: MailboxAdvanceCursorInput): Promise<MailboxCursorState>;
|
|
112
|
+
readCursor(tenant: TenantId, deviceId: string): Promise<MailboxCursorState>;
|
|
113
|
+
/** Retention hook: delete acked rows, dead-letter unacked ones. */
|
|
114
|
+
collectRetired(tenant: TenantId, input: MailboxRetentionInput): Promise<MailboxRetentionResult>;
|
|
115
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The declared method inventory of every core port (sprint I7).
|
|
3
|
+
*
|
|
4
|
+
* This table is contract data, not test data — it says what a port IS, and it
|
|
5
|
+
* is enforced from two directions that must read the same table:
|
|
6
|
+
*
|
|
7
|
+
* - `__tests__/constraints.test.ts` scans the *source interfaces* in this
|
|
8
|
+
* package and asserts each listed method exists, is async, and takes a
|
|
9
|
+
* required `TenantId` first.
|
|
10
|
+
* - `@byok-sdk/conformance`'s port-inventory dimension asserts every *composition
|
|
11
|
+
* under test* implements exactly these methods — no missing method, and no
|
|
12
|
+
* extra one that the contract has not pinned down and that therefore no
|
|
13
|
+
* other composition would implement.
|
|
14
|
+
*
|
|
15
|
+
* It lives in shipped source rather than under `__tests__/` because the second
|
|
16
|
+
* enforcer is now a separate package (S4A story O-005): a `core → conformance`
|
|
17
|
+
* devDependency for a table `core` itself asserts against would be a cycle,
|
|
18
|
+
* and the direction that has to hold is `conformance → core`.
|
|
19
|
+
*
|
|
20
|
+
* Adding a port method means editing this table, which is the point: a port
|
|
21
|
+
* grows by contract, not by whichever composition needed something.
|
|
22
|
+
*/
|
|
23
|
+
import type { CoreStoreName } from './stores';
|
|
24
|
+
export declare const CORE_PORT_METHODS: Readonly<Record<CoreStoreName, readonly string[]>>;
|
|
25
|
+
/** The interface each port name is declared as, for the source-side scan. */
|
|
26
|
+
export declare const CORE_PORT_INTERFACES: Readonly<Record<CoreStoreName, string>>;
|