@systemfsoftware/agent-storage-postgres 0.0.0-stage → 0.1.0-beta.192
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/PostgresStorage-D9IqvmQ2.mjs +1860 -0
- package/dist/PostgresStorage-D9IqvmQ2.mjs.map +1 -0
- package/dist/PostgresStorage-zKTn_ufd.d.mts +63 -0
- package/dist/PostgresStorage.d.mts +2 -0
- package/dist/PostgresStorage.mjs +2 -0
- package/dist/PostgresStorageError-DCuaf7EF.mjs +50 -0
- package/dist/PostgresStorageError-DCuaf7EF.mjs.map +1 -0
- package/dist/PostgresStorageError-mnbXuBHP.d.mts +48 -0
- package/dist/PostgresStorageError.d.mts +2 -0
- package/dist/PostgresStorageError.mjs +1 -0
- package/dist/index.d.mts +3 -0
- package/dist/index.mjs +3 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/package.json +57 -3
- package/src/PostgresStorage.ts +339 -0
- package/src/PostgresStorageError.ts +69 -0
- package/src/index.ts +2 -0
- package/src/internal/layout-expression.ts +209 -0
- package/src/internal/postgres-storage.ts +144 -0
- package/src/internal/storage-layout.ts +1591 -0
- package/README.md +0 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PostgresStorage-D9IqvmQ2.mjs","names":[],"sources":["../src/internal/layout-expression.ts","../src/internal/storage-layout.ts","../src/internal/postgres-storage.ts","../src/PostgresStorage.ts"],"sourcesContent":["/** Closed expression vocabulary for the frozen Postgres layout. */\nexport type LayoutExpression =\n | readonly ['column' | 'text' | 'json' | 'length', string]\n | readonly ['integer', number]\n | readonly ['notNull' | 'null', LayoutExpression]\n | readonly [\n 'eq' | 'ne' | 'gt' | 'ge' | 'lt' | 'le' | 'subtract' | 'shift',\n LayoutExpression,\n LayoutExpression,\n ]\n | readonly ['in' | 'notIn', LayoutExpression, ReadonlyArray<string | number>]\n | readonly ['and', ReadonlyArray<LayoutExpression>]\n\n/** Decode deparser syntax into meaning; unknown tokens/forms fail closed. Never execute it. */\nconst readExpressions = (input: string): ReadonlyArray<LayoutExpression> | undefined => {\n if (input.length > 16_384) return undefined\n const tokens: Array<{ kind: string; value: string }> = []\n\n const token =\n /\\s+|\"(?:[^\"]|\"\")*\"|'(?:[^']|'')*'|->>|>>|::|<>|[a-z_][a-z_0-9]*|(?:256|[0-9]|[1-4][0-9]|5[0-2])(?![0-9])|>=|<=|[=(),[\\]>.<-]/giy\n\n while (token.lastIndex < input.length) {\n const match = token.exec(input)?.[0]\n\n if (match === undefined || tokens.length >= 512) return undefined\n if (/^\\s/.test(match)) continue\n const quote = match[0]\n\n tokens.push(\n quote === '\"' || quote === \"'\"\n ? { kind: quote, value: match.slice(1, -1).replaceAll(quote + quote, quote) }\n : { kind: 'bare', value: match.toLowerCase() },\n )\n }\n let position = 0\n\n const take = (value: string) => {\n if (tokens[position]?.kind !== 'bare' || tokens[position]?.value !== value) return false\n position++\n\n return true\n }\n\n const identifier = (): string | undefined => {\n const next = tokens[position]\n\n if (next === undefined || next.kind === \"'\" || !/^[a-z_][a-z_0-9]*$/i.test(next.value)) {\n return undefined\n }\n position++\n if (!take('.')) return next.value\n const member = identifier()\n\n return next.value === 'pg_catalog' && member !== undefined ? `pg_catalog.${member}` : undefined\n }\n\n const operand = (): LayoutExpression | undefined => {\n let value: LayoutExpression | undefined\n const next = tokens[position]\n\n if (take('(')) {\n value = expression()\n if (!take(')')) return undefined\n } else if (next?.kind === \"'\") {\n position++\n value = ['text', next.value]\n if (take('::')) {\n const type = identifier()\n\n if (type !== 'text' && type !== 'pg_catalog.text') return undefined\n }\n } else if (next?.kind === 'bare' && /^(?:256|[0-9]|[1-4][0-9]|5[0-2])$/.test(next.value)) {\n position++\n value = ['integer', Number(next.value)]\n } else {\n const name = identifier()\n\n if (name === undefined) return undefined\n if ((name === 'length' || name === 'pg_catalog.length') && take('(')) {\n const column = identifier()\n\n if (column === undefined || !take(')')) return undefined\n value = ['length', column]\n } else value = ['column', name]\n }\n if (take('::')) {\n const type = identifier()\n\n if (value?.[0] !== 'integer' || (type !== 'bigint' && type !== 'pg_catalog.int8')) {\n return undefined\n }\n }\n if (take('->>')) {\n const key = operand()\n\n if (value?.[0] !== 'column' || value[1] !== 'read_metadata' || key?.[0] !== 'text') {\n return undefined\n }\n\n return ['json', key[1]]\n }\n\n if (take('-')) {\n const right = operand()\n\n return right === undefined || value === undefined ? undefined : ['subtract', value, right]\n }\n if (take('>>')) {\n const right = operand()\n\n return value === undefined || right?.[0] !== 'integer' || right[1] > 52\n ? undefined\n : ['shift', value, right]\n }\n\n return value\n }\n\n const textList = (array: boolean): ReadonlyArray<string | number> | undefined => {\n if (!take('(')) return undefined\n if (array && (!take('array') || !take('['))) return undefined\n const values: Array<string | number> = []\n\n do {\n const item = operand()\n\n if (item?.[0] !== 'text' && item?.[0] !== 'integer') return undefined\n values.push(item[1])\n } while (take(','))\n if (array && !take(']')) return undefined\n\n return take(')') ? values : undefined\n }\n\n const comparison = (): LayoutExpression | undefined => {\n const left = operand()\n\n if (left === undefined) return undefined\n if (take('is')) {\n const tag = take('not') ? 'notNull' : 'null'\n\n return take('null') ? [tag, left] : undefined\n }\n const negated = take('not')\n\n if (negated || take('in')) {\n if (negated && !take('in')) return undefined\n const values = textList(false)\n\n return values === undefined ? undefined : [negated ? 'notIn' : 'in', left, values]\n }\n\n const operator = take('=')\n ? 'eq'\n : take('<>')\n ? 'ne'\n : take('>=')\n ? 'ge'\n : take('<=')\n ? 'le'\n : take('>')\n ? 'gt'\n : take('<')\n ? 'lt'\n : undefined\n\n if (operator === undefined) return left\n if ((operator === 'eq' && take('any')) || (operator === 'ne' && take('all'))) {\n const values = textList(true)\n\n return values === undefined ? undefined : [operator === 'eq' ? 'in' : 'notIn', left, values]\n }\n const right = operand()\n\n return right === undefined ? undefined : [operator, left, right]\n }\n\n const expression = (): LayoutExpression | undefined => {\n const parts: Array<LayoutExpression> = []\n\n do {\n const part = comparison()\n\n if (part === undefined) return undefined\n parts.push(...(part[0] === 'and' ? part[1] : [part]))\n } while (take('and'))\n\n return parts.length === 1 ? parts[0] : ['and', parts]\n }\n\n const expressions: Array<LayoutExpression> = []\n\n do {\n const value = expression()\n\n if (value === undefined) return undefined\n expressions.push(value)\n } while (take(','))\n\n return position === tokens.length ? expressions : undefined\n}\n\nexport const matchesLayoutExpressions = (\n actual: string | null,\n expected: ReadonlyArray<LayoutExpression>,\n): boolean =>\n actual === null\n ? expected.length === 0\n : JSON.stringify(readExpressions(actual)) === JSON.stringify(expected)\n","import { RECORD_TAGS } from '@systemfsoftware/agent-storage-sql/sql-canonical-storage'\nimport {\n assertLegacyMessagePublicationDrained,\n backfillPeerMessageRetention,\n} from '@systemfsoftware/agent-storage-sql/sql-message-delivery-store'\nimport { makeSqlQuery, SqlInteger } from '@systemfsoftware/agent-storage-sql/sql-storage'\nimport {\n SQL_PROMPT_PREDICATE,\n upgradeExecutionCheckpoints,\n} from '@systemfsoftware/agent-storage-sql/sql-thread-native-reads'\nimport {\n createSqlThreadWorkTables,\n upgradeSqlThreadWorkIndex,\n} from '@systemfsoftware/agent-storage-sql/sql-thread-work'\nimport { CURRENT_RECORD_FORMAT, PROMPT_EVIDENCE_TAGS } from '@systemfsoftware/agent/records'\nimport * as Effect from 'effect/Effect'\nimport * as Schema from 'effect/Schema'\nimport * as SqlClient from 'effect/sql/SqlClient'\n\nimport {\n PostgresStorageCompatibilityError,\n PostgresStorageCorruptionError,\n PostgresStorageError,\n} from '../PostgresStorageError'\nimport { type LayoutExpression, matchesLayoutExpressions } from './layout-expression'\n\nexport const CurrentPostgresStorageVersion = 31\n\n/** The released layout 25 already has observe_settlement; only these indexes are new. */\nconst layout26IndexStatements = {\n effect_agent_subscriptions_capacity:\n \"CREATE INDEX effect_agent_subscriptions_capacity ON __NAMESPACE__.effect_agent_subscriptions (tenant_id, source_address, expires_at_millis) WHERE state IN ('active', 'paused')\",\n effect_agent_subscriptions_owner_capacity:\n \"CREATE INDEX effect_agent_subscriptions_owner_capacity ON __NAMESPACE__.effect_agent_subscriptions (tenant_id, source_address, owner_id, expires_at_millis) WHERE state IN ('active', 'paused')\",\n effect_agent_subscription_deliveries_capacity:\n \"CREATE INDEX effect_agent_subscription_deliveries_capacity ON __NAMESPACE__.effect_agent_subscription_deliveries (tenant_id, source_address, owner_id) WHERE state IN ('selected', 'prepared')\",\n effect_agent_subscription_deliveries_observing:\n \"CREATE INDEX effect_agent_subscription_deliveries_observing ON __NAMESPACE__.effect_agent_subscription_deliveries (tenant_id, source_address, owner_id) WHERE state='delivered' AND observe_settlement\",\n effect_agent_message_deliveries_peer_retained:\n 'CREATE INDEX effect_agent_message_deliveries_peer_retained ON __NAMESPACE__.effect_agent_message_deliveries(owner_thread_id, peer_retained_until_millis, message_id) WHERE peer_retained_until_millis IS NOT NULL',\n}\n\n/** Only live child membership changes on reservation mutations. */\nconst liveChildFunctionBody = `\nDECLARE owner_id TEXT;\nBEGIN\n IF TG_OP <> 'INSERT' THEN\n DELETE FROM __NAMESPACE__.effect_agent_live_child_reservations WHERE reservation_id=OLD.reservation_id;\n END IF;\n IF TG_OP <> 'DELETE' AND NEW.status <> 'released' THEN\n SELECT thread_id INTO STRICT owner_id FROM __NAMESPACE__.effect_agent_submissions WHERE submission_id=NEW.parent_submission_id;\n INSERT INTO __NAMESPACE__.effect_agent_live_child_reservations (reservation_id, thread_id) VALUES (NEW.reservation_id, owner_id);\n END IF;\n IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;\n RETURN NEW;\nEND;\n`\n\nconst liveChildTriggers = [\n {\n name: 'effect_agent_live_child_insert',\n table: 'effect_agent_child_reservations',\n event: 'INSERT',\n },\n {\n name: 'effect_agent_live_child_update',\n table: 'effect_agent_child_reservations',\n event: 'UPDATE',\n },\n {\n name: 'effect_agent_live_child_delete',\n table: 'effect_agent_child_reservations',\n event: 'DELETE',\n },\n] as const\n\n/** Fresh layout. Released predecessors take the ordered steps below. */\nconst layoutStatements = [\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_storage_version\" ( id BOOLEAN PRIMARY KEY NOT NULL, version BIGINT NOT NULL, CONSTRAINT effect_agent_storage_version_single_row CHECK (id) )',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_threads\" ( thread_id TEXT COLLATE \"C\" PRIMARY KEY NOT NULL, created_at TEXT COLLATE \"C\", tail_sequence BIGINT NOT NULL, work_version BIGINT NOT NULL DEFAULT 3, work_state TEXT COLLATE \"C\" NOT NULL DEFAULT \\'ready\\', work_through_sequence BIGINT NOT NULL DEFAULT 0, work_reporting BIGINT NOT NULL DEFAULT 0, work_entry_count BIGINT NOT NULL DEFAULT 0, worker_input_sequence BIGINT, worker_settlement_sequence BIGINT )',\n 'CREATE TABLE __NAMESPACE__.effect_agent_envelopes (envelope_key BIGSERIAL PRIMARY KEY NOT NULL, content_digest TEXT COLLATE \"C\" UNIQUE NOT NULL, prefix TEXT COLLATE \"C\" NOT NULL, before_payload TEXT COLLATE \"C\" NOT NULL, before_record_id TEXT COLLATE \"C\" NOT NULL, suffix TEXT COLLATE \"C\" NOT NULL)',\n 'CREATE TABLE __NAMESPACE__.effect_agent_run_keys (run_key BIGSERIAL PRIMARY KEY NOT NULL, thread_id TEXT COLLATE \"C\" NOT NULL, run_id TEXT COLLATE \"C\" NOT NULL, UNIQUE (thread_id, run_id), FOREIGN KEY (thread_id) REFERENCES __NAMESPACE__.effect_agent_threads(thread_id) ON DELETE RESTRICT)',\n 'CREATE TABLE __NAMESPACE__.effect_agent_definitions (definition_key BIGSERIAL PRIMARY KEY NOT NULL, content_digest TEXT COLLATE \"C\" UNIQUE NOT NULL, value_json TEXT COLLATE \"C\" NOT NULL)',\n 'CREATE TABLE __NAMESPACE__.effect_agent_executions (thread_id TEXT COLLATE \"C\" NOT NULL, run_id TEXT COLLATE \"C\" NOT NULL, input_sequence BIGINT NOT NULL, revision BIGINT NOT NULL, checkpoint_json TEXT COLLATE \"C\" NOT NULL, last_commit_id TEXT COLLATE \"C\", last_commit_digest TEXT COLLATE \"C\", PRIMARY KEY (thread_id, run_id), FOREIGN KEY (thread_id) REFERENCES __NAMESPACE__.effect_agent_threads(thread_id) ON DELETE RESTRICT)',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_canonical_batches\" ( thread_id TEXT COLLATE \"C\" NOT NULL, batch_id TEXT COLLATE \"C\" NOT NULL, first_sequence BIGINT NOT NULL, last_sequence BIGINT NOT NULL, producer_id_json TEXT COLLATE \"C\" NOT NULL, CONSTRAINT effect_agent_canonical_batches_span CHECK (first_sequence >= 1 AND last_sequence >= first_sequence AND last_sequence - first_sequence < 256), PRIMARY KEY (thread_id, batch_id), FOREIGN KEY (thread_id) REFERENCES __NAMESPACE__.\"effect_agent_threads\"(thread_id) ON DELETE RESTRICT )',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_canonical_records\" ( thread_id TEXT COLLATE \"C\" NOT NULL, sequence BIGINT NOT NULL, record_id TEXT COLLATE \"C\" NOT NULL, created_at_json TEXT COLLATE \"C\" NOT NULL, envelope_key BIGINT NOT NULL, payload_json TEXT COLLATE \"C\", record_tag BIGINT NOT NULL, run_id BIGINT, tool_call_id TEXT COLLATE \"C\", input_kind TEXT COLLATE \"C\", source_submission_id TEXT COLLATE \"C\", message_id TEXT COLLATE \"C\", submission_id TEXT COLLATE \"C\", application_input BIGINT NOT NULL, context_through BIGINT, context_kind TEXT COLLATE \"C\", worker_thread_id TEXT COLLATE \"C\", handoff BIGINT NOT NULL, PRIMARY KEY (thread_id, sequence), UNIQUE (thread_id, record_id), FOREIGN KEY (thread_id) REFERENCES __NAMESPACE__.\"effect_agent_threads\"(thread_id) ON DELETE RESTRICT )',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_record_runs\" ( thread_id TEXT COLLATE \"C\" NOT NULL, run_id BIGINT NOT NULL, sequence BIGINT NOT NULL, PRIMARY KEY (thread_id, run_id, sequence), FOREIGN KEY (thread_id, sequence) REFERENCES __NAMESPACE__.\"effect_agent_canonical_records\"(thread_id, sequence) ON DELETE RESTRICT )',\n 'CREATE TABLE __NAMESPACE__.effect_agent_rollover_buckets (thread_id TEXT COLLATE \"C\" NOT NULL, height BIGINT NOT NULL, bucket BIGINT NOT NULL, sequence BIGINT NOT NULL, PRIMARY KEY (thread_id, height, bucket, sequence), FOREIGN KEY (thread_id, sequence) REFERENCES __NAMESPACE__.effect_agent_canonical_records(thread_id, sequence) ON DELETE RESTRICT)',\n 'CREATE TABLE __NAMESPACE__.effect_agent_tool_declarations (thread_id TEXT COLLATE \"C\" NOT NULL, settlement_record_id TEXT COLLATE \"C\" NOT NULL, sequence BIGINT NOT NULL, PRIMARY KEY (thread_id, settlement_record_id, sequence), FOREIGN KEY (thread_id, sequence) REFERENCES __NAMESPACE__.effect_agent_canonical_records(thread_id, sequence) ON DELETE RESTRICT)',\n 'CREATE INDEX effect_agent_tool_declarations_sequence ON __NAMESPACE__.effect_agent_tool_declarations(thread_id, sequence)',\n 'CREATE TABLE __NAMESPACE__.effect_agent_record_refusals (thread_id TEXT COLLATE \"C\" NOT NULL, reservation_record_id TEXT COLLATE \"C\" NOT NULL, sequence BIGINT NOT NULL, PRIMARY KEY (thread_id, reservation_record_id, sequence), FOREIGN KEY (thread_id, sequence) REFERENCES __NAMESPACE__.effect_agent_canonical_records(thread_id, sequence) ON DELETE RESTRICT)',\n 'CREATE INDEX effect_agent_record_refusals_sequence ON __NAMESPACE__.effect_agent_record_refusals(thread_id, sequence)',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_submissions\" ( submission_id TEXT COLLATE \"C\" PRIMARY KEY NOT NULL, thread_id TEXT COLLATE \"C\" NOT NULL, queue_sequence BIGINT NOT NULL, principal TEXT COLLATE \"C\" NOT NULL, idempotency_key TEXT COLLATE \"C\" NOT NULL, agent_id TEXT COLLATE \"C\" NOT NULL, definition_key BIGINT NOT NULL, deployment_id TEXT COLLATE \"C\" NOT NULL, input_json TEXT COLLATE \"C\" NOT NULL, input_digest TEXT COLLATE \"C\" NOT NULL, receipt_id TEXT COLLATE \"C\" NOT NULL, state TEXT COLLATE \"C\" NOT NULL, settled_outcome TEXT COLLATE \"C\", settled_record_id TEXT COLLATE \"C\", finalized_at TEXT COLLATE \"C\", created_at TEXT COLLATE \"C\" NOT NULL, ready_at TEXT COLLATE \"C\", input_applied_record_id TEXT COLLATE \"C\", input_applied_sequence BIGINT, joined_host_submission_id TEXT COLLATE \"C\", suspended_reason_json TEXT COLLATE \"C\", suspended_at TEXT COLLATE \"C\", unknown_reason TEXT COLLATE \"C\", unknown_tool_call_ids_json TEXT COLLATE \"C\", parent_submission_id TEXT COLLATE \"C\", parent_tool_call_id TEXT COLLATE \"C\", admission_group TEXT COLLATE \"C\", admission_fence_json TEXT COLLATE \"C\", worker_admission_json TEXT COLLATE \"C\", message_admission_json TEXT COLLATE \"C\", UNIQUE (thread_id, principal, idempotency_key), UNIQUE (thread_id, queue_sequence) )',\n 'CREATE INDEX effect_agent_submissions_group ON __NAMESPACE__.\"effect_agent_submissions\" (thread_id, admission_group) WHERE admission_group IS NOT NULL AND state <> \\'settled\\'',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_abort_intents\" ( submission_id TEXT COLLATE \"C\" PRIMARY KEY NOT NULL, author TEXT COLLATE \"C\" NOT NULL, reason TEXT COLLATE \"C\" NOT NULL, requested_at TEXT COLLATE \"C\" NOT NULL, canonical_record_id TEXT COLLATE \"C\", FOREIGN KEY (submission_id) REFERENCES __NAMESPACE__.\"effect_agent_submissions\"(submission_id) ON DELETE RESTRICT )',\n 'CREATE INDEX effect_agent_submissions_joined_host ON __NAMESPACE__.\"effect_agent_submissions\" (joined_host_submission_id) WHERE joined_host_submission_id IS NOT NULL',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_approval_decisions\" ( submission_id TEXT COLLATE \"C\" NOT NULL, tool_call_id TEXT COLLATE \"C\" NOT NULL, decision TEXT COLLATE \"C\" NOT NULL, resolver TEXT COLLATE \"C\" NOT NULL, reason TEXT COLLATE \"C\" NOT NULL, decided_at TEXT COLLATE \"C\" NOT NULL, PRIMARY KEY (submission_id, tool_call_id), FOREIGN KEY (submission_id) REFERENCES __NAMESPACE__.\"effect_agent_submissions\"(submission_id) ON DELETE RESTRICT )',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_unknown_resolutions\" ( submission_id TEXT COLLATE \"C\" NOT NULL, tool_call_id TEXT COLLATE \"C\" NOT NULL, resolution_kind TEXT COLLATE \"C\" NOT NULL, author TEXT COLLATE \"C\" NOT NULL, reason TEXT COLLATE \"C\" NOT NULL, resolution_json TEXT COLLATE \"C\" NOT NULL, resolved_at TEXT COLLATE \"C\" NOT NULL, PRIMARY KEY (submission_id, tool_call_id, resolution_kind), FOREIGN KEY (submission_id) REFERENCES __NAMESPACE__.\"effect_agent_submissions\"(submission_id) ON DELETE RESTRICT )',\n 'CREATE INDEX effect_agent_submissions_parent ON __NAMESPACE__.\"effect_agent_submissions\" (parent_submission_id) WHERE parent_submission_id IS NOT NULL',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_child_reservations\" ( reservation_id TEXT COLLATE \"C\" PRIMARY KEY NOT NULL, parent_submission_id TEXT COLLATE \"C\" NOT NULL, parent_tool_call_id TEXT COLLATE \"C\" NOT NULL, child_submission_id TEXT COLLATE \"C\", status TEXT COLLATE \"C\" NOT NULL, allocation_json TEXT COLLATE \"C\" NOT NULL, allocation_digest TEXT COLLATE \"C\" NOT NULL, accounting_json TEXT COLLATE \"C\", reserved_at TEXT COLLATE \"C\" NOT NULL, release_began_at TEXT COLLATE \"C\", released_at TEXT COLLATE \"C\", UNIQUE (parent_submission_id, parent_tool_call_id), FOREIGN KEY (parent_submission_id) REFERENCES __NAMESPACE__.\"effect_agent_submissions\"(submission_id) ON DELETE RESTRICT )',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_schedules\" ( tenant_id TEXT COLLATE \"C\" NOT NULL, owner_id TEXT COLLATE \"C\" NOT NULL, schedule_id TEXT COLLATE \"C\" NOT NULL, deadline_at_millis BIGINT, record_json TEXT COLLATE \"C\" NOT NULL, uses_capacity BOOLEAN NOT NULL, PRIMARY KEY (tenant_id, owner_id, schedule_id) )',\n 'CREATE INDEX effect_agent_schedules_deadline ON __NAMESPACE__.\"effect_agent_schedules\" (deadline_at_millis, tenant_id, owner_id, schedule_id) WHERE deadline_at_millis IS NOT NULL',\n 'CREATE INDEX effect_agent_schedules_owner_deadline ON __NAMESPACE__.\"effect_agent_schedules\" (tenant_id, owner_id, deadline_at_millis, schedule_id) WHERE deadline_at_millis IS NOT NULL',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_subscription_sequences\" ( tenant_id TEXT COLLATE \"C\" NOT NULL, source_address TEXT COLLATE \"C\" NOT NULL, sequence BIGINT NOT NULL, event_scan_cursor TEXT COLLATE \"C\" NOT NULL, delivery_scan_cursor TEXT COLLATE \"C\" NOT NULL, recovery_scan_cursor BIGINT NOT NULL, PRIMARY KEY (tenant_id, source_address) )',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_subscriptions\" ( tenant_id TEXT COLLATE \"C\" NOT NULL, source_address TEXT COLLATE \"C\" NOT NULL, owner_id TEXT COLLATE \"C\" NOT NULL, subscription_id TEXT COLLATE \"C\" NOT NULL, ordinal BIGINT NOT NULL, source_name TEXT COLLATE \"C\" NOT NULL, source_version TEXT COLLATE \"C\" NOT NULL, matching_key TEXT COLLATE \"C\" NOT NULL, state TEXT COLLATE \"C\" NOT NULL, expires_at_millis BIGINT, recovery_at_millis BIGINT, recovery_present BIGINT NOT NULL DEFAULT 0, record_json TEXT COLLATE \"C\" NOT NULL, PRIMARY KEY (tenant_id, source_address, owner_id, subscription_id), UNIQUE (tenant_id, source_address, ordinal) )',\n 'CREATE INDEX effect_agent_subscriptions_owner ON __NAMESPACE__.\"effect_agent_subscriptions\" (tenant_id, source_address, owner_id, ordinal)',\n 'CREATE INDEX effect_agent_subscriptions_candidates ON __NAMESPACE__.\"effect_agent_subscriptions\" (tenant_id, source_address, source_name, source_version, matching_key, ordinal)',\n 'CREATE INDEX effect_agent_subscriptions_recovery ON __NAMESPACE__.\"effect_agent_subscriptions\" (tenant_id, source_address, recovery_at_millis, ordinal) WHERE recovery_at_millis IS NOT NULL',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_subscription_events\" ( tenant_id TEXT COLLATE \"C\" NOT NULL, source_address TEXT COLLATE \"C\" NOT NULL, event_id TEXT COLLATE \"C\" NOT NULL, source_name TEXT COLLATE \"C\" NOT NULL, source_version TEXT COLLATE \"C\" NOT NULL, matching_key TEXT COLLATE \"C\" NOT NULL, payload_digest TEXT COLLATE \"C\" NOT NULL, cutoff BIGINT NOT NULL, cursor BIGINT NOT NULL, routing_complete BIGINT NOT NULL, tombstone BIGINT NOT NULL DEFAULT 0, next_attempt_at_millis BIGINT NOT NULL, record_json TEXT COLLATE \"C\" NOT NULL, PRIMARY KEY (tenant_id, source_address, event_id) )',\n 'CREATE INDEX effect_agent_subscription_events_pending ON __NAMESPACE__.\"effect_agent_subscription_events\" (tenant_id, source_address, routing_complete, next_attempt_at_millis, event_id)',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_subscription_deliveries\" ( tenant_id TEXT COLLATE \"C\" NOT NULL, source_address TEXT COLLATE \"C\" NOT NULL, owner_id TEXT COLLATE \"C\" NOT NULL, subscription_id TEXT COLLATE \"C\" NOT NULL, event_id TEXT COLLATE \"C\" NOT NULL, delivery_key TEXT COLLATE \"C\" NOT NULL, state TEXT COLLATE \"C\" NOT NULL, next_attempt_at_millis BIGINT NOT NULL, record_json TEXT COLLATE \"C\" NOT NULL, retry_parked BOOLEAN NOT NULL, observe_settlement BOOLEAN NOT NULL, PRIMARY KEY (tenant_id, source_address, owner_id, subscription_id, event_id), UNIQUE (tenant_id, source_address, delivery_key) )',\n 'CREATE INDEX effect_agent_subscription_deliveries_pending ON __NAMESPACE__.\"effect_agent_subscription_deliveries\" (tenant_id, source_address, state, next_attempt_at_millis, delivery_key)',\n 'CREATE INDEX effect_agent_subscription_deliveries_registration ON __NAMESPACE__.\"effect_agent_subscription_deliveries\" (tenant_id, source_address, owner_id, subscription_id, delivery_key)',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_message_deliveries\" ( owner_thread_id TEXT COLLATE \"C\" NOT NULL, message_id TEXT COLLATE \"C\" NOT NULL, version BIGINT NOT NULL, state TEXT COLLATE \"C\" NOT NULL, deadline_at_millis BIGINT, peer_retained_until_millis BIGINT, record_json TEXT COLLATE \"C\" NOT NULL, read_metadata JSONB NOT NULL, PRIMARY KEY (owner_thread_id, message_id) )',\n 'CREATE INDEX effect_agent_message_deliveries_due ON __NAMESPACE__.\"effect_agent_message_deliveries\" (deadline_at_millis, owner_thread_id, message_id) WHERE deadline_at_millis IS NOT NULL',\n 'CREATE INDEX effect_agent_submissions_nonterminal ON __NAMESPACE__.\"effect_agent_submissions\" (thread_id, queue_sequence) WHERE state <> \\'settled\\'',\n 'CREATE TABLE __NAMESPACE__.\"effect_agent_worker_stops\" (thread_id TEXT COLLATE \"C\" PRIMARY KEY NOT NULL, terminal TEXT COLLATE \"C\")',\n \"CREATE INDEX effect_agent_worker_starts ON __NAMESPACE__.\\\"effect_agent_message_deliveries\\\"(owner_thread_id, (read_metadata ->> 'delegationId'), (read_metadata ->> 'targetAgentId'), message_id) WHERE (read_metadata ->> 'workerStart') = 'true'\",\n \"CREATE INDEX effect_agent_worker_pending ON __NAMESPACE__.\\\"effect_agent_message_deliveries\\\"(owner_thread_id, (read_metadata ->> 'threadId'), message_id) WHERE state IN ('pending', 'parked') AND (read_metadata ->> 'hasReceipt') = 'false'\",\n 'CREATE INDEX effect_agent_records_call ON __NAMESPACE__.\"effect_agent_canonical_records\"(thread_id, record_tag, run_id, tool_call_id) WHERE tool_call_id IS NOT NULL',\n 'CREATE INDEX effect_agent_records_run_input ON __NAMESPACE__.\"effect_agent_canonical_records\"(thread_id, run_id) WHERE record_tag = 30 AND input_kind = \\'user\\'',\n 'CREATE INDEX effect_agent_records_subtree ON __NAMESPACE__.\"effect_agent_canonical_records\"(thread_id, source_submission_id, sequence) WHERE record_tag = 22',\n 'CREATE INDEX effect_agent_records_worker_input ON __NAMESPACE__.\"effect_agent_canonical_records\"(thread_id, message_id) WHERE record_tag = 34',\n \"CREATE INDEX effect_agent_message_deliveries_pending ON __NAMESPACE__.\\\"effect_agent_message_deliveries\\\"(owner_thread_id, message_id) WHERE state NOT IN ('processed', 'refused')\",\n 'CREATE INDEX effect_agent_records_tag ON __NAMESPACE__.\"effect_agent_canonical_records\"(thread_id, record_tag, sequence)',\n 'CREATE INDEX effect_agent_records_handoff ON __NAMESPACE__.\"effect_agent_canonical_records\"(thread_id, sequence) WHERE handoff = 1',\n 'CREATE INDEX effect_agent_records_application_input ON __NAMESPACE__.effect_agent_canonical_records(thread_id, sequence) WHERE application_input = 1',\n `CREATE INDEX effect_agent_records_prompt ON __NAMESPACE__.effect_agent_canonical_records(thread_id, sequence) WHERE ${SQL_PROMPT_PREDICATE}`,\n 'CREATE INDEX effect_agent_records_admitted_input ON __NAMESPACE__.effect_agent_canonical_records(thread_id, sequence) WHERE record_tag = 30 AND submission_id IS NOT NULL',\n 'CREATE INDEX effect_agent_records_worker_funding ON __NAMESPACE__.effect_agent_canonical_records(thread_id, source_submission_id, sequence, message_id) WHERE record_tag = 34',\n 'CREATE INDEX effect_agent_records_worker_completed ON __NAMESPACE__.effect_agent_canonical_records(thread_id, message_id, sequence) WHERE record_tag = 32',\n 'CREATE INDEX effect_agent_records_worker_stop ON __NAMESPACE__.effect_agent_canonical_records(thread_id, worker_thread_id, sequence) WHERE record_tag = 38',\n \"CREATE INDEX effect_agent_message_deliveries_identity ON __NAMESPACE__.effect_agent_message_deliveries(owner_thread_id, (read_metadata ->> 'messageId'))\",\n \"CREATE INDEX effect_agent_message_deliveries_peer ON __NAMESPACE__.effect_agent_message_deliveries(owner_thread_id, message_id) WHERE state NOT IN ('processed', 'refused') AND (read_metadata ->> 'peer') = 'true'\",\n 'CREATE TABLE __NAMESPACE__.effect_agent_journal_ranges (thread_id TEXT COLLATE \"C\" NOT NULL, first_sequence BIGINT NOT NULL, last_sequence BIGINT NOT NULL, record_count BIGINT NOT NULL, batch_count BIGINT NOT NULL, byte_count BIGINT NOT NULL, state TEXT COLLATE \"C\" NOT NULL, locator TEXT COLLATE \"C\", PRIMARY KEY (thread_id, first_sequence), FOREIGN KEY (thread_id) REFERENCES __NAMESPACE__.effect_agent_threads(thread_id) ON DELETE RESTRICT)',\n 'CREATE TABLE __NAMESPACE__.effect_agent_archive_batches (thread_id TEXT COLLATE \"C\" NOT NULL, batch_id TEXT COLLATE \"C\" NOT NULL, range_first_sequence BIGINT NOT NULL, batch_json TEXT COLLATE \"C\" NOT NULL, PRIMARY KEY (thread_id, batch_id), FOREIGN KEY (thread_id, batch_id) REFERENCES __NAMESPACE__.effect_agent_canonical_batches(thread_id, batch_id) ON DELETE RESTRICT, CONSTRAINT effect_agent_archive_batches_range_fkey FOREIGN KEY (thread_id, range_first_sequence) REFERENCES __NAMESPACE__.effect_agent_journal_ranges(thread_id, first_sequence) ON DELETE RESTRICT)',\n 'CREATE TABLE __NAMESPACE__.effect_agent_archive_records (thread_id TEXT COLLATE \"C\" NOT NULL, sequence BIGINT NOT NULL, range_first_sequence BIGINT NOT NULL, record_json TEXT COLLATE \"C\" NOT NULL, PRIMARY KEY (thread_id, sequence), FOREIGN KEY (thread_id, sequence) REFERENCES __NAMESPACE__.effect_agent_canonical_records(thread_id, sequence) ON DELETE RESTRICT, CONSTRAINT effect_agent_archive_records_range_fkey FOREIGN KEY (thread_id, range_first_sequence) REFERENCES __NAMESPACE__.effect_agent_journal_ranges(thread_id, first_sequence) ON DELETE RESTRICT)',\n 'CREATE UNIQUE INDEX effect_agent_canonical_batches_sequence ON __NAMESPACE__.effect_agent_canonical_batches(thread_id, first_sequence)',\n 'CREATE TABLE __NAMESPACE__.effect_agent_live_child_reservations (reservation_id TEXT COLLATE \"C\" PRIMARY KEY NOT NULL, thread_id TEXT COLLATE \"C\" NOT NULL)',\n 'CREATE INDEX effect_agent_live_child_reservations_thread ON __NAMESPACE__.effect_agent_live_child_reservations(thread_id, reservation_id)',\n // Compact native positions keep accepted identities out of bounded export cursors.\n // Persistent scalar FIFO derivatives; rebuild from canonical input/settlement boundaries.\n // Writer-local import indexes; rows are removed before publication.\n 'CREATE TABLE __NAMESPACE__.effect_agent_import_delivery_visits (thread_id TEXT COLLATE \"C\" NOT NULL, message_id TEXT COLLATE \"C\" NOT NULL, path_id TEXT COLLATE \"C\" NOT NULL, completed BIGINT NOT NULL, PRIMARY KEY (thread_id, message_id))',\n 'CREATE INDEX effect_agent_import_delivery_visits_path ON __NAMESPACE__.effect_agent_import_delivery_visits(thread_id, path_id)',\n `CREATE FUNCTION __NAMESPACE__.effect_agent_live_child_mutation() RETURNS trigger LANGUAGE plpgsql AS $transfer$${liveChildFunctionBody}$transfer$`,\n \"CREATE INDEX effect_agent_message_deliveries_capacity ON __NAMESPACE__.effect_agent_message_deliveries(owner_thread_id, (read_metadata ->> 'workerUpdate'), message_id) WHERE state IN ('pending', 'accepted', 'parked')\",\n ...liveChildTriggers.map(\n (trigger) =>\n `CREATE TRIGGER ${trigger.name} AFTER ${trigger.event} ON __NAMESPACE__.${trigger.table} FOR EACH ROW EXECUTE FUNCTION __NAMESPACE__.effect_agent_live_child_mutation()`,\n ),\n ...Object.values(layout26IndexStatements),\n] as const\n\ntype LayoutConstraint =\n | readonly [kind: 'p' | 'u', columns: ReadonlyArray<string>]\n | readonly [\n kind: 'f',\n columns: ReadonlyArray<string>,\n targetTable: string,\n targetColumns: ReadonlyArray<string>,\n ]\n | readonly [kind: 'c', columns: ReadonlyArray<string>, expression: LayoutExpression]\n\ninterface LayoutIndex {\n readonly table: string\n readonly columns: ReadonlyArray<string | null>\n readonly unique?: boolean\n readonly primary?: boolean\n readonly expressions?: ReadonlyArray<string | LayoutExpression>\n readonly predicate?: LayoutExpression\n}\n\n// Logical layout expectations. Physical index storage parameters and tablespaces are not\n// part of compatibility. Expression expectations are canonical data; a closed recognizer\n// accepts the deparser spellings of these forms and rejects every other form.\nconst layoutShape: Readonly<\n Record<\n string,\n {\n readonly columns: ReadonlyArray<string>\n readonly constraints: Readonly<Record<string, LayoutConstraint>>\n }\n >\n> = {\n effect_agent_executions: {\n columns: [\n 'thread_id:text:true',\n 'run_id:text:true',\n 'input_sequence:bigint:true',\n 'revision:bigint:true',\n 'checkpoint_json:text:true',\n 'last_commit_id:text:false',\n 'last_commit_digest:text:false',\n ],\n constraints: {\n effect_agent_executions_pkey: ['p', ['thread_id', 'run_id']],\n effect_agent_executions_thread_id_fkey: [\n 'f',\n ['thread_id'],\n 'effect_agent_threads',\n ['thread_id'],\n ],\n },\n },\n effect_agent_journal_ranges: {\n columns: [\n 'thread_id:text:true',\n 'first_sequence:bigint:true',\n 'last_sequence:bigint:true',\n 'record_count:bigint:true',\n 'batch_count:bigint:true',\n 'byte_count:bigint:true',\n 'state:text:true',\n 'locator:text:false',\n ],\n constraints: {\n effect_agent_journal_ranges_pkey: ['p', ['thread_id', 'first_sequence']],\n effect_agent_journal_ranges_thread_id_fkey: [\n 'f',\n ['thread_id'],\n 'effect_agent_threads',\n ['thread_id'],\n ],\n },\n },\n effect_agent_archive_batches: {\n columns: [\n 'thread_id:text:true',\n 'batch_id:text:true',\n 'range_first_sequence:bigint:true',\n 'batch_json:text:true',\n ],\n constraints: {\n effect_agent_archive_batches_pkey: ['p', ['thread_id', 'batch_id']],\n effect_agent_archive_batches_thread_id_batch_id_fkey: [\n 'f',\n ['thread_id', 'batch_id'],\n 'effect_agent_canonical_batches',\n ['thread_id', 'batch_id'],\n ],\n effect_agent_archive_batches_range_fkey: [\n 'f',\n ['thread_id', 'range_first_sequence'],\n 'effect_agent_journal_ranges',\n ['thread_id', 'first_sequence'],\n ],\n },\n },\n effect_agent_archive_records: {\n columns: [\n 'thread_id:text:true',\n 'sequence:bigint:true',\n 'range_first_sequence:bigint:true',\n 'record_json:text:true',\n ],\n constraints: {\n effect_agent_archive_records_pkey: ['p', ['thread_id', 'sequence']],\n effect_agent_archive_records_thread_id_sequence_fkey: [\n 'f',\n ['thread_id', 'sequence'],\n 'effect_agent_canonical_records',\n ['thread_id', 'sequence'],\n ],\n effect_agent_archive_records_range_fkey: [\n 'f',\n ['thread_id', 'range_first_sequence'],\n 'effect_agent_journal_ranges',\n ['thread_id', 'first_sequence'],\n ],\n },\n },\n effect_agent_abort_intents: {\n columns: [\n 'submission_id:text:true',\n 'author:text:true',\n 'reason:text:true',\n 'requested_at:text:true',\n 'canonical_record_id:text:false',\n ],\n constraints: {\n effect_agent_abort_intents_pkey: ['p', ['submission_id']],\n effect_agent_abort_intents_submission_id_fkey: [\n 'f',\n ['submission_id'],\n 'effect_agent_submissions',\n ['submission_id'],\n ],\n },\n },\n effect_agent_approval_decisions: {\n columns: [\n 'submission_id:text:true',\n 'tool_call_id:text:true',\n 'decision:text:true',\n 'resolver:text:true',\n 'reason:text:true',\n 'decided_at:text:true',\n ],\n constraints: {\n effect_agent_approval_decisions_pkey: ['p', ['submission_id', 'tool_call_id']],\n effect_agent_approval_decisions_submission_id_fkey: [\n 'f',\n ['submission_id'],\n 'effect_agent_submissions',\n ['submission_id'],\n ],\n },\n },\n effect_agent_envelopes: {\n columns: [\n 'envelope_key:bigint:true',\n 'content_digest:text:true',\n 'prefix:text:true',\n 'before_payload:text:true',\n 'before_record_id:text:true',\n 'suffix:text:true',\n ],\n constraints: {\n effect_agent_envelopes_pkey: ['p', ['envelope_key']],\n effect_agent_envelopes_content_digest_key: ['u', ['content_digest']],\n },\n },\n effect_agent_run_keys: {\n columns: ['run_key:bigint:true', 'thread_id:text:true', 'run_id:text:true'],\n constraints: {\n effect_agent_run_keys_pkey: ['p', ['run_key']],\n effect_agent_run_keys_thread_id_run_id_key: ['u', ['thread_id', 'run_id']],\n effect_agent_run_keys_thread_id_fkey: [\n 'f',\n ['thread_id'],\n 'effect_agent_threads',\n ['thread_id'],\n ],\n },\n },\n effect_agent_definitions: {\n columns: ['definition_key:bigint:true', 'content_digest:text:true', 'value_json:text:true'],\n constraints: {\n effect_agent_definitions_pkey: ['p', ['definition_key']],\n effect_agent_definitions_content_digest_key: ['u', ['content_digest']],\n },\n },\n effect_agent_canonical_batches: {\n columns: [\n 'thread_id:text:true',\n 'batch_id:text:true',\n 'first_sequence:bigint:true',\n 'last_sequence:bigint:true',\n 'producer_id_json:text:true',\n ],\n constraints: {\n effect_agent_canonical_batches_pkey: ['p', ['thread_id', 'batch_id']],\n effect_agent_canonical_batches_span: [\n 'c',\n ['first_sequence', 'last_sequence'],\n [\n 'and',\n [\n ['ge', ['column', 'first_sequence'], ['integer', 1]],\n ['ge', ['column', 'last_sequence'], ['column', 'first_sequence']],\n [\n 'lt',\n ['subtract', ['column', 'last_sequence'], ['column', 'first_sequence']],\n ['integer', 256],\n ],\n ],\n ],\n ],\n effect_agent_canonical_batches_thread_id_fkey: [\n 'f',\n ['thread_id'],\n 'effect_agent_threads',\n ['thread_id'],\n ],\n },\n },\n effect_agent_tool_declarations: {\n columns: ['thread_id:text:true', 'settlement_record_id:text:true', 'sequence:bigint:true'],\n constraints: {\n effect_agent_tool_declarations_pkey: ['p', ['thread_id', 'settlement_record_id', 'sequence']],\n effect_agent_tool_declarations_thread_id_sequence_fkey: [\n 'f',\n ['thread_id', 'sequence'],\n 'effect_agent_canonical_records',\n ['thread_id', 'sequence'],\n ],\n },\n },\n effect_agent_record_refusals: {\n columns: ['thread_id:text:true', 'reservation_record_id:text:true', 'sequence:bigint:true'],\n constraints: {\n effect_agent_record_refusals_pkey: ['p', ['thread_id', 'reservation_record_id', 'sequence']],\n effect_agent_record_refusals_thread_id_sequence_fkey: [\n 'f',\n ['thread_id', 'sequence'],\n 'effect_agent_canonical_records',\n ['thread_id', 'sequence'],\n ],\n },\n },\n effect_agent_live_child_reservations: {\n columns: ['reservation_id:text:true', 'thread_id:text:true'],\n constraints: { effect_agent_live_child_reservations_pkey: ['p', ['reservation_id']] },\n },\n effect_agent_record_runs: {\n columns: ['thread_id:text:true', 'run_id:bigint:true', 'sequence:bigint:true'],\n constraints: {\n effect_agent_record_runs_pkey: ['p', ['thread_id', 'run_id', 'sequence']],\n effect_agent_record_runs_thread_id_sequence_fkey: [\n 'f',\n ['thread_id', 'sequence'],\n 'effect_agent_canonical_records',\n ['thread_id', 'sequence'],\n ],\n },\n },\n effect_agent_canonical_records: {\n columns: [\n 'thread_id:text:true',\n 'sequence:bigint:true',\n 'record_id:text:true',\n 'created_at_json:text:true',\n 'envelope_key:bigint:true',\n 'payload_json:text:false',\n 'record_tag:bigint:true',\n 'run_id:bigint:false',\n 'tool_call_id:text:false',\n 'input_kind:text:false',\n 'source_submission_id:text:false',\n 'message_id:text:false',\n 'submission_id:text:false',\n 'application_input:bigint:true',\n 'context_through:bigint:false',\n 'context_kind:text:false',\n 'worker_thread_id:text:false',\n 'handoff:bigint:true',\n ],\n constraints: {\n effect_agent_canonical_records_pkey: ['p', ['thread_id', 'sequence']],\n effect_agent_canonical_records_thread_id_fkey: [\n 'f',\n ['thread_id'],\n 'effect_agent_threads',\n ['thread_id'],\n ],\n effect_agent_canonical_records_thread_id_record_id_key: ['u', ['thread_id', 'record_id']],\n },\n },\n // Retained only for exact predecessor layout validation.\n effect_agent_checkpoints: {\n columns: ['thread_id:text:true', 'through_sequence:bigint:true', 'checkpoint_json:text:true'],\n constraints: {\n effect_agent_checkpoints_pkey: ['p', ['thread_id', 'through_sequence']],\n effect_agent_checkpoints_thread_id_fkey: [\n 'f',\n ['thread_id'],\n 'effect_agent_threads',\n ['thread_id'],\n ],\n },\n },\n effect_agent_child_reservations: {\n columns: [\n 'reservation_id:text:true',\n 'parent_submission_id:text:true',\n 'parent_tool_call_id:text:true',\n 'child_submission_id:text:false',\n 'status:text:true',\n 'allocation_json:text:true',\n 'allocation_digest:text:true',\n 'accounting_json:text:false',\n 'reserved_at:text:true',\n 'release_began_at:text:false',\n 'released_at:text:false',\n ],\n constraints: {\n effect_agent_child_reservatio_parent_submission_id_parent_t_key: [\n 'u',\n ['parent_submission_id', 'parent_tool_call_id'],\n ],\n effect_agent_child_reservations_parent_submission_id_fkey: [\n 'f',\n ['parent_submission_id'],\n 'effect_agent_submissions',\n ['submission_id'],\n ],\n effect_agent_child_reservations_pkey: ['p', ['reservation_id']],\n },\n },\n effect_agent_message_deliveries: {\n columns: [\n 'owner_thread_id:text:true',\n 'message_id:text:true',\n 'version:bigint:true',\n 'state:text:true',\n 'deadline_at_millis:bigint:false',\n 'peer_retained_until_millis:bigint:false',\n 'record_json:text:true',\n 'read_metadata:jsonb:true',\n ],\n constraints: { effect_agent_message_deliveries_pkey: ['p', ['owner_thread_id', 'message_id']] },\n },\n effect_agent_schedules: {\n columns: [\n 'tenant_id:text:true',\n 'owner_id:text:true',\n 'schedule_id:text:true',\n 'deadline_at_millis:bigint:false',\n 'record_json:text:true',\n 'uses_capacity:boolean:true',\n ],\n constraints: { effect_agent_schedules_pkey: ['p', ['tenant_id', 'owner_id', 'schedule_id']] },\n },\n effect_agent_storage_version: {\n columns: ['id:boolean:true', 'version:bigint:true'],\n constraints: {\n effect_agent_storage_version_pkey: ['p', ['id']],\n effect_agent_storage_version_single_row: ['c', ['id'], ['column', 'id']],\n },\n },\n effect_agent_submissions: {\n columns: [\n 'submission_id:text:true',\n 'thread_id:text:true',\n 'queue_sequence:bigint:true',\n 'principal:text:true',\n 'idempotency_key:text:true',\n 'agent_id:text:true',\n 'definition_key:bigint:true',\n 'deployment_id:text:true',\n 'input_json:text:true',\n 'input_digest:text:true',\n 'receipt_id:text:true',\n 'state:text:true',\n 'settled_outcome:text:false',\n 'settled_record_id:text:false',\n 'finalized_at:text:false',\n 'created_at:text:true',\n 'ready_at:text:false',\n 'input_applied_record_id:text:false',\n 'input_applied_sequence:bigint:false',\n 'joined_host_submission_id:text:false',\n 'suspended_reason_json:text:false',\n 'suspended_at:text:false',\n 'unknown_reason:text:false',\n 'unknown_tool_call_ids_json:text:false',\n 'parent_submission_id:text:false',\n 'parent_tool_call_id:text:false',\n 'admission_group:text:false',\n 'admission_fence_json:text:false',\n 'worker_admission_json:text:false',\n 'message_admission_json:text:false',\n ],\n constraints: {\n effect_agent_submissions_pkey: ['p', ['submission_id']],\n effect_agent_submissions_thread_id_principal_idempotency_ke_key: [\n 'u',\n ['thread_id', 'principal', 'idempotency_key'],\n ],\n effect_agent_submissions_thread_id_queue_sequence_key: ['u', ['thread_id', 'queue_sequence']],\n },\n },\n effect_agent_subscription_deliveries: {\n columns: [\n 'tenant_id:text:true',\n 'source_address:text:true',\n 'owner_id:text:true',\n 'subscription_id:text:true',\n 'event_id:text:true',\n 'delivery_key:text:true',\n 'state:text:true',\n 'next_attempt_at_millis:bigint:true',\n 'record_json:text:true',\n 'retry_parked:boolean:true',\n 'observe_settlement:boolean:true',\n ],\n constraints: {\n effect_agent_subscription_del_tenant_id_source_address_deli_key: [\n 'u',\n ['tenant_id', 'source_address', 'delivery_key'],\n ],\n effect_agent_subscription_deliveries_pkey: [\n 'p',\n ['tenant_id', 'source_address', 'owner_id', 'subscription_id', 'event_id'],\n ],\n },\n },\n effect_agent_subscription_events: {\n columns: [\n 'tenant_id:text:true',\n 'source_address:text:true',\n 'event_id:text:true',\n 'source_name:text:true',\n 'source_version:text:true',\n 'matching_key:text:true',\n 'payload_digest:text:true',\n 'cutoff:bigint:true',\n 'cursor:bigint:true',\n 'routing_complete:bigint:true',\n 'tombstone:bigint:true',\n 'next_attempt_at_millis:bigint:true',\n 'record_json:text:true',\n ],\n constraints: {\n effect_agent_subscription_events_pkey: ['p', ['tenant_id', 'source_address', 'event_id']],\n },\n },\n effect_agent_subscription_sequences: {\n columns: [\n 'tenant_id:text:true',\n 'source_address:text:true',\n 'sequence:bigint:true',\n 'event_scan_cursor:text:true',\n 'delivery_scan_cursor:text:true',\n 'recovery_scan_cursor:bigint:true',\n ],\n constraints: {\n effect_agent_subscription_sequences_pkey: ['p', ['tenant_id', 'source_address']],\n },\n },\n effect_agent_subscriptions: {\n columns: [\n 'tenant_id:text:true',\n 'source_address:text:true',\n 'owner_id:text:true',\n 'subscription_id:text:true',\n 'ordinal:bigint:true',\n 'source_name:text:true',\n 'source_version:text:true',\n 'matching_key:text:true',\n 'state:text:true',\n 'expires_at_millis:bigint:false',\n 'recovery_at_millis:bigint:false',\n 'recovery_present:bigint:true',\n 'record_json:text:true',\n ],\n constraints: {\n effect_agent_subscriptions_pkey: [\n 'p',\n ['tenant_id', 'source_address', 'owner_id', 'subscription_id'],\n ],\n effect_agent_subscriptions_tenant_id_source_address_ordinal_key: [\n 'u',\n ['tenant_id', 'source_address', 'ordinal'],\n ],\n },\n },\n effect_agent_rollover_buckets: {\n columns: [\n 'thread_id:text:true',\n 'height:bigint:true',\n 'bucket:bigint:true',\n 'sequence:bigint:true',\n ],\n constraints: {\n effect_agent_rollover_buckets_pkey: ['p', ['thread_id', 'height', 'bucket', 'sequence']],\n effect_agent_rollover_buckets_thread_id_sequence_fkey: [\n 'f',\n ['thread_id', 'sequence'],\n 'effect_agent_canonical_records',\n ['thread_id', 'sequence'],\n ],\n },\n },\n effect_agent_threads: {\n columns: [\n 'thread_id:text:true',\n 'created_at:text:false',\n 'tail_sequence:bigint:true',\n 'work_version:bigint:true',\n 'work_state:text:true',\n 'work_through_sequence:bigint:true',\n 'work_reporting:bigint:true',\n 'work_entry_count:bigint:true',\n 'worker_input_sequence:bigint:false',\n 'worker_settlement_sequence:bigint:false',\n ],\n constraints: { effect_agent_threads_pkey: ['p', ['thread_id']] },\n },\n effect_agent_unknown_resolutions: {\n columns: [\n 'submission_id:text:true',\n 'tool_call_id:text:true',\n 'resolution_kind:text:true',\n 'author:text:true',\n 'reason:text:true',\n 'resolution_json:text:true',\n 'resolved_at:text:true',\n ],\n constraints: {\n effect_agent_unknown_resolutions_pkey: [\n 'p',\n ['submission_id', 'tool_call_id', 'resolution_kind'],\n ],\n effect_agent_unknown_resolutions_submission_id_fkey: [\n 'f',\n ['submission_id'],\n 'effect_agent_submissions',\n ['submission_id'],\n ],\n },\n },\n effect_agent_import_delivery_visits: {\n columns: [\n 'thread_id:text:true',\n 'message_id:text:true',\n 'path_id:text:true',\n 'completed:bigint:true',\n ],\n constraints: { effect_agent_import_delivery_visits_pkey: ['p', ['thread_id', 'message_id']] },\n },\n effect_agent_worker_stops: {\n columns: ['thread_id:text:true', 'terminal:text:false'],\n constraints: { effect_agent_worker_stops_pkey: ['p', ['thread_id']] },\n },\n}\n\nconst layoutIndexes: Readonly<Record<string, LayoutIndex>> = {\n effect_agent_tool_declarations_sequence: {\n table: 'effect_agent_tool_declarations',\n columns: ['thread_id', 'sequence'],\n },\n effect_agent_record_refusals_sequence: {\n table: 'effect_agent_record_refusals',\n columns: ['thread_id', 'sequence'],\n },\n effect_agent_live_child_reservations_thread: {\n table: 'effect_agent_live_child_reservations',\n columns: ['thread_id', 'reservation_id'],\n },\n effect_agent_canonical_batches_last: {\n table: 'effect_agent_canonical_batches',\n columns: ['thread_id', 'last_sequence'],\n },\n effect_agent_canonical_batches_sequence: {\n table: 'effect_agent_canonical_batches',\n columns: ['thread_id', 'first_sequence'],\n unique: true,\n },\n\n effect_agent_import_delivery_visits_path: {\n table: 'effect_agent_import_delivery_visits',\n columns: ['thread_id', 'path_id'],\n },\n effect_agent_records_application_input: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'sequence'],\n predicate: ['eq', ['column', 'application_input'], ['integer', 1]],\n },\n effect_agent_records_prompt: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'sequence'],\n predicate: [\n 'in',\n ['column', 'record_tag'],\n PROMPT_EVIDENCE_TAGS.map((tag) => RECORD_TAGS[tag]),\n ],\n },\n effect_agent_records_admitted_input: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'sequence'],\n predicate: [\n 'and',\n [\n ['eq', ['column', 'record_tag'], ['integer', 30]],\n ['notNull', ['column', 'submission_id']],\n ],\n ],\n },\n effect_agent_records_worker_funding: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'source_submission_id', 'sequence', 'message_id'],\n predicate: ['eq', ['column', 'record_tag'], ['integer', 34]],\n },\n effect_agent_records_worker_completed: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'message_id', 'sequence'],\n predicate: ['eq', ['column', 'record_tag'], ['integer', 32]],\n },\n effect_agent_records_worker_stop: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'worker_thread_id', 'sequence'],\n predicate: ['eq', ['column', 'record_tag'], ['integer', 38]],\n },\n effect_agent_message_deliveries_identity: {\n table: 'effect_agent_message_deliveries',\n columns: ['owner_thread_id', null],\n expressions: ['messageId'],\n },\n effect_agent_message_deliveries_peer_retained: {\n table: 'effect_agent_message_deliveries',\n columns: ['owner_thread_id', 'peer_retained_until_millis', 'message_id'],\n predicate: ['notNull', ['column', 'peer_retained_until_millis']],\n },\n effect_agent_message_deliveries_peer: {\n table: 'effect_agent_message_deliveries',\n columns: ['owner_thread_id', 'message_id'],\n predicate: [\n 'and',\n [\n ['notIn', ['column', 'state'], ['processed', 'refused']],\n ['eq', ['json', 'peer'], ['text', 'true']],\n ],\n ],\n },\n effect_agent_records_tag: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'record_tag', 'sequence'],\n },\n effect_agent_records_handoff: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'sequence'],\n predicate: ['eq', ['column', 'handoff'], ['integer', 1]],\n },\n effect_agent_message_deliveries_due: {\n table: 'effect_agent_message_deliveries',\n columns: ['deadline_at_millis', 'owner_thread_id', 'message_id'],\n predicate: ['notNull', ['column', 'deadline_at_millis']],\n },\n effect_agent_message_deliveries_capacity: {\n table: 'effect_agent_message_deliveries',\n columns: ['owner_thread_id', null, 'message_id'],\n expressions: ['workerUpdate'],\n predicate: ['in', ['column', 'state'], ['pending', 'accepted', 'parked']],\n },\n effect_agent_message_deliveries_pending: {\n table: 'effect_agent_message_deliveries',\n columns: ['owner_thread_id', 'message_id'],\n predicate: ['notIn', ['column', 'state'], ['processed', 'refused']],\n },\n effect_agent_records_call: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'record_tag', 'run_id', 'tool_call_id'],\n predicate: ['notNull', ['column', 'tool_call_id']],\n },\n effect_agent_records_run_input: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'run_id'],\n predicate: [\n 'and',\n [\n ['eq', ['column', 'record_tag'], ['integer', 30]],\n ['eq', ['column', 'input_kind'], ['text', 'user']],\n ],\n ],\n },\n effect_agent_records_subtree: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'source_submission_id', 'sequence'],\n predicate: ['eq', ['column', 'record_tag'], ['integer', 22]],\n },\n effect_agent_records_worker_input: {\n table: 'effect_agent_canonical_records',\n columns: ['thread_id', 'message_id'],\n predicate: ['eq', ['column', 'record_tag'], ['integer', 34]],\n },\n effect_agent_schedules_deadline: {\n table: 'effect_agent_schedules',\n columns: ['deadline_at_millis', 'tenant_id', 'owner_id', 'schedule_id'],\n predicate: ['notNull', ['column', 'deadline_at_millis']],\n },\n effect_agent_schedules_owner_deadline: {\n table: 'effect_agent_schedules',\n columns: ['tenant_id', 'owner_id', 'deadline_at_millis', 'schedule_id'],\n predicate: ['notNull', ['column', 'deadline_at_millis']],\n },\n effect_agent_submissions_group: {\n table: 'effect_agent_submissions',\n columns: ['thread_id', 'admission_group'],\n predicate: [\n 'and',\n [\n ['notNull', ['column', 'admission_group']],\n ['ne', ['column', 'state'], ['text', 'settled']],\n ],\n ],\n },\n effect_agent_submissions_joined_host: {\n table: 'effect_agent_submissions',\n columns: ['joined_host_submission_id'],\n predicate: ['notNull', ['column', 'joined_host_submission_id']],\n },\n effect_agent_submissions_nonterminal: {\n table: 'effect_agent_submissions',\n columns: ['thread_id', 'queue_sequence'],\n predicate: ['ne', ['column', 'state'], ['text', 'settled']],\n },\n effect_agent_submissions_parent: {\n table: 'effect_agent_submissions',\n columns: ['parent_submission_id'],\n predicate: ['notNull', ['column', 'parent_submission_id']],\n },\n effect_agent_subscription_deliveries_pending: {\n table: 'effect_agent_subscription_deliveries',\n columns: ['tenant_id', 'source_address', 'state', 'next_attempt_at_millis', 'delivery_key'],\n },\n effect_agent_subscription_deliveries_capacity: {\n table: 'effect_agent_subscription_deliveries',\n columns: ['tenant_id', 'source_address', 'owner_id'],\n predicate: ['in', ['column', 'state'], ['selected', 'prepared']],\n },\n effect_agent_subscription_deliveries_observing: {\n table: 'effect_agent_subscription_deliveries',\n columns: ['tenant_id', 'source_address', 'owner_id'],\n predicate: [\n 'and',\n [\n ['eq', ['column', 'state'], ['text', 'delivered']],\n ['column', 'observe_settlement'],\n ],\n ],\n },\n effect_agent_subscription_deliveries_registration: {\n table: 'effect_agent_subscription_deliveries',\n columns: ['tenant_id', 'source_address', 'owner_id', 'subscription_id', 'delivery_key'],\n },\n effect_agent_subscription_events_pending: {\n table: 'effect_agent_subscription_events',\n columns: [\n 'tenant_id',\n 'source_address',\n 'routing_complete',\n 'next_attempt_at_millis',\n 'event_id',\n ],\n },\n effect_agent_subscriptions_candidates: {\n table: 'effect_agent_subscriptions',\n columns: [\n 'tenant_id',\n 'source_address',\n 'source_name',\n 'source_version',\n 'matching_key',\n 'ordinal',\n ],\n },\n effect_agent_subscriptions_owner: {\n table: 'effect_agent_subscriptions',\n columns: ['tenant_id', 'source_address', 'owner_id', 'ordinal'],\n },\n effect_agent_subscriptions_capacity: {\n table: 'effect_agent_subscriptions',\n columns: ['tenant_id', 'source_address', 'expires_at_millis'],\n predicate: ['in', ['column', 'state'], ['active', 'paused']],\n },\n effect_agent_subscriptions_owner_capacity: {\n table: 'effect_agent_subscriptions',\n columns: ['tenant_id', 'source_address', 'owner_id', 'expires_at_millis'],\n predicate: ['in', ['column', 'state'], ['active', 'paused']],\n },\n effect_agent_subscriptions_recovery: {\n table: 'effect_agent_subscriptions',\n columns: ['tenant_id', 'source_address', 'recovery_at_millis', 'ordinal'],\n predicate: ['notNull', ['column', 'recovery_at_millis']],\n },\n effect_agent_worker_pending: {\n table: 'effect_agent_message_deliveries',\n columns: ['owner_thread_id', null, 'message_id'],\n expressions: ['threadId'],\n predicate: [\n 'and',\n [\n ['in', ['column', 'state'], ['pending', 'parked']],\n ['eq', ['json', 'hasReceipt'], ['text', 'false']],\n ],\n ],\n },\n effect_agent_worker_starts: {\n table: 'effect_agent_message_deliveries',\n columns: ['owner_thread_id', null, null, 'message_id'],\n expressions: ['delegationId', 'targetAgentId'],\n predicate: ['eq', ['json', 'workerStart'], ['text', 'true']],\n },\n}\n\nconst headerStatement =\n 'CREATE TABLE __NAMESPACE__.effect_agent_schema (singleton BIGINT PRIMARY KEY NOT NULL CHECK (singleton = 1), layout_version BIGINT NOT NULL CHECK (layout_version > 0), record_format TEXT NOT NULL CHECK (length(record_format) > 0))'\n\nconst quote = (namespace: string) => `\"${namespace.replaceAll('\"', '\"\"')}\"`\n\nconst qualify = (statement: string, namespace: string) => statement.replaceAll('__NAMESPACE__', quote(namespace))\n\nconst NameRows = Schema.Array(Schema.Struct({ name: Schema.String, kind: Schema.String }))\n\nconst ColumnRows = Schema.Array(\n Schema.Struct({\n name: Schema.String,\n column_name: Schema.String,\n type: Schema.String,\n not_null: Schema.Boolean,\n collation: Schema.NullOr(Schema.String),\n }),\n)\n\nconst ConstraintRows = Schema.Array(\n Schema.Struct({\n table_name: Schema.String,\n name: Schema.String,\n kind: Schema.String,\n columns: Schema.Array(Schema.String),\n target_table: Schema.NullOr(Schema.String),\n target_schema: Schema.NullOr(Schema.String),\n target_columns: Schema.Array(Schema.String),\n expression: Schema.NullOr(Schema.String),\n enforcement_ok: Schema.Boolean,\n }),\n)\n\nconst IndexRows = Schema.Array(\n Schema.Struct({\n name: Schema.String,\n table_name: Schema.String,\n columns: Schema.Array(Schema.NullOr(Schema.String)),\n is_unique: Schema.Boolean,\n is_primary: Schema.Boolean,\n expressions: Schema.NullOr(Schema.String),\n predicate: Schema.NullOr(Schema.String),\n structure_ok: Schema.Boolean,\n }),\n)\n\nconst sameIndexColumns = Schema.toEquivalence(Schema.Array(Schema.NullOr(Schema.String)))\n\nconst matchesIndex = (actual: (typeof IndexRows.Type)[number] | undefined, expected: LayoutIndex) =>\n actual !== undefined &&\n actual.structure_ok &&\n actual.table_name === expected.table &&\n actual.is_unique === (expected.unique ?? false) &&\n actual.is_primary === (expected.primary ?? false) &&\n sameIndexColumns(actual.columns, expected.columns) &&\n matchesLayoutExpressions(\n actual.expressions,\n (expected.expressions ?? []).map((key) => (typeof key === 'string' ? ['json', key] : key)),\n ) &&\n matchesLayoutExpressions(\n actual.predicate,\n expected.predicate === undefined ? [] : [expected.predicate],\n )\n\nconst sameStrings = Schema.toEquivalence(Schema.Array(Schema.String))\n\nconst Header = Schema.Tuple([\n Schema.Struct({\n singleton: SqlInteger,\n layout_version: SqlInteger,\n record_format: Schema.NonEmptyString,\n }),\n])\n\nconst Legacy = Schema.Tuple([Schema.Struct({ id: Schema.Literal(true), version: SqlInteger })])\n\nconst incompatible = (actualVersion: number, message: string) =>\n PostgresStorageCompatibilityError.make({\n actualVersion,\n supportedVersion: CurrentPostgresStorageVersion,\n message: `${message} Keep the original database; the store was not changed.`,\n })\n\nconst decode = <A, I>(schema: Schema.Codec<A, I>, value: unknown, table: string) =>\n Schema.decodeUnknownEffect(schema)(value, { onExcessProperty: 'error' }).pipe(\n Effect.mapError(() =>\n PostgresStorageCorruptionError.make({\n table,\n rowKey: 'schema',\n message: 'Malformed storage layout or version header.',\n })\n ),\n )\n\nexport interface PostgresStorageHeader {\n readonly layoutVersion: number\n readonly recordFormat: string\n}\n\n/** No DDL or transaction acquisition. The caller owns the snapshot/writer lock across subsequent work. */\nexport const inspectPostgresStorage = Effect.fnUntraced(function*(\n namespace: string,\n allowReleasedUpgrade = false,\n) {\n const sql = yield* SqlClient.SqlClient\n const { table, execute } = yield* makeSqlQuery(namespace)\n\n const names = yield* decode(\n NameRows,\n yield* execute(sql<Record<string, unknown>>`\n SELECT c.relname AS name, c.relkind::text AS kind FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace\n WHERE n.nspname=${namespace} AND starts_with(c.relname, 'effect_agent_')\n `),\n 'pg_class',\n )\n\n const versionTable = names.find((row) => row.name === 'effect_agent_storage_version')\n const schemaTable = names.find((row) => row.name === 'effect_agent_schema')\n\n if (versionTable === undefined) {\n const independent = new Set([\n 'effect_agent_activity_metadata',\n 'effect_agent_activity_metadata_pkey',\n 'effect_agent_activity_processor_state_v2',\n 'effect_agent_activity_processor_state_v2_pkey',\n ])\n\n if (names.every((row) => independent.has(row.name))) return undefined\n\n return yield* incompatible(0, 'Unversioned or incomplete Effect Agent storage.')\n }\n if (versionTable.kind !== 'r') return yield* incompatible(0, 'Malformed version table.')\n\n const [legacy] = yield* decode(\n Legacy,\n yield* execute(\n sql<Record<string, unknown>>`SELECT * FROM ${table('effect_agent_storage_version')}`,\n ),\n 'effect_agent_storage_version',\n )\n\n if (\n legacy.version !== CurrentPostgresStorageVersion &&\n !(\n allowReleasedUpgrade &&\n (legacy.version === 25 ||\n legacy.version === 26 ||\n legacy.version === 27 ||\n legacy.version === 28 ||\n legacy.version === 29 ||\n legacy.version === 30)\n )\n ) {\n return yield* incompatible(legacy.version, `Unsupported storage version ${legacy.version}.`)\n }\n if (schemaTable?.kind !== 'r') {\n return yield* incompatible(legacy.version, 'Missing or malformed singleton schema table.')\n }\n\n const [row] = yield* decode(\n Header,\n yield* execute(sql<Record<string, unknown>>`SELECT * FROM ${table('effect_agent_schema')}`),\n 'effect_agent_schema',\n )\n\n if (row.singleton !== 1 || row.layout_version !== legacy.version) {\n return yield* incompatible(row.layout_version, 'Unsupported or conflicting layout headers.')\n }\n const header = { layoutVersion: row.layout_version, recordFormat: row.record_format }\n\n if (header.recordFormat !== CURRENT_RECORD_FORMAT) {\n return yield* incompatible(\n header.layoutVersion,\n `Unsupported record format ${header.recordFormat}.`,\n )\n }\n\n if (\n legacy.version === 25 &&\n names.some((row) => Object.hasOwn(layout26IndexStatements, row.name))\n ) {\n return yield* incompatible(25, 'Layout 25 contains layout 26 indexes.')\n }\n\n const columns = yield* decode(\n ColumnRows,\n yield* execute(sql<Record<string, unknown>>`\n SELECT c.relname AS name, a.attname AS column_name,\n CASE WHEN a.atttypmod <> -1 THEN ''\n WHEN a.atttypid='pg_catalog.int8'::regtype THEN 'bigint'\n WHEN a.atttypid='pg_catalog.bool'::regtype THEN 'boolean'\n WHEN a.atttypid='pg_catalog.text'::regtype THEN 'text'\n WHEN a.atttypid='pg_catalog.jsonb'::regtype THEN 'jsonb' ELSE '' END AS type,\n a.attnotnull AS not_null,\n cn.nspname || '.' || co.collname AS collation\n FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace JOIN pg_attribute a ON a.attrelid=c.oid\n LEFT JOIN pg_collation co ON co.oid=a.attcollation LEFT JOIN pg_namespace cn ON cn.oid=co.collnamespace\n WHERE n.nspname=${namespace} AND starts_with(c.relname, 'effect_agent_') AND c.relkind='r' AND a.attnum>0 AND NOT a.attisdropped\n ORDER BY c.relname,a.attnum\n `),\n 'pg_attribute',\n )\n\n // Shipped expressions use only pinned built-ins. Any function/operator dependency\n // denotes an extension or user-defined overload, even if its deparsed spelling matches.\n const constraints = yield* decode(\n ConstraintRows,\n yield* execute(sql<Record<string, unknown>>`\n SELECT c.relname AS table_name, k.conname AS name, k.contype::text AS kind,\n to_jsonb(ARRAY(SELECT a.attname FROM unnest(k.conkey) WITH ORDINALITY v(attnum, position)\n JOIN pg_attribute a ON a.attrelid=k.conrelid AND a.attnum=v.attnum ORDER BY v.position)) AS columns,\n r.relname AS target_table, rn.nspname AS target_schema,\n to_jsonb(ARRAY(SELECT a.attname FROM unnest(k.confkey) WITH ORDINALITY v(attnum, position)\n JOIN pg_attribute a ON a.attrelid=k.confrelid AND a.attnum=v.attnum ORDER BY v.position)) AS target_columns,\n pg_get_expr(k.conbin, k.conrelid, false) AS expression,\n (k.convalidated AND NOT k.condeferrable AND NOT k.condeferred\n AND k.conislocal AND k.coninhcount=0 AND k.conparentid=0\n AND (k.contype<>'c' OR NOT k.connoinherit)\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid='pg_constraint'::regclass\n AND d.objid=k.oid AND d.refclassid IN ('pg_proc'::regclass, 'pg_operator'::regclass))\n AND (k.contype NOT IN ('p','u') OR ic.relname=k.conname)\n AND (k.contype<>'f' OR (k.confupdtype='a' AND k.confdeltype='r' AND k.confmatchtype='s'\n AND k.conpfeqop <@ ARRAY['pg_catalog.=(text,text)'::regoperator, 'pg_catalog.=(bigint,bigint)'::regoperator]::oid[]\n AND k.conppeqop <@ ARRAY['pg_catalog.=(text,text)'::regoperator, 'pg_catalog.=(bigint,bigint)'::regoperator]::oid[]\n AND k.conffeqop <@ ARRAY['pg_catalog.=(text,text)'::regoperator, 'pg_catalog.=(bigint,bigint)'::regoperator]::oid[]))) AS enforcement_ok\n FROM pg_constraint k JOIN pg_class c ON c.oid=k.conrelid\n JOIN pg_namespace n ON n.oid=c.relnamespace\n LEFT JOIN pg_class r ON r.oid=k.confrelid LEFT JOIN pg_namespace rn ON rn.oid=r.relnamespace\n LEFT JOIN pg_class ic ON ic.oid=k.conindid\n WHERE n.nspname=${namespace} AND k.contype IN ('p','u','f','c','x')\n `),\n 'pg_constraint',\n )\n\n // Frozen keys use btree ASC NULLS LAST (indoption=0), default built-in opclasses,\n // and the column collation, database default for JSON text, or none for integer expressions.\n const indexes = yield* decode(\n IndexRows,\n yield* execute(sql<Record<string, unknown>>`\n SELECT ic.relname AS name, c.relname AS table_name,\n to_jsonb(ARRAY(SELECT a.attname FROM unnest(i.indkey) WITH ORDINALITY v(attnum, position)\n LEFT JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=v.attnum ORDER BY v.position)) AS columns,\n i.indisunique AS is_unique, i.indisprimary AS is_primary,\n pg_get_expr(i.indexprs, i.indrelid, false) AS expressions,\n pg_get_expr(i.indpred, i.indrelid, false) AS predicate,\n (ic.relkind='i' AND am.amname='btree' AND i.indisvalid AND i.indisready AND i.indislive\n AND NOT i.indisexclusion AND i.indimmediate AND NOT i.indnullsnotdistinct\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid='pg_class'::regclass\n AND d.objid=i.indexrelid AND d.refclassid IN ('pg_proc'::regclass, 'pg_operator'::regclass))\n AND i.indnatts=i.indnkeyatts AND NOT EXISTS (\n SELECT 1 FROM unnest(i.indkey, i.indcollation, i.indclass, i.indoption)\n WITH ORDINALITY v(attnum, collation_oid, opclass, options, position)\n JOIN pg_attribute ia ON ia.attrelid=i.indexrelid AND ia.attnum=v.position\n LEFT JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=v.attnum\n JOIN pg_opclass op ON op.oid=v.opclass\n WHERE v.options<>0 OR NOT op.opcdefault OR op.opcnamespace<>'pg_catalog'::regnamespace\n OR op.opcintype<>ia.atttypid OR op.opcmethod<>ic.relam\n OR v.collation_oid<>CASE WHEN v.attnum=0 THEN\n CASE WHEN ia.atttypid='pg_catalog.text'::regtype THEN 'pg_catalog.default'::regcollation::oid ELSE 0::oid END\n ELSE a.attcollation END\n )) AS structure_ok\n FROM pg_index i JOIN pg_class ic ON ic.oid=i.indexrelid JOIN pg_class c ON c.oid=i.indrelid\n JOIN pg_namespace n ON n.oid=c.relnamespace JOIN pg_am am ON am.oid=ic.relam\n WHERE n.nspname=${namespace}\n `),\n 'pg_index',\n )\n\n const expectedShape: typeof layoutShape = {\n ...layoutShape,\n effect_agent_schema: {\n columns: ['singleton:bigint:true', 'layout_version:bigint:true', 'record_format:text:true'],\n constraints: {\n effect_agent_schema_pkey: ['p', ['singleton']],\n effect_agent_schema_singleton_check: [\n 'c',\n ['singleton'],\n ['eq', ['column', 'singleton'], ['integer', 1]],\n ],\n effect_agent_schema_layout_version_check: [\n 'c',\n ['layout_version'],\n ['gt', ['column', 'layout_version'], ['integer', 0]],\n ],\n effect_agent_schema_record_format_check: [\n 'c',\n ['record_format'],\n ['gt', ['length', 'record_format'], ['integer', 0]],\n ],\n },\n },\n }\n\n for (const [name, expected] of Object.entries(expectedShape)) {\n if (name === 'effect_agent_checkpoints' && legacy.version >= 29) {\n if (names.some((row) => row.name === name)) {\n return yield* incompatible(\n legacy.version,\n 'Current layout contains retired generic checkpoints.',\n )\n }\n continue\n }\n const tableColumns = columns.filter((row) => row.name === name)\n const actualConstraints = constraints.filter((row) => row.table_name === name)\n\n const expectedColumns = legacy.version === 25 && name === 'effect_agent_message_deliveries'\n ? expected.columns.filter((column) => column !== 'peer_retained_until_millis:bigint:false')\n : expected.columns\n\n if (\n names.find((row) => row.name === name)?.kind !== 'r' ||\n !sameStrings(\n // ADD COLUMN appends physically; named-column queries do not depend on that order.\n tableColumns.map((row) => `${row.column_name}:${row.type}:${row.not_null}`).sort(),\n [...expectedColumns].sort(),\n ) ||\n tableColumns.some(\n (row) =>\n row.collation !==\n (row.type === 'text'\n ? name === 'effect_agent_schema'\n ? 'pg_catalog.default'\n : 'pg_catalog.C'\n : null),\n ) ||\n actualConstraints.length !== Object.keys(expected.constraints).length\n ) {\n return yield* incompatible(legacy.version, `Missing or incompatible layout table ${name}.`)\n }\n\n for (const [constraintName, constraint] of Object.entries(expected.constraints)) {\n const actual = actualConstraints.find((row) => row.name === constraintName)\n const [kind, keyColumns] = constraint\n\n if (\n actual === undefined ||\n !actual.enforcement_ok ||\n actual.kind !== kind ||\n !sameStrings(actual.columns, keyColumns) ||\n actual.target_table !== (constraint[0] === 'f' ? constraint[2] : null) ||\n actual.target_schema !== (kind === 'f' ? namespace : null) ||\n !sameStrings(actual.target_columns, constraint[0] === 'f' ? constraint[3] : []) ||\n !matchesLayoutExpressions(actual.expression, constraint[0] === 'c' ? [constraint[2]] : [])\n ) {\n return yield* incompatible(\n legacy.version,\n `Missing or incompatible layout constraint ${constraintName}.`,\n )\n }\n\n if (\n (kind === 'p' || kind === 'u') &&\n !matchesIndex(\n indexes.find((row) => row.name === constraintName),\n {\n table: name,\n columns: keyColumns,\n unique: true,\n primary: kind === 'p',\n },\n )\n ) {\n return yield* incompatible(\n legacy.version,\n `Missing or incompatible layout index ${constraintName}.`,\n )\n }\n }\n }\n for (const [name, expected] of Object.entries(layoutIndexes)) {\n if (legacy.version === 25 && Object.hasOwn(layout26IndexStatements, name)) continue\n if (name === 'effect_agent_canonical_batches_last' && legacy.version >= 28) {\n if (indexes.some((row) => row.name === name)) {\n return yield* incompatible(\n legacy.version,\n `Layout ${legacy.version} contains the retired batch-end index.`,\n )\n }\n continue\n }\n if (\n !matchesIndex(\n indexes.find((row) => row.name === name),\n expected,\n )\n ) {\n return yield* incompatible(legacy.version, `Missing or incompatible layout index ${name}.`)\n }\n }\n\n const functions = yield* decode(\n Schema.Array(\n Schema.Struct({\n source: Schema.String,\n safe: Schema.Boolean,\n }),\n ),\n yield* execute(sql`\n SELECT p.prosrc AS source, (l.lanname='plpgsql' AND p.prorettype='pg_catalog.trigger'::regtype\n AND p.pronargs=0 AND NOT p.prosecdef AND p.proconfig IS NULL AND p.prokind='f') AS safe\n FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace JOIN pg_language l ON l.oid=p.prolang\n WHERE n.nspname=${namespace} AND p.proname='effect_agent_live_child_mutation'`),\n 'pg_proc',\n )\n\n if (\n functions.length !== 1 ||\n !functions[0]?.safe ||\n functions[0].source !== qualify(liveChildFunctionBody, namespace)\n ) {\n return yield* incompatible(\n legacy.version,\n 'Missing or incompatible live child trigger function.',\n )\n }\n\n const triggers = yield* decode(\n Schema.Array(\n Schema.Struct({\n name: Schema.String,\n table_name: Schema.String,\n type: SqlInteger,\n enabled: Schema.String,\n function_name: Schema.String,\n function_schema: Schema.String,\n arguments: Schema.String,\n safe: Schema.Boolean,\n }),\n ),\n yield* execute(sql`\n SELECT t.tgname AS name, c.relname AS table_name, t.tgtype::bigint AS type,\n t.tgenabled::text AS enabled, p.proname AS function_name, pn.nspname AS function_schema,\n encode(t.tgargs, 'hex') AS arguments,\n (NOT t.tgisinternal AND t.tgconstraint=0 AND NOT t.tgdeferrable AND NOT t.tginitdeferred\n AND t.tgqual IS NULL AND t.tgnargs=0 AND t.tgattr=''::int2vector) AS safe\n FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace\n JOIN pg_proc p ON p.oid=t.tgfoid JOIN pg_namespace pn ON pn.oid=p.pronamespace\n WHERE n.nspname=${namespace} AND (\n starts_with(t.tgname, 'effect_agent_live_child_') OR (\n ${legacy.version < CurrentPostgresStorageVersion} AND NOT t.tgisinternal\n AND c.relname IN ${sql.in(Object.keys(expectedShape))}\n )\n )`),\n 'pg_trigger',\n )\n\n for (const expected of liveChildTriggers) {\n const actual = triggers.find((trigger) => trigger.name === expected.name)\n\n if (\n actual === undefined ||\n !actual.safe ||\n actual.table_name !== expected.table ||\n actual.type !== (expected.event === 'INSERT' ? 5 : expected.event === 'UPDATE' ? 17 : 9) ||\n actual.enabled !== 'O' ||\n actual.function_name !== 'effect_agent_live_child_mutation' ||\n actual.function_schema !== namespace ||\n actual.arguments !== ''\n ) {\n return yield* incompatible(\n legacy.version,\n `Missing or incompatible live child trigger ${expected.name}.`,\n )\n }\n }\n // Backfill must not execute undeclared triggers that could rewrite retained evidence.\n if (triggers.length !== liveChildTriggers.length) {\n return yield* incompatible(legacy.version, 'Unexpected Thread storage triggers.')\n }\n\n return header\n})\n\n/** Export opening never creates a schema, runs layout steps, or initializes a journal. */\nexport const readPostgresStorageHeader = Effect.fnUntraced(function*(namespace: string) {\n const header = yield* inspectPostgresStorage(namespace)\n\n if (header === undefined) {\n return yield* incompatible(0, 'No initialized Thread storage to export.')\n }\n\n return header\n})\n\n/** The caller owns one writer transaction encompassing inspection, DDL, backfill, and both headers. */\nexport const applyPostgresLayout = Effect.fnUntraced(function*(\n namespace: string,\n header: PostgresStorageHeader | undefined,\n) {\n const sql = yield* SqlClient.SqlClient\n const { table, execute } = yield* makeSqlQuery(namespace)\n\n if (header !== undefined) {\n if (header.layoutVersion === CurrentPostgresStorageVersion) return header\n if (\n header.layoutVersion !== 25 &&\n header.layoutVersion !== 26 &&\n header.layoutVersion !== 27 &&\n header.layoutVersion !== 28 &&\n header.layoutVersion !== 29 &&\n header.layoutVersion !== 30\n ) {\n return yield* incompatible(header.layoutVersion, 'Unsupported layout upgrade.')\n }\n\n if (header.layoutVersion < 30) {\n yield* assertLegacyMessagePublicationDrained(namespace).pipe(\n Effect.mapError((cause) =>\n cause.reason === 'conflict'\n ? incompatible(\n header.layoutVersion,\n 'Recover work discovery and drain peer, report and update publication using the previous library version before upgrading.',\n )\n : PostgresStorageError.make({\n operation: cause.operation,\n message: cause.message,\n cause,\n })\n ),\n )\n }\n\n yield* upgradeSqlThreadWorkIndex(namespace).pipe(\n Effect.mapError((cause) =>\n PostgresStorageError.make({ operation: cause.operation, message: cause.message, cause })\n ),\n )\n\n // READ COMMITTED must observe in-flight writers before reading checkpoints for conversion.\n if (header.layoutVersion < 27) {\n yield* execute(\n sql`LOCK TABLE ${table('effect_agent_executions')} IN SHARE ROW EXCLUSIVE MODE`,\n )\n }\n\n if (header.layoutVersion === 25) {\n yield* execute(\n sql`ALTER TABLE ${table('effect_agent_message_deliveries')} ADD COLUMN peer_retained_until_millis BIGINT`,\n )\n yield* backfillPeerMessageRetention(namespace).pipe(\n Effect.catchTag('MessageDeliveryError', (cause) =>\n PostgresStorageCorruptionError.make({\n table: 'effect_agent_message_deliveries',\n rowKey: 'layout-25-upgrade',\n message: `Invalid retained delivery during layout upgrade: ${cause.operation}.`,\n })),\n )\n for (const statement of Object.values(layout26IndexStatements)) {\n yield* sql.unsafe(qualify(statement, namespace)).withoutTransform\n }\n }\n if (header.layoutVersion < 27) {\n yield* upgradeExecutionCheckpoints(namespace).pipe(\n Effect.catchTag('ThreadStoreError', (cause) =>\n PostgresStorageCorruptionError.make({\n table: 'effect_agent_executions',\n rowKey: 'upgrade',\n message: `Invalid retained execution; upgrade rolled back: ${cause.message}`,\n })),\n )\n }\n if (header.layoutVersion < 30) {\n if (header.layoutVersion <= 27) {\n yield* execute(sql`DROP INDEX ${table('effect_agent_canonical_batches_last')}`)\n }\n // Retire only the derived generic snapshot cache. This step preserves the exact\n // canonical and operational bytes; earlier layout conversions remain independent.\n if (header.layoutVersion < 29) {\n yield* execute(sql`DROP TABLE ${table('effect_agent_checkpoints')}`)\n }\n yield* execute(\n sql`DROP INDEX IF EXISTS ${table('effect_agent_records_delivery_predecessor')}`,\n )\n yield* execute(sql`DROP INDEX IF EXISTS ${table('effect_agent_work_entries_message')}`)\n yield* execute(sql`DROP INDEX IF EXISTS ${table('effect_agent_work_entries_peer')}`)\n yield* createSqlThreadWorkTables(namespace).pipe(\n Effect.mapError((cause) =>\n PostgresStorageError.make({ operation: cause.operation, message: cause.message, cause })\n ),\n )\n }\n yield* execute(\n sql`UPDATE ${table('effect_agent_storage_version')} SET version=${CurrentPostgresStorageVersion} WHERE id=TRUE`,\n )\n yield* execute(\n sql`UPDATE ${table('effect_agent_schema')} SET layout_version=${CurrentPostgresStorageVersion} WHERE singleton=1`,\n )\n\n // The enclosing transaction also rolls back DDL and backfill if final validation fails.\n return yield* readPostgresStorageHeader(namespace)\n }\n for (const statement of layoutStatements) {\n yield* sql.unsafe(qualify(statement, namespace)).withoutTransform\n }\n yield* createSqlThreadWorkTables(namespace).pipe(\n Effect.mapError((cause) =>\n PostgresStorageError.make({ operation: cause.operation, message: cause.message, cause })\n ),\n )\n yield* sql.unsafe(qualify(headerStatement, namespace)).withoutTransform\n yield* execute(\n sql`INSERT INTO ${\n table('effect_agent_storage_version')\n } (id, version) VALUES (TRUE, ${CurrentPostgresStorageVersion})`,\n )\n yield* execute(\n sql`INSERT INTO ${\n table('effect_agent_schema')\n } (singleton, layout_version, record_format) VALUES (1, ${CurrentPostgresStorageVersion}, ${CURRENT_RECORD_FORMAT})`,\n )\n\n return yield* readPostgresStorageHeader(namespace)\n})\n","import { makeSqlJournal, sqlStorageOwner } from '@systemfsoftware/agent-storage-sql/sql-journal'\nimport {\n type CorruptionErrorFields,\n makeSqlQuery,\n makeSqlTransaction,\n type StorageErrorFields,\n} from '@systemfsoftware/agent-storage-sql/sql-storage'\nimport * as Effect from 'effect/Effect'\nimport * as Schema from 'effect/Schema'\nimport * as SqlClient from 'effect/sql/SqlClient'\nimport * as SqlError from 'effect/sql/SqlError'\n\nimport {\n PostgresStorageCorruptionError,\n PostgresStorageError,\n type PostgresStorageFailpointError,\n type PostgresStorageFailpointLocation,\n PostgresWriteContention,\n} from '../PostgresStorageError'\nimport { applyPostgresLayout, inspectPostgresStorage } from './storage-layout'\n\nexport { CurrentPostgresStorageVersion, readPostgresStorageHeader } from './storage-layout'\n\nconst storageError = (operation: string) => (cause: SqlError.SqlError) =>\n PostgresStorageError.make({ operation, cause, message: cause.message })\n\nexport const classifyWriteFailure =\n (operation: string) => (cause: SqlError.SqlError): PostgresStorageError | PostgresWriteContention =>\n cause.reason._tag === 'SerializationError' ||\n cause.reason._tag === 'DeadlockError' ||\n cause.reason._tag === 'LockTimeoutError'\n ? PostgresWriteContention.make({\n operation,\n cause,\n message: `Postgres reported a transient transaction conflict; ${operation} is safe to retry.`,\n })\n : storageError(operation)(cause)\n\n/**\n * Applications route each Thread to one scoped owner. This local gate is shared by all ports\n * using the same client/namespace; it is not a distributed lock or failover protocol.\n */\nexport const makeWriteTransaction = Effect.fnUntraced(function*(\n sql: SqlClient.SqlClient,\n lockTimeout: number,\n namespace: string,\n) {\n const owner = yield* sqlStorageOwner(sql, namespace)\n\n const transaction = makeSqlTransaction(sql, {\n begin: 'BEGIN ISOLATION LEVEL READ COMMITTED',\n prelude: sql`SELECT set_config('lock_timeout', ${`${lockTimeout}ms`}, true)`.withoutTransform,\n })\n\n return <A, E, R>(body: Effect.Effect<A, E, R>) => owner.withMutation(transaction(body))\n})\n\n/** Every page of a multi-query export observes the same snapshot without creating write authority. */\nconst withReadTransaction = (sql: SqlClient.SqlClient) =>\n makeSqlTransaction(sql, { begin: 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY' })\n\n/** Run while holding the owner transaction, including when this schema does not yet exist. */\nexport const ensurePostgresSchema = Effect.fnUntraced(function*(schema: string) {\n const sql = yield* SqlClient.SqlClient\n const { execute } = yield* makeSqlQuery()\n\n const existing = yield* execute(sql`SELECT 1 FROM pg_namespace WHERE nspname = ${schema}`)\n\n // Even IF NOT EXISTS requires database-wide CREATE permission.\n if (existing.length === 0) {\n yield* execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql(schema)}`)\n }\n})\n\nexport const postgresStorageErrors = {\n storage: (fields: StorageErrorFields) => PostgresStorageError.make(fields),\n corruption: (fields: CorruptionErrorFields) => PostgresStorageCorruptionError.make(fields),\n isCorruption: Schema.is(PostgresStorageCorruptionError),\n}\n\nconst isTransactionFailure = Schema.is(\n Schema.Union([PostgresStorageError, PostgresWriteContention]),\n)\n\n/** Inspect under the owner gate before any DDL; current headers commit together. */\nexport const initializePostgresStorage = Effect.fn('PostgresStorage.initializeLayout')(function*({\n lockTimeout,\n schema,\n}: {\n readonly lockTimeout: number\n readonly schema: string\n}) {\n const sql = yield* SqlClient.SqlClient\n\n const write = yield* makeWriteTransaction(sql, lockTimeout, schema)\n\n yield* write(\n Effect.gen(function*() {\n const header = yield* inspectPostgresStorage(schema, true)\n\n if (header === undefined) yield* ensurePostgresSchema(schema)\n yield* applyPostgresLayout(schema, header)\n }),\n ).pipe(\n Effect.catchTag('SqlError', (error) => Effect.fail(classifyWriteFailure('initialize storage')(error))),\n )\n})\n\n/** Bind shared journal operations without repeating format initialization. */\nexport const makePostgresJournal = Effect.fnUntraced(function*(\n lockTimeout: number,\n hitFailpoint: (\n location: PostgresStorageFailpointLocation,\n ) => Effect.Effect<void, PostgresStorageFailpointError>,\n namespace: string,\n) {\n const sql = yield* SqlClient.SqlClient\n const write = yield* makeWriteTransaction(sql, lockTimeout, namespace)\n const read = withReadTransaction(sql)\n\n return yield* makeSqlJournal({\n namespace,\n errors: postgresStorageErrors,\n hitFailpoint,\n transactions: {\n withWriteTransaction: (operation) => <A, E, R>(body: Effect.Effect<A, E, R>) =>\n write(body).pipe(\n Effect.mapError((error) => {\n if (SqlError.isSqlError(error)) return classifyWriteFailure(operation)(error)\n if (Schema.is(PostgresStorageError)(error) && SqlError.isSqlError(error.cause)) {\n return classifyWriteFailure(error.operation)(error.cause)\n }\n\n return error\n }),\n ),\n withReadTransaction: (operation) => <A, E, R>(body: Effect.Effect<A, E, R>) =>\n read(body).pipe(\n Effect.mapError((error) => SqlError.isSqlError(error) ? storageError(operation)(error) : error),\n ),\n isTransactionFailure,\n },\n })\n})\n","import { makeSqlActivityStore } from '@systemfsoftware/agent-storage-sql/sql-activity-store'\nimport { sqlStorageOwner } from '@systemfsoftware/agent-storage-sql/sql-journal'\nimport {\n makeSqlMessageDeliveryStore,\n registerCanonicalMessageWriter,\n} from '@systemfsoftware/agent-storage-sql/sql-message-delivery-store'\nimport {\n makeSqlScheduleStore,\n SqlScheduleWriteTransaction,\n} from '@systemfsoftware/agent-storage-sql/sql-schedule-store'\nimport { makeSqlTransaction } from '@systemfsoftware/agent-storage-sql/sql-storage'\nimport { makeSqlSubmissionLedgerKernel } from '@systemfsoftware/agent-storage-sql/sql-submission-ledger'\nimport { makeSqlSubscriptionStore } from '@systemfsoftware/agent-storage-sql/sql-subscription-store'\nimport { makeSqlThreadImport } from '@systemfsoftware/agent-storage-sql/sql-thread-import'\nimport { makeSqlThreadStoreKernel } from '@systemfsoftware/agent-storage-sql/sql-thread-store'\nimport {\n ActivityMutationFailpoint,\n ActivityProcessorStore,\n ActivityStoreError,\n} from '@systemfsoftware/agent/activity-store'\nimport { MessageDeliveryStore, type MessageDeliveryStoreLimits } from '@systemfsoftware/agent/message-delivery'\nimport { StorageOwner } from '@systemfsoftware/agent/run-storage'\nimport { ScheduleStore } from '@systemfsoftware/agent/schedule'\nimport { SettlementPublisher } from '@systemfsoftware/agent/settlement-publisher'\nimport { LedgerError, SubmissionLedger } from '@systemfsoftware/agent/submission-ledger'\nimport { SourcePartition, SubscriptionError, SubscriptionStore } from '@systemfsoftware/agent/subscription'\nimport { ThreadImport } from '@systemfsoftware/agent/thread-import'\nimport type { ThreadExportRequest } from '@systemfsoftware/agent/thread-store'\nimport { ThreadReader, ThreadStore } from '@systemfsoftware/agent/thread-store'\nimport { checkExportSource } from '@systemfsoftware/agent/thread-transfer'\nimport * as Context from 'effect/Context'\nimport * as Effect from 'effect/Effect'\nimport * as Layer from 'effect/Layer'\nimport * as Schema from 'effect/Schema'\nimport * as SqlClient from 'effect/sql/SqlClient'\n\nimport {\n classifyWriteFailure,\n ensurePostgresSchema,\n initializePostgresStorage,\n makePostgresJournal,\n makeWriteTransaction,\n postgresStorageErrors,\n readPostgresStorageHeader,\n} from './internal/postgres-storage'\nimport {\n PostgresStorageError,\n type PostgresStorageFailpointError,\n type PostgresStorageFailpointLocation,\n} from './PostgresStorageError'\n\nexport { CurrentPostgresStorageVersion } from './internal/postgres-storage'\n\nexport type PostgresStorageFailpointHandler = (\n location: PostgresStorageFailpointLocation,\n) => Effect.Effect<void, PostgresStorageFailpointError>\n\nconst Settings = Schema.Struct({\n observationPollInterval: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n lockTimeout: Schema.Int.check(Schema.isGreaterThan(0)),\n verifyOnOpen: Schema.Boolean,\n schema: Schema.NonEmptyString.check(\n Schema.isMaxLength(63),\n Schema.isPattern(/^[a-z_][a-z0-9_]*$/),\n ),\n})\n\nexport interface PostgresStorageOptions {\n /** Namespace for qualified storage tables, created under the owner gate when absent. Defaults to public. */\n readonly schema?: string | undefined\n /** Journal observation polling interval in milliseconds. Defaults to 25. */\n readonly observationPollInterval?: number | undefined\n /** Positive database lock timeout in milliseconds. Defaults to 5,000. */\n readonly lockTimeout?: number | undefined\n /** Audit stored payloads, identities, and batch coverage on open. Defaults to false. */\n readonly verifyOnOpen?: boolean | undefined\n readonly failpoint?: PostgresStorageFailpointHandler | undefined\n readonly activityFailpoint?: ActivityMutationFailpoint['Service']['hit'] | undefined\n}\n\nconst settings = (options: PostgresStorageOptions) =>\n Schema.decodeEffect(Settings)({\n observationPollInterval: options.observationPollInterval ?? 25,\n lockTimeout: options.lockTimeout ?? 5_000,\n verifyOnOpen: options.verifyOnOpen ?? false,\n schema: options.schema ?? 'public',\n }).pipe(\n Effect.mapError((cause) =>\n PostgresStorageError.make({\n cause,\n operation: 'configure Postgres storage',\n message: cause.message,\n })\n ),\n )\n\nconst initialize = Effect.fnUntraced(function*(options: PostgresStorageOptions) {\n const config = yield* settings(options)\n\n yield* initializePostgresStorage(config)\n\n return config\n})\n\nconst openJournal = Effect.fnUntraced(function*(options: PostgresStorageOptions) {\n const config = yield* initialize(options)\n const hitFailpoint: PostgresStorageFailpointHandler = options.failpoint ?? (() => Effect.void)\n const journal = yield* makePostgresJournal(config.lockTimeout, hitFailpoint, config.schema)\n\n return { config, journal, hitFailpoint }\n})\n\ntype Journal = Effect.Success<ReturnType<typeof openJournal>>\n\nconst makeThreadStore = ({ config, journal, hitFailpoint }: Journal) =>\n makeSqlThreadStoreKernel(journal, {\n ...config,\n namespace: config.schema,\n errors: postgresStorageErrors,\n hitFailpoint,\n offsetPrefix: 'effect-agent-postgres@1:',\n }).pipe(Effect.map((services) => ({ ...services, owner: journal.owner })))\n\nconst makeSubmissionLedger = ({ config, journal, hitFailpoint }: Journal) =>\n makeSqlSubmissionLedgerKernel(journal, {\n namespace: config.schema,\n errors: postgresStorageErrors,\n hitFailpoint,\n offsetPrefix: 'effect-agent-postgres@1:',\n sqlFailure: (operation) => (cause) => {\n const internal = classifyWriteFailure(operation)(cause)\n\n return LedgerError.make({ operation, message: internal.message, cause: internal })\n },\n }).pipe(Effect.map((services) => ({ ...services, owner: journal.owner })))\n\n/**\n * Thread history and submissions over one scoped owner. The application must route each Thread\n * exclusively to this owner; Postgres does not provide distributed ownership or failover here.\n */\nexport const layerWith = (options: PostgresStorageOptions) =>\n ThreadReader.layer().pipe(\n Layer.provideMerge(\n Layer.effectContext(\n Effect.gen(function*() {\n const journal = yield* openJournal(options)\n const threadStore = yield* makeThreadStore(journal)\n const submissionLedger = yield* makeSubmissionLedger(journal)\n\n return Context.make(ThreadStore, threadStore.store).pipe(\n Context.add(ThreadImport, threadStore.importer),\n Context.add(SubmissionLedger, submissionLedger.ledger),\n Context.add(SettlementPublisher, submissionLedger.publisher),\n Context.add(StorageOwner, journal.journal.owner),\n )\n }),\n ),\n ),\n )\n\n/**\n * Thread history and submissions with default settings. Requires SqlClient, Digest, and SecureRandom.\n * SQL text parameters, including identities, must exclude NUL and unpaired UTF-16\n * surrogates. Canonical JSON payload strings remain intact through escaped encoding.\n */\nexport const layer = layerWith({})\n\n/** Standalone thread history over the application's SqlClient and Digest. */\nexport const threadStoreLayer = (options: PostgresStorageOptions = {}) =>\n ThreadReader.layer().pipe(\n Layer.provideMerge(\n Layer.effectContext(\n Effect.flatMap(openJournal(options), makeThreadStore).pipe(\n Effect.map(({ store, importer, owner }) =>\n Context.make(ThreadStore, store).pipe(\n Context.add(ThreadImport, importer),\n Context.add(StorageOwner, owner),\n )\n ),\n ),\n ),\n ),\n )\n\n/** Export a quiesced current-layout store through a read-only snapshot; never run DDL. */\nexport const exportThread = Effect.fn('PostgresStorage.exportThread')(function*(\n request: ThreadExportRequest,\n options: PostgresStorageOptions = {},\n) {\n yield* checkExportSource(request.threadId)\n const config = yield* settings(options)\n const sql = yield* SqlClient.SqlClient\n\n return yield* Effect.scoped(\n Effect.gen(function*() {\n const owner = yield* sqlStorageOwner(sql, config.schema)\n\n return yield* owner.withMutation(\n makeSqlTransaction(sql, {\n begin: 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY',\n })(\n Effect.gen(function*() {\n yield* readPostgresStorageHeader(config.schema)\n\n const transfer = yield* makeSqlThreadImport({\n owner,\n namespace: config.schema,\n offsetPrefix: 'effect-agent-postgres@1:',\n read: (body) => body,\n write: () => Effect.die('A read-only exporter cannot import'),\n })\n\n return yield* transfer.export(request)\n }),\n ).pipe(\n Effect.catchTag('SqlError', (cause) =>\n PostgresStorageError.make({\n operation: 'export Thread snapshot',\n message: cause.message,\n cause,\n })),\n ),\n )\n }),\n )\n})\n\n/** Submissions and canonical settlement publication over the application's SqlClient, Digest, and SecureRandom. */\nexport const submissionLedgerLayer = (options: PostgresStorageOptions = {}) =>\n Layer.effectContext(\n Effect.flatMap(openJournal(options), makeSubmissionLedger).pipe(\n Effect.map((services) =>\n Context.make(SubmissionLedger, services.ledger).pipe(\n Context.add(SettlementPublisher, services.publisher),\n Context.add(StorageOwner, services.owner),\n )\n ),\n ),\n )\n\n/** Schedules over the application's SqlClient. */\nexport const scheduleStoreLayer = (options: PostgresStorageOptions = {}) =>\n Layer.unwrap(\n Effect.gen(function*() {\n const sql = yield* SqlClient.SqlClient\n const config = yield* initialize(options)\n const run = yield* makeWriteTransaction(sql, config.lockTimeout, config.schema)\n\n return Layer.effect(ScheduleStore, makeSqlScheduleStore(config.schema)).pipe(\n Layer.provide(Layer.succeed(SqlScheduleWriteTransaction, { run })),\n )\n }),\n )\n\n/** Message delivery over the application's SqlClient and Digest, with optional live capacity and payload limits. */\nexport const messageDeliveryStoreLayer = (\n options: PostgresStorageOptions & {\n readonly limits?: MessageDeliveryStoreLimits | undefined\n } = {},\n) =>\n Layer.effect(\n MessageDeliveryStore,\n Effect.gen(function*() {\n const sql = yield* SqlClient.SqlClient\n const config = yield* initialize(options)\n\n const owner = yield* sqlStorageOwner(sql, config.schema)\n\n const store = yield* makeSqlMessageDeliveryStore(owner, options.limits, {\n namespace: config.schema,\n transaction: yield* makeWriteTransaction(sql, config.lockTimeout, config.schema),\n })\n\n yield* registerCanonicalMessageWriter(owner, store)\n\n return store\n }),\n )\n\n/** Subscriptions owned by an explicit partition. Invalid partitions fail before accessing SQL. */\nexport const subscriptionStoreLayer = (\n owned: SourcePartition,\n options: PostgresStorageOptions = {},\n) =>\n Layer.effect(\n SubscriptionStore,\n Effect.gen(function*() {\n const partition = yield* Schema.decodeEffect(SourcePartition)(owned).pipe(\n Effect.mapError(() => SubscriptionError.make({ reason: 'validation', code: 'partition' })),\n )\n\n const config = yield* initialize(options)\n const sql = yield* SqlClient.SqlClient\n const transaction = yield* makeWriteTransaction(sql, config.lockTimeout, config.schema)\n\n // Retention DDL must share the owner gate with format initialization.\n return yield* transaction(\n makeSqlSubscriptionStore(partition, {\n namespace: config.schema,\n transaction,\n maxStoredJsonLength: 16 * 1024 * 1024,\n }),\n ).pipe(\n Effect.catchTag('SqlError', () => SubscriptionError.make({ reason: 'storage', code: 'initialize' })),\n )\n }),\n )\n\n/**\n * Independent activity progress over one shared SqlClient; does not initialize the Thread journal.\n * Route each activity key to one process. Sessions are local and close with their owning Scope.\n */\nexport const activityStoreLayer = (options: PostgresStorageOptions = {}) =>\n Layer.effect(\n ActivityProcessorStore,\n Effect.gen(function*() {\n const sql = yield* SqlClient.SqlClient\n const config = yield* settings(options)\n\n return yield* makeSqlActivityStore(\n yield* makeWriteTransaction(sql, config.lockTimeout, config.schema),\n ensurePostgresSchema(config.schema).pipe(\n Effect.mapError(() =>\n ActivityStoreError.make({\n operation: 'initialize activity schema',\n reason: 'unavailable',\n })\n ),\n ),\n config.schema,\n )\n }),\n ).pipe(\n Layer.provide(\n options.activityFailpoint === undefined\n ? ActivityMutationFailpoint.layer\n : Layer.succeed(ActivityMutationFailpoint)({ hit: options.activityFailpoint }),\n ),\n )\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,MAAM,mBAAmB,UAA+D;CACtF,IAAI,MAAM,SAAS,OAAQ,OAAO,KAAA;CAClC,MAAM,SAAiD,CAAC;CAExD,MAAM,QACJ;CAEF,OAAO,MAAM,YAAY,MAAM,QAAQ;EACrC,MAAM,QAAQ,MAAM,KAAK,KAAK,CAAC,GAAG;EAElC,IAAI,UAAU,KAAA,KAAa,OAAO,UAAU,KAAK,OAAO,KAAA;EACxD,IAAI,MAAM,KAAK,KAAK,GAAG;EACvB,MAAM,QAAQ,MAAM;EAEpB,OAAO,KACL,UAAU,QAAO,UAAU,MACvB;GAAE,MAAM;GAAO,OAAO,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,WAAW,QAAQ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AK,KAAK;CACxB,SAAS,KAAK,GAAG;CAEjB,OAAO,aAAa,OAAO,SAAS,cAAc,KAAA;AACpD;AAEA,MAAa,4BACX,QACA,aAEA,WAAW,OACP,SAAS,WAAW,IACpB,KAAK,UAAU,gBAAgB,MAAM,CAAC,MAAM,KAAK,UAAU,QAAQ;;ACtLzE,MAAa,gCAAgC;;AAG7C,MAAM,0BAA0B;CAC9B,qCACE;CACF,2CACE;CACF,+CACE;CACF,gDACE;CACF,+CACE;AACJ;;AAGA,MAAM,wBAAwB;;;;;;;;;;;;;;AAe9B,MAAM,oBAAoB;CACxB;EACE,MAAM;EACN,OAAO;EACP,OAAO;CACT;CACA;EACE,MAAM;EACN,OAAO;EACP,OAAO;CACT;CACA;EACE,MAAM;EACN,OAAO;EACP,OAAO;CACT;AACF;;AAGA,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,uHAAuH;CACvH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAIA;CACA;CACA,kHAAkH,sBAAsB;CACxI;CACA,GAAG,kBAAkB,KAClB,YACC,kBAAkB,QAAQ,KAAK,SAAS,QAAQ,MAAM,oBAAoB,QAAQ,MAAM,gFAC5F;CACA,GAAG,OAAO,OAAO,uBAAuB;AAC1C;AAwBA,MAAM,cAQF;CACF,yBAAyB;EACvB,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;GACA;EACF;EACA,aAAa;GACX,8BAA8B,CAAC,KAAK,CAAC,aAAa,QAAQ,CAAC;GAC3D,wCAAwC;IACtC;IACA,CAAC,WAAW;IACZ;IACA,CAAC,WAAW;GACd;EACF;CACF;CACA,6BAA6B;EAC3B,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;EACA,aAAa;GACX,kCAAkC,CAAC,KAAK,CAAC,aAAa,gBAAgB,CAAC;GACvE,4CAA4C;IAC1C;IACA,CAAC,WAAW;IACZ;IACA,CAAC,WAAW;GACd;EACF;CACF;CACA,8BAA8B;EAC5B,SAAS;GACP;GACA;GACA;GACA;EACF;EACA,aAAa;GACX,mCAAmC,CAAC,KAAK,CAAC,aAAa,UAAU,CAAC;GAClE,sDAAsD;IACpD;IACA,CAAC,aAAa,UAAU;IACxB;IACA,CAAC,aAAa,UAAU;GAC1B;GACA,yCAAyC;IACvC;IACA,CAAC,aAAa,sBAAsB;IACpC;IACA,CAAC,aAAa,gBAAgB;GAChC;EACF;CACF;CACA,8BAA8B;EAC5B,SAAS;GACP;GACA;GACA;GACA;EACF;EACA,aAAa;GACX,mCAAmC,CAAC,KAAK,CAAC,aAAa,UAAU,CAAC;GAClE,sDAAsD;IACpD;IACA,CAAC,aAAa,UAAU;IACxB;IACA,CAAC,aAAa,UAAU;GAC1B;GACA,yCAAyC;IACvC;IACA,CAAC,aAAa,sBAAsB;IACpC;IACA,CAAC,aAAa,gBAAgB;GAChC;EACF;CACF;CACA,4BAA4B;EAC1B,SAAS;GACP;GACA;GACA;GACA;GACA;EACF;EACA,aAAa;GACX,iCAAiC,CAAC,KAAK,CAAC,eAAe,CAAC;GACxD,+CAA+C;IAC7C;IACA,CAAC,eAAe;IAChB;IACA,CAAC,eAAe;GAClB;EACF;CACF;CACA,iCAAiC;EAC/B,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;EACF;EACA,aAAa;GACX,sCAAsC,CAAC,KAAK,CAAC,iBAAiB,cAAc,CAAC;GAC7E,oDAAoD;IAClD;IACA,CAAC,eAAe;IAChB;IACA,CAAC,eAAe;GAClB;EACF;CACF;CACA,wBAAwB;EACtB,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;EACF;EACA,aAAa;GACX,6BA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,CAAC,eAAe;GAClB;GACA,sCAAsC,CAAC,KAAK,CAAC,gBAAgB,CAAC;EAChE;CACF;CACA,iCAAiC;EAC/B,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;EACA,aAAa,EAAE,sCAAsC,CAAC,KAAK,CAAC,mBAAmB,YAAY,CAAC,EAAE;CAChG;CACA,wBAAwB;EACtB,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;EACF;EACA,aAAa,EAAE,6BAA6B,CAAC,KAAK;GAAC;GAAa;GAAY;EAAa,CAAC,EAAE;CAC9F;CACA,8BAA8B;EAC5B,SAAS,CAAC,mBAAmB,qBAAqB;EAClD,aAAa;GACX,mCAAmC,CAAC,KAAK,CAAC,IAAI,CAAC;GAC/C,yCAAyC;IAAC;IAAK,CAAC,IAAI;IAAG,CAAC,UAAU,IAAI;GAAC;EACzE;CACF;CACA,0BAA0B;EACxB,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;EACA,aAAa;GACX,+BAA+B,CAAC,KAAK,CAAC,eAAe,CAAC;GACtD,iEAAiE,CAC/D,KACA;IAAC;IAAa;IAAa;GAAiB,CAC9C;GACA,uDAAuD,CAAC,KAAK,CAAC,aAAa,gBAAgB,CAAC;EAC9F;CACF;CACA,sCAAsC;EACpC,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;EACA,aAAa;GACX,iEAAiE,CAC/D,KACA;IAAC;IAAa;IAAkB;GAAc,CAChD;GACA,2CAA2C,CACzC,KACA;IAAC;IAAa;IAAkB;IAAY;IAAmB;GAAU,CAC3E;EACF;CACF;CACA,kCAAkC;EAChC,SAAS;GACP;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;EACA,aAAa,E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,CAAC,KAAK,CAAC,CAAC,KACnE,OAAO,eAAe,kBAAkB,KAAK;EAAE,QAAQ;EAAc,MAAM;CAAY,CAAC,CAAC,CAC3F;CAEA,MAAM,SAAS,OAAO,WAAW,OAAO;CACxC,MAAM,MAAM,OAAO,UAAU;CAC7B,MAAM,cAAc,OAAO,qBAAqB,KAAK,OAAO,aAAa,OAAO,MAAM;CAGtF,OAAO,OAAO,YACZ,yBAAyB,WAAW;EAClC,WAAW,OAAO;EAClB;EACA,qBAAqB;CACvB,CAAC,CACH,CAAC,CAAC,KACA,OAAO,SAAS,kBAAkB,kBAAkB,KAAK;EAAE,QAAQ;EAAW,MAAM;CAAa,CAAC,CAAC,CACrG;AACF,CAAC,CACH;;;;;AAMF,MAAa,sBAAsB,UAAkC,CAAC,MACpE,MAAM,OACJ,wBACA,OAAO,IAAI,aAAY;CACrB,MAAM,MAAM,OAAO,UAAU;CAC7B,MAAM,SAAS,OAAO,SAAS,OAAO;CAEtC,OAAO,OAAO,qBACZ,OAAO,qBAAqB,KAAK,OAAO,aAAa,OAAO,MAAM,GAClE,qBAAqB,OAAO,MAAM,CAAC,CAAC,KAClC,OAAO,eACL,mBAAmB,KAAK;EACtB,WAAW;EACX,QAAQ;CACV,CAAC,CACH,CACF,GACA,OAAO,MACT;AACF,CAAC,CACH,CAAC,CAAC,KACA,MAAM,QACJ,QAAQ,sBAAsB,KAAA,IAC1B,0BAA0B,QAC1B,MAAM,QAAQ,yBAAyB,CAAC,CAAC,EAAE,KAAK,QAAQ,kBAAkB,CAAC,CACjF,CACF"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { a as PostgresStorageFailpointError, c as PostgresWriteContention, n as PostgresStorageCorruptionError, o as PostgresStorageFailpointLocation, r as PostgresStorageError, t as PostgresStorageCompatibilityError } from "./PostgresStorageError-mnbXuBHP.mjs";
|
|
2
|
+
import { ActivityMutationFailpoint, ActivityProcessorStore, ActivityStoreError } from "@systemfsoftware/agent/activity-store";
|
|
3
|
+
import { MessageDeliveryStore, MessageDeliveryStoreLimits } from "@systemfsoftware/agent/message-delivery";
|
|
4
|
+
import { StorageOwner } from "@systemfsoftware/agent/run-storage";
|
|
5
|
+
import { ScheduleStore } from "@systemfsoftware/agent/schedule";
|
|
6
|
+
import { SettlementPublisher } from "@systemfsoftware/agent/settlement-publisher";
|
|
7
|
+
import { SubmissionLedger } from "@systemfsoftware/agent/submission-ledger";
|
|
8
|
+
import { SourcePartition, SubscriptionError, SubscriptionStore } from "@systemfsoftware/agent/subscription";
|
|
9
|
+
import { ThreadImport } from "@systemfsoftware/agent/thread-import";
|
|
10
|
+
import { ThreadExportRequest, ThreadReader, ThreadStore } from "@systemfsoftware/agent/thread-store";
|
|
11
|
+
import * as Effect from "effect/Effect";
|
|
12
|
+
import * as Layer from "effect/Layer";
|
|
13
|
+
import * as SqlClient from "effect/sql/SqlClient";
|
|
14
|
+
import "@systemfsoftware/agent-storage-sql/sql-storage";
|
|
15
|
+
import "effect/sql/SqlError";
|
|
16
|
+
declare const CurrentPostgresStorageVersion = 31;
|
|
17
|
+
declare namespace PostgresStorage_d_exports {
|
|
18
|
+
export { CurrentPostgresStorageVersion, PostgresStorageFailpointHandler, PostgresStorageOptions, activityStoreLayer, exportThread, layer, layerWith, messageDeliveryStoreLayer, scheduleStoreLayer, submissionLedgerLayer, subscriptionStoreLayer, threadStoreLayer };
|
|
19
|
+
}
|
|
20
|
+
type PostgresStorageFailpointHandler = (location: PostgresStorageFailpointLocation) => Effect.Effect<void, PostgresStorageFailpointError>;
|
|
21
|
+
interface PostgresStorageOptions {
|
|
22
|
+
/** Namespace for qualified storage tables, created under the owner gate when absent. Defaults to public. */
|
|
23
|
+
readonly schema?: string | undefined;
|
|
24
|
+
/** Journal observation polling interval in milliseconds. Defaults to 25. */
|
|
25
|
+
readonly observationPollInterval?: number | undefined;
|
|
26
|
+
/** Positive database lock timeout in milliseconds. Defaults to 5,000. */
|
|
27
|
+
readonly lockTimeout?: number | undefined;
|
|
28
|
+
/** Audit stored payloads, identities, and batch coverage on open. Defaults to false. */
|
|
29
|
+
readonly verifyOnOpen?: boolean | undefined;
|
|
30
|
+
readonly failpoint?: PostgresStorageFailpointHandler | undefined;
|
|
31
|
+
readonly activityFailpoint?: ActivityMutationFailpoint['Service']['hit'] | undefined;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Thread history and submissions over one scoped owner. The application must route each Thread
|
|
35
|
+
* exclusively to this owner; Postgres does not provide distributed ownership or failover here.
|
|
36
|
+
*/
|
|
37
|
+
declare const layerWith: (options: PostgresStorageOptions) => Layer.Layer<SettlementPublisher | StorageOwner | SubmissionLedger | ThreadImport | ThreadReader | ThreadStore, PostgresStorageCompatibilityError | PostgresStorageCorruptionError | PostgresStorageError | PostgresWriteContention, import("effect/crypto/Digest").Digest | import("effect/crypto/SecureRandom").SecureRandom | SqlClient.SqlClient>;
|
|
38
|
+
/**
|
|
39
|
+
* Thread history and submissions with default settings. Requires SqlClient, Digest, and SecureRandom.
|
|
40
|
+
* SQL text parameters, including identities, must exclude NUL and unpaired UTF-16
|
|
41
|
+
* surrogates. Canonical JSON payload strings remain intact through escaped encoding.
|
|
42
|
+
*/
|
|
43
|
+
declare const layer: Layer.Layer<SettlementPublisher | StorageOwner | SubmissionLedger | ThreadImport | ThreadReader | ThreadStore, PostgresStorageCompatibilityError | PostgresStorageCorruptionError | PostgresStorageError | PostgresWriteContention, import("effect/crypto/Digest").Digest | import("effect/crypto/SecureRandom").SecureRandom | SqlClient.SqlClient>;
|
|
44
|
+
/** Standalone thread history over the application's SqlClient and Digest. */
|
|
45
|
+
declare const threadStoreLayer: (options?: PostgresStorageOptions) => Layer.Layer<StorageOwner | ThreadImport | ThreadReader | ThreadStore, PostgresStorageCompatibilityError | PostgresStorageCorruptionError | PostgresStorageError | PostgresWriteContention, import("effect/crypto/Digest").Digest | SqlClient.SqlClient>;
|
|
46
|
+
/** Export a quiesced current-layout store through a read-only snapshot; never run DDL. */
|
|
47
|
+
declare const exportThread: (request: ThreadExportRequest, options?: PostgresStorageOptions | undefined) => Effect.Effect<import("@systemfsoftware/agent/thread-store").ThreadExport, PostgresStorageCompatibilityError | PostgresStorageCorruptionError | PostgresStorageError | import("@systemfsoftware/agent/thread-store").ThreadExportRejected | import("@systemfsoftware/agent/thread-store").ThreadNotMaterialized | import("@systemfsoftware/agent/thread-store").ThreadStoreError, import("effect/crypto/Digest").Digest | SqlClient.SqlClient>;
|
|
48
|
+
/** Submissions and canonical settlement publication over the application's SqlClient, Digest, and SecureRandom. */
|
|
49
|
+
declare const submissionLedgerLayer: (options?: PostgresStorageOptions) => Layer.Layer<SettlementPublisher | StorageOwner | SubmissionLedger, PostgresStorageCompatibilityError | PostgresStorageCorruptionError | PostgresStorageError | PostgresWriteContention, import("effect/crypto/Digest").Digest | import("effect/crypto/SecureRandom").SecureRandom | SqlClient.SqlClient>;
|
|
50
|
+
/** Schedules over the application's SqlClient. */
|
|
51
|
+
declare const scheduleStoreLayer: (options?: PostgresStorageOptions) => Layer.Layer<ScheduleStore, PostgresStorageCompatibilityError | PostgresStorageCorruptionError | PostgresStorageError | PostgresWriteContention, SqlClient.SqlClient>;
|
|
52
|
+
/** Message delivery over the application's SqlClient and Digest, with optional live capacity and payload limits. */
|
|
53
|
+
declare const messageDeliveryStoreLayer: (options?: PostgresStorageOptions & {
|
|
54
|
+
readonly limits?: MessageDeliveryStoreLimits | undefined;
|
|
55
|
+
}) => Layer.Layer<MessageDeliveryStore, import("@systemfsoftware/agent/message-delivery").MessageDeliveryError | PostgresStorageCompatibilityError | PostgresStorageCorruptionError | PostgresStorageError | PostgresWriteContention, import("effect/crypto/Digest").Digest | SqlClient.SqlClient>;
|
|
56
|
+
/** Subscriptions owned by an explicit partition. Invalid partitions fail before accessing SQL. */
|
|
57
|
+
declare const subscriptionStoreLayer: (owned: SourcePartition, options?: PostgresStorageOptions) => Layer.Layer<SubscriptionStore, PostgresStorageCompatibilityError | PostgresStorageCorruptionError | PostgresStorageError | PostgresWriteContention | SubscriptionError, SqlClient.SqlClient>;
|
|
58
|
+
/**
|
|
59
|
+
* Independent activity progress over one shared SqlClient; does not initialize the Thread journal.
|
|
60
|
+
* Route each activity key to one process. Sessions are local and close with their owning Scope.
|
|
61
|
+
*/
|
|
62
|
+
declare const activityStoreLayer: (options?: PostgresStorageOptions) => Layer.Layer<ActivityProcessorStore, import("@systemfsoftware/agent/activity-store").ActivityMutationFailure | ActivityStoreError | PostgresStorageError, SqlClient.SqlClient>;
|
|
63
|
+
export { exportThread as a, messageDeliveryStoreLayer as c, subscriptionStoreLayer as d, threadStoreLayer as f, activityStoreLayer as i, scheduleStoreLayer as l, PostgresStorageOptions as n, layer as o, CurrentPostgresStorageVersion as p, PostgresStorage_d_exports as r, layerWith as s, PostgresStorageFailpointHandler as t, submissionLedgerLayer as u };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as exportThread, c as messageDeliveryStoreLayer, d as subscriptionStoreLayer, f as threadStoreLayer, i as activityStoreLayer, l as scheduleStoreLayer, n as PostgresStorageOptions, o as layer, p as CurrentPostgresStorageVersion, s as layerWith, t as PostgresStorageFailpointHandler, u as submissionLedgerLayer } from "./PostgresStorage-zKTn_ufd.mjs";
|
|
2
|
+
export { CurrentPostgresStorageVersion, PostgresStorageFailpointHandler, PostgresStorageOptions, activityStoreLayer, exportThread, layer, layerWith, messageDeliveryStoreLayer, scheduleStoreLayer, submissionLedgerLayer, subscriptionStoreLayer, threadStoreLayer };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import "./PostgresStorageError-DCuaf7EF.mjs";
|
|
2
|
+
export { d as CurrentPostgresStorageVersion, n as activityStoreLayer, r as exportThread, i as layer, a as layerWith, o as messageDeliveryStoreLayer, s as scheduleStoreLayer, c as submissionLedgerLayer, l as subscriptionStoreLayer, u as threadStoreLayer } from "./PostgresStorage-D9IqvmQ2.mjs";
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
|
|
2
|
+
import { SqlStorageFailpointLocation } from "@systemfsoftware/agent-storage-sql/sql-storage-failpoint";
|
|
3
|
+
import * as Schema from "effect/Schema";
|
|
4
|
+
// src/PostgresStorageError.ts
|
|
5
|
+
var PostgresStorageError_exports = /* @__PURE__ */ __exportAll({
|
|
6
|
+
PostgresStorageCompatibilityError: () => PostgresStorageCompatibilityError,
|
|
7
|
+
PostgresStorageCorruptionError: () => PostgresStorageCorruptionError,
|
|
8
|
+
PostgresStorageError: () => PostgresStorageError,
|
|
9
|
+
PostgresStorageFailpointError: () => PostgresStorageFailpointError,
|
|
10
|
+
PostgresStorageFailpointLocation: () => PostgresStorageFailpointLocation,
|
|
11
|
+
PostgresWriteContention: () => PostgresWriteContention
|
|
12
|
+
});
|
|
13
|
+
/** The database uses an unsupported or inconsistent storage layout or record format. */
|
|
14
|
+
var PostgresStorageCompatibilityError = class extends Schema.TaggedError()("PostgresStorageCompatibilityError", {
|
|
15
|
+
actualVersion: Schema.Int,
|
|
16
|
+
message: Schema.String,
|
|
17
|
+
supportedVersion: Schema.Int
|
|
18
|
+
}) {};
|
|
19
|
+
/** Stored bytes failed the current Schema and cannot be used as recovery truth. */
|
|
20
|
+
var PostgresStorageCorruptionError = class extends Schema.TaggedError()("PostgresStorageCorruptionError", {
|
|
21
|
+
message: Schema.String,
|
|
22
|
+
rowKey: Schema.String,
|
|
23
|
+
table: Schema.String
|
|
24
|
+
}) {};
|
|
25
|
+
/** Postgres infrastructure failed while opening or operating the store. */
|
|
26
|
+
var PostgresStorageError = class extends Schema.TaggedError()("PostgresStorageError", {
|
|
27
|
+
cause: Schema.optionalKey(Schema.Defect()),
|
|
28
|
+
message: Schema.String,
|
|
29
|
+
operation: Schema.String
|
|
30
|
+
}) {};
|
|
31
|
+
/**
|
|
32
|
+
* A write transaction lost a concurrency race and was rolled back by Postgres: a
|
|
33
|
+
* serialization failure (40001), a deadlock (40P01), or a lock timeout (55P03). The
|
|
34
|
+
* transaction mutated no canonical state and is safe to retry.
|
|
35
|
+
*/
|
|
36
|
+
var PostgresWriteContention = class extends Schema.TaggedError()("PostgresWriteContention", {
|
|
37
|
+
cause: Schema.optionalKey(Schema.Defect()),
|
|
38
|
+
message: Schema.String,
|
|
39
|
+
operation: Schema.String
|
|
40
|
+
}) {};
|
|
41
|
+
const PostgresStorageFailpointLocation = SqlStorageFailpointLocation;
|
|
42
|
+
/** Deterministic test-only fault or pause injected at a Postgres operation boundary. */
|
|
43
|
+
var PostgresStorageFailpointError = class extends Schema.TaggedError()("PostgresStorageFailpointError", { location: PostgresStorageFailpointLocation }) {
|
|
44
|
+
get message() {
|
|
45
|
+
return `Injected Postgres storage failure at ${this.location}.`;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
export { PostgresStorageFailpointError as a, PostgresStorageError_exports as i, PostgresStorageCorruptionError as n, PostgresStorageFailpointLocation as o, PostgresStorageError as r, PostgresWriteContention as s, PostgresStorageCompatibilityError as t };
|
|
49
|
+
|
|
50
|
+
//# sourceMappingURL=PostgresStorageError-DCuaf7EF.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PostgresStorageError-DCuaf7EF.mjs","names":[],"sources":["../src/PostgresStorageError.ts"],"sourcesContent":["import { SqlStorageFailpointLocation } from '@systemfsoftware/agent-storage-sql/sql-storage-failpoint'\nimport * as Schema from 'effect/Schema'\n\n/** The database uses an unsupported or inconsistent storage layout or record format. */\nexport class PostgresStorageCompatibilityError extends Schema.TaggedError<PostgresStorageCompatibilityError>()(\n 'PostgresStorageCompatibilityError',\n {\n actualVersion: Schema.Int,\n message: Schema.String,\n supportedVersion: Schema.Int,\n },\n) {}\n\n/** Stored bytes failed the current Schema and cannot be used as recovery truth. */\nexport class PostgresStorageCorruptionError extends Schema.TaggedError<PostgresStorageCorruptionError>()(\n 'PostgresStorageCorruptionError',\n {\n message: Schema.String,\n rowKey: Schema.String,\n table: Schema.String,\n },\n) {}\n\n/** Postgres infrastructure failed while opening or operating the store. */\nexport class PostgresStorageError extends Schema.TaggedError<PostgresStorageError>()(\n 'PostgresStorageError',\n {\n cause: Schema.optionalKey(Schema.Defect()),\n message: Schema.String,\n operation: Schema.String,\n },\n) {}\n\n/**\n * A write transaction lost a concurrency race and was rolled back by Postgres: a\n * serialization failure (40001), a deadlock (40P01), or a lock timeout (55P03). The\n * transaction mutated no canonical state and is safe to retry.\n */\nexport class PostgresWriteContention extends Schema.TaggedError<PostgresWriteContention>()(\n 'PostgresWriteContention',\n {\n cause: Schema.optionalKey(Schema.Defect()),\n message: Schema.String,\n operation: Schema.String,\n },\n) {}\n\nexport const PostgresStorageFailpointLocation = SqlStorageFailpointLocation\n\nexport type PostgresStorageFailpointLocation = typeof PostgresStorageFailpointLocation.Type\n\n/** Deterministic test-only fault or pause injected at a Postgres operation boundary. */\nexport class PostgresStorageFailpointError extends Schema.TaggedError<PostgresStorageFailpointError>()(\n 'PostgresStorageFailpointError',\n {\n location: PostgresStorageFailpointLocation,\n },\n) {\n override get message() {\n return `Injected Postgres storage failure at ${this.location}.`\n }\n}\n\n/** Every way opening Postgres storage can fail before it serves a request. */\nexport type PostgresStorageInitializationError =\n | PostgresStorageCompatibilityError\n | PostgresStorageCorruptionError\n | PostgresStorageError\n | PostgresWriteContention\n"],"mappings":";;;;;;;;;;;;;AAIA,IAAa,oCAAb,cAAuD,OAAO,YAA+C,CAAC,CAC5G,qCACA;CACE,eAAe,OAAO;CACtB,SAAS,OAAO;CAChB,kBAAkB,OAAO;AAC3B,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,iCAAb,cAAoD,OAAO,YAA4C,CAAC,CACtG,kCACA;CACE,SAAS,OAAO;CAChB,QAAQ,OAAO;CACf,OAAO,OAAO;AAChB,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA;CACE,OAAO,OAAO,YAAY,OAAO,OAAO,CAAC;CACzC,SAAS,OAAO;CAChB,WAAW,OAAO;AACpB,CACF,CAAC,CAAC,CAAC;;;;;;AAOH,IAAa,0BAAb,cAA6C,OAAO,YAAqC,CAAC,CACxF,2BACA;CACE,OAAO,OAAO,YAAY,OAAO,OAAO,CAAC;CACzC,SAAS,OAAO;CAChB,WAAW,OAAO;AACpB,CACF,CAAC,CAAC,CAAC;AAEH,MAAa,mCAAmC;;AAKhD,IAAa,gCAAb,cAAmD,OAAO,YAA2C,CAAC,CACpG,iCACA,EACE,UAAU,iCACZ,CACF,CAAC,CAAC;CACA,IAAa,UAAU;EACrB,OAAO,wCAAwC,KAAK,SAAS;CAC/D;AACF"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import * as Schema from "effect/Schema";
|
|
2
|
+
declare namespace PostgresStorageError_d_exports {
|
|
3
|
+
export { PostgresStorageCompatibilityError, PostgresStorageCorruptionError, PostgresStorageError, PostgresStorageFailpointError, PostgresStorageFailpointLocation, PostgresStorageInitializationError, PostgresWriteContention };
|
|
4
|
+
}
|
|
5
|
+
declare const PostgresStorageCompatibilityError_base: Schema.Class<PostgresStorageCompatibilityError, Schema.TaggedStruct<"PostgresStorageCompatibilityError", {
|
|
6
|
+
readonly actualVersion: Schema.Int;
|
|
7
|
+
readonly message: Schema.String;
|
|
8
|
+
readonly supportedVersion: Schema.Int;
|
|
9
|
+
}>, import("effect/Cause").YieldableError>;
|
|
10
|
+
/** The database uses an unsupported or inconsistent storage layout or record format. */
|
|
11
|
+
declare class PostgresStorageCompatibilityError extends PostgresStorageCompatibilityError_base {}
|
|
12
|
+
declare const PostgresStorageCorruptionError_base: Schema.Class<PostgresStorageCorruptionError, Schema.TaggedStruct<"PostgresStorageCorruptionError", {
|
|
13
|
+
readonly message: Schema.String;
|
|
14
|
+
readonly rowKey: Schema.String;
|
|
15
|
+
readonly table: Schema.String;
|
|
16
|
+
}>, import("effect/Cause").YieldableError>;
|
|
17
|
+
/** Stored bytes failed the current Schema and cannot be used as recovery truth. */
|
|
18
|
+
declare class PostgresStorageCorruptionError extends PostgresStorageCorruptionError_base {}
|
|
19
|
+
declare const PostgresStorageError_base: Schema.Class<PostgresStorageError, Schema.TaggedStruct<"PostgresStorageError", {
|
|
20
|
+
readonly cause: Schema.optionalKey<Schema.Defect>;
|
|
21
|
+
readonly message: Schema.String;
|
|
22
|
+
readonly operation: Schema.String;
|
|
23
|
+
}>, import("effect/Cause").YieldableError>;
|
|
24
|
+
/** Postgres infrastructure failed while opening or operating the store. */
|
|
25
|
+
declare class PostgresStorageError extends PostgresStorageError_base {}
|
|
26
|
+
declare const PostgresWriteContention_base: Schema.Class<PostgresWriteContention, Schema.TaggedStruct<"PostgresWriteContention", {
|
|
27
|
+
readonly cause: Schema.optionalKey<Schema.Defect>;
|
|
28
|
+
readonly message: Schema.String;
|
|
29
|
+
readonly operation: Schema.String;
|
|
30
|
+
}>, import("effect/Cause").YieldableError>;
|
|
31
|
+
/**
|
|
32
|
+
* A write transaction lost a concurrency race and was rolled back by Postgres: a
|
|
33
|
+
* serialization failure (40001), a deadlock (40P01), or a lock timeout (55P03). The
|
|
34
|
+
* transaction mutated no canonical state and is safe to retry.
|
|
35
|
+
*/
|
|
36
|
+
declare class PostgresWriteContention extends PostgresWriteContention_base {}
|
|
37
|
+
declare const PostgresStorageFailpointLocation: Schema.Literals<readonly ["materialize:before", "materialize:after", "append:before", "append:after-batch-insert", "append:after-record-insert", "append:after-tail-update", "append:after", "export:after-thread-read", "ledger:admit:before", "ledger:admit:after", "ledger:mark-ready:before", "ledger:mark-ready:after", "ledger:claim:before", "ledger:claim:after", "ledger:mark-input-applied:before", "ledger:mark-input-applied:after", "ledger:finalize-settlement:before", "ledger:finalize-settlement:after", "ledger:request-abort:before", "ledger:request-abort:after", "ledger:claim-joining:before", "ledger:claim-joining:after", "ledger:mark-joined:before", "ledger:mark-joined:after", "ledger:revert-joining:before", "ledger:revert-joining:after", "ledger:suspend:before", "ledger:suspend:after", "ledger:approval-decision:before", "ledger:approval-decision:after", "ledger:mark-unknown:before", "ledger:mark-unknown:after", "ledger:unknown-resolution:before", "ledger:unknown-resolution:after", "ledger:child-reservation:before", "ledger:child-reservation:after", "ledger:child-attach:before", "ledger:child-attach:after", "ledger:child-release-pending:before", "ledger:child-release-pending:after", "ledger:child-release:before", "ledger:child-release:after", "ledger:child-settled:before", "ledger:child-settled:after"]>;
|
|
38
|
+
type PostgresStorageFailpointLocation = typeof PostgresStorageFailpointLocation.Type;
|
|
39
|
+
declare const PostgresStorageFailpointError_base: Schema.Class<PostgresStorageFailpointError, Schema.TaggedStruct<"PostgresStorageFailpointError", {
|
|
40
|
+
readonly location: Schema.Literals<readonly ["materialize:before", "materialize:after", "append:before", "append:after-batch-insert", "append:after-record-insert", "append:after-tail-update", "append:after", "export:after-thread-read", "ledger:admit:before", "ledger:admit:after", "ledger:mark-ready:before", "ledger:mark-ready:after", "ledger:claim:before", "ledger:claim:after", "ledger:mark-input-applied:before", "ledger:mark-input-applied:after", "ledger:finalize-settlement:before", "ledger:finalize-settlement:after", "ledger:request-abort:before", "ledger:request-abort:after", "ledger:claim-joining:before", "ledger:claim-joining:after", "ledger:mark-joined:before", "ledger:mark-joined:after", "ledger:revert-joining:before", "ledger:revert-joining:after", "ledger:suspend:before", "ledger:suspend:after", "ledger:approval-decision:before", "ledger:approval-decision:after", "ledger:mark-unknown:before", "ledger:mark-unknown:after", "ledger:unknown-resolution:before", "ledger:unknown-resolution:after", "ledger:child-reservation:before", "ledger:child-reservation:after", "ledger:child-attach:before", "ledger:child-attach:after", "ledger:child-release-pending:before", "ledger:child-release-pending:after", "ledger:child-release:before", "ledger:child-release:after", "ledger:child-settled:before", "ledger:child-settled:after"]>;
|
|
41
|
+
}>, import("effect/Cause").YieldableError>;
|
|
42
|
+
/** Deterministic test-only fault or pause injected at a Postgres operation boundary. */
|
|
43
|
+
declare class PostgresStorageFailpointError extends PostgresStorageFailpointError_base {
|
|
44
|
+
get message(): string;
|
|
45
|
+
}
|
|
46
|
+
/** Every way opening Postgres storage can fail before it serves a request. */
|
|
47
|
+
type PostgresStorageInitializationError = PostgresStorageCompatibilityError | PostgresStorageCorruptionError | PostgresStorageError | PostgresWriteContention;
|
|
48
|
+
export { PostgresStorageFailpointError as a, PostgresWriteContention as c, PostgresStorageError_d_exports as i, PostgresStorageCorruptionError as n, PostgresStorageFailpointLocation as o, PostgresStorageError as r, PostgresStorageInitializationError as s, PostgresStorageCompatibilityError as t };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as PostgresStorageFailpointError, c as PostgresWriteContention, n as PostgresStorageCorruptionError, o as PostgresStorageFailpointLocation, r as PostgresStorageError, s as PostgresStorageInitializationError, t as PostgresStorageCompatibilityError } from "./PostgresStorageError-mnbXuBHP.mjs";
|
|
2
|
+
export { PostgresStorageCompatibilityError, PostgresStorageCorruptionError, PostgresStorageError, PostgresStorageFailpointError, PostgresStorageFailpointLocation, PostgresStorageInitializationError, PostgresWriteContention };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as PostgresStorageCompatibilityError, n as PostgresStorageCorruptionError, r as PostgresStorageError, a as PostgresStorageFailpointError, o as PostgresStorageFailpointLocation, s as PostgresWriteContention } from "./PostgresStorageError-DCuaf7EF.mjs";
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { r as PostgresStorage_d_exports } from "./PostgresStorage-zKTn_ufd.mjs";
|
|
2
|
+
import { i as PostgresStorageError_d_exports } from "./PostgresStorageError-mnbXuBHP.mjs";
|
|
3
|
+
export { PostgresStorage_d_exports as PostgresStorage, PostgresStorageError_d_exports as PostgresStorageError };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { t as PostgresStorage_exports } from "./PostgresStorage-D9IqvmQ2.mjs";
|
|
2
|
+
import { i as PostgresStorageError_exports } from "./PostgresStorageError-DCuaf7EF.mjs";
|
|
3
|
+
export { PostgresStorage_exports as PostgresStorage, PostgresStorageError_exports as PostgresStorageError };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// \0rolldown/runtime.js
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __exportAll = (all, flags) => {
|
|
4
|
+
let target = Object.setPrototypeOf({}, null);
|
|
5
|
+
for (var name in all) __defProp(target, name, {
|
|
6
|
+
get: all[name],
|
|
7
|
+
enumerable: true
|
|
8
|
+
});
|
|
9
|
+
if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
10
|
+
return flags & 2 ? target : Object.preventExtensions(target);
|
|
11
|
+
};
|
|
12
|
+
export { __exportAll as t };
|