@byok-sdk/core 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +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/skill-pack.ts","../src/stores.ts","../src/ports-contract.ts","../src/attestation.ts","../src/device-assertion.ts","../src/pairing.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/skill-pack.ts","../src/in-memory/truth.ts","../src/in-memory/clock.ts","../src/in-memory/index.ts"],"names":["z","parts","DEFAULT_LIST_LIMIT"],"mappings":";;;AA+BO,IAAM,gBAAA,GAAmB;AAAA;AAAA,EAE9B,iBAAA,EAAmB,mBAAA;AAAA,EACnB,oBAAA,EAAsB,sBAAA;AAAA;AAAA,EAGtB,uBAAA,EAAyB,yBAAA;AAAA;AAAA,EAGzB,8BAAA,EAAgC,gCAAA;AAAA,EAChC,sBAAA,EAAwB,wBAAA;AAAA;AAAA,EAGxB,sBAAA,EAAwB,wBAAA;AAAA,EACxB,6BAAA,EAA+B,+BAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO/B,0BAAA,EAA4B,4BAAA;AAAA;AAAA,EAG5B,yBAAA,EAA2B,2BAAA;AAAA,EAC3B,yBAAA,EAA2B,2BAAA;AAAA;AAAA,EAG3B,oBAAA,EAAsB,sBAAA;AAAA,EACtB,iBAAA,EAAmB,mBAAA;AAAA,EACnB,wBAAA,EAA0B,0BAAA;AAAA,EAC1B,qBAAA,EAAuB,uBAAA;AAAA,EACvB,oBAAA,EAAsB,sBAAA;AAAA,EACtB,cAAA,EAAgB,gBAAA;AAAA;AAAA,EAGhB,sBAAA,E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Q,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 // device assertion (plan device-assertion-broker) — deliberately its own\n // code rather than reusing `proof_envelope_invalid`: the two envelopes are\n // non-interchangeable by design, and one shared \"envelope was bad\" code is\n // exactly how a log stops being able to say which authentication surface was\n // probed.\n assertion_envelope_invalid: 'assertion_envelope_invalid',\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_key_prefix_invalid: 'object_key_prefix_invalid',\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\n // skill packs (plan `skill-pack-delivery-channel`)\n skill_pack_manifest_invalid: 'skill_pack_manifest_invalid',\n skill_pack_frontmatter_invalid: 'skill_pack_frontmatter_invalid',\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\n/** Opaque bytes produced after the mailbox has atomically reserved their delivery sequence. */\nexport interface MailboxBody {\n readonly body: string;\n readonly bodyHash: ContentHash;\n readonly byteSize: bigint;\n}\n\nexport interface MailboxAppendInput {\n readonly deviceId: string;\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 * Builds the opaque body around the sequence reserved by this append.\n *\n * The store invokes this only for a new row and commits the returned bytes\n * at exactly that `seq`. Allocation, materialization, and insertion are one\n * per-device serialized operation; otherwise concurrent offers could commit\n * out of order and let an ack skip a late lower sequence.\n */\n readonly materialize: (seq: number) => MailboxBody | Promise<MailboxBody>;\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 * What a deployment-level key namespace may look like: slash-joined segments of\n * lowercase alphanumerics, `.`, `_`, and `-`, each starting with an\n * alphanumeric. No leading or trailing slash, and therefore no empty segment.\n *\n * Narrow on purpose, and narrower than S3 keys allow. A prefix is spliced into\n * every key this SDK ever writes, so the only prefixes worth accepting are the\n * ones that reach the object store spelled exactly as configured: anything\n * requiring percent-encoding would give the deployment's objects two names, and\n * anything with an empty segment would make `a//b` and `a/b` the same key at\n * rest but different strings in config. Case is folded out for the same reason\n * {@link contentHash} refuses uppercase hex — one address, one spelling.\n */\nexport const OBJECT_KEY_PREFIX_PATTERN = /^[a-z0-9][a-z0-9._-]*(\\/[a-z0-9][a-z0-9._-]*)*$/;\n\n/** A validated deployment key namespace. Branded, so only the mint point below can produce one. */\nexport type ObjectKeyPrefix = string & { readonly __byokObjectKeyPrefix: unique symbol };\n\n/**\n * The single mint point for {@link ObjectKeyPrefix}.\n *\n * There is no \"empty means no prefix\" spelling here: a composition that has no\n * prefix omits the option, and one that passes `''` has misconfigured something\n * (an unset environment variable is the usual way). Accepting it silently would\n * make the two indistinguishable at exactly the moment the difference decides\n * where a deployment's objects live.\n *\n * @throws {ByokCoreError} code `object_key_prefix_invalid`.\n */\nexport function objectKeyPrefix(value: string): ObjectKeyPrefix {\n if (!OBJECT_KEY_PREFIX_PATTERN.test(value)) {\n throw new ByokCoreError(\n 'object_key_prefix_invalid',\n `Object key prefix must match ${OBJECT_KEY_PREFIX_PATTERN.source}, received ${JSON.stringify(value)}.`,\n );\n }\n return value as ObjectKeyPrefix;\n}\n\n/**\n * Tenant-scoped object key, e.g.\n * `tenants/<tenantId>/objects/sha256/<hex>` (§12.7.4).\n *\n * `prefix` namespaces the whole layout — `<prefix>/tenants/...` — so one bucket\n * can hold several deployments without either of them owning the bucket root.\n * Omitting it produces the unprefixed key verbatim, which is what makes the\n * option safe to add: every object already at rest was written without one.\n *\n * The prefix is an IMMUTABLE property of a deployment. It is spliced in here\n * and nowhere else, and nothing reads a key back under a second layout: change\n * a live deployment's prefix and its existing objects become unaddressable.\n * See `R2BlobStoreOptions.keyPrefix` in `@byok-sdk/cloud-postgres` for the full\n * operational contract.\n */\nexport function tenantObjectKey(\n tenant: TenantId,\n hash: ContentHash,\n prefix?: ObjectKeyPrefix,\n): string {\n const hex = hash.slice('sha256:'.length);\n const key = `tenants/${tenant as string}/objects/sha256/${hex}`;\n return prefix === undefined ? key : `${prefix as string}/${key}`;\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 * Skill packs: declarative content a SaaS deployment distributes to a paired\n * device (plan `skill-pack-delivery-channel`, Phase 1).\n *\n * A pack is an `agentskills.io`-shaped `SKILL.md` plus its static companion\n * files. That is the WHOLE of it, and the narrowness is the design:\n *\n * 1. **No executable surface, by schema.** {@link SkillPackManifestSchema} is a\n * `strictObject`, so an unknown key is a rejection rather than a field\n * someone's tooling might later start honoring, and\n * {@link SKILL_PACK_FORBIDDEN_FIELDS} names the specific ones — `exec`,\n * `env`, `credential`, `hooks`, `allowed-tools` — that get their own\n * rejection message. The credential-isolation rule this SDK is built around\n * (§9.1) cannot be enforced downstream if the manifest can carry a command\n * to run or an environment to run it in, so it is enforced here, once.\n * 2. **Every declared limit has an evaluation point in this file.** A size cap\n * that nothing measures, a path rule that nothing checks, and a content hash\n * that nothing verifies are the same failure: a security claim with no\n * enforcement behind it. {@link checkSkillPackManifest} evaluates the\n * manifest-level limits and {@link checkSkillPackFileContent} evaluates the\n * byte-level ones, both returning a named rejection instead of a boolean, so\n * a caller can say which limit fired.\n * 3. **Hashing lives outside core.** Core has no `node:` import and no crypto\n * (the same rule `blob.ts` and `attestation.ts` follow), so this module owns\n * the canonical bytes a hash is taken over ({@link skillPackContentHashInput})\n * and the comparison, never the digest itself. The installer supplies what it\n * observed; core decides whether that is acceptable.\n *\n * Distribution is hosted HTTP (`@byok-sdk/cloud`'s `GET /byok/skill-packs`),\n * declared through ADR-010 as `skills.pack`. Nothing here touches the frozen v1\n * wire envelope, and there is deliberately no new message type: a pack is\n * content a device PULLS after reading a declaration, not a message a server\n * pushes into a task stream.\n */\nimport { z } from 'zod';\nimport { CONTENT_HASH_PATTERN, contentHash, type ContentHash } from './blob';\nimport { ByokCoreError } from './errors';\nimport type { TenantId } from './tenant';\n\nexport const SKILL_PACK_MANIFEST_SCHEMA_ID = 'byok-skill-pack-v1';\n\n/**\n * Pack names: lowercase, starting alphanumeric — the same shape\n * `OBJECT_KEY_PREFIX_PATTERN` accepts per segment, for the same reason. A pack\n * name becomes a directory name on a real device filesystem, so the accepted\n * set is the one that reaches disk spelled exactly as declared: no case folding\n * to collide over, no separator, no leading dot, nothing needing escaping.\n */\nexport const SKILL_PACK_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;\nexport const SKILL_PACK_NAME_MAX_LENGTH = 64;\nexport const SKILL_PACK_DESCRIPTION_MAX_LENGTH = 1024;\n\n/** `MAJOR.MINOR.PATCH`. A pack version orders two publications of one name; it is not a range language. */\nexport const SKILL_PACK_VERSION_PATTERN = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$/;\n\n/**\n * Relative POSIX paths only: slash-joined segments of alphanumerics, `.`, `_`\n * and `-`, each STARTING with an alphanumeric.\n *\n * That single \"starts with an alphanumeric\" rule is what closes the traversal\n * class rather than a blocklist of spellings: `..` cannot match (a segment may\n * not begin with `.`), an absolute path cannot match (no leading slash), an\n * empty segment cannot match (`a//b`), a Windows drive or UNC path cannot match\n * (no `:`, no `\\`), a home-relative path cannot match (no `~`), and a dotfile\n * cannot match either. A blocklist would have to anticipate every encoding of\n * the same idea; this allowlist has nothing to anticipate.\n */\nexport const SKILL_PACK_FILE_PATH_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*(\\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;\nexport const SKILL_PACK_FILE_PATH_MAX_LENGTH = 200;\n\n/** The entry file every pack must carry, spelled as `agentskills.io` spells it. */\nexport const SKILL_PACK_ENTRY_PATH = 'SKILL.md';\n\n/** Per-file ceiling, measured in BYTES over the observed content — never in characters. */\nexport const SKILL_PACK_FILE_MAX_BYTES = 262_144;\n/** Whole-pack ceiling, over the sum of the observed file sizes. */\nexport const SKILL_PACK_MAX_BYTES = 1_048_576;\nexport const SKILL_PACK_MAX_FILES = 64;\n\n/**\n * Manifest keys that must never exist, listed so the prohibition is testable\n * rather than implied.\n *\n * `strictObject` already rejects every unknown key, so this list adds no new\n * authority — it adds a NAMED rejection for the subset that matters: an\n * operator who sees `unrecognized key: \"env\"` learns nothing about why, and a\n * reviewer reading the schema cannot tell whether the omission was a decision\n * or an oversight. Pinned from both directions by\n * `__tests__/skill-pack.test.ts`.\n */\nexport const SKILL_PACK_FORBIDDEN_FIELDS = [\n 'exec',\n 'command',\n 'entrypoint',\n 'run',\n 'script',\n 'shell',\n 'env',\n 'environment',\n 'credential',\n 'credentials',\n 'secret',\n 'secrets',\n 'token',\n 'apiKey',\n 'api_key',\n 'allowedTools',\n 'allowed-tools',\n 'hooks',\n 'preinstall',\n 'postinstall',\n] as const;\n\nconst ContentHashSchema = z\n .string()\n .regex(CONTENT_HASH_PATTERN)\n .transform((value) => contentHash(value));\n\n/** One file in a pack: where it goes, what it must hash to, and how big it is. */\nexport const SkillPackFileSchema = z.strictObject({\n path: z.string().min(1).max(SKILL_PACK_FILE_PATH_MAX_LENGTH).regex(SKILL_PACK_FILE_PATH_PATTERN),\n contentHash: ContentHashSchema,\n byteSize: z.number().int().nonnegative().max(SKILL_PACK_FILE_MAX_BYTES),\n});\n\nexport type SkillPackFile = z.infer<typeof SkillPackFileSchema>;\n\n/**\n * The published description of one pack.\n *\n * `contentHash` addresses the manifest AS A WHOLE — see\n * {@link skillPackContentHashInput} — which is what makes an install\n * content-addressed: two publications that differ in any field a device can\n * observe land in two directories, and re-installing an unchanged pack is a\n * no-op rather than a partial overwrite.\n */\nexport const SkillPackManifestSchema = z.strictObject({\n schema: z.literal(SKILL_PACK_MANIFEST_SCHEMA_ID),\n name: z.string().min(1).max(SKILL_PACK_NAME_MAX_LENGTH).regex(SKILL_PACK_NAME_PATTERN),\n version: z.string().regex(SKILL_PACK_VERSION_PATTERN),\n description: z.string().min(1).max(SKILL_PACK_DESCRIPTION_MAX_LENGTH),\n files: z.array(SkillPackFileSchema).min(1).max(SKILL_PACK_MAX_FILES),\n contentHash: ContentHashSchema,\n});\n\nexport type SkillPackManifest = z.infer<typeof SkillPackManifestSchema>;\n\n/**\n * Parses a manifest fail-closed.\n *\n * @throws {ByokCoreError} code `skill_pack_manifest_invalid`.\n */\nexport function parseSkillPackManifest(input: unknown): SkillPackManifest {\n if (typeof input === 'object' && input !== null) {\n const present = SKILL_PACK_FORBIDDEN_FIELDS.filter((field) =>\n Object.prototype.hasOwnProperty.call(input, field),\n );\n if (present.length > 0) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `A skill pack manifest carries no executable or credential surface; refusing ${present\n .map((field) => JSON.stringify(field))\n .join(', ')}.`,\n );\n }\n }\n const result = SkillPackManifestSchema.safeParse(input);\n if (!result.success) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Invalid skill pack manifest: ${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 * The exact bytes `manifest.contentHash` is the sha256 of.\n *\n * Written out here, in core, because both ends have to agree on it and neither\n * end may derive its own version: the publisher hashes this string to mint the\n * address, the installer hashes it again to verify what it fetched, and a\n * disagreement between the two would make every install either falsely\n * accepted or unconditionally rejected. Newline-delimited and terminated so no\n * field's content can be shifted into the next field's position, and the file\n * rows are sorted by path so two publishers that enumerate a directory in\n * different orders still mint the same address.\n */\nexport function skillPackContentHashInput(manifest: {\n readonly name: string;\n readonly version: string;\n readonly description: string;\n readonly files: readonly SkillPackFile[];\n}): string {\n const rows = [...manifest.files]\n .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))\n .map((file) => `${file.path}\\n${file.contentHash as string}\\n${file.byteSize}\\n`);\n return [\n `${SKILL_PACK_MANIFEST_SCHEMA_ID}\\n`,\n `${manifest.name}\\n`,\n `${manifest.version}\\n`,\n `${manifest.description.length}\\n`,\n `${manifest.description}\\n`,\n `${manifest.files.length}\\n`,\n ...rows,\n ].join('');\n}\n\n/** Every way a pack can be refused. One name per declared limit — see {@link SkillPackCheck}. */\nexport const SKILL_PACK_REJECTIONS = [\n 'path-unsafe',\n 'duplicate-path',\n 'entry-missing',\n 'file-count-over-cap',\n 'file-over-cap',\n 'pack-over-cap',\n 'size-mismatch',\n 'hash-mismatch',\n 'name-mismatch',\n] as const;\nexport type SkillPackRejection = (typeof SKILL_PACK_REJECTIONS)[number];\n\n/**\n * Outcome of a check. `bytes` is the measured total on the accept path so a\n * caller can record what it admitted; a rejection always names WHICH limit\n * fired, because \"the pack was rejected\" is not an operable message.\n */\nexport type SkillPackCheck =\n | { readonly ok: true; readonly bytes: number }\n | { readonly ok: false; readonly reason: SkillPackRejection; readonly detail: string };\n\n/** Non-throwing path-safety predicate — the one authority on what a pack may name. */\nexport function isSkillPackPathSafe(path: string): boolean {\n return (\n path.length > 0 &&\n path.length <= SKILL_PACK_FILE_PATH_MAX_LENGTH &&\n SKILL_PACK_FILE_PATH_PATTERN.test(path)\n );\n}\n\n/**\n * The manifest-level limits, evaluated.\n *\n * Runs over a manifest that has already parsed, so the per-field caps zod owns\n * are not re-litigated here. What is left is everything zod cannot see: the\n * relationships BETWEEN files (a duplicate path, a missing entry file, a total\n * that clears every per-file cap and still blows the pack cap).\n */\nexport function checkSkillPackManifest(manifest: SkillPackManifest): SkillPackCheck {\n if (manifest.files.length > SKILL_PACK_MAX_FILES) {\n return {\n ok: false,\n reason: 'file-count-over-cap',\n detail: `${manifest.files.length} files exceeds the ${SKILL_PACK_MAX_FILES} file limit.`,\n };\n }\n\n const seen = new Set<string>();\n let bytes = 0;\n for (const file of manifest.files) {\n if (!isSkillPackPathSafe(file.path)) {\n return { ok: false, reason: 'path-unsafe', detail: `${JSON.stringify(file.path)} is not a safe relative path.` };\n }\n if (seen.has(file.path)) {\n return { ok: false, reason: 'duplicate-path', detail: `${JSON.stringify(file.path)} is declared twice.` };\n }\n seen.add(file.path);\n if (file.byteSize > SKILL_PACK_FILE_MAX_BYTES) {\n return {\n ok: false,\n reason: 'file-over-cap',\n detail: `${JSON.stringify(file.path)} declares ${file.byteSize} bytes, over the ${SKILL_PACK_FILE_MAX_BYTES} byte per-file limit.`,\n };\n }\n bytes += file.byteSize;\n }\n\n if (!seen.has(SKILL_PACK_ENTRY_PATH)) {\n return {\n ok: false,\n reason: 'entry-missing',\n detail: `A skill pack must carry ${SKILL_PACK_ENTRY_PATH}.`,\n };\n }\n if (bytes > SKILL_PACK_MAX_BYTES) {\n return {\n ok: false,\n reason: 'pack-over-cap',\n detail: `${bytes} declared bytes exceeds the ${SKILL_PACK_MAX_BYTES} byte pack limit.`,\n };\n }\n return { ok: true, bytes };\n}\n\n/** What an installer actually measured for one file, as opposed to what the manifest declared. */\nexport interface ObservedSkillPackFile {\n readonly byteSize: number;\n readonly contentHash: ContentHash;\n}\n\n/**\n * The byte-level limits, evaluated against what was actually fetched.\n *\n * The asymmetry with {@link checkSkillPackManifest} is the point: the declared\n * size is a claim by the publisher and the observed size is a fact about the\n * bytes on the device, so the cap is enforced on the OBSERVED value. A check\n * that only ever measured the declaration would pass a 4 KiB manifest row\n * attached to a 40 MiB response.\n */\nexport function checkSkillPackFileContent(\n declared: SkillPackFile,\n observed: ObservedSkillPackFile,\n): SkillPackCheck {\n if (!isSkillPackPathSafe(declared.path)) {\n return { ok: false, reason: 'path-unsafe', detail: `${JSON.stringify(declared.path)} is not a safe relative path.` };\n }\n if (observed.byteSize > SKILL_PACK_FILE_MAX_BYTES) {\n return {\n ok: false,\n reason: 'file-over-cap',\n detail: `${JSON.stringify(declared.path)} delivered ${observed.byteSize} bytes, over the ${SKILL_PACK_FILE_MAX_BYTES} byte per-file limit.`,\n };\n }\n if (observed.byteSize !== declared.byteSize) {\n return {\n ok: false,\n reason: 'size-mismatch',\n detail: `${JSON.stringify(declared.path)} declared ${declared.byteSize} bytes and delivered ${observed.byteSize}.`,\n };\n }\n if ((observed.contentHash as string) !== (declared.contentHash as string)) {\n return {\n ok: false,\n reason: 'hash-mismatch',\n detail: `${JSON.stringify(declared.path)} declared ${declared.contentHash as string} and delivered ${observed.contentHash as string}.`,\n };\n }\n return { ok: true, bytes: observed.byteSize };\n}\n\n/**\n * `SKILL.md` frontmatter, in the `agentskills.io` shape: exactly `name` and\n * `description`, both required.\n *\n * The allowlist is the whole contract. `allowed-tools`, `hooks` and friends are\n * real fields in other skill dialects and every one of them widens what a pack\n * can ask a runtime to do; a parser that merely IGNORED them would still let a\n * pack ship them to a host that does not.\n */\nexport interface SkillFrontmatter {\n readonly name: string;\n readonly description: string;\n}\n\n/** The only frontmatter keys a pack may declare. */\nexport const SKILL_FRONTMATTER_FIELDS = ['name', 'description'] as const;\n\nconst FRONTMATTER_DELIMITER = '---';\nconst FRONTMATTER_LINE_PATTERN = /^([A-Za-z][A-Za-z0-9_-]*):[ \\t]*(.*)$/;\n\nfunction unquote(value: string): string | undefined {\n const trimmed = value.trim();\n if (trimmed.length >= 2) {\n const first = trimmed[0];\n const last = trimmed[trimmed.length - 1];\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n const inner = trimmed.slice(1, -1);\n return inner.includes(first) ? undefined : inner;\n }\n }\n return trimmed;\n}\n\n/**\n * Parses and validates a `SKILL.md`'s frontmatter block.\n *\n * Deliberately not a YAML engine: this is a closed two-key grammar, and the\n * whole reason to hand-write it is that a general parser would happily accept\n * anchors, aliases, nested maps, multi-document streams and block scalars —\n * every one of which is a way to express something this format has decided not\n * to have. Anything outside the grammar is a rejection, never a skipped line.\n *\n * @throws {ByokCoreError} code `skill_pack_frontmatter_invalid`.\n */\nexport function parseSkillFrontmatter(text: string): SkillFrontmatter {\n const reject = (message: string): never => {\n throw new ByokCoreError('skill_pack_frontmatter_invalid', message);\n };\n\n const lines = text.split('\\n');\n if (lines[0]?.trimEnd() !== FRONTMATTER_DELIMITER) {\n reject(`A skill file must open with a ${FRONTMATTER_DELIMITER} frontmatter delimiter.`);\n }\n const closing = lines.findIndex((line, index) => index > 0 && line.trimEnd() === FRONTMATTER_DELIMITER);\n if (closing < 0) reject(`The frontmatter block is not closed by a ${FRONTMATTER_DELIMITER} line.`);\n\n const fields = new Map<string, string>();\n for (const line of lines.slice(1, closing)) {\n if (line.trim().length === 0) continue;\n const match = FRONTMATTER_LINE_PATTERN.exec(line);\n if (match === null) reject(`Frontmatter line ${JSON.stringify(line)} is not a \\`key: value\\` pair.`);\n const key = match![1]!;\n if (!(SKILL_FRONTMATTER_FIELDS as readonly string[]).includes(key)) {\n reject(\n `Frontmatter key ${JSON.stringify(key)} is not one of ${SKILL_FRONTMATTER_FIELDS.join(', ')}; a skill declares no tools, hooks, or environment.`,\n );\n }\n if (fields.has(key)) reject(`Frontmatter key ${JSON.stringify(key)} is declared twice.`);\n const value = unquote(match![2]!);\n if (value === undefined || value.length === 0) {\n reject(`Frontmatter key ${JSON.stringify(key)} has no usable value.`);\n }\n fields.set(key, value!);\n }\n\n const name = fields.get('name');\n const description = fields.get('description');\n if (name === undefined) reject('Frontmatter is missing `name`.');\n if (description === undefined) reject('Frontmatter is missing `description`.');\n if (name!.length > SKILL_PACK_NAME_MAX_LENGTH || !SKILL_PACK_NAME_PATTERN.test(name!)) {\n reject(\n `Frontmatter \\`name\\` must match ${SKILL_PACK_NAME_PATTERN.source} and be at most ${SKILL_PACK_NAME_MAX_LENGTH} characters.`,\n );\n }\n if (description!.length > SKILL_PACK_DESCRIPTION_MAX_LENGTH) {\n reject(`Frontmatter \\`description\\` exceeds ${SKILL_PACK_DESCRIPTION_MAX_LENGTH} characters.`);\n }\n return { name: name!, description: description! };\n}\n\n/**\n * The entry file's own declaration must agree with the manifest's.\n *\n * Two authorities naming the same pack is not a redundancy to tolerate — a\n * device that installed under one name and handed the runtime a skill calling\n * itself another would be projecting content nobody asked for.\n */\nexport function checkSkillPackEntry(manifest: SkillPackManifest, entryText: string): SkillPackCheck {\n const frontmatter = parseSkillFrontmatter(entryText);\n if (frontmatter.name !== manifest.name) {\n return {\n ok: false,\n reason: 'name-mismatch',\n detail: `${SKILL_PACK_ENTRY_PATH} declares ${JSON.stringify(frontmatter.name)} but the manifest declares ${JSON.stringify(manifest.name)}.`,\n };\n }\n return { ok: true, bytes: new TextEncoder().encode(entryText).length };\n}\n\n/** One file's bytes, as the distribution surface hands them over. */\nexport interface SkillPackFileContent {\n readonly path: string;\n readonly contentHash: ContentHash;\n readonly byteSize: number;\n /** UTF-8 text. A pack carries Markdown, YAML and static text assets — never binaries, never archives. */\n readonly content: string;\n}\n\n/** What a publisher hands the store: the validated manifest plus the bytes it addresses. */\nexport interface SkillPackPublishInput {\n readonly manifest: SkillPackManifest;\n readonly files: readonly { readonly path: string; readonly content: string }[];\n}\n\nexport interface SkillPackListQuery {\n readonly limit?: number;\n}\n\n/**\n * Skill pack port. Tenant-first, async, content plus manifest.\n *\n * Registered in `ports-contract.ts` as a core PORT, and deliberately not (yet)\n * a member of `CoreStores`: a composition contract that named it would oblige\n * every existing composition to implement it in the same slice, and the\n * Postgres implementation is Phase 2 of this plan. See `ports-contract.ts` for\n * the full note on that split.\n *\n * Raises: `skill_pack_manifest_invalid` (a publish whose bytes disagree with\n * the manifest it was handed).\n */\nexport interface SkillPackStore {\n /** Idempotent per (tenant, name, contentHash). Publishing a changed pack under the same name replaces it. */\n publish(tenant: TenantId, input: SkillPackPublishInput): Promise<SkillPackManifest>;\n get(tenant: TenantId, name: string): Promise<SkillPackManifest | undefined>;\n list(tenant: TenantId, query: SkillPackListQuery): Promise<readonly SkillPackManifest[]>;\n readFile(tenant: TenantId, name: string, path: string): Promise<SkillPackFileContent | undefined>;\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 { SkillPackStore } from './skill-pack';\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 * Skill-pack storage is a MANDATORY member: every composition creates the\n * tables and supplies the port (Phase 2 of `skill-pack-delivery-channel`).\n * Storage presence is not capability advertisement — the wire route/capability\n * stays optional in `@byok-sdk/cloud` (`includeSkillPacks`), and a deployment\n * that never declares `skills.pack` simply keeps the tables empty.\n */\n readonly skillPacks: SkillPackStore;\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 'skillPacks',\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 { CORE_STORE_NAMES, type CoreStoreName } from './stores';\n\n/**\n * Ports that are core ports but NOT members of the composition contract.\n *\n * Now empty, and that is the whole point of Phase 2. Phase 1 of\n * `skill-pack-delivery-channel` held `skillPacks` here as a self-declared\n * temporary bridge: adding it to `CoreStores` before its Postgres\n * implementation existed would have obliged every composition to implement it\n * in the same slice, and the alternatives — an optional port member (a\n * compatibility fallback, forbidden) or a port outside the contract table\n * entirely (exempt from the tenant-first scan, the one rule most worth having)\n * — were both worse. Phase 2 delivered that implementation and moved\n * `skillPacks` into `CORE_STORE_NAMES`, so this list goes back to empty exactly\n * as the Phase 1 note promised. The empty set stays named rather than deleted:\n * it is the testable statement \"every core port is a composition member\", which\n * `CORE_STORE_NAMES` alone cannot make.\n */\nexport const CORE_NON_COMPOSITION_PORT_NAMES = [] as const;\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 skillPacks: ['publish', 'get', 'list', 'readFile'],\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 skillPacks: 'SkillPackStore',\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\n/**\n * HTTP header carrying the base64url device-proof envelope on a truth-route\n * request (§12.6.3). Both the daemon that mints the proof and the host that\n * decodes it must name the exact same header, so it is a single wire constant\n * here rather than a string re-spelled on each side.\n */\nexport const DEVICE_PROOF_HEADER = 'x-byok-device-proof';\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 * Device assertion envelope, canonical signing bytes, and verifier\n * (plan `device-assertion-broker`, P3 ①-⑤).\n *\n * A device assertion is a short-lived, audience-scoped statement a *paired\n * device* makes about itself — \"this device, paired to this product against\n * this server, wants to talk to `<audience>` for the next two minutes\" — signed\n * with the same Ed25519 device identity key `attestation.ts`'s device proof\n * uses. A sibling CLI installed alongside the daemon presents one to the host's\n * cloud, which exchanges it for a product session. It is NOT a request-bound\n * proof (`attestation.ts`) and the two must never be interchangeable; see the\n * domain prefix below.\n *\n * Four decisions this file encodes, none of them re-litigable here:\n *\n * 1. **A custom JSON signing envelope, not JWS.** The domain prefix has to be\n * *inside* the signed bytes. JWS puts its type tag in a header that no\n * verifier is required to check, which is a fail-open shape: a token minted\n * for one purpose verifies for another as long as the key matches. So this\n * clones the mechanism `attestation.ts` already froze — RFC 8785-subset\n * canonicalization (`canonicalizeJson`, imported, never re-implemented) plus\n * a golden fixture pinning the exact bytes.\n * 2. **What the claims deliberately do NOT carry.** No `devicePublicKey`: a\n * verifier must resolve the key from its own device directory by `deviceId`,\n * or the envelope becomes self-authenticating. No caller identity: every\n * process under the same UID can reach the control socket, so a \"who asked\"\n * field would be synthesized authority, not evidence. No `keyId`: there is\n * no key-rotation story for this envelope yet, and a field nothing populates\n * honestly is a structure that invites a verifier to trust it.\n * 3. **`audience` is a single string, never an array.** A multi-audience token\n * forces every verifier to agree on the same containment rule; one string\n * compared with `===` cannot be got wrong.\n * 4. **The verifier cannot forget the revocation check.** {@link\n * verifyDeviceAssertion} takes `revoked` as a REQUIRED dependency, so a\n * caller that never looked the device row up does not compile. The daemon's\n * own local checks (see `@byok-sdk/client`'s `assertion.issue`) are only half\n * of revocation; the other half is this recheck at exchange time, and no\n * documentation may claim the daemon satisfies \"synchronous invalidation\"\n * on its own.\n *\n * Like `attestation.ts`, this module is crypto-free: signature verification is\n * an injected port (`DeviceAssertionVerifier`), because core must load on\n * Workers and `node:crypto`/WebCrypto disagree about key handling.\n */\nimport { z } from 'zod';\nimport { canonicalizeJson, type JsonObject, type JsonValue } from './attestation';\nimport { ByokCoreError } from './errors';\n\n/** Envelope schema id, self-consistent with the domain prefix below. */\nexport const DEVICE_ASSERTION_SCHEMA_ID = 'byok-device-assertion-v1';\n\n/**\n * Domain separation prefix, prepended to the canonical claim bytes before\n * signing.\n *\n * Must remain mutually NON-PREFIX with the other two things this same Ed25519\n * device key signs — `byok-nonce-v1\\n` (challenge/token renewal, see\n * `@byok-sdk/client`'s `device-keys.ts`) and `byok-device-proof-v1\\n`\n * (`attestation.ts`) — so no signature over one domain can ever be reinterpreted\n * as a signature over another. `packages/core/src/__tests__/device-assertion.test.ts`\n * asserts the three-way non-prefix property directly; that assertion is the\n * falsifier for this whole design, not a nicety.\n */\nexport const DEVICE_ASSERTION_DOMAIN_PREFIX = 'byok-device-assertion-v1\\n';\n\nexport const DEVICE_ASSERTION_VERSION = 1;\n\n/** Signature algorithms this envelope version admits. */\nexport const DEVICE_ASSERTION_ALGORITHMS = ['ed25519'] as const;\nexport type DeviceAssertionAlgorithm = (typeof DEVICE_ASSERTION_ALGORITHMS)[number];\n\n/**\n * Default assertion lifetime. Short on purpose: the daemon keeps no `jti`\n * ledger (it is not on the verification path and could not stop a real replay\n * anyway), so a narrow expiry window plus a burn-on-use verifier is the whole\n * replay story.\n */\nexport const DEVICE_ASSERTION_DEFAULT_TTL_MS = 120_000;\n\n/**\n * Hard ceiling on the lifetime, enforced at BOTH ends: a daemon refuses to be\n * configured above it, and {@link verifyDeviceAssertion} refuses an envelope\n * whose own `issuedAt`→`expiresAt` span exceeds it regardless of who minted it.\n */\nexport const DEVICE_ASSERTION_MAX_TTL_MS = 300_000;\n\n/** Bound on the `audience` claim, in UTF-8 bytes — an allowlist entry is a short identifier, not a document. */\nexport const DEVICE_ASSERTION_AUDIENCE_MAX_BYTES = 256;\n\n/** base64url of 16 CSPRNG bytes (128 bits), unpadded. */\nconst JTI_PATTERN = /^[A-Za-z0-9_-]{22}$/;\n\n/** base64url of a raw 64-byte Ed25519 signature, unpadded. */\nconst SIGNATURE_PATTERN = /^[A-Za-z0-9_-]{86}$/;\n\nfunction utf8ByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n// ---------------------------------------------------------------------------\n// Claims\n// ---------------------------------------------------------------------------\n\n/**\n * The signed claim set. `strictObject` with every member REQUIRED: an optional\n * claim is a claim a verifier may or may not see, and this envelope is small\n * enough that there is no honest reason for one.\n *\n * `issuer` is the paired server's origin (scheme + host + port, normalized) —\n * it binds the assertion to the deployment the device is actually paired\n * against, so an assertion minted by a device paired to a staging server cannot\n * be presented to production.\n */\nexport const DeviceAssertionClaimsSchema = z.strictObject({\n version: z.literal(DEVICE_ASSERTION_VERSION),\n /** The paired server's origin, normalized (`new URL(serverUrl).origin`). */\n issuer: z.string().min(1),\n productId: z.string().min(1),\n /** The device row this assertion claims to be. A lookup key, never authority — the row is the authority. */\n deviceId: z.string().min(1),\n /** Exactly one audience, compared with `===` by every verifier. Never an array, never a prefix. */\n audience: z\n .string()\n .min(1)\n .refine((value) => utf8ByteLength(value) <= DEVICE_ASSERTION_AUDIENCE_MAX_BYTES, {\n message: `audience must be at most ${DEVICE_ASSERTION_AUDIENCE_MAX_BYTES} UTF-8 bytes`,\n }),\n /** 128-bit CSPRNG token, base64url unpadded. The verifier burns it; the signer never reuses one. */\n jti: z.string().regex(JTI_PATTERN),\n issuedAt: z.iso.datetime(),\n expiresAt: z.iso.datetime(),\n});\n\nexport type DeviceAssertionClaims = z.infer<typeof DeviceAssertionClaimsSchema>;\n\nexport const DeviceAssertionEnvelopeV1Schema = z.strictObject({\n schema: z.literal(DEVICE_ASSERTION_SCHEMA_ID),\n algorithm: z.enum(DEVICE_ASSERTION_ALGORITHMS),\n protected: DeviceAssertionClaimsSchema,\n /** Raw 64-byte Ed25519 signature, base64url unpadded. */\n signature: z.string().regex(SIGNATURE_PATTERN),\n});\n\nexport type DeviceAssertionEnvelopeV1 = z.infer<typeof DeviceAssertionEnvelopeV1Schema>;\n\n/**\n * Parses an envelope fail-closed.\n *\n * @throws {ByokCoreError} code `assertion_envelope_invalid`.\n */\nexport function parseDeviceAssertionEnvelope(input: unknown): DeviceAssertionEnvelopeV1 {\n const result = DeviceAssertionEnvelopeV1Schema.safeParse(input);\n if (!result.success) {\n throw new ByokCoreError(\n 'assertion_envelope_invalid',\n `Invalid device assertion 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 — the same\n * discipline `deviceProofCanonicalClaims` documents. Nothing here is optional,\n * so there is no absent-key decision to get wrong; the explicit projection is\n * what keeps it that way if a field is ever added.\n */\nexport function deviceAssertionCanonicalClaims(claims: DeviceAssertionClaims): JsonObject {\n const canonical: Record<string, JsonValue> = {\n version: claims.version,\n issuer: claims.issuer,\n productId: claims.productId,\n deviceId: claims.deviceId,\n audience: claims.audience,\n jti: claims.jti,\n issuedAt: claims.issuedAt,\n expiresAt: claims.expiresAt,\n };\n return canonical;\n}\n\n/** Canonical JSON text of the claim set, without the domain prefix. */\nexport function deviceAssertionCanonicalJson(claims: DeviceAssertionClaims): string {\n return canonicalizeJson(deviceAssertionCanonicalClaims(claims));\n}\n\n/**\n * The exact bytes a device signs and a verifier reconstructs:\n * `byok-device-assertion-v1\\n` followed by the canonical claim JSON, UTF-8\n * encoded.\n *\n * Frozen by `src/__tests__/golden/device-assertion-v1.canonical.json`.\n */\nexport function deviceAssertionSigningInput(claims: DeviceAssertionClaims): Uint8Array {\n return new TextEncoder().encode(\n DEVICE_ASSERTION_DOMAIN_PREFIX + deviceAssertionCanonicalJson(claims),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Verify\n// ---------------------------------------------------------------------------\n\nexport interface DeviceAssertionVerifyInput {\n readonly algorithm: DeviceAssertionAlgorithm;\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, for the same reason `DeviceProofVerifier`\n * exists: core is Node-free and Workers-safe, so it answers no cryptographic\n * question itself. Kept separate from `DeviceProofVerifier` even though the\n * shapes coincide — one composition object satisfies both — because this file's\n * entire purpose is that the two domains never become interchangeable, and a\n * shared type is the first step toward a shared code path.\n */\nexport interface DeviceAssertionVerifier {\n verify(input: DeviceAssertionVerifyInput): Promise<boolean>;\n}\n\n/**\n * The device-row fields a verification reads — the verifier's OWN directory\n * row, resolved by `deviceId`, never anything the envelope carried.\n *\n * Both fields together, from one lookup, are what make forgetting impossible:\n * the caller cannot obtain `publicKeyJwkX` without also obtaining the current\n * `revoked` state, because they arrive as one object from one call.\n */\nexport interface DeviceAssertionDeviceRow {\n /** JWK `x` of the device's registered Ed25519 public key. The ONLY key a signature is ever checked against. */\n readonly publicKeyJwkX: string;\n /** The row's CURRENT revocation state, read in the same lookup as the key. */\n readonly revoked: boolean;\n}\n\n/**\n * Everything a verification needs that is NOT in the envelope.\n *\n * The device row is supplied through a LOOKUP PORT, not as a pre-fetched\n * value, and that is the whole point (this is the faithful clone of\n * `DeviceProofVerifier`'s \"core is never a second authority on device\n * identity\" shape). `verifyDeviceAssertion` reads `deviceId` from the parsed\n * claims and calls `lookupDevice(deviceId)` ITSELF, so:\n *\n * - There is no way to invoke a verification without providing the means to\n * look the current row up — \"I forgot to check revocation\" cannot be\n * expressed, because the function does the lookup, not the caller.\n * - Both the public key AND the revocation state come from that one row, so a\n * caller cannot pass a key while claiming `revoked: false` from thin air.\n * - The `deviceId` handed to `lookupDevice` is the claimed one; the row it\n * returns is authority. A device asserting an identity it is not is caught\n * by the lookup missing, or by the returned row's key failing the signature.\n */\nexport interface DeviceAssertionVerifyDeps {\n readonly verifier: DeviceAssertionVerifier;\n /**\n * Resolve the verifier's own device row by the claimed `deviceId`.\n * `undefined` for an unknown device. Sync or async; awaited either way.\n */\n readonly lookupDevice: (\n deviceId: string,\n ) => Promise<DeviceAssertionDeviceRow | undefined> | DeviceAssertionDeviceRow | undefined;\n /** Injected instant — core never reads a wall clock (`stores.ts`'s `Clock`). */\n readonly now: Date;\n /** Bound on `issuedAt`→`expiresAt`. Defaults to (and may never exceed) {@link DEVICE_ASSERTION_MAX_TTL_MS}. */\n readonly maxLifetimeMs?: number;\n}\n\nfunction parseInstant(value: string): number | undefined {\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\n/**\n * Raw Ed25519 public key as a JWK `x`: 32 bytes, base64url unpadded — exactly\n * 43 characters. The envelope's `algorithm` is a closed `ed25519`, so the row's\n * key must be an Ed25519 key of this exact shape.\n */\nconst EDDSA_JWK_X_PATTERN = /^[A-Za-z0-9_-]{43}$/;\n\n/**\n * codex round-2 F2: strict runtime validation of a looked-up device row, since\n * `lookupDevice` is a caller-supplied port whose return value TypeScript cannot\n * enforce at runtime. Fails closed on any shape that isn't exactly a usable row:\n *\n * - `revoked` must be the literal boolean `false`. A missing, `undefined`,\n * truthy, or non-boolean `revoked` is a malformed row — and a missing\n * `revoked` reading as \"not revoked\" (`undefined` is falsey) is precisely the\n * fail-open this guard closes: a revoked device must never slip through on a\n * row shape the caller got wrong.\n * - `publicKeyJwkX` must be a present, well-formed Ed25519 JWK `x`. A missing or\n * malformed key is rejected here, before any crypto — so a bad key can never\n * reach (and throw inside) the verifier port either.\n */\nfunction isUsableDeviceRow(row: unknown): row is DeviceAssertionDeviceRow {\n if (row === null || typeof row !== 'object') return false;\n if ((row as { revoked?: unknown }).revoked !== false) return false;\n const key = (row as { publicKeyJwkX?: unknown }).publicKeyJwkX;\n return typeof key === 'string' && EDDSA_JWK_X_PATTERN.test(key);\n}\n\n/**\n * Verifies an assertion and returns its claims, or `undefined`.\n *\n * Every rejected state collapses to `undefined` — malformed input, an unknown\n * or revoked device, an expired or over-long window, a bad signature — so a\n * route has one response for all of them and cannot accidentally leak which\n * check failed. That is the same shape `authenticateDeviceProof`\n * (`@byok-sdk/cloud`) already uses.\n *\n * The row lookup and both authority reads (key, revocation) happen INSIDE this\n * function — see {@link DeviceAssertionVerifyDeps}. What the caller MUST still\n * do afterward, and this cannot: assert `claims.audience` equals the audience\n * it actually serves, assert `claims.issuer`/`claims.productId` match its own\n * deployment, and BURN `claims.jti` so the assertion cannot be presented\n * twice. The daemon keeps no `jti` ledger; single use is entirely the\n * verifier's job.\n */\nexport async function verifyDeviceAssertion(\n input: unknown,\n deps: DeviceAssertionVerifyDeps,\n): Promise<DeviceAssertionClaims | undefined> {\n const maxLifetimeMs = deps.maxLifetimeMs ?? DEVICE_ASSERTION_MAX_TTL_MS;\n if (\n !Number.isSafeInteger(maxLifetimeMs) ||\n maxLifetimeMs <= 0 ||\n maxLifetimeMs > DEVICE_ASSERTION_MAX_TTL_MS\n ) {\n return undefined;\n }\n\n let envelope: DeviceAssertionEnvelopeV1;\n try {\n envelope = parseDeviceAssertionEnvelope(input);\n } catch {\n return undefined;\n }\n const claims = envelope.protected;\n\n // Resolve the row by the CLAIMED deviceId, then read authority from the row.\n // An unknown device, a revoked one, and a MALFORMED one all stop here, before\n // any crypto is done on the claimed identity's behalf. The row is validated\n // strictly (codex round-2 F2): `revoked` must be exactly `false` and the key\n // must be a well-formed Ed25519 JWK `x` — a missing `revoked` never reads as\n // \"not revoked\", and a missing/malformed key never reaches the verifier.\n const row = await deps.lookupDevice(claims.deviceId);\n if (!isUsableDeviceRow(row)) return undefined;\n\n const issuedAt = parseInstant(claims.issuedAt);\n const expiresAt = parseInstant(claims.expiresAt);\n if (issuedAt === undefined || expiresAt === undefined) return undefined;\n if (expiresAt <= issuedAt) return undefined;\n if (expiresAt - issuedAt > maxLifetimeMs) return undefined;\n\n // No clock-skew allowance: this envelope's whole safety margin is its short\n // window, and a tolerance knob is just that window quietly widened. A\n // deployment whose clocks disagree by minutes has a clock problem to fix, not\n // an assertion lifetime to extend. Validity is a half-open interval\n // `[issuedAt, expiresAt)` — at the exact `expiresAt` instant the assertion is\n // already expired, so the check is `now >= expiresAt`, not `now > expiresAt`.\n const now = deps.now.getTime();\n if (!Number.isFinite(now)) return undefined;\n if (now < issuedAt || now >= expiresAt) return undefined;\n\n const verified = await deps.verifier.verify({\n algorithm: envelope.algorithm,\n // The row's key, never an envelope-supplied one.\n publicKey: row.publicKeyJwkX,\n signature: envelope.signature,\n signingInput: deviceAssertionSigningInput(claims),\n });\n if (!verified) return undefined;\n\n return claims;\n}\n","/**\n * Nonce-signing domain separation for device token renewal (docs/protocol.md §6.2).\n *\n * S1 (GAP-004) put a domain tag in front of every challenge nonce a device\n * signs: the device key is a long-lived identity key that other planes (S6\n * device proof) also sign structured messages with, so without a tag a\n * signature produced for one purpose would be a valid signature for another.\n *\n * The tag started life as three separate literals — one in the daemon, one on\n * the hosted surface, one on the reference server — each with a comment saying\n * it was byte-identical to the others. That is a drift hazard written down, not\n * a design: three copies agree only until someone edits one. This module is the\n * single authority, and it lives in core for the same reason\n * {@link DEVICE_PROOF_DOMAIN_PREFIX} does — core is the one package all three\n * ends already depend on, it is Node-free and Workers-safe, and it holds no\n * crypto of its own. What travels is *bytes to sign*; who signs them, and with\n * which primitive, stays with each end.\n *\n * There is deliberately no dual mode and no grace window: a raw, unprefixed\n * nonce signature is simply invalid, and a device on an older encoding re-pairs.\n */\n\n/**\n * The domain-separation prefix a device signs along with a challenge nonce.\n *\n * Byte-frozen: `62 79 6f 6b 2d 6e 6f 6e 63 65 2d 76 31 0a` (14 bytes, UTF-8).\n * Changing it invalidates every deployed device's token-renewal path, so it is\n * a wire constant, not a tunable.\n */\nexport const NONCE_SIGNING_DOMAIN = 'byok-nonce-v1\\n';\n\n/**\n * The exact bytes a device signs for a challenge nonce, and the exact bytes a\n * verifier reconstructs: {@link NONCE_SIGNING_DOMAIN} followed by `nonce`,\n * UTF-8 encoded.\n *\n * `TextEncoder` is a platform global on Node and Workers alike, which is what\n * lets the one authority sit in a package that imports no `node:` builtin.\n */\nexport function nonceSigningBytes(nonce: string): Uint8Array {\n return new TextEncoder().encode(NONCE_SIGNING_DOMAIN + nonce);\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 mutationTail: Promise<void>;\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 appended = device.mutationTail.then(async () => {\n const existing = device.byMessageId.get(input.messageId);\n if (existing !== undefined) return existing;\n\n const seq = device.nextSeq;\n const materialized = await input.materialize(seq);\n const message: MailboxMessage = {\n tenantId: tenant,\n deviceId: input.deviceId,\n seq,\n messageId: input.messageId,\n ...materialized,\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 // A failed materializer rejects its own append but must not poison the\n // per-device serializer; the next append starts from the same sequence.\n device.mutationTail = appended.then(\n () => undefined,\n () => undefined,\n );\n return appended;\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 const advanced = device.mutationTail.then(() => {\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 device.mutationTail = advanced.then(\n () => undefined,\n () => undefined,\n );\n return advanced;\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 mutationTail: Promise.resolve(),\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 SkillPackStore} reference (plan `skill-pack-delivery-channel`).\n *\n * The interesting property is what `publish` refuses. This store cannot hash —\n * core has no crypto — so it is NOT the integrity authority for a pack, and it\n * does not pretend to be: the publisher mints the addresses and the installing\n * device re-derives and verifies every one of them. What this store CAN check\n * without crypto, it checks, and rejects rather than storing a pack whose\n * manifest and bytes already disagree at publish time: the declared path set\n * must be exactly the delivered path set, and every delivered file's UTF-8 byte\n * length must equal what its row declared.\n *\n * Storing that pair unchecked would be the worse failure mode by far — the\n * device would fetch, verify, reject, and have no way to tell a corrupt\n * publication from a tampered response.\n */\nimport {\n SKILL_PACK_ENTRY_PATH,\n checkSkillPackEntry,\n checkSkillPackManifest,\n type SkillPackFileContent,\n type SkillPackListQuery,\n type SkillPackManifest,\n type SkillPackPublishInput,\n type SkillPackStore,\n} from '../skill-pack';\nimport { ByokCoreError } from '../errors';\nimport { tenantKey, type TenantId } from '../tenant';\n\nconst DEFAULT_LIST_LIMIT = 50;\n\ninterface StoredPack {\n readonly manifest: SkillPackManifest;\n readonly contents: ReadonlyMap<string, string>;\n}\n\nexport class InMemorySkillPackStore implements SkillPackStore {\n readonly #packs = new Map<string, StoredPack>();\n\n async publish(tenant: TenantId, input: SkillPackPublishInput): Promise<SkillPackManifest> {\n const { manifest } = input;\n const structural = checkSkillPackManifest(manifest);\n if (!structural.ok) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${structural.reason} — ${structural.detail}`,\n );\n }\n\n const contents = new Map<string, string>();\n for (const file of input.files) {\n if (contents.has(file.path)) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(file.path)} was supplied twice.`,\n );\n }\n contents.set(file.path, file.content);\n }\n\n for (const declared of manifest.files) {\n const content = contents.get(declared.path);\n if (content === undefined) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(declared.path)} is declared but was not supplied.`,\n );\n }\n const bytes = new TextEncoder().encode(content).length;\n if (bytes !== declared.byteSize) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(declared.path)} declares ${declared.byteSize} bytes and supplies ${bytes}.`,\n );\n }\n }\n if (contents.size !== manifest.files.length) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${contents.size} files were supplied for ${manifest.files.length} declared rows.`,\n );\n }\n\n const entry = checkSkillPackEntry(manifest, contents.get(SKILL_PACK_ENTRY_PATH)!);\n if (!entry.ok) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${entry.reason} — ${entry.detail}`,\n );\n }\n\n this.#packs.set(tenantKey(tenant, manifest.name), { manifest, contents });\n return manifest;\n }\n\n async get(tenant: TenantId, name: string): Promise<SkillPackManifest | undefined> {\n return this.#packs.get(tenantKey(tenant, name))?.manifest;\n }\n\n async list(tenant: TenantId, query: SkillPackListQuery): Promise<readonly SkillPackManifest[]> {\n const prefix = tenantKey(tenant, '');\n const manifests: SkillPackManifest[] = [];\n for (const [key, pack] of this.#packs.entries()) {\n if (!key.startsWith(prefix)) continue;\n manifests.push(pack.manifest);\n }\n manifests.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n return manifests.slice(0, query.limit ?? DEFAULT_LIST_LIMIT);\n }\n\n async readFile(\n tenant: TenantId,\n name: string,\n path: string,\n ): Promise<SkillPackFileContent | undefined> {\n const pack = this.#packs.get(tenantKey(tenant, name));\n if (pack === undefined) return undefined;\n const declared = pack.manifest.files.find((file) => file.path === path);\n const content = pack.contents.get(path);\n if (declared === undefined || content === undefined) return undefined;\n return {\n path: declared.path,\n contentHash: declared.contentHash,\n byteSize: declared.byteSize,\n content,\n };\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 { InMemorySkillPackStore } from './skill-pack';\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';\nexport { InMemorySkillPackStore } from './skill-pack';\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 skillPacks: new InMemorySkillPackStore(),\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"]}
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/skill-pack.ts","../src/stores.ts","../src/ports-contract.ts","../src/attestation.ts","../src/device-assertion.ts","../src/pairing.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/skill-pack.ts","../src/in-memory/truth.ts","../src/in-memory/clock.ts","../src/in-memory/index.ts"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AAO,CAAA;AAAA,IACzB,CAAA;AAAA,IACA,QAAQ,EAAA,EAAkB;AACxB,MAAA,OAAA,IAAW,EAAA;AAAA,IACb,CAAA;AAAA,IACA,IAAI,OAAA,EAAqB;AACvB,MAAA,OAAA,GAAU,QAAQ,OAAA,EAAQ;AAAA,IAC5B;AAAA,GACF;AACF;;;ACcO,SAAS,wBAAA,CACd,OAAA,GAA+B,EAAC,EACP;AACzB,EAAA,MAAM,KAAA,GAAe,OAAA,CAAQ,KAAA,IAAS,kBAAA,EAAmB;AACzD,EAAA,MAAM,OAAA,GAAU,IAAI,mBAAA,CAAoB,KAAK,CAAA;AAC7C,EAAA,MAAM,MAAA,GAAqB;AAAA,IACzB,OAAA,EAAS,IAAI,oBAAA,CAAqB,KAAK,CAAA;AAAA,IACvC,KAAA,EAAO,IAAI,kBAAA,CAAmB,KAAK,CAAA;AAAA,IACnC,KAAA,EAAO,IAAI,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,CAAA;AAAA,IAC5C,UAAA,EAAY,IAAI,sBAAA;AAAuB,GACzC;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 // device assertion (plan device-assertion-broker) — deliberately its own\n // code rather than reusing `proof_envelope_invalid`: the two envelopes are\n // non-interchangeable by design, and one shared \"envelope was bad\" code is\n // exactly how a log stops being able to say which authentication surface was\n // probed.\n assertion_envelope_invalid: 'assertion_envelope_invalid',\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_key_prefix_invalid: 'object_key_prefix_invalid',\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\n // skill packs (plan `skill-pack-delivery-channel`)\n skill_pack_manifest_invalid: 'skill_pack_manifest_invalid',\n skill_pack_frontmatter_invalid: 'skill_pack_frontmatter_invalid',\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\n/** Opaque bytes produced after the mailbox has atomically reserved their delivery sequence. */\nexport interface MailboxBody {\n readonly body: string;\n readonly bodyHash: ContentHash;\n readonly byteSize: bigint;\n}\n\nexport interface MailboxAppendInput {\n readonly deviceId: string;\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 * Builds the opaque body around the sequence reserved by this append.\n *\n * The store invokes this only for a new row and commits the returned bytes\n * at exactly that `seq`. Allocation, materialization, and insertion are one\n * per-device serialized operation; otherwise concurrent offers could commit\n * out of order and let an ack skip a late lower sequence.\n */\n readonly materialize: (seq: number) => MailboxBody | Promise<MailboxBody>;\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 /**\n * Logical MCP toolset IDs this daemon reported as configured. Discovery\n * only: local task acceptance remains the fail-closed authority. Omission\n * means legacy/unknown; an empty array means known-none.\n */\n readonly configuredToolsets?: readonly 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 /** Validated logical IDs only; executable connector definitions never belong here. */\n readonly configuredToolsets?: readonly 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 * What a deployment-level key namespace may look like: slash-joined segments of\n * lowercase alphanumerics, `.`, `_`, and `-`, each starting with an\n * alphanumeric. No leading or trailing slash, and therefore no empty segment.\n *\n * Narrow on purpose, and narrower than S3 keys allow. A prefix is spliced into\n * every key this SDK ever writes, so the only prefixes worth accepting are the\n * ones that reach the object store spelled exactly as configured: anything\n * requiring percent-encoding would give the deployment's objects two names, and\n * anything with an empty segment would make `a//b` and `a/b` the same key at\n * rest but different strings in config. Case is folded out for the same reason\n * {@link contentHash} refuses uppercase hex — one address, one spelling.\n */\nexport const OBJECT_KEY_PREFIX_PATTERN = /^[a-z0-9][a-z0-9._-]*(\\/[a-z0-9][a-z0-9._-]*)*$/;\n\n/** A validated deployment key namespace. Branded, so only the mint point below can produce one. */\nexport type ObjectKeyPrefix = string & { readonly __byokObjectKeyPrefix: unique symbol };\n\n/**\n * The single mint point for {@link ObjectKeyPrefix}.\n *\n * There is no \"empty means no prefix\" spelling here: a composition that has no\n * prefix omits the option, and one that passes `''` has misconfigured something\n * (an unset environment variable is the usual way). Accepting it silently would\n * make the two indistinguishable at exactly the moment the difference decides\n * where a deployment's objects live.\n *\n * @throws {ByokCoreError} code `object_key_prefix_invalid`.\n */\nexport function objectKeyPrefix(value: string): ObjectKeyPrefix {\n if (!OBJECT_KEY_PREFIX_PATTERN.test(value)) {\n throw new ByokCoreError(\n 'object_key_prefix_invalid',\n `Object key prefix must match ${OBJECT_KEY_PREFIX_PATTERN.source}, received ${JSON.stringify(value)}.`,\n );\n }\n return value as ObjectKeyPrefix;\n}\n\n/**\n * Tenant-scoped object key, e.g.\n * `tenants/<tenantId>/objects/sha256/<hex>` (§12.7.4).\n *\n * `prefix` namespaces the whole layout — `<prefix>/tenants/...` — so one bucket\n * can hold several deployments without either of them owning the bucket root.\n * Omitting it produces the unprefixed key verbatim, which is what makes the\n * option safe to add: every object already at rest was written without one.\n *\n * The prefix is an IMMUTABLE property of a deployment. It is spliced in here\n * and nowhere else, and nothing reads a key back under a second layout: change\n * a live deployment's prefix and its existing objects become unaddressable.\n * See `R2BlobStoreOptions.keyPrefix` in `@byok-sdk/cloud-dataplane` for the full\n * operational contract.\n */\nexport function tenantObjectKey(\n tenant: TenantId,\n hash: ContentHash,\n prefix?: ObjectKeyPrefix,\n): string {\n const hex = hash.slice('sha256:'.length);\n const key = `tenants/${tenant as string}/objects/sha256/${hex}`;\n return prefix === undefined ? key : `${prefix as string}/${key}`;\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 * Skill packs: declarative content a SaaS deployment distributes to a paired\n * device (plan `skill-pack-delivery-channel`, Phase 1).\n *\n * A pack is an `agentskills.io`-shaped `SKILL.md` plus its static companion\n * files. That is the WHOLE of it, and the narrowness is the design:\n *\n * 1. **No executable surface, by schema.** {@link SkillPackManifestSchema} is a\n * `strictObject`, so an unknown key is a rejection rather than a field\n * someone's tooling might later start honoring, and\n * {@link SKILL_PACK_FORBIDDEN_FIELDS} names the specific ones — `exec`,\n * `env`, `credential`, `hooks`, `allowed-tools` — that get their own\n * rejection message. The credential-isolation rule this SDK is built around\n * (§9.1) cannot be enforced downstream if the manifest can carry a command\n * to run or an environment to run it in, so it is enforced here, once.\n * 2. **Every declared limit has an evaluation point in this file.** A size cap\n * that nothing measures, a path rule that nothing checks, and a content hash\n * that nothing verifies are the same failure: a security claim with no\n * enforcement behind it. {@link checkSkillPackManifest} evaluates the\n * manifest-level limits and {@link checkSkillPackFileContent} evaluates the\n * byte-level ones, both returning a named rejection instead of a boolean, so\n * a caller can say which limit fired.\n * 3. **Hashing lives outside core.** Core has no `node:` import and no crypto\n * (the same rule `blob.ts` and `attestation.ts` follow), so this module owns\n * the canonical bytes a hash is taken over ({@link skillPackContentHashInput})\n * and the comparison, never the digest itself. The installer supplies what it\n * observed; core decides whether that is acceptable.\n *\n * Distribution is hosted HTTP (`@byok-sdk/cloud`'s `GET /byok/skill-packs`),\n * declared through ADR-010 as `skills.pack`. Nothing here touches the frozen v1\n * wire envelope, and there is deliberately no new message type: a pack is\n * content a device PULLS after reading a declaration, not a message a server\n * pushes into a task stream.\n */\nimport { z } from 'zod';\nimport { CONTENT_HASH_PATTERN, contentHash, type ContentHash } from './blob';\nimport { ByokCoreError } from './errors';\nimport type { TenantId } from './tenant';\n\nexport const SKILL_PACK_MANIFEST_SCHEMA_ID = 'byok-skill-pack-v1';\n\n/**\n * Pack names: lowercase, starting alphanumeric — the same shape\n * `OBJECT_KEY_PREFIX_PATTERN` accepts per segment, for the same reason. A pack\n * name becomes a directory name on a real device filesystem, so the accepted\n * set is the one that reaches disk spelled exactly as declared: no case folding\n * to collide over, no separator, no leading dot, nothing needing escaping.\n */\nexport const SKILL_PACK_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;\nexport const SKILL_PACK_NAME_MAX_LENGTH = 64;\nexport const SKILL_PACK_DESCRIPTION_MAX_LENGTH = 1024;\n\n/** `MAJOR.MINOR.PATCH`. A pack version orders two publications of one name; it is not a range language. */\nexport const SKILL_PACK_VERSION_PATTERN = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$/;\n\n/**\n * Relative POSIX paths only: slash-joined segments of alphanumerics, `.`, `_`\n * and `-`, each STARTING with an alphanumeric.\n *\n * That single \"starts with an alphanumeric\" rule is what closes the traversal\n * class rather than a blocklist of spellings: `..` cannot match (a segment may\n * not begin with `.`), an absolute path cannot match (no leading slash), an\n * empty segment cannot match (`a//b`), a Windows drive or UNC path cannot match\n * (no `:`, no `\\`), a home-relative path cannot match (no `~`), and a dotfile\n * cannot match either. A blocklist would have to anticipate every encoding of\n * the same idea; this allowlist has nothing to anticipate.\n */\nexport const SKILL_PACK_FILE_PATH_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*(\\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;\nexport const SKILL_PACK_FILE_PATH_MAX_LENGTH = 200;\n\n/** The entry file every pack must carry, spelled as `agentskills.io` spells it. */\nexport const SKILL_PACK_ENTRY_PATH = 'SKILL.md';\n\n/** Per-file ceiling, measured in BYTES over the observed content — never in characters. */\nexport const SKILL_PACK_FILE_MAX_BYTES = 262_144;\n/** Whole-pack ceiling, over the sum of the observed file sizes. */\nexport const SKILL_PACK_MAX_BYTES = 1_048_576;\nexport const SKILL_PACK_MAX_FILES = 64;\n\n/**\n * Manifest keys that must never exist, listed so the prohibition is testable\n * rather than implied.\n *\n * `strictObject` already rejects every unknown key, so this list adds no new\n * authority — it adds a NAMED rejection for the subset that matters: an\n * operator who sees `unrecognized key: \"env\"` learns nothing about why, and a\n * reviewer reading the schema cannot tell whether the omission was a decision\n * or an oversight. Pinned from both directions by\n * `__tests__/skill-pack.test.ts`.\n */\nexport const SKILL_PACK_FORBIDDEN_FIELDS = [\n 'exec',\n 'command',\n 'entrypoint',\n 'run',\n 'script',\n 'shell',\n 'env',\n 'environment',\n 'credential',\n 'credentials',\n 'secret',\n 'secrets',\n 'token',\n 'apiKey',\n 'api_key',\n 'allowedTools',\n 'allowed-tools',\n 'hooks',\n 'preinstall',\n 'postinstall',\n] as const;\n\nconst ContentHashSchema = z\n .string()\n .regex(CONTENT_HASH_PATTERN)\n .transform((value) => contentHash(value));\n\n/** One file in a pack: where it goes, what it must hash to, and how big it is. */\nexport const SkillPackFileSchema = z.strictObject({\n path: z.string().min(1).max(SKILL_PACK_FILE_PATH_MAX_LENGTH).regex(SKILL_PACK_FILE_PATH_PATTERN),\n contentHash: ContentHashSchema,\n byteSize: z.number().int().nonnegative().max(SKILL_PACK_FILE_MAX_BYTES),\n});\n\nexport type SkillPackFile = z.infer<typeof SkillPackFileSchema>;\n\n/**\n * The published description of one pack.\n *\n * `contentHash` addresses the manifest AS A WHOLE — see\n * {@link skillPackContentHashInput} — which is what makes an install\n * content-addressed: two publications that differ in any field a device can\n * observe land in two directories, and re-installing an unchanged pack is a\n * no-op rather than a partial overwrite.\n */\nexport const SkillPackManifestSchema = z.strictObject({\n schema: z.literal(SKILL_PACK_MANIFEST_SCHEMA_ID),\n name: z.string().min(1).max(SKILL_PACK_NAME_MAX_LENGTH).regex(SKILL_PACK_NAME_PATTERN),\n version: z.string().regex(SKILL_PACK_VERSION_PATTERN),\n description: z.string().min(1).max(SKILL_PACK_DESCRIPTION_MAX_LENGTH),\n files: z.array(SkillPackFileSchema).min(1).max(SKILL_PACK_MAX_FILES),\n contentHash: ContentHashSchema,\n});\n\nexport type SkillPackManifest = z.infer<typeof SkillPackManifestSchema>;\n\n/**\n * Parses a manifest fail-closed.\n *\n * @throws {ByokCoreError} code `skill_pack_manifest_invalid`.\n */\nexport function parseSkillPackManifest(input: unknown): SkillPackManifest {\n if (typeof input === 'object' && input !== null) {\n const present = SKILL_PACK_FORBIDDEN_FIELDS.filter((field) =>\n Object.prototype.hasOwnProperty.call(input, field),\n );\n if (present.length > 0) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `A skill pack manifest carries no executable or credential surface; refusing ${present\n .map((field) => JSON.stringify(field))\n .join(', ')}.`,\n );\n }\n }\n const result = SkillPackManifestSchema.safeParse(input);\n if (!result.success) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Invalid skill pack manifest: ${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 * The exact bytes `manifest.contentHash` is the sha256 of.\n *\n * Written out here, in core, because both ends have to agree on it and neither\n * end may derive its own version: the publisher hashes this string to mint the\n * address, the installer hashes it again to verify what it fetched, and a\n * disagreement between the two would make every install either falsely\n * accepted or unconditionally rejected. Newline-delimited and terminated so no\n * field's content can be shifted into the next field's position, and the file\n * rows are sorted by path so two publishers that enumerate a directory in\n * different orders still mint the same address.\n */\nexport function skillPackContentHashInput(manifest: {\n readonly name: string;\n readonly version: string;\n readonly description: string;\n readonly files: readonly SkillPackFile[];\n}): string {\n const rows = [...manifest.files]\n .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))\n .map((file) => `${file.path}\\n${file.contentHash as string}\\n${file.byteSize}\\n`);\n return [\n `${SKILL_PACK_MANIFEST_SCHEMA_ID}\\n`,\n `${manifest.name}\\n`,\n `${manifest.version}\\n`,\n `${manifest.description.length}\\n`,\n `${manifest.description}\\n`,\n `${manifest.files.length}\\n`,\n ...rows,\n ].join('');\n}\n\n/** Every way a pack can be refused. One name per declared limit — see {@link SkillPackCheck}. */\nexport const SKILL_PACK_REJECTIONS = [\n 'path-unsafe',\n 'duplicate-path',\n 'entry-missing',\n 'file-count-over-cap',\n 'file-over-cap',\n 'pack-over-cap',\n 'size-mismatch',\n 'hash-mismatch',\n 'name-mismatch',\n] as const;\nexport type SkillPackRejection = (typeof SKILL_PACK_REJECTIONS)[number];\n\n/**\n * Outcome of a check. `bytes` is the measured total on the accept path so a\n * caller can record what it admitted; a rejection always names WHICH limit\n * fired, because \"the pack was rejected\" is not an operable message.\n */\nexport type SkillPackCheck =\n | { readonly ok: true; readonly bytes: number }\n | { readonly ok: false; readonly reason: SkillPackRejection; readonly detail: string };\n\n/** Non-throwing path-safety predicate — the one authority on what a pack may name. */\nexport function isSkillPackPathSafe(path: string): boolean {\n return (\n path.length > 0 &&\n path.length <= SKILL_PACK_FILE_PATH_MAX_LENGTH &&\n SKILL_PACK_FILE_PATH_PATTERN.test(path)\n );\n}\n\n/**\n * The manifest-level limits, evaluated.\n *\n * Runs over a manifest that has already parsed, so the per-field caps zod owns\n * are not re-litigated here. What is left is everything zod cannot see: the\n * relationships BETWEEN files (a duplicate path, a missing entry file, a total\n * that clears every per-file cap and still blows the pack cap).\n */\nexport function checkSkillPackManifest(manifest: SkillPackManifest): SkillPackCheck {\n if (manifest.files.length > SKILL_PACK_MAX_FILES) {\n return {\n ok: false,\n reason: 'file-count-over-cap',\n detail: `${manifest.files.length} files exceeds the ${SKILL_PACK_MAX_FILES} file limit.`,\n };\n }\n\n const seen = new Set<string>();\n let bytes = 0;\n for (const file of manifest.files) {\n if (!isSkillPackPathSafe(file.path)) {\n return { ok: false, reason: 'path-unsafe', detail: `${JSON.stringify(file.path)} is not a safe relative path.` };\n }\n if (seen.has(file.path)) {\n return { ok: false, reason: 'duplicate-path', detail: `${JSON.stringify(file.path)} is declared twice.` };\n }\n seen.add(file.path);\n if (file.byteSize > SKILL_PACK_FILE_MAX_BYTES) {\n return {\n ok: false,\n reason: 'file-over-cap',\n detail: `${JSON.stringify(file.path)} declares ${file.byteSize} bytes, over the ${SKILL_PACK_FILE_MAX_BYTES} byte per-file limit.`,\n };\n }\n bytes += file.byteSize;\n }\n\n if (!seen.has(SKILL_PACK_ENTRY_PATH)) {\n return {\n ok: false,\n reason: 'entry-missing',\n detail: `A skill pack must carry ${SKILL_PACK_ENTRY_PATH}.`,\n };\n }\n if (bytes > SKILL_PACK_MAX_BYTES) {\n return {\n ok: false,\n reason: 'pack-over-cap',\n detail: `${bytes} declared bytes exceeds the ${SKILL_PACK_MAX_BYTES} byte pack limit.`,\n };\n }\n return { ok: true, bytes };\n}\n\n/** What an installer actually measured for one file, as opposed to what the manifest declared. */\nexport interface ObservedSkillPackFile {\n readonly byteSize: number;\n readonly contentHash: ContentHash;\n}\n\n/**\n * The byte-level limits, evaluated against what was actually fetched.\n *\n * The asymmetry with {@link checkSkillPackManifest} is the point: the declared\n * size is a claim by the publisher and the observed size is a fact about the\n * bytes on the device, so the cap is enforced on the OBSERVED value. A check\n * that only ever measured the declaration would pass a 4 KiB manifest row\n * attached to a 40 MiB response.\n */\nexport function checkSkillPackFileContent(\n declared: SkillPackFile,\n observed: ObservedSkillPackFile,\n): SkillPackCheck {\n if (!isSkillPackPathSafe(declared.path)) {\n return { ok: false, reason: 'path-unsafe', detail: `${JSON.stringify(declared.path)} is not a safe relative path.` };\n }\n if (observed.byteSize > SKILL_PACK_FILE_MAX_BYTES) {\n return {\n ok: false,\n reason: 'file-over-cap',\n detail: `${JSON.stringify(declared.path)} delivered ${observed.byteSize} bytes, over the ${SKILL_PACK_FILE_MAX_BYTES} byte per-file limit.`,\n };\n }\n if (observed.byteSize !== declared.byteSize) {\n return {\n ok: false,\n reason: 'size-mismatch',\n detail: `${JSON.stringify(declared.path)} declared ${declared.byteSize} bytes and delivered ${observed.byteSize}.`,\n };\n }\n if ((observed.contentHash as string) !== (declared.contentHash as string)) {\n return {\n ok: false,\n reason: 'hash-mismatch',\n detail: `${JSON.stringify(declared.path)} declared ${declared.contentHash as string} and delivered ${observed.contentHash as string}.`,\n };\n }\n return { ok: true, bytes: observed.byteSize };\n}\n\n/**\n * `SKILL.md` frontmatter, in the `agentskills.io` shape: exactly `name` and\n * `description`, both required.\n *\n * The allowlist is the whole contract. `allowed-tools`, `hooks` and friends are\n * real fields in other skill dialects and every one of them widens what a pack\n * can ask a runtime to do; a parser that merely IGNORED them would still let a\n * pack ship them to a host that does not.\n */\nexport interface SkillFrontmatter {\n readonly name: string;\n readonly description: string;\n}\n\n/** The only frontmatter keys a pack may declare. */\nexport const SKILL_FRONTMATTER_FIELDS = ['name', 'description'] as const;\n\nconst FRONTMATTER_DELIMITER = '---';\nconst FRONTMATTER_LINE_PATTERN = /^([A-Za-z][A-Za-z0-9_-]*):[ \\t]*(.*)$/;\n\nfunction unquote(value: string): string | undefined {\n const trimmed = value.trim();\n if (trimmed.length >= 2) {\n const first = trimmed[0];\n const last = trimmed[trimmed.length - 1];\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n const inner = trimmed.slice(1, -1);\n return inner.includes(first) ? undefined : inner;\n }\n }\n return trimmed;\n}\n\n/**\n * Parses and validates a `SKILL.md`'s frontmatter block.\n *\n * Deliberately not a YAML engine: this is a closed two-key grammar, and the\n * whole reason to hand-write it is that a general parser would happily accept\n * anchors, aliases, nested maps, multi-document streams and block scalars —\n * every one of which is a way to express something this format has decided not\n * to have. Anything outside the grammar is a rejection, never a skipped line.\n *\n * @throws {ByokCoreError} code `skill_pack_frontmatter_invalid`.\n */\nexport function parseSkillFrontmatter(text: string): SkillFrontmatter {\n const reject = (message: string): never => {\n throw new ByokCoreError('skill_pack_frontmatter_invalid', message);\n };\n\n const lines = text.split('\\n');\n if (lines[0]?.trimEnd() !== FRONTMATTER_DELIMITER) {\n reject(`A skill file must open with a ${FRONTMATTER_DELIMITER} frontmatter delimiter.`);\n }\n const closing = lines.findIndex((line, index) => index > 0 && line.trimEnd() === FRONTMATTER_DELIMITER);\n if (closing < 0) reject(`The frontmatter block is not closed by a ${FRONTMATTER_DELIMITER} line.`);\n\n const fields = new Map<string, string>();\n for (const line of lines.slice(1, closing)) {\n if (line.trim().length === 0) continue;\n const match = FRONTMATTER_LINE_PATTERN.exec(line);\n if (match === null) reject(`Frontmatter line ${JSON.stringify(line)} is not a \\`key: value\\` pair.`);\n const key = match![1]!;\n if (!(SKILL_FRONTMATTER_FIELDS as readonly string[]).includes(key)) {\n reject(\n `Frontmatter key ${JSON.stringify(key)} is not one of ${SKILL_FRONTMATTER_FIELDS.join(', ')}; a skill declares no tools, hooks, or environment.`,\n );\n }\n if (fields.has(key)) reject(`Frontmatter key ${JSON.stringify(key)} is declared twice.`);\n const value = unquote(match![2]!);\n if (value === undefined || value.length === 0) {\n reject(`Frontmatter key ${JSON.stringify(key)} has no usable value.`);\n }\n fields.set(key, value!);\n }\n\n const name = fields.get('name');\n const description = fields.get('description');\n if (name === undefined) reject('Frontmatter is missing `name`.');\n if (description === undefined) reject('Frontmatter is missing `description`.');\n if (name!.length > SKILL_PACK_NAME_MAX_LENGTH || !SKILL_PACK_NAME_PATTERN.test(name!)) {\n reject(\n `Frontmatter \\`name\\` must match ${SKILL_PACK_NAME_PATTERN.source} and be at most ${SKILL_PACK_NAME_MAX_LENGTH} characters.`,\n );\n }\n if (description!.length > SKILL_PACK_DESCRIPTION_MAX_LENGTH) {\n reject(`Frontmatter \\`description\\` exceeds ${SKILL_PACK_DESCRIPTION_MAX_LENGTH} characters.`);\n }\n return { name: name!, description: description! };\n}\n\n/**\n * The entry file's own declaration must agree with the manifest's.\n *\n * Two authorities naming the same pack is not a redundancy to tolerate — a\n * device that installed under one name and handed the runtime a skill calling\n * itself another would be projecting content nobody asked for.\n */\nexport function checkSkillPackEntry(manifest: SkillPackManifest, entryText: string): SkillPackCheck {\n const frontmatter = parseSkillFrontmatter(entryText);\n if (frontmatter.name !== manifest.name) {\n return {\n ok: false,\n reason: 'name-mismatch',\n detail: `${SKILL_PACK_ENTRY_PATH} declares ${JSON.stringify(frontmatter.name)} but the manifest declares ${JSON.stringify(manifest.name)}.`,\n };\n }\n return { ok: true, bytes: new TextEncoder().encode(entryText).length };\n}\n\n/** One file's bytes, as the distribution surface hands them over. */\nexport interface SkillPackFileContent {\n readonly path: string;\n readonly contentHash: ContentHash;\n readonly byteSize: number;\n /** UTF-8 text. A pack carries Markdown, YAML and static text assets — never binaries, never archives. */\n readonly content: string;\n}\n\n/** What a publisher hands the store: the validated manifest plus the bytes it addresses. */\nexport interface SkillPackPublishInput {\n readonly manifest: SkillPackManifest;\n readonly files: readonly { readonly path: string; readonly content: string }[];\n}\n\nexport interface SkillPackListQuery {\n readonly limit?: number;\n}\n\n/**\n * Skill pack port. Tenant-first, async, content plus manifest.\n *\n * Registered in `ports-contract.ts` as a core PORT, and deliberately not (yet)\n * a member of `CoreStores`: a composition contract that named it would oblige\n * every existing composition to implement it in the same slice, and the\n * Postgres implementation is Phase 2 of this plan. See `ports-contract.ts` for\n * the full note on that split.\n *\n * Raises: `skill_pack_manifest_invalid` (a publish whose bytes disagree with\n * the manifest it was handed).\n */\nexport interface SkillPackStore {\n /** Idempotent per (tenant, name, contentHash). Publishing a changed pack under the same name replaces it. */\n publish(tenant: TenantId, input: SkillPackPublishInput): Promise<SkillPackManifest>;\n get(tenant: TenantId, name: string): Promise<SkillPackManifest | undefined>;\n list(tenant: TenantId, query: SkillPackListQuery): Promise<readonly SkillPackManifest[]>;\n readFile(tenant: TenantId, name: string, path: string): Promise<SkillPackFileContent | undefined>;\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 { SkillPackStore } from './skill-pack';\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 * Skill-pack storage is a MANDATORY member: every composition creates the\n * tables and supplies the port (Phase 2 of `skill-pack-delivery-channel`).\n * Storage presence is not capability advertisement — the wire route/capability\n * stays optional in `@byok-sdk/cloud` (`includeSkillPacks`), and a deployment\n * that never declares `skills.pack` simply keeps the tables empty.\n */\n readonly skillPacks: SkillPackStore;\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 'skillPacks',\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 { CORE_STORE_NAMES, type CoreStoreName } from './stores';\n\n/**\n * Ports that are core ports but NOT members of the composition contract.\n *\n * Now empty, and that is the whole point of Phase 2. Phase 1 of\n * `skill-pack-delivery-channel` held `skillPacks` here as a self-declared\n * temporary bridge: adding it to `CoreStores` before its Postgres\n * implementation existed would have obliged every composition to implement it\n * in the same slice, and the alternatives — an optional port member (a\n * compatibility fallback, forbidden) or a port outside the contract table\n * entirely (exempt from the tenant-first scan, the one rule most worth having)\n * — were both worse. Phase 2 delivered that implementation and moved\n * `skillPacks` into `CORE_STORE_NAMES`, so this list goes back to empty exactly\n * as the Phase 1 note promised. The empty set stays named rather than deleted:\n * it is the testable statement \"every core port is a composition member\", which\n * `CORE_STORE_NAMES` alone cannot make.\n */\nexport const CORE_NON_COMPOSITION_PORT_NAMES = [] as const;\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 skillPacks: ['publish', 'get', 'list', 'readFile'],\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 skillPacks: 'SkillPackStore',\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\n/**\n * HTTP header carrying the base64url device-proof envelope on a truth-route\n * request (§12.6.3). Both the daemon that mints the proof and the host that\n * decodes it must name the exact same header, so it is a single wire constant\n * here rather than a string re-spelled on each side.\n */\nexport const DEVICE_PROOF_HEADER = 'x-byok-device-proof';\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 * Device assertion envelope, canonical signing bytes, and verifier\n * (plan `device-assertion-broker`, P3 ①-⑤).\n *\n * A device assertion is a short-lived, audience-scoped statement a *paired\n * device* makes about itself — \"this device, paired to this product against\n * this server, wants to talk to `<audience>` for the next two minutes\" — signed\n * with the same Ed25519 device identity key `attestation.ts`'s device proof\n * uses. A sibling CLI installed alongside the daemon presents one to the host's\n * cloud, which exchanges it for a product session. It is NOT a request-bound\n * proof (`attestation.ts`) and the two must never be interchangeable; see the\n * domain prefix below.\n *\n * Four decisions this file encodes, none of them re-litigable here:\n *\n * 1. **A custom JSON signing envelope, not JWS.** The domain prefix has to be\n * *inside* the signed bytes. JWS puts its type tag in a header that no\n * verifier is required to check, which is a fail-open shape: a token minted\n * for one purpose verifies for another as long as the key matches. So this\n * clones the mechanism `attestation.ts` already froze — RFC 8785-subset\n * canonicalization (`canonicalizeJson`, imported, never re-implemented) plus\n * a golden fixture pinning the exact bytes.\n * 2. **What the claims deliberately do NOT carry.** No `devicePublicKey`: a\n * verifier must resolve the key from its own device directory by `deviceId`,\n * or the envelope becomes self-authenticating. No caller identity: every\n * process under the same UID can reach the control socket, so a \"who asked\"\n * field would be synthesized authority, not evidence. No `keyId`: there is\n * no key-rotation story for this envelope yet, and a field nothing populates\n * honestly is a structure that invites a verifier to trust it.\n * 3. **`audience` is a single string, never an array.** A multi-audience token\n * forces every verifier to agree on the same containment rule; one string\n * compared with `===` cannot be got wrong.\n * 4. **The verifier cannot forget the revocation check.** {@link\n * verifyDeviceAssertion} takes `revoked` as a REQUIRED dependency, so a\n * caller that never looked the device row up does not compile. The daemon's\n * own local checks (see `@byok-sdk/client`'s `assertion.issue`) are only half\n * of revocation; the other half is this recheck at exchange time, and no\n * documentation may claim the daemon satisfies \"synchronous invalidation\"\n * on its own.\n *\n * Like `attestation.ts`, this module is crypto-free: signature verification is\n * an injected port (`DeviceAssertionVerifier`), because core must load on\n * Workers and `node:crypto`/WebCrypto disagree about key handling.\n */\nimport { z } from 'zod';\nimport { canonicalizeJson, type JsonObject, type JsonValue } from './attestation';\nimport { ByokCoreError } from './errors';\n\n/** Envelope schema id, self-consistent with the domain prefix below. */\nexport const DEVICE_ASSERTION_SCHEMA_ID = 'byok-device-assertion-v1';\n\n/**\n * Domain separation prefix, prepended to the canonical claim bytes before\n * signing.\n *\n * Must remain mutually NON-PREFIX with the other two things this same Ed25519\n * device key signs — `byok-nonce-v1\\n` (challenge/token renewal, see\n * `@byok-sdk/client`'s `device-keys.ts`) and `byok-device-proof-v1\\n`\n * (`attestation.ts`) — so no signature over one domain can ever be reinterpreted\n * as a signature over another. `packages/core/src/__tests__/device-assertion.test.ts`\n * asserts the three-way non-prefix property directly; that assertion is the\n * falsifier for this whole design, not a nicety.\n */\nexport const DEVICE_ASSERTION_DOMAIN_PREFIX = 'byok-device-assertion-v1\\n';\n\nexport const DEVICE_ASSERTION_VERSION = 1;\n\n/** Signature algorithms this envelope version admits. */\nexport const DEVICE_ASSERTION_ALGORITHMS = ['ed25519'] as const;\nexport type DeviceAssertionAlgorithm = (typeof DEVICE_ASSERTION_ALGORITHMS)[number];\n\n/**\n * Default assertion lifetime. Short on purpose: the daemon keeps no `jti`\n * ledger (it is not on the verification path and could not stop a real replay\n * anyway), so a narrow expiry window plus a burn-on-use verifier is the whole\n * replay story.\n */\nexport const DEVICE_ASSERTION_DEFAULT_TTL_MS = 120_000;\n\n/**\n * Hard ceiling on the lifetime, enforced at BOTH ends: a daemon refuses to be\n * configured above it, and {@link verifyDeviceAssertion} refuses an envelope\n * whose own `issuedAt`→`expiresAt` span exceeds it regardless of who minted it.\n */\nexport const DEVICE_ASSERTION_MAX_TTL_MS = 300_000;\n\n/** Bound on the `audience` claim, in UTF-8 bytes — an allowlist entry is a short identifier, not a document. */\nexport const DEVICE_ASSERTION_AUDIENCE_MAX_BYTES = 256;\n\n/** base64url of 16 CSPRNG bytes (128 bits), unpadded. */\nconst JTI_PATTERN = /^[A-Za-z0-9_-]{22}$/;\n\n/** base64url of a raw 64-byte Ed25519 signature, unpadded. */\nconst SIGNATURE_PATTERN = /^[A-Za-z0-9_-]{86}$/;\n\nfunction utf8ByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n// ---------------------------------------------------------------------------\n// Claims\n// ---------------------------------------------------------------------------\n\n/**\n * The signed claim set. `strictObject` with every member REQUIRED: an optional\n * claim is a claim a verifier may or may not see, and this envelope is small\n * enough that there is no honest reason for one.\n *\n * `issuer` is the paired server's origin (scheme + host + port, normalized) —\n * it binds the assertion to the deployment the device is actually paired\n * against, so an assertion minted by a device paired to a staging server cannot\n * be presented to production.\n */\nexport const DeviceAssertionClaimsSchema = z.strictObject({\n version: z.literal(DEVICE_ASSERTION_VERSION),\n /** The paired server's origin, normalized (`new URL(serverUrl).origin`). */\n issuer: z.string().min(1),\n productId: z.string().min(1),\n /** The device row this assertion claims to be. A lookup key, never authority — the row is the authority. */\n deviceId: z.string().min(1),\n /** Exactly one audience, compared with `===` by every verifier. Never an array, never a prefix. */\n audience: z\n .string()\n .min(1)\n .refine((value) => utf8ByteLength(value) <= DEVICE_ASSERTION_AUDIENCE_MAX_BYTES, {\n message: `audience must be at most ${DEVICE_ASSERTION_AUDIENCE_MAX_BYTES} UTF-8 bytes`,\n }),\n /** 128-bit CSPRNG token, base64url unpadded. The verifier burns it; the signer never reuses one. */\n jti: z.string().regex(JTI_PATTERN),\n issuedAt: z.iso.datetime(),\n expiresAt: z.iso.datetime(),\n});\n\nexport type DeviceAssertionClaims = z.infer<typeof DeviceAssertionClaimsSchema>;\n\nexport const DeviceAssertionEnvelopeV1Schema = z.strictObject({\n schema: z.literal(DEVICE_ASSERTION_SCHEMA_ID),\n algorithm: z.enum(DEVICE_ASSERTION_ALGORITHMS),\n protected: DeviceAssertionClaimsSchema,\n /** Raw 64-byte Ed25519 signature, base64url unpadded. */\n signature: z.string().regex(SIGNATURE_PATTERN),\n});\n\nexport type DeviceAssertionEnvelopeV1 = z.infer<typeof DeviceAssertionEnvelopeV1Schema>;\n\n/**\n * Parses an envelope fail-closed.\n *\n * @throws {ByokCoreError} code `assertion_envelope_invalid`.\n */\nexport function parseDeviceAssertionEnvelope(input: unknown): DeviceAssertionEnvelopeV1 {\n const result = DeviceAssertionEnvelopeV1Schema.safeParse(input);\n if (!result.success) {\n throw new ByokCoreError(\n 'assertion_envelope_invalid',\n `Invalid device assertion 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 — the same\n * discipline `deviceProofCanonicalClaims` documents. Nothing here is optional,\n * so there is no absent-key decision to get wrong; the explicit projection is\n * what keeps it that way if a field is ever added.\n */\nexport function deviceAssertionCanonicalClaims(claims: DeviceAssertionClaims): JsonObject {\n const canonical: Record<string, JsonValue> = {\n version: claims.version,\n issuer: claims.issuer,\n productId: claims.productId,\n deviceId: claims.deviceId,\n audience: claims.audience,\n jti: claims.jti,\n issuedAt: claims.issuedAt,\n expiresAt: claims.expiresAt,\n };\n return canonical;\n}\n\n/** Canonical JSON text of the claim set, without the domain prefix. */\nexport function deviceAssertionCanonicalJson(claims: DeviceAssertionClaims): string {\n return canonicalizeJson(deviceAssertionCanonicalClaims(claims));\n}\n\n/**\n * The exact bytes a device signs and a verifier reconstructs:\n * `byok-device-assertion-v1\\n` followed by the canonical claim JSON, UTF-8\n * encoded.\n *\n * Frozen by `src/__tests__/golden/device-assertion-v1.canonical.json`.\n */\nexport function deviceAssertionSigningInput(claims: DeviceAssertionClaims): Uint8Array {\n return new TextEncoder().encode(\n DEVICE_ASSERTION_DOMAIN_PREFIX + deviceAssertionCanonicalJson(claims),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Verify\n// ---------------------------------------------------------------------------\n\nexport interface DeviceAssertionVerifyInput {\n readonly algorithm: DeviceAssertionAlgorithm;\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, for the same reason `DeviceProofVerifier`\n * exists: core is Node-free and Workers-safe, so it answers no cryptographic\n * question itself. Kept separate from `DeviceProofVerifier` even though the\n * shapes coincide — one composition object satisfies both — because this file's\n * entire purpose is that the two domains never become interchangeable, and a\n * shared type is the first step toward a shared code path.\n */\nexport interface DeviceAssertionVerifier {\n verify(input: DeviceAssertionVerifyInput): Promise<boolean>;\n}\n\n/**\n * The device-row fields a verification reads — the verifier's OWN directory\n * row, resolved by `deviceId`, never anything the envelope carried.\n *\n * Both fields together, from one lookup, are what make forgetting impossible:\n * the caller cannot obtain `publicKeyJwkX` without also obtaining the current\n * `revoked` state, because they arrive as one object from one call.\n */\nexport interface DeviceAssertionDeviceRow {\n /** JWK `x` of the device's registered Ed25519 public key. The ONLY key a signature is ever checked against. */\n readonly publicKeyJwkX: string;\n /** The row's CURRENT revocation state, read in the same lookup as the key. */\n readonly revoked: boolean;\n}\n\n/**\n * Everything a verification needs that is NOT in the envelope.\n *\n * The device row is supplied through a LOOKUP PORT, not as a pre-fetched\n * value, and that is the whole point (this is the faithful clone of\n * `DeviceProofVerifier`'s \"core is never a second authority on device\n * identity\" shape). `verifyDeviceAssertion` reads `deviceId` from the parsed\n * claims and calls `lookupDevice(deviceId)` ITSELF, so:\n *\n * - There is no way to invoke a verification without providing the means to\n * look the current row up — \"I forgot to check revocation\" cannot be\n * expressed, because the function does the lookup, not the caller.\n * - Both the public key AND the revocation state come from that one row, so a\n * caller cannot pass a key while claiming `revoked: false` from thin air.\n * - The `deviceId` handed to `lookupDevice` is the claimed one; the row it\n * returns is authority. A device asserting an identity it is not is caught\n * by the lookup missing, or by the returned row's key failing the signature.\n */\nexport interface DeviceAssertionVerifyDeps {\n readonly verifier: DeviceAssertionVerifier;\n /**\n * Resolve the verifier's own device row by the claimed `deviceId`.\n * `undefined` for an unknown device. Sync or async; awaited either way.\n */\n readonly lookupDevice: (\n deviceId: string,\n ) => Promise<DeviceAssertionDeviceRow | undefined> | DeviceAssertionDeviceRow | undefined;\n /** Injected instant — core never reads a wall clock (`stores.ts`'s `Clock`). */\n readonly now: Date;\n /** Bound on `issuedAt`→`expiresAt`. Defaults to (and may never exceed) {@link DEVICE_ASSERTION_MAX_TTL_MS}. */\n readonly maxLifetimeMs?: number;\n}\n\nfunction parseInstant(value: string): number | undefined {\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\n/**\n * Raw Ed25519 public key as a JWK `x`: 32 bytes, base64url unpadded — exactly\n * 43 characters. The envelope's `algorithm` is a closed `ed25519`, so the row's\n * key must be an Ed25519 key of this exact shape.\n */\nconst EDDSA_JWK_X_PATTERN = /^[A-Za-z0-9_-]{43}$/;\n\n/**\n * codex round-2 F2: strict runtime validation of a looked-up device row, since\n * `lookupDevice` is a caller-supplied port whose return value TypeScript cannot\n * enforce at runtime. Fails closed on any shape that isn't exactly a usable row:\n *\n * - `revoked` must be the literal boolean `false`. A missing, `undefined`,\n * truthy, or non-boolean `revoked` is a malformed row — and a missing\n * `revoked` reading as \"not revoked\" (`undefined` is falsey) is precisely the\n * fail-open this guard closes: a revoked device must never slip through on a\n * row shape the caller got wrong.\n * - `publicKeyJwkX` must be a present, well-formed Ed25519 JWK `x`. A missing or\n * malformed key is rejected here, before any crypto — so a bad key can never\n * reach (and throw inside) the verifier port either.\n */\nfunction isUsableDeviceRow(row: unknown): row is DeviceAssertionDeviceRow {\n if (row === null || typeof row !== 'object') return false;\n if ((row as { revoked?: unknown }).revoked !== false) return false;\n const key = (row as { publicKeyJwkX?: unknown }).publicKeyJwkX;\n return typeof key === 'string' && EDDSA_JWK_X_PATTERN.test(key);\n}\n\n/**\n * Verifies an assertion and returns its claims, or `undefined`.\n *\n * Every rejected state collapses to `undefined` — malformed input, an unknown\n * or revoked device, an expired or over-long window, a bad signature — so a\n * route has one response for all of them and cannot accidentally leak which\n * check failed. That is the same shape `authenticateDeviceProof`\n * (`@byok-sdk/cloud`) already uses.\n *\n * The row lookup and both authority reads (key, revocation) happen INSIDE this\n * function — see {@link DeviceAssertionVerifyDeps}. What the caller MUST still\n * do afterward, and this cannot: assert `claims.audience` equals the audience\n * it actually serves, assert `claims.issuer`/`claims.productId` match its own\n * deployment, and BURN `claims.jti` so the assertion cannot be presented\n * twice. The daemon keeps no `jti` ledger; single use is entirely the\n * verifier's job.\n */\nexport async function verifyDeviceAssertion(\n input: unknown,\n deps: DeviceAssertionVerifyDeps,\n): Promise<DeviceAssertionClaims | undefined> {\n const maxLifetimeMs = deps.maxLifetimeMs ?? DEVICE_ASSERTION_MAX_TTL_MS;\n if (\n !Number.isSafeInteger(maxLifetimeMs) ||\n maxLifetimeMs <= 0 ||\n maxLifetimeMs > DEVICE_ASSERTION_MAX_TTL_MS\n ) {\n return undefined;\n }\n\n let envelope: DeviceAssertionEnvelopeV1;\n try {\n envelope = parseDeviceAssertionEnvelope(input);\n } catch {\n return undefined;\n }\n const claims = envelope.protected;\n\n // Resolve the row by the CLAIMED deviceId, then read authority from the row.\n // An unknown device, a revoked one, and a MALFORMED one all stop here, before\n // any crypto is done on the claimed identity's behalf. The row is validated\n // strictly (codex round-2 F2): `revoked` must be exactly `false` and the key\n // must be a well-formed Ed25519 JWK `x` — a missing `revoked` never reads as\n // \"not revoked\", and a missing/malformed key never reaches the verifier.\n const row = await deps.lookupDevice(claims.deviceId);\n if (!isUsableDeviceRow(row)) return undefined;\n\n const issuedAt = parseInstant(claims.issuedAt);\n const expiresAt = parseInstant(claims.expiresAt);\n if (issuedAt === undefined || expiresAt === undefined) return undefined;\n if (expiresAt <= issuedAt) return undefined;\n if (expiresAt - issuedAt > maxLifetimeMs) return undefined;\n\n // No clock-skew allowance: this envelope's whole safety margin is its short\n // window, and a tolerance knob is just that window quietly widened. A\n // deployment whose clocks disagree by minutes has a clock problem to fix, not\n // an assertion lifetime to extend. Validity is a half-open interval\n // `[issuedAt, expiresAt)` — at the exact `expiresAt` instant the assertion is\n // already expired, so the check is `now >= expiresAt`, not `now > expiresAt`.\n const now = deps.now.getTime();\n if (!Number.isFinite(now)) return undefined;\n if (now < issuedAt || now >= expiresAt) return undefined;\n\n const verified = await deps.verifier.verify({\n algorithm: envelope.algorithm,\n // The row's key, never an envelope-supplied one.\n publicKey: row.publicKeyJwkX,\n signature: envelope.signature,\n signingInput: deviceAssertionSigningInput(claims),\n });\n if (!verified) return undefined;\n\n return claims;\n}\n","/**\n * Nonce-signing domain separation for device token renewal (docs/protocol.md §6.2).\n *\n * S1 (GAP-004) put a domain tag in front of every challenge nonce a device\n * signs: the device key is a long-lived identity key that other planes (S6\n * device proof) also sign structured messages with, so without a tag a\n * signature produced for one purpose would be a valid signature for another.\n *\n * The tag started life as three separate literals — one in the daemon, one on\n * the hosted surface, one on the reference server — each with a comment saying\n * it was byte-identical to the others. That is a drift hazard written down, not\n * a design: three copies agree only until someone edits one. This module is the\n * single authority, and it lives in core for the same reason\n * {@link DEVICE_PROOF_DOMAIN_PREFIX} does — core is the one package all three\n * ends already depend on, it is Node-free and Workers-safe, and it holds no\n * crypto of its own. What travels is *bytes to sign*; who signs them, and with\n * which primitive, stays with each end.\n *\n * There is deliberately no dual mode and no grace window: a raw, unprefixed\n * nonce signature is simply invalid, and a device on an older encoding re-pairs.\n */\n\n/**\n * The domain-separation prefix a device signs along with a challenge nonce.\n *\n * Byte-frozen: `62 79 6f 6b 2d 6e 6f 6e 63 65 2d 76 31 0a` (14 bytes, UTF-8).\n * Changing it invalidates every deployed device's token-renewal path, so it is\n * a wire constant, not a tunable.\n */\nexport const NONCE_SIGNING_DOMAIN = 'byok-nonce-v1\\n';\n\n/**\n * The exact bytes a device signs for a challenge nonce, and the exact bytes a\n * verifier reconstructs: {@link NONCE_SIGNING_DOMAIN} followed by `nonce`,\n * UTF-8 encoded.\n *\n * `TextEncoder` is a platform global on Node and Workers alike, which is what\n * lets the one authority sit in a package that imports no `node:` builtin.\n */\nexport function nonceSigningBytes(nonce: string): Uint8Array {\n return new TextEncoder().encode(NONCE_SIGNING_DOMAIN + nonce);\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 ...(input.configuredToolsets === undefined\n ? {}\n : { configuredToolsets: Object.freeze([...input.configuredToolsets]) }),\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 mutationTail: Promise<void>;\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 appended = device.mutationTail.then(async () => {\n const existing = device.byMessageId.get(input.messageId);\n if (existing !== undefined) return existing;\n\n const seq = device.nextSeq;\n const materialized = await input.materialize(seq);\n const message: MailboxMessage = {\n tenantId: tenant,\n deviceId: input.deviceId,\n seq,\n messageId: input.messageId,\n ...materialized,\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 // A failed materializer rejects its own append but must not poison the\n // per-device serializer; the next append starts from the same sequence.\n device.mutationTail = appended.then(\n () => undefined,\n () => undefined,\n );\n return appended;\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 const advanced = device.mutationTail.then(() => {\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 device.mutationTail = advanced.then(\n () => undefined,\n () => undefined,\n );\n return advanced;\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 mutationTail: Promise.resolve(),\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 SkillPackStore} reference (plan `skill-pack-delivery-channel`).\n *\n * The interesting property is what `publish` refuses. This store cannot hash —\n * core has no crypto — so it is NOT the integrity authority for a pack, and it\n * does not pretend to be: the publisher mints the addresses and the installing\n * device re-derives and verifies every one of them. What this store CAN check\n * without crypto, it checks, and rejects rather than storing a pack whose\n * manifest and bytes already disagree at publish time: the declared path set\n * must be exactly the delivered path set, and every delivered file's UTF-8 byte\n * length must equal what its row declared.\n *\n * Storing that pair unchecked would be the worse failure mode by far — the\n * device would fetch, verify, reject, and have no way to tell a corrupt\n * publication from a tampered response.\n */\nimport {\n SKILL_PACK_ENTRY_PATH,\n checkSkillPackEntry,\n checkSkillPackManifest,\n type SkillPackFileContent,\n type SkillPackListQuery,\n type SkillPackManifest,\n type SkillPackPublishInput,\n type SkillPackStore,\n} from '../skill-pack';\nimport { ByokCoreError } from '../errors';\nimport { tenantKey, type TenantId } from '../tenant';\n\nconst DEFAULT_LIST_LIMIT = 50;\n\ninterface StoredPack {\n readonly manifest: SkillPackManifest;\n readonly contents: ReadonlyMap<string, string>;\n}\n\nexport class InMemorySkillPackStore implements SkillPackStore {\n readonly #packs = new Map<string, StoredPack>();\n\n async publish(tenant: TenantId, input: SkillPackPublishInput): Promise<SkillPackManifest> {\n const { manifest } = input;\n const structural = checkSkillPackManifest(manifest);\n if (!structural.ok) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${structural.reason} — ${structural.detail}`,\n );\n }\n\n const contents = new Map<string, string>();\n for (const file of input.files) {\n if (contents.has(file.path)) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(file.path)} was supplied twice.`,\n );\n }\n contents.set(file.path, file.content);\n }\n\n for (const declared of manifest.files) {\n const content = contents.get(declared.path);\n if (content === undefined) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(declared.path)} is declared but was not supplied.`,\n );\n }\n const bytes = new TextEncoder().encode(content).length;\n if (bytes !== declared.byteSize) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${JSON.stringify(declared.path)} declares ${declared.byteSize} bytes and supplies ${bytes}.`,\n );\n }\n }\n if (contents.size !== manifest.files.length) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${contents.size} files were supplied for ${manifest.files.length} declared rows.`,\n );\n }\n\n const entry = checkSkillPackEntry(manifest, contents.get(SKILL_PACK_ENTRY_PATH)!);\n if (!entry.ok) {\n throw new ByokCoreError(\n 'skill_pack_manifest_invalid',\n `Refusing to publish ${JSON.stringify(manifest.name)}: ${entry.reason} — ${entry.detail}`,\n );\n }\n\n this.#packs.set(tenantKey(tenant, manifest.name), { manifest, contents });\n return manifest;\n }\n\n async get(tenant: TenantId, name: string): Promise<SkillPackManifest | undefined> {\n return this.#packs.get(tenantKey(tenant, name))?.manifest;\n }\n\n async list(tenant: TenantId, query: SkillPackListQuery): Promise<readonly SkillPackManifest[]> {\n const prefix = tenantKey(tenant, '');\n const manifests: SkillPackManifest[] = [];\n for (const [key, pack] of this.#packs.entries()) {\n if (!key.startsWith(prefix)) continue;\n manifests.push(pack.manifest);\n }\n manifests.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n return manifests.slice(0, query.limit ?? DEFAULT_LIST_LIMIT);\n }\n\n async readFile(\n tenant: TenantId,\n name: string,\n path: string,\n ): Promise<SkillPackFileContent | undefined> {\n const pack = this.#packs.get(tenantKey(tenant, name));\n if (pack === undefined) return undefined;\n const declared = pack.manifest.files.find((file) => file.path === path);\n const content = pack.contents.get(path);\n if (declared === undefined || content === undefined) return undefined;\n return {\n path: declared.path,\n contentHash: declared.contentHash,\n byteSize: declared.byteSize,\n content,\n };\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 { InMemorySkillPackStore } from './skill-pack';\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';\nexport { InMemorySkillPackStore } from './skill-pack';\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 skillPacks: new InMemorySkillPackStore(),\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"]}