@systemfsoftware/agent-storage-postgres 0.0.0-bootstrap.0 → 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.
@@ -0,0 +1,1591 @@
1
+ import { RECORD_TAGS } from '@systemfsoftware/agent-storage-sql/sql-canonical-storage'
2
+ import {
3
+ assertLegacyMessagePublicationDrained,
4
+ backfillPeerMessageRetention,
5
+ } from '@systemfsoftware/agent-storage-sql/sql-message-delivery-store'
6
+ import { makeSqlQuery, SqlInteger } from '@systemfsoftware/agent-storage-sql/sql-storage'
7
+ import {
8
+ SQL_PROMPT_PREDICATE,
9
+ upgradeExecutionCheckpoints,
10
+ } from '@systemfsoftware/agent-storage-sql/sql-thread-native-reads'
11
+ import {
12
+ createSqlThreadWorkTables,
13
+ upgradeSqlThreadWorkIndex,
14
+ } from '@systemfsoftware/agent-storage-sql/sql-thread-work'
15
+ import { CURRENT_RECORD_FORMAT, PROMPT_EVIDENCE_TAGS } from '@systemfsoftware/agent/records'
16
+ import * as Effect from 'effect/Effect'
17
+ import * as Schema from 'effect/Schema'
18
+ import * as SqlClient from 'effect/sql/SqlClient'
19
+
20
+ import {
21
+ PostgresStorageCompatibilityError,
22
+ PostgresStorageCorruptionError,
23
+ PostgresStorageError,
24
+ } from '../PostgresStorageError'
25
+ import { type LayoutExpression, matchesLayoutExpressions } from './layout-expression'
26
+
27
+ export const CurrentPostgresStorageVersion = 31
28
+
29
+ /** The released layout 25 already has observe_settlement; only these indexes are new. */
30
+ const layout26IndexStatements = {
31
+ effect_agent_subscriptions_capacity:
32
+ "CREATE INDEX effect_agent_subscriptions_capacity ON __NAMESPACE__.effect_agent_subscriptions (tenant_id, source_address, expires_at_millis) WHERE state IN ('active', 'paused')",
33
+ effect_agent_subscriptions_owner_capacity:
34
+ "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')",
35
+ effect_agent_subscription_deliveries_capacity:
36
+ "CREATE INDEX effect_agent_subscription_deliveries_capacity ON __NAMESPACE__.effect_agent_subscription_deliveries (tenant_id, source_address, owner_id) WHERE state IN ('selected', 'prepared')",
37
+ effect_agent_subscription_deliveries_observing:
38
+ "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",
39
+ effect_agent_message_deliveries_peer_retained:
40
+ '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',
41
+ }
42
+
43
+ /** Only live child membership changes on reservation mutations. */
44
+ const liveChildFunctionBody = `
45
+ DECLARE owner_id TEXT;
46
+ BEGIN
47
+ IF TG_OP <> 'INSERT' THEN
48
+ DELETE FROM __NAMESPACE__.effect_agent_live_child_reservations WHERE reservation_id=OLD.reservation_id;
49
+ END IF;
50
+ IF TG_OP <> 'DELETE' AND NEW.status <> 'released' THEN
51
+ SELECT thread_id INTO STRICT owner_id FROM __NAMESPACE__.effect_agent_submissions WHERE submission_id=NEW.parent_submission_id;
52
+ INSERT INTO __NAMESPACE__.effect_agent_live_child_reservations (reservation_id, thread_id) VALUES (NEW.reservation_id, owner_id);
53
+ END IF;
54
+ IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
55
+ RETURN NEW;
56
+ END;
57
+ `
58
+
59
+ const liveChildTriggers = [
60
+ {
61
+ name: 'effect_agent_live_child_insert',
62
+ table: 'effect_agent_child_reservations',
63
+ event: 'INSERT',
64
+ },
65
+ {
66
+ name: 'effect_agent_live_child_update',
67
+ table: 'effect_agent_child_reservations',
68
+ event: 'UPDATE',
69
+ },
70
+ {
71
+ name: 'effect_agent_live_child_delete',
72
+ table: 'effect_agent_child_reservations',
73
+ event: 'DELETE',
74
+ },
75
+ ] as const
76
+
77
+ /** Fresh layout. Released predecessors take the ordered steps below. */
78
+ const layoutStatements = [
79
+ '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) )',
80
+ '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 )',
81
+ '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)',
82
+ '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)',
83
+ '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)',
84
+ '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)',
85
+ '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 )',
86
+ '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 )',
87
+ '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 )',
88
+ '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)',
89
+ '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)',
90
+ 'CREATE INDEX effect_agent_tool_declarations_sequence ON __NAMESPACE__.effect_agent_tool_declarations(thread_id, sequence)',
91
+ '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)',
92
+ 'CREATE INDEX effect_agent_record_refusals_sequence ON __NAMESPACE__.effect_agent_record_refusals(thread_id, sequence)',
93
+ '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) )',
94
+ 'CREATE INDEX effect_agent_submissions_group ON __NAMESPACE__."effect_agent_submissions" (thread_id, admission_group) WHERE admission_group IS NOT NULL AND state <> \'settled\'',
95
+ '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 )',
96
+ 'CREATE INDEX effect_agent_submissions_joined_host ON __NAMESPACE__."effect_agent_submissions" (joined_host_submission_id) WHERE joined_host_submission_id IS NOT NULL',
97
+ '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 )',
98
+ '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 )',
99
+ 'CREATE INDEX effect_agent_submissions_parent ON __NAMESPACE__."effect_agent_submissions" (parent_submission_id) WHERE parent_submission_id IS NOT NULL',
100
+ '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 )',
101
+ '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) )',
102
+ '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',
103
+ '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',
104
+ '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) )',
105
+ '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) )',
106
+ 'CREATE INDEX effect_agent_subscriptions_owner ON __NAMESPACE__."effect_agent_subscriptions" (tenant_id, source_address, owner_id, ordinal)',
107
+ 'CREATE INDEX effect_agent_subscriptions_candidates ON __NAMESPACE__."effect_agent_subscriptions" (tenant_id, source_address, source_name, source_version, matching_key, ordinal)',
108
+ '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',
109
+ '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) )',
110
+ '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)',
111
+ '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) )',
112
+ 'CREATE INDEX effect_agent_subscription_deliveries_pending ON __NAMESPACE__."effect_agent_subscription_deliveries" (tenant_id, source_address, state, next_attempt_at_millis, delivery_key)',
113
+ 'CREATE INDEX effect_agent_subscription_deliveries_registration ON __NAMESPACE__."effect_agent_subscription_deliveries" (tenant_id, source_address, owner_id, subscription_id, delivery_key)',
114
+ '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) )',
115
+ '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',
116
+ 'CREATE INDEX effect_agent_submissions_nonterminal ON __NAMESPACE__."effect_agent_submissions" (thread_id, queue_sequence) WHERE state <> \'settled\'',
117
+ 'CREATE TABLE __NAMESPACE__."effect_agent_worker_stops" (thread_id TEXT COLLATE "C" PRIMARY KEY NOT NULL, terminal TEXT COLLATE "C")',
118
+ "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'",
119
+ "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'",
120
+ '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',
121
+ '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\'',
122
+ 'CREATE INDEX effect_agent_records_subtree ON __NAMESPACE__."effect_agent_canonical_records"(thread_id, source_submission_id, sequence) WHERE record_tag = 22',
123
+ 'CREATE INDEX effect_agent_records_worker_input ON __NAMESPACE__."effect_agent_canonical_records"(thread_id, message_id) WHERE record_tag = 34',
124
+ "CREATE INDEX effect_agent_message_deliveries_pending ON __NAMESPACE__.\"effect_agent_message_deliveries\"(owner_thread_id, message_id) WHERE state NOT IN ('processed', 'refused')",
125
+ 'CREATE INDEX effect_agent_records_tag ON __NAMESPACE__."effect_agent_canonical_records"(thread_id, record_tag, sequence)',
126
+ 'CREATE INDEX effect_agent_records_handoff ON __NAMESPACE__."effect_agent_canonical_records"(thread_id, sequence) WHERE handoff = 1',
127
+ 'CREATE INDEX effect_agent_records_application_input ON __NAMESPACE__.effect_agent_canonical_records(thread_id, sequence) WHERE application_input = 1',
128
+ `CREATE INDEX effect_agent_records_prompt ON __NAMESPACE__.effect_agent_canonical_records(thread_id, sequence) WHERE ${SQL_PROMPT_PREDICATE}`,
129
+ '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',
130
+ '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',
131
+ 'CREATE INDEX effect_agent_records_worker_completed ON __NAMESPACE__.effect_agent_canonical_records(thread_id, message_id, sequence) WHERE record_tag = 32',
132
+ 'CREATE INDEX effect_agent_records_worker_stop ON __NAMESPACE__.effect_agent_canonical_records(thread_id, worker_thread_id, sequence) WHERE record_tag = 38',
133
+ "CREATE INDEX effect_agent_message_deliveries_identity ON __NAMESPACE__.effect_agent_message_deliveries(owner_thread_id, (read_metadata ->> 'messageId'))",
134
+ "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'",
135
+ '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)',
136
+ '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)',
137
+ '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)',
138
+ 'CREATE UNIQUE INDEX effect_agent_canonical_batches_sequence ON __NAMESPACE__.effect_agent_canonical_batches(thread_id, first_sequence)',
139
+ 'CREATE TABLE __NAMESPACE__.effect_agent_live_child_reservations (reservation_id TEXT COLLATE "C" PRIMARY KEY NOT NULL, thread_id TEXT COLLATE "C" NOT NULL)',
140
+ 'CREATE INDEX effect_agent_live_child_reservations_thread ON __NAMESPACE__.effect_agent_live_child_reservations(thread_id, reservation_id)',
141
+ // Compact native positions keep accepted identities out of bounded export cursors.
142
+ // Persistent scalar FIFO derivatives; rebuild from canonical input/settlement boundaries.
143
+ // Writer-local import indexes; rows are removed before publication.
144
+ '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))',
145
+ 'CREATE INDEX effect_agent_import_delivery_visits_path ON __NAMESPACE__.effect_agent_import_delivery_visits(thread_id, path_id)',
146
+ `CREATE FUNCTION __NAMESPACE__.effect_agent_live_child_mutation() RETURNS trigger LANGUAGE plpgsql AS $transfer$${liveChildFunctionBody}$transfer$`,
147
+ "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')",
148
+ ...liveChildTriggers.map(
149
+ (trigger) =>
150
+ `CREATE TRIGGER ${trigger.name} AFTER ${trigger.event} ON __NAMESPACE__.${trigger.table} FOR EACH ROW EXECUTE FUNCTION __NAMESPACE__.effect_agent_live_child_mutation()`,
151
+ ),
152
+ ...Object.values(layout26IndexStatements),
153
+ ] as const
154
+
155
+ type LayoutConstraint =
156
+ | readonly [kind: 'p' | 'u', columns: ReadonlyArray<string>]
157
+ | readonly [
158
+ kind: 'f',
159
+ columns: ReadonlyArray<string>,
160
+ targetTable: string,
161
+ targetColumns: ReadonlyArray<string>,
162
+ ]
163
+ | readonly [kind: 'c', columns: ReadonlyArray<string>, expression: LayoutExpression]
164
+
165
+ interface LayoutIndex {
166
+ readonly table: string
167
+ readonly columns: ReadonlyArray<string | null>
168
+ readonly unique?: boolean
169
+ readonly primary?: boolean
170
+ readonly expressions?: ReadonlyArray<string | LayoutExpression>
171
+ readonly predicate?: LayoutExpression
172
+ }
173
+
174
+ // Logical layout expectations. Physical index storage parameters and tablespaces are not
175
+ // part of compatibility. Expression expectations are canonical data; a closed recognizer
176
+ // accepts the deparser spellings of these forms and rejects every other form.
177
+ const layoutShape: Readonly<
178
+ Record<
179
+ string,
180
+ {
181
+ readonly columns: ReadonlyArray<string>
182
+ readonly constraints: Readonly<Record<string, LayoutConstraint>>
183
+ }
184
+ >
185
+ > = {
186
+ effect_agent_executions: {
187
+ columns: [
188
+ 'thread_id:text:true',
189
+ 'run_id:text:true',
190
+ 'input_sequence:bigint:true',
191
+ 'revision:bigint:true',
192
+ 'checkpoint_json:text:true',
193
+ 'last_commit_id:text:false',
194
+ 'last_commit_digest:text:false',
195
+ ],
196
+ constraints: {
197
+ effect_agent_executions_pkey: ['p', ['thread_id', 'run_id']],
198
+ effect_agent_executions_thread_id_fkey: [
199
+ 'f',
200
+ ['thread_id'],
201
+ 'effect_agent_threads',
202
+ ['thread_id'],
203
+ ],
204
+ },
205
+ },
206
+ effect_agent_journal_ranges: {
207
+ columns: [
208
+ 'thread_id:text:true',
209
+ 'first_sequence:bigint:true',
210
+ 'last_sequence:bigint:true',
211
+ 'record_count:bigint:true',
212
+ 'batch_count:bigint:true',
213
+ 'byte_count:bigint:true',
214
+ 'state:text:true',
215
+ 'locator:text:false',
216
+ ],
217
+ constraints: {
218
+ effect_agent_journal_ranges_pkey: ['p', ['thread_id', 'first_sequence']],
219
+ effect_agent_journal_ranges_thread_id_fkey: [
220
+ 'f',
221
+ ['thread_id'],
222
+ 'effect_agent_threads',
223
+ ['thread_id'],
224
+ ],
225
+ },
226
+ },
227
+ effect_agent_archive_batches: {
228
+ columns: [
229
+ 'thread_id:text:true',
230
+ 'batch_id:text:true',
231
+ 'range_first_sequence:bigint:true',
232
+ 'batch_json:text:true',
233
+ ],
234
+ constraints: {
235
+ effect_agent_archive_batches_pkey: ['p', ['thread_id', 'batch_id']],
236
+ effect_agent_archive_batches_thread_id_batch_id_fkey: [
237
+ 'f',
238
+ ['thread_id', 'batch_id'],
239
+ 'effect_agent_canonical_batches',
240
+ ['thread_id', 'batch_id'],
241
+ ],
242
+ effect_agent_archive_batches_range_fkey: [
243
+ 'f',
244
+ ['thread_id', 'range_first_sequence'],
245
+ 'effect_agent_journal_ranges',
246
+ ['thread_id', 'first_sequence'],
247
+ ],
248
+ },
249
+ },
250
+ effect_agent_archive_records: {
251
+ columns: [
252
+ 'thread_id:text:true',
253
+ 'sequence:bigint:true',
254
+ 'range_first_sequence:bigint:true',
255
+ 'record_json:text:true',
256
+ ],
257
+ constraints: {
258
+ effect_agent_archive_records_pkey: ['p', ['thread_id', 'sequence']],
259
+ effect_agent_archive_records_thread_id_sequence_fkey: [
260
+ 'f',
261
+ ['thread_id', 'sequence'],
262
+ 'effect_agent_canonical_records',
263
+ ['thread_id', 'sequence'],
264
+ ],
265
+ effect_agent_archive_records_range_fkey: [
266
+ 'f',
267
+ ['thread_id', 'range_first_sequence'],
268
+ 'effect_agent_journal_ranges',
269
+ ['thread_id', 'first_sequence'],
270
+ ],
271
+ },
272
+ },
273
+ effect_agent_abort_intents: {
274
+ columns: [
275
+ 'submission_id:text:true',
276
+ 'author:text:true',
277
+ 'reason:text:true',
278
+ 'requested_at:text:true',
279
+ 'canonical_record_id:text:false',
280
+ ],
281
+ constraints: {
282
+ effect_agent_abort_intents_pkey: ['p', ['submission_id']],
283
+ effect_agent_abort_intents_submission_id_fkey: [
284
+ 'f',
285
+ ['submission_id'],
286
+ 'effect_agent_submissions',
287
+ ['submission_id'],
288
+ ],
289
+ },
290
+ },
291
+ effect_agent_approval_decisions: {
292
+ columns: [
293
+ 'submission_id:text:true',
294
+ 'tool_call_id:text:true',
295
+ 'decision:text:true',
296
+ 'resolver:text:true',
297
+ 'reason:text:true',
298
+ 'decided_at:text:true',
299
+ ],
300
+ constraints: {
301
+ effect_agent_approval_decisions_pkey: ['p', ['submission_id', 'tool_call_id']],
302
+ effect_agent_approval_decisions_submission_id_fkey: [
303
+ 'f',
304
+ ['submission_id'],
305
+ 'effect_agent_submissions',
306
+ ['submission_id'],
307
+ ],
308
+ },
309
+ },
310
+ effect_agent_envelopes: {
311
+ columns: [
312
+ 'envelope_key:bigint:true',
313
+ 'content_digest:text:true',
314
+ 'prefix:text:true',
315
+ 'before_payload:text:true',
316
+ 'before_record_id:text:true',
317
+ 'suffix:text:true',
318
+ ],
319
+ constraints: {
320
+ effect_agent_envelopes_pkey: ['p', ['envelope_key']],
321
+ effect_agent_envelopes_content_digest_key: ['u', ['content_digest']],
322
+ },
323
+ },
324
+ effect_agent_run_keys: {
325
+ columns: ['run_key:bigint:true', 'thread_id:text:true', 'run_id:text:true'],
326
+ constraints: {
327
+ effect_agent_run_keys_pkey: ['p', ['run_key']],
328
+ effect_agent_run_keys_thread_id_run_id_key: ['u', ['thread_id', 'run_id']],
329
+ effect_agent_run_keys_thread_id_fkey: [
330
+ 'f',
331
+ ['thread_id'],
332
+ 'effect_agent_threads',
333
+ ['thread_id'],
334
+ ],
335
+ },
336
+ },
337
+ effect_agent_definitions: {
338
+ columns: ['definition_key:bigint:true', 'content_digest:text:true', 'value_json:text:true'],
339
+ constraints: {
340
+ effect_agent_definitions_pkey: ['p', ['definition_key']],
341
+ effect_agent_definitions_content_digest_key: ['u', ['content_digest']],
342
+ },
343
+ },
344
+ effect_agent_canonical_batches: {
345
+ columns: [
346
+ 'thread_id:text:true',
347
+ 'batch_id:text:true',
348
+ 'first_sequence:bigint:true',
349
+ 'last_sequence:bigint:true',
350
+ 'producer_id_json:text:true',
351
+ ],
352
+ constraints: {
353
+ effect_agent_canonical_batches_pkey: ['p', ['thread_id', 'batch_id']],
354
+ effect_agent_canonical_batches_span: [
355
+ 'c',
356
+ ['first_sequence', 'last_sequence'],
357
+ [
358
+ 'and',
359
+ [
360
+ ['ge', ['column', 'first_sequence'], ['integer', 1]],
361
+ ['ge', ['column', 'last_sequence'], ['column', 'first_sequence']],
362
+ [
363
+ 'lt',
364
+ ['subtract', ['column', 'last_sequence'], ['column', 'first_sequence']],
365
+ ['integer', 256],
366
+ ],
367
+ ],
368
+ ],
369
+ ],
370
+ effect_agent_canonical_batches_thread_id_fkey: [
371
+ 'f',
372
+ ['thread_id'],
373
+ 'effect_agent_threads',
374
+ ['thread_id'],
375
+ ],
376
+ },
377
+ },
378
+ effect_agent_tool_declarations: {
379
+ columns: ['thread_id:text:true', 'settlement_record_id:text:true', 'sequence:bigint:true'],
380
+ constraints: {
381
+ effect_agent_tool_declarations_pkey: ['p', ['thread_id', 'settlement_record_id', 'sequence']],
382
+ effect_agent_tool_declarations_thread_id_sequence_fkey: [
383
+ 'f',
384
+ ['thread_id', 'sequence'],
385
+ 'effect_agent_canonical_records',
386
+ ['thread_id', 'sequence'],
387
+ ],
388
+ },
389
+ },
390
+ effect_agent_record_refusals: {
391
+ columns: ['thread_id:text:true', 'reservation_record_id:text:true', 'sequence:bigint:true'],
392
+ constraints: {
393
+ effect_agent_record_refusals_pkey: ['p', ['thread_id', 'reservation_record_id', 'sequence']],
394
+ effect_agent_record_refusals_thread_id_sequence_fkey: [
395
+ 'f',
396
+ ['thread_id', 'sequence'],
397
+ 'effect_agent_canonical_records',
398
+ ['thread_id', 'sequence'],
399
+ ],
400
+ },
401
+ },
402
+ effect_agent_live_child_reservations: {
403
+ columns: ['reservation_id:text:true', 'thread_id:text:true'],
404
+ constraints: { effect_agent_live_child_reservations_pkey: ['p', ['reservation_id']] },
405
+ },
406
+ effect_agent_record_runs: {
407
+ columns: ['thread_id:text:true', 'run_id:bigint:true', 'sequence:bigint:true'],
408
+ constraints: {
409
+ effect_agent_record_runs_pkey: ['p', ['thread_id', 'run_id', 'sequence']],
410
+ effect_agent_record_runs_thread_id_sequence_fkey: [
411
+ 'f',
412
+ ['thread_id', 'sequence'],
413
+ 'effect_agent_canonical_records',
414
+ ['thread_id', 'sequence'],
415
+ ],
416
+ },
417
+ },
418
+ effect_agent_canonical_records: {
419
+ columns: [
420
+ 'thread_id:text:true',
421
+ 'sequence:bigint:true',
422
+ 'record_id:text:true',
423
+ 'created_at_json:text:true',
424
+ 'envelope_key:bigint:true',
425
+ 'payload_json:text:false',
426
+ 'record_tag:bigint:true',
427
+ 'run_id:bigint:false',
428
+ 'tool_call_id:text:false',
429
+ 'input_kind:text:false',
430
+ 'source_submission_id:text:false',
431
+ 'message_id:text:false',
432
+ 'submission_id:text:false',
433
+ 'application_input:bigint:true',
434
+ 'context_through:bigint:false',
435
+ 'context_kind:text:false',
436
+ 'worker_thread_id:text:false',
437
+ 'handoff:bigint:true',
438
+ ],
439
+ constraints: {
440
+ effect_agent_canonical_records_pkey: ['p', ['thread_id', 'sequence']],
441
+ effect_agent_canonical_records_thread_id_fkey: [
442
+ 'f',
443
+ ['thread_id'],
444
+ 'effect_agent_threads',
445
+ ['thread_id'],
446
+ ],
447
+ effect_agent_canonical_records_thread_id_record_id_key: ['u', ['thread_id', 'record_id']],
448
+ },
449
+ },
450
+ // Retained only for exact predecessor layout validation.
451
+ effect_agent_checkpoints: {
452
+ columns: ['thread_id:text:true', 'through_sequence:bigint:true', 'checkpoint_json:text:true'],
453
+ constraints: {
454
+ effect_agent_checkpoints_pkey: ['p', ['thread_id', 'through_sequence']],
455
+ effect_agent_checkpoints_thread_id_fkey: [
456
+ 'f',
457
+ ['thread_id'],
458
+ 'effect_agent_threads',
459
+ ['thread_id'],
460
+ ],
461
+ },
462
+ },
463
+ effect_agent_child_reservations: {
464
+ columns: [
465
+ 'reservation_id:text:true',
466
+ 'parent_submission_id:text:true',
467
+ 'parent_tool_call_id:text:true',
468
+ 'child_submission_id:text:false',
469
+ 'status:text:true',
470
+ 'allocation_json:text:true',
471
+ 'allocation_digest:text:true',
472
+ 'accounting_json:text:false',
473
+ 'reserved_at:text:true',
474
+ 'release_began_at:text:false',
475
+ 'released_at:text:false',
476
+ ],
477
+ constraints: {
478
+ effect_agent_child_reservatio_parent_submission_id_parent_t_key: [
479
+ 'u',
480
+ ['parent_submission_id', 'parent_tool_call_id'],
481
+ ],
482
+ effect_agent_child_reservations_parent_submission_id_fkey: [
483
+ 'f',
484
+ ['parent_submission_id'],
485
+ 'effect_agent_submissions',
486
+ ['submission_id'],
487
+ ],
488
+ effect_agent_child_reservations_pkey: ['p', ['reservation_id']],
489
+ },
490
+ },
491
+ effect_agent_message_deliveries: {
492
+ columns: [
493
+ 'owner_thread_id:text:true',
494
+ 'message_id:text:true',
495
+ 'version:bigint:true',
496
+ 'state:text:true',
497
+ 'deadline_at_millis:bigint:false',
498
+ 'peer_retained_until_millis:bigint:false',
499
+ 'record_json:text:true',
500
+ 'read_metadata:jsonb:true',
501
+ ],
502
+ constraints: { effect_agent_message_deliveries_pkey: ['p', ['owner_thread_id', 'message_id']] },
503
+ },
504
+ effect_agent_schedules: {
505
+ columns: [
506
+ 'tenant_id:text:true',
507
+ 'owner_id:text:true',
508
+ 'schedule_id:text:true',
509
+ 'deadline_at_millis:bigint:false',
510
+ 'record_json:text:true',
511
+ 'uses_capacity:boolean:true',
512
+ ],
513
+ constraints: { effect_agent_schedules_pkey: ['p', ['tenant_id', 'owner_id', 'schedule_id']] },
514
+ },
515
+ effect_agent_storage_version: {
516
+ columns: ['id:boolean:true', 'version:bigint:true'],
517
+ constraints: {
518
+ effect_agent_storage_version_pkey: ['p', ['id']],
519
+ effect_agent_storage_version_single_row: ['c', ['id'], ['column', 'id']],
520
+ },
521
+ },
522
+ effect_agent_submissions: {
523
+ columns: [
524
+ 'submission_id:text:true',
525
+ 'thread_id:text:true',
526
+ 'queue_sequence:bigint:true',
527
+ 'principal:text:true',
528
+ 'idempotency_key:text:true',
529
+ 'agent_id:text:true',
530
+ 'definition_key:bigint:true',
531
+ 'deployment_id:text:true',
532
+ 'input_json:text:true',
533
+ 'input_digest:text:true',
534
+ 'receipt_id:text:true',
535
+ 'state:text:true',
536
+ 'settled_outcome:text:false',
537
+ 'settled_record_id:text:false',
538
+ 'finalized_at:text:false',
539
+ 'created_at:text:true',
540
+ 'ready_at:text:false',
541
+ 'input_applied_record_id:text:false',
542
+ 'input_applied_sequence:bigint:false',
543
+ 'joined_host_submission_id:text:false',
544
+ 'suspended_reason_json:text:false',
545
+ 'suspended_at:text:false',
546
+ 'unknown_reason:text:false',
547
+ 'unknown_tool_call_ids_json:text:false',
548
+ 'parent_submission_id:text:false',
549
+ 'parent_tool_call_id:text:false',
550
+ 'admission_group:text:false',
551
+ 'admission_fence_json:text:false',
552
+ 'worker_admission_json:text:false',
553
+ 'message_admission_json:text:false',
554
+ ],
555
+ constraints: {
556
+ effect_agent_submissions_pkey: ['p', ['submission_id']],
557
+ effect_agent_submissions_thread_id_principal_idempotency_ke_key: [
558
+ 'u',
559
+ ['thread_id', 'principal', 'idempotency_key'],
560
+ ],
561
+ effect_agent_submissions_thread_id_queue_sequence_key: ['u', ['thread_id', 'queue_sequence']],
562
+ },
563
+ },
564
+ effect_agent_subscription_deliveries: {
565
+ columns: [
566
+ 'tenant_id:text:true',
567
+ 'source_address:text:true',
568
+ 'owner_id:text:true',
569
+ 'subscription_id:text:true',
570
+ 'event_id:text:true',
571
+ 'delivery_key:text:true',
572
+ 'state:text:true',
573
+ 'next_attempt_at_millis:bigint:true',
574
+ 'record_json:text:true',
575
+ 'retry_parked:boolean:true',
576
+ 'observe_settlement:boolean:true',
577
+ ],
578
+ constraints: {
579
+ effect_agent_subscription_del_tenant_id_source_address_deli_key: [
580
+ 'u',
581
+ ['tenant_id', 'source_address', 'delivery_key'],
582
+ ],
583
+ effect_agent_subscription_deliveries_pkey: [
584
+ 'p',
585
+ ['tenant_id', 'source_address', 'owner_id', 'subscription_id', 'event_id'],
586
+ ],
587
+ },
588
+ },
589
+ effect_agent_subscription_events: {
590
+ columns: [
591
+ 'tenant_id:text:true',
592
+ 'source_address:text:true',
593
+ 'event_id:text:true',
594
+ 'source_name:text:true',
595
+ 'source_version:text:true',
596
+ 'matching_key:text:true',
597
+ 'payload_digest:text:true',
598
+ 'cutoff:bigint:true',
599
+ 'cursor:bigint:true',
600
+ 'routing_complete:bigint:true',
601
+ 'tombstone:bigint:true',
602
+ 'next_attempt_at_millis:bigint:true',
603
+ 'record_json:text:true',
604
+ ],
605
+ constraints: {
606
+ effect_agent_subscription_events_pkey: ['p', ['tenant_id', 'source_address', 'event_id']],
607
+ },
608
+ },
609
+ effect_agent_subscription_sequences: {
610
+ columns: [
611
+ 'tenant_id:text:true',
612
+ 'source_address:text:true',
613
+ 'sequence:bigint:true',
614
+ 'event_scan_cursor:text:true',
615
+ 'delivery_scan_cursor:text:true',
616
+ 'recovery_scan_cursor:bigint:true',
617
+ ],
618
+ constraints: {
619
+ effect_agent_subscription_sequences_pkey: ['p', ['tenant_id', 'source_address']],
620
+ },
621
+ },
622
+ effect_agent_subscriptions: {
623
+ columns: [
624
+ 'tenant_id:text:true',
625
+ 'source_address:text:true',
626
+ 'owner_id:text:true',
627
+ 'subscription_id:text:true',
628
+ 'ordinal:bigint:true',
629
+ 'source_name:text:true',
630
+ 'source_version:text:true',
631
+ 'matching_key:text:true',
632
+ 'state:text:true',
633
+ 'expires_at_millis:bigint:false',
634
+ 'recovery_at_millis:bigint:false',
635
+ 'recovery_present:bigint:true',
636
+ 'record_json:text:true',
637
+ ],
638
+ constraints: {
639
+ effect_agent_subscriptions_pkey: [
640
+ 'p',
641
+ ['tenant_id', 'source_address', 'owner_id', 'subscription_id'],
642
+ ],
643
+ effect_agent_subscriptions_tenant_id_source_address_ordinal_key: [
644
+ 'u',
645
+ ['tenant_id', 'source_address', 'ordinal'],
646
+ ],
647
+ },
648
+ },
649
+ effect_agent_rollover_buckets: {
650
+ columns: [
651
+ 'thread_id:text:true',
652
+ 'height:bigint:true',
653
+ 'bucket:bigint:true',
654
+ 'sequence:bigint:true',
655
+ ],
656
+ constraints: {
657
+ effect_agent_rollover_buckets_pkey: ['p', ['thread_id', 'height', 'bucket', 'sequence']],
658
+ effect_agent_rollover_buckets_thread_id_sequence_fkey: [
659
+ 'f',
660
+ ['thread_id', 'sequence'],
661
+ 'effect_agent_canonical_records',
662
+ ['thread_id', 'sequence'],
663
+ ],
664
+ },
665
+ },
666
+ effect_agent_threads: {
667
+ columns: [
668
+ 'thread_id:text:true',
669
+ 'created_at:text:false',
670
+ 'tail_sequence:bigint:true',
671
+ 'work_version:bigint:true',
672
+ 'work_state:text:true',
673
+ 'work_through_sequence:bigint:true',
674
+ 'work_reporting:bigint:true',
675
+ 'work_entry_count:bigint:true',
676
+ 'worker_input_sequence:bigint:false',
677
+ 'worker_settlement_sequence:bigint:false',
678
+ ],
679
+ constraints: { effect_agent_threads_pkey: ['p', ['thread_id']] },
680
+ },
681
+ effect_agent_unknown_resolutions: {
682
+ columns: [
683
+ 'submission_id:text:true',
684
+ 'tool_call_id:text:true',
685
+ 'resolution_kind:text:true',
686
+ 'author:text:true',
687
+ 'reason:text:true',
688
+ 'resolution_json:text:true',
689
+ 'resolved_at:text:true',
690
+ ],
691
+ constraints: {
692
+ effect_agent_unknown_resolutions_pkey: [
693
+ 'p',
694
+ ['submission_id', 'tool_call_id', 'resolution_kind'],
695
+ ],
696
+ effect_agent_unknown_resolutions_submission_id_fkey: [
697
+ 'f',
698
+ ['submission_id'],
699
+ 'effect_agent_submissions',
700
+ ['submission_id'],
701
+ ],
702
+ },
703
+ },
704
+ effect_agent_import_delivery_visits: {
705
+ columns: [
706
+ 'thread_id:text:true',
707
+ 'message_id:text:true',
708
+ 'path_id:text:true',
709
+ 'completed:bigint:true',
710
+ ],
711
+ constraints: { effect_agent_import_delivery_visits_pkey: ['p', ['thread_id', 'message_id']] },
712
+ },
713
+ effect_agent_worker_stops: {
714
+ columns: ['thread_id:text:true', 'terminal:text:false'],
715
+ constraints: { effect_agent_worker_stops_pkey: ['p', ['thread_id']] },
716
+ },
717
+ }
718
+
719
+ const layoutIndexes: Readonly<Record<string, LayoutIndex>> = {
720
+ effect_agent_tool_declarations_sequence: {
721
+ table: 'effect_agent_tool_declarations',
722
+ columns: ['thread_id', 'sequence'],
723
+ },
724
+ effect_agent_record_refusals_sequence: {
725
+ table: 'effect_agent_record_refusals',
726
+ columns: ['thread_id', 'sequence'],
727
+ },
728
+ effect_agent_live_child_reservations_thread: {
729
+ table: 'effect_agent_live_child_reservations',
730
+ columns: ['thread_id', 'reservation_id'],
731
+ },
732
+ effect_agent_canonical_batches_last: {
733
+ table: 'effect_agent_canonical_batches',
734
+ columns: ['thread_id', 'last_sequence'],
735
+ },
736
+ effect_agent_canonical_batches_sequence: {
737
+ table: 'effect_agent_canonical_batches',
738
+ columns: ['thread_id', 'first_sequence'],
739
+ unique: true,
740
+ },
741
+
742
+ effect_agent_import_delivery_visits_path: {
743
+ table: 'effect_agent_import_delivery_visits',
744
+ columns: ['thread_id', 'path_id'],
745
+ },
746
+ effect_agent_records_application_input: {
747
+ table: 'effect_agent_canonical_records',
748
+ columns: ['thread_id', 'sequence'],
749
+ predicate: ['eq', ['column', 'application_input'], ['integer', 1]],
750
+ },
751
+ effect_agent_records_prompt: {
752
+ table: 'effect_agent_canonical_records',
753
+ columns: ['thread_id', 'sequence'],
754
+ predicate: [
755
+ 'in',
756
+ ['column', 'record_tag'],
757
+ PROMPT_EVIDENCE_TAGS.map((tag) => RECORD_TAGS[tag]),
758
+ ],
759
+ },
760
+ effect_agent_records_admitted_input: {
761
+ table: 'effect_agent_canonical_records',
762
+ columns: ['thread_id', 'sequence'],
763
+ predicate: [
764
+ 'and',
765
+ [
766
+ ['eq', ['column', 'record_tag'], ['integer', 30]],
767
+ ['notNull', ['column', 'submission_id']],
768
+ ],
769
+ ],
770
+ },
771
+ effect_agent_records_worker_funding: {
772
+ table: 'effect_agent_canonical_records',
773
+ columns: ['thread_id', 'source_submission_id', 'sequence', 'message_id'],
774
+ predicate: ['eq', ['column', 'record_tag'], ['integer', 34]],
775
+ },
776
+ effect_agent_records_worker_completed: {
777
+ table: 'effect_agent_canonical_records',
778
+ columns: ['thread_id', 'message_id', 'sequence'],
779
+ predicate: ['eq', ['column', 'record_tag'], ['integer', 32]],
780
+ },
781
+ effect_agent_records_worker_stop: {
782
+ table: 'effect_agent_canonical_records',
783
+ columns: ['thread_id', 'worker_thread_id', 'sequence'],
784
+ predicate: ['eq', ['column', 'record_tag'], ['integer', 38]],
785
+ },
786
+ effect_agent_message_deliveries_identity: {
787
+ table: 'effect_agent_message_deliveries',
788
+ columns: ['owner_thread_id', null],
789
+ expressions: ['messageId'],
790
+ },
791
+ effect_agent_message_deliveries_peer_retained: {
792
+ table: 'effect_agent_message_deliveries',
793
+ columns: ['owner_thread_id', 'peer_retained_until_millis', 'message_id'],
794
+ predicate: ['notNull', ['column', 'peer_retained_until_millis']],
795
+ },
796
+ effect_agent_message_deliveries_peer: {
797
+ table: 'effect_agent_message_deliveries',
798
+ columns: ['owner_thread_id', 'message_id'],
799
+ predicate: [
800
+ 'and',
801
+ [
802
+ ['notIn', ['column', 'state'], ['processed', 'refused']],
803
+ ['eq', ['json', 'peer'], ['text', 'true']],
804
+ ],
805
+ ],
806
+ },
807
+ effect_agent_records_tag: {
808
+ table: 'effect_agent_canonical_records',
809
+ columns: ['thread_id', 'record_tag', 'sequence'],
810
+ },
811
+ effect_agent_records_handoff: {
812
+ table: 'effect_agent_canonical_records',
813
+ columns: ['thread_id', 'sequence'],
814
+ predicate: ['eq', ['column', 'handoff'], ['integer', 1]],
815
+ },
816
+ effect_agent_message_deliveries_due: {
817
+ table: 'effect_agent_message_deliveries',
818
+ columns: ['deadline_at_millis', 'owner_thread_id', 'message_id'],
819
+ predicate: ['notNull', ['column', 'deadline_at_millis']],
820
+ },
821
+ effect_agent_message_deliveries_capacity: {
822
+ table: 'effect_agent_message_deliveries',
823
+ columns: ['owner_thread_id', null, 'message_id'],
824
+ expressions: ['workerUpdate'],
825
+ predicate: ['in', ['column', 'state'], ['pending', 'accepted', 'parked']],
826
+ },
827
+ effect_agent_message_deliveries_pending: {
828
+ table: 'effect_agent_message_deliveries',
829
+ columns: ['owner_thread_id', 'message_id'],
830
+ predicate: ['notIn', ['column', 'state'], ['processed', 'refused']],
831
+ },
832
+ effect_agent_records_call: {
833
+ table: 'effect_agent_canonical_records',
834
+ columns: ['thread_id', 'record_tag', 'run_id', 'tool_call_id'],
835
+ predicate: ['notNull', ['column', 'tool_call_id']],
836
+ },
837
+ effect_agent_records_run_input: {
838
+ table: 'effect_agent_canonical_records',
839
+ columns: ['thread_id', 'run_id'],
840
+ predicate: [
841
+ 'and',
842
+ [
843
+ ['eq', ['column', 'record_tag'], ['integer', 30]],
844
+ ['eq', ['column', 'input_kind'], ['text', 'user']],
845
+ ],
846
+ ],
847
+ },
848
+ effect_agent_records_subtree: {
849
+ table: 'effect_agent_canonical_records',
850
+ columns: ['thread_id', 'source_submission_id', 'sequence'],
851
+ predicate: ['eq', ['column', 'record_tag'], ['integer', 22]],
852
+ },
853
+ effect_agent_records_worker_input: {
854
+ table: 'effect_agent_canonical_records',
855
+ columns: ['thread_id', 'message_id'],
856
+ predicate: ['eq', ['column', 'record_tag'], ['integer', 34]],
857
+ },
858
+ effect_agent_schedules_deadline: {
859
+ table: 'effect_agent_schedules',
860
+ columns: ['deadline_at_millis', 'tenant_id', 'owner_id', 'schedule_id'],
861
+ predicate: ['notNull', ['column', 'deadline_at_millis']],
862
+ },
863
+ effect_agent_schedules_owner_deadline: {
864
+ table: 'effect_agent_schedules',
865
+ columns: ['tenant_id', 'owner_id', 'deadline_at_millis', 'schedule_id'],
866
+ predicate: ['notNull', ['column', 'deadline_at_millis']],
867
+ },
868
+ effect_agent_submissions_group: {
869
+ table: 'effect_agent_submissions',
870
+ columns: ['thread_id', 'admission_group'],
871
+ predicate: [
872
+ 'and',
873
+ [
874
+ ['notNull', ['column', 'admission_group']],
875
+ ['ne', ['column', 'state'], ['text', 'settled']],
876
+ ],
877
+ ],
878
+ },
879
+ effect_agent_submissions_joined_host: {
880
+ table: 'effect_agent_submissions',
881
+ columns: ['joined_host_submission_id'],
882
+ predicate: ['notNull', ['column', 'joined_host_submission_id']],
883
+ },
884
+ effect_agent_submissions_nonterminal: {
885
+ table: 'effect_agent_submissions',
886
+ columns: ['thread_id', 'queue_sequence'],
887
+ predicate: ['ne', ['column', 'state'], ['text', 'settled']],
888
+ },
889
+ effect_agent_submissions_parent: {
890
+ table: 'effect_agent_submissions',
891
+ columns: ['parent_submission_id'],
892
+ predicate: ['notNull', ['column', 'parent_submission_id']],
893
+ },
894
+ effect_agent_subscription_deliveries_pending: {
895
+ table: 'effect_agent_subscription_deliveries',
896
+ columns: ['tenant_id', 'source_address', 'state', 'next_attempt_at_millis', 'delivery_key'],
897
+ },
898
+ effect_agent_subscription_deliveries_capacity: {
899
+ table: 'effect_agent_subscription_deliveries',
900
+ columns: ['tenant_id', 'source_address', 'owner_id'],
901
+ predicate: ['in', ['column', 'state'], ['selected', 'prepared']],
902
+ },
903
+ effect_agent_subscription_deliveries_observing: {
904
+ table: 'effect_agent_subscription_deliveries',
905
+ columns: ['tenant_id', 'source_address', 'owner_id'],
906
+ predicate: [
907
+ 'and',
908
+ [
909
+ ['eq', ['column', 'state'], ['text', 'delivered']],
910
+ ['column', 'observe_settlement'],
911
+ ],
912
+ ],
913
+ },
914
+ effect_agent_subscription_deliveries_registration: {
915
+ table: 'effect_agent_subscription_deliveries',
916
+ columns: ['tenant_id', 'source_address', 'owner_id', 'subscription_id', 'delivery_key'],
917
+ },
918
+ effect_agent_subscription_events_pending: {
919
+ table: 'effect_agent_subscription_events',
920
+ columns: [
921
+ 'tenant_id',
922
+ 'source_address',
923
+ 'routing_complete',
924
+ 'next_attempt_at_millis',
925
+ 'event_id',
926
+ ],
927
+ },
928
+ effect_agent_subscriptions_candidates: {
929
+ table: 'effect_agent_subscriptions',
930
+ columns: [
931
+ 'tenant_id',
932
+ 'source_address',
933
+ 'source_name',
934
+ 'source_version',
935
+ 'matching_key',
936
+ 'ordinal',
937
+ ],
938
+ },
939
+ effect_agent_subscriptions_owner: {
940
+ table: 'effect_agent_subscriptions',
941
+ columns: ['tenant_id', 'source_address', 'owner_id', 'ordinal'],
942
+ },
943
+ effect_agent_subscriptions_capacity: {
944
+ table: 'effect_agent_subscriptions',
945
+ columns: ['tenant_id', 'source_address', 'expires_at_millis'],
946
+ predicate: ['in', ['column', 'state'], ['active', 'paused']],
947
+ },
948
+ effect_agent_subscriptions_owner_capacity: {
949
+ table: 'effect_agent_subscriptions',
950
+ columns: ['tenant_id', 'source_address', 'owner_id', 'expires_at_millis'],
951
+ predicate: ['in', ['column', 'state'], ['active', 'paused']],
952
+ },
953
+ effect_agent_subscriptions_recovery: {
954
+ table: 'effect_agent_subscriptions',
955
+ columns: ['tenant_id', 'source_address', 'recovery_at_millis', 'ordinal'],
956
+ predicate: ['notNull', ['column', 'recovery_at_millis']],
957
+ },
958
+ effect_agent_worker_pending: {
959
+ table: 'effect_agent_message_deliveries',
960
+ columns: ['owner_thread_id', null, 'message_id'],
961
+ expressions: ['threadId'],
962
+ predicate: [
963
+ 'and',
964
+ [
965
+ ['in', ['column', 'state'], ['pending', 'parked']],
966
+ ['eq', ['json', 'hasReceipt'], ['text', 'false']],
967
+ ],
968
+ ],
969
+ },
970
+ effect_agent_worker_starts: {
971
+ table: 'effect_agent_message_deliveries',
972
+ columns: ['owner_thread_id', null, null, 'message_id'],
973
+ expressions: ['delegationId', 'targetAgentId'],
974
+ predicate: ['eq', ['json', 'workerStart'], ['text', 'true']],
975
+ },
976
+ }
977
+
978
+ const headerStatement =
979
+ '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))'
980
+
981
+ const quote = (namespace: string) => `"${namespace.replaceAll('"', '""')}"`
982
+
983
+ const qualify = (statement: string, namespace: string) => statement.replaceAll('__NAMESPACE__', quote(namespace))
984
+
985
+ const NameRows = Schema.Array(Schema.Struct({ name: Schema.String, kind: Schema.String }))
986
+
987
+ const ColumnRows = Schema.Array(
988
+ Schema.Struct({
989
+ name: Schema.String,
990
+ column_name: Schema.String,
991
+ type: Schema.String,
992
+ not_null: Schema.Boolean,
993
+ collation: Schema.NullOr(Schema.String),
994
+ }),
995
+ )
996
+
997
+ const ConstraintRows = Schema.Array(
998
+ Schema.Struct({
999
+ table_name: Schema.String,
1000
+ name: Schema.String,
1001
+ kind: Schema.String,
1002
+ columns: Schema.Array(Schema.String),
1003
+ target_table: Schema.NullOr(Schema.String),
1004
+ target_schema: Schema.NullOr(Schema.String),
1005
+ target_columns: Schema.Array(Schema.String),
1006
+ expression: Schema.NullOr(Schema.String),
1007
+ enforcement_ok: Schema.Boolean,
1008
+ }),
1009
+ )
1010
+
1011
+ const IndexRows = Schema.Array(
1012
+ Schema.Struct({
1013
+ name: Schema.String,
1014
+ table_name: Schema.String,
1015
+ columns: Schema.Array(Schema.NullOr(Schema.String)),
1016
+ is_unique: Schema.Boolean,
1017
+ is_primary: Schema.Boolean,
1018
+ expressions: Schema.NullOr(Schema.String),
1019
+ predicate: Schema.NullOr(Schema.String),
1020
+ structure_ok: Schema.Boolean,
1021
+ }),
1022
+ )
1023
+
1024
+ const sameIndexColumns = Schema.toEquivalence(Schema.Array(Schema.NullOr(Schema.String)))
1025
+
1026
+ const matchesIndex = (actual: (typeof IndexRows.Type)[number] | undefined, expected: LayoutIndex) =>
1027
+ actual !== undefined &&
1028
+ actual.structure_ok &&
1029
+ actual.table_name === expected.table &&
1030
+ actual.is_unique === (expected.unique ?? false) &&
1031
+ actual.is_primary === (expected.primary ?? false) &&
1032
+ sameIndexColumns(actual.columns, expected.columns) &&
1033
+ matchesLayoutExpressions(
1034
+ actual.expressions,
1035
+ (expected.expressions ?? []).map((key) => (typeof key === 'string' ? ['json', key] : key)),
1036
+ ) &&
1037
+ matchesLayoutExpressions(
1038
+ actual.predicate,
1039
+ expected.predicate === undefined ? [] : [expected.predicate],
1040
+ )
1041
+
1042
+ const sameStrings = Schema.toEquivalence(Schema.Array(Schema.String))
1043
+
1044
+ const Header = Schema.Tuple([
1045
+ Schema.Struct({
1046
+ singleton: SqlInteger,
1047
+ layout_version: SqlInteger,
1048
+ record_format: Schema.NonEmptyString,
1049
+ }),
1050
+ ])
1051
+
1052
+ const Legacy = Schema.Tuple([Schema.Struct({ id: Schema.Literal(true), version: SqlInteger })])
1053
+
1054
+ const incompatible = (actualVersion: number, message: string) =>
1055
+ PostgresStorageCompatibilityError.make({
1056
+ actualVersion,
1057
+ supportedVersion: CurrentPostgresStorageVersion,
1058
+ message: `${message} Keep the original database; the store was not changed.`,
1059
+ })
1060
+
1061
+ const decode = <A, I>(schema: Schema.Codec<A, I>, value: unknown, table: string) =>
1062
+ Schema.decodeUnknownEffect(schema)(value, { onExcessProperty: 'error' }).pipe(
1063
+ Effect.mapError(() =>
1064
+ PostgresStorageCorruptionError.make({
1065
+ table,
1066
+ rowKey: 'schema',
1067
+ message: 'Malformed storage layout or version header.',
1068
+ })
1069
+ ),
1070
+ )
1071
+
1072
+ export interface PostgresStorageHeader {
1073
+ readonly layoutVersion: number
1074
+ readonly recordFormat: string
1075
+ }
1076
+
1077
+ /** No DDL or transaction acquisition. The caller owns the snapshot/writer lock across subsequent work. */
1078
+ export const inspectPostgresStorage = Effect.fnUntraced(function*(
1079
+ namespace: string,
1080
+ allowReleasedUpgrade = false,
1081
+ ) {
1082
+ const sql = yield* SqlClient.SqlClient
1083
+ const { table, execute } = yield* makeSqlQuery(namespace)
1084
+
1085
+ const names = yield* decode(
1086
+ NameRows,
1087
+ yield* execute(sql<Record<string, unknown>>`
1088
+ SELECT c.relname AS name, c.relkind::text AS kind FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
1089
+ WHERE n.nspname=${namespace} AND starts_with(c.relname, 'effect_agent_')
1090
+ `),
1091
+ 'pg_class',
1092
+ )
1093
+
1094
+ const versionTable = names.find((row) => row.name === 'effect_agent_storage_version')
1095
+ const schemaTable = names.find((row) => row.name === 'effect_agent_schema')
1096
+
1097
+ if (versionTable === undefined) {
1098
+ const independent = new Set([
1099
+ 'effect_agent_activity_metadata',
1100
+ 'effect_agent_activity_metadata_pkey',
1101
+ 'effect_agent_activity_processor_state_v2',
1102
+ 'effect_agent_activity_processor_state_v2_pkey',
1103
+ ])
1104
+
1105
+ if (names.every((row) => independent.has(row.name))) return undefined
1106
+
1107
+ return yield* incompatible(0, 'Unversioned or incomplete Effect Agent storage.')
1108
+ }
1109
+ if (versionTable.kind !== 'r') return yield* incompatible(0, 'Malformed version table.')
1110
+
1111
+ const [legacy] = yield* decode(
1112
+ Legacy,
1113
+ yield* execute(
1114
+ sql<Record<string, unknown>>`SELECT * FROM ${table('effect_agent_storage_version')}`,
1115
+ ),
1116
+ 'effect_agent_storage_version',
1117
+ )
1118
+
1119
+ if (
1120
+ legacy.version !== CurrentPostgresStorageVersion &&
1121
+ !(
1122
+ allowReleasedUpgrade &&
1123
+ (legacy.version === 25 ||
1124
+ legacy.version === 26 ||
1125
+ legacy.version === 27 ||
1126
+ legacy.version === 28 ||
1127
+ legacy.version === 29 ||
1128
+ legacy.version === 30)
1129
+ )
1130
+ ) {
1131
+ return yield* incompatible(legacy.version, `Unsupported storage version ${legacy.version}.`)
1132
+ }
1133
+ if (schemaTable?.kind !== 'r') {
1134
+ return yield* incompatible(legacy.version, 'Missing or malformed singleton schema table.')
1135
+ }
1136
+
1137
+ const [row] = yield* decode(
1138
+ Header,
1139
+ yield* execute(sql<Record<string, unknown>>`SELECT * FROM ${table('effect_agent_schema')}`),
1140
+ 'effect_agent_schema',
1141
+ )
1142
+
1143
+ if (row.singleton !== 1 || row.layout_version !== legacy.version) {
1144
+ return yield* incompatible(row.layout_version, 'Unsupported or conflicting layout headers.')
1145
+ }
1146
+ const header = { layoutVersion: row.layout_version, recordFormat: row.record_format }
1147
+
1148
+ if (header.recordFormat !== CURRENT_RECORD_FORMAT) {
1149
+ return yield* incompatible(
1150
+ header.layoutVersion,
1151
+ `Unsupported record format ${header.recordFormat}.`,
1152
+ )
1153
+ }
1154
+
1155
+ if (
1156
+ legacy.version === 25 &&
1157
+ names.some((row) => Object.hasOwn(layout26IndexStatements, row.name))
1158
+ ) {
1159
+ return yield* incompatible(25, 'Layout 25 contains layout 26 indexes.')
1160
+ }
1161
+
1162
+ const columns = yield* decode(
1163
+ ColumnRows,
1164
+ yield* execute(sql<Record<string, unknown>>`
1165
+ SELECT c.relname AS name, a.attname AS column_name,
1166
+ CASE WHEN a.atttypmod <> -1 THEN ''
1167
+ WHEN a.atttypid='pg_catalog.int8'::regtype THEN 'bigint'
1168
+ WHEN a.atttypid='pg_catalog.bool'::regtype THEN 'boolean'
1169
+ WHEN a.atttypid='pg_catalog.text'::regtype THEN 'text'
1170
+ WHEN a.atttypid='pg_catalog.jsonb'::regtype THEN 'jsonb' ELSE '' END AS type,
1171
+ a.attnotnull AS not_null,
1172
+ cn.nspname || '.' || co.collname AS collation
1173
+ FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace JOIN pg_attribute a ON a.attrelid=c.oid
1174
+ LEFT JOIN pg_collation co ON co.oid=a.attcollation LEFT JOIN pg_namespace cn ON cn.oid=co.collnamespace
1175
+ WHERE n.nspname=${namespace} AND starts_with(c.relname, 'effect_agent_') AND c.relkind='r' AND a.attnum>0 AND NOT a.attisdropped
1176
+ ORDER BY c.relname,a.attnum
1177
+ `),
1178
+ 'pg_attribute',
1179
+ )
1180
+
1181
+ // Shipped expressions use only pinned built-ins. Any function/operator dependency
1182
+ // denotes an extension or user-defined overload, even if its deparsed spelling matches.
1183
+ const constraints = yield* decode(
1184
+ ConstraintRows,
1185
+ yield* execute(sql<Record<string, unknown>>`
1186
+ SELECT c.relname AS table_name, k.conname AS name, k.contype::text AS kind,
1187
+ to_jsonb(ARRAY(SELECT a.attname FROM unnest(k.conkey) WITH ORDINALITY v(attnum, position)
1188
+ JOIN pg_attribute a ON a.attrelid=k.conrelid AND a.attnum=v.attnum ORDER BY v.position)) AS columns,
1189
+ r.relname AS target_table, rn.nspname AS target_schema,
1190
+ to_jsonb(ARRAY(SELECT a.attname FROM unnest(k.confkey) WITH ORDINALITY v(attnum, position)
1191
+ JOIN pg_attribute a ON a.attrelid=k.confrelid AND a.attnum=v.attnum ORDER BY v.position)) AS target_columns,
1192
+ pg_get_expr(k.conbin, k.conrelid, false) AS expression,
1193
+ (k.convalidated AND NOT k.condeferrable AND NOT k.condeferred
1194
+ AND k.conislocal AND k.coninhcount=0 AND k.conparentid=0
1195
+ AND (k.contype<>'c' OR NOT k.connoinherit)
1196
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid='pg_constraint'::regclass
1197
+ AND d.objid=k.oid AND d.refclassid IN ('pg_proc'::regclass, 'pg_operator'::regclass))
1198
+ AND (k.contype NOT IN ('p','u') OR ic.relname=k.conname)
1199
+ AND (k.contype<>'f' OR (k.confupdtype='a' AND k.confdeltype='r' AND k.confmatchtype='s'
1200
+ AND k.conpfeqop <@ ARRAY['pg_catalog.=(text,text)'::regoperator, 'pg_catalog.=(bigint,bigint)'::regoperator]::oid[]
1201
+ AND k.conppeqop <@ ARRAY['pg_catalog.=(text,text)'::regoperator, 'pg_catalog.=(bigint,bigint)'::regoperator]::oid[]
1202
+ AND k.conffeqop <@ ARRAY['pg_catalog.=(text,text)'::regoperator, 'pg_catalog.=(bigint,bigint)'::regoperator]::oid[]))) AS enforcement_ok
1203
+ FROM pg_constraint k JOIN pg_class c ON c.oid=k.conrelid
1204
+ JOIN pg_namespace n ON n.oid=c.relnamespace
1205
+ LEFT JOIN pg_class r ON r.oid=k.confrelid LEFT JOIN pg_namespace rn ON rn.oid=r.relnamespace
1206
+ LEFT JOIN pg_class ic ON ic.oid=k.conindid
1207
+ WHERE n.nspname=${namespace} AND k.contype IN ('p','u','f','c','x')
1208
+ `),
1209
+ 'pg_constraint',
1210
+ )
1211
+
1212
+ // Frozen keys use btree ASC NULLS LAST (indoption=0), default built-in opclasses,
1213
+ // and the column collation, database default for JSON text, or none for integer expressions.
1214
+ const indexes = yield* decode(
1215
+ IndexRows,
1216
+ yield* execute(sql<Record<string, unknown>>`
1217
+ SELECT ic.relname AS name, c.relname AS table_name,
1218
+ to_jsonb(ARRAY(SELECT a.attname FROM unnest(i.indkey) WITH ORDINALITY v(attnum, position)
1219
+ LEFT JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=v.attnum ORDER BY v.position)) AS columns,
1220
+ i.indisunique AS is_unique, i.indisprimary AS is_primary,
1221
+ pg_get_expr(i.indexprs, i.indrelid, false) AS expressions,
1222
+ pg_get_expr(i.indpred, i.indrelid, false) AS predicate,
1223
+ (ic.relkind='i' AND am.amname='btree' AND i.indisvalid AND i.indisready AND i.indislive
1224
+ AND NOT i.indisexclusion AND i.indimmediate AND NOT i.indnullsnotdistinct
1225
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid='pg_class'::regclass
1226
+ AND d.objid=i.indexrelid AND d.refclassid IN ('pg_proc'::regclass, 'pg_operator'::regclass))
1227
+ AND i.indnatts=i.indnkeyatts AND NOT EXISTS (
1228
+ SELECT 1 FROM unnest(i.indkey, i.indcollation, i.indclass, i.indoption)
1229
+ WITH ORDINALITY v(attnum, collation_oid, opclass, options, position)
1230
+ JOIN pg_attribute ia ON ia.attrelid=i.indexrelid AND ia.attnum=v.position
1231
+ LEFT JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=v.attnum
1232
+ JOIN pg_opclass op ON op.oid=v.opclass
1233
+ WHERE v.options<>0 OR NOT op.opcdefault OR op.opcnamespace<>'pg_catalog'::regnamespace
1234
+ OR op.opcintype<>ia.atttypid OR op.opcmethod<>ic.relam
1235
+ OR v.collation_oid<>CASE WHEN v.attnum=0 THEN
1236
+ CASE WHEN ia.atttypid='pg_catalog.text'::regtype THEN 'pg_catalog.default'::regcollation::oid ELSE 0::oid END
1237
+ ELSE a.attcollation END
1238
+ )) AS structure_ok
1239
+ FROM pg_index i JOIN pg_class ic ON ic.oid=i.indexrelid JOIN pg_class c ON c.oid=i.indrelid
1240
+ JOIN pg_namespace n ON n.oid=c.relnamespace JOIN pg_am am ON am.oid=ic.relam
1241
+ WHERE n.nspname=${namespace}
1242
+ `),
1243
+ 'pg_index',
1244
+ )
1245
+
1246
+ const expectedShape: typeof layoutShape = {
1247
+ ...layoutShape,
1248
+ effect_agent_schema: {
1249
+ columns: ['singleton:bigint:true', 'layout_version:bigint:true', 'record_format:text:true'],
1250
+ constraints: {
1251
+ effect_agent_schema_pkey: ['p', ['singleton']],
1252
+ effect_agent_schema_singleton_check: [
1253
+ 'c',
1254
+ ['singleton'],
1255
+ ['eq', ['column', 'singleton'], ['integer', 1]],
1256
+ ],
1257
+ effect_agent_schema_layout_version_check: [
1258
+ 'c',
1259
+ ['layout_version'],
1260
+ ['gt', ['column', 'layout_version'], ['integer', 0]],
1261
+ ],
1262
+ effect_agent_schema_record_format_check: [
1263
+ 'c',
1264
+ ['record_format'],
1265
+ ['gt', ['length', 'record_format'], ['integer', 0]],
1266
+ ],
1267
+ },
1268
+ },
1269
+ }
1270
+
1271
+ for (const [name, expected] of Object.entries(expectedShape)) {
1272
+ if (name === 'effect_agent_checkpoints' && legacy.version >= 29) {
1273
+ if (names.some((row) => row.name === name)) {
1274
+ return yield* incompatible(
1275
+ legacy.version,
1276
+ 'Current layout contains retired generic checkpoints.',
1277
+ )
1278
+ }
1279
+ continue
1280
+ }
1281
+ const tableColumns = columns.filter((row) => row.name === name)
1282
+ const actualConstraints = constraints.filter((row) => row.table_name === name)
1283
+
1284
+ const expectedColumns = legacy.version === 25 && name === 'effect_agent_message_deliveries'
1285
+ ? expected.columns.filter((column) => column !== 'peer_retained_until_millis:bigint:false')
1286
+ : expected.columns
1287
+
1288
+ if (
1289
+ names.find((row) => row.name === name)?.kind !== 'r' ||
1290
+ !sameStrings(
1291
+ // ADD COLUMN appends physically; named-column queries do not depend on that order.
1292
+ tableColumns.map((row) => `${row.column_name}:${row.type}:${row.not_null}`).sort(),
1293
+ [...expectedColumns].sort(),
1294
+ ) ||
1295
+ tableColumns.some(
1296
+ (row) =>
1297
+ row.collation !==
1298
+ (row.type === 'text'
1299
+ ? name === 'effect_agent_schema'
1300
+ ? 'pg_catalog.default'
1301
+ : 'pg_catalog.C'
1302
+ : null),
1303
+ ) ||
1304
+ actualConstraints.length !== Object.keys(expected.constraints).length
1305
+ ) {
1306
+ return yield* incompatible(legacy.version, `Missing or incompatible layout table ${name}.`)
1307
+ }
1308
+
1309
+ for (const [constraintName, constraint] of Object.entries(expected.constraints)) {
1310
+ const actual = actualConstraints.find((row) => row.name === constraintName)
1311
+ const [kind, keyColumns] = constraint
1312
+
1313
+ if (
1314
+ actual === undefined ||
1315
+ !actual.enforcement_ok ||
1316
+ actual.kind !== kind ||
1317
+ !sameStrings(actual.columns, keyColumns) ||
1318
+ actual.target_table !== (constraint[0] === 'f' ? constraint[2] : null) ||
1319
+ actual.target_schema !== (kind === 'f' ? namespace : null) ||
1320
+ !sameStrings(actual.target_columns, constraint[0] === 'f' ? constraint[3] : []) ||
1321
+ !matchesLayoutExpressions(actual.expression, constraint[0] === 'c' ? [constraint[2]] : [])
1322
+ ) {
1323
+ return yield* incompatible(
1324
+ legacy.version,
1325
+ `Missing or incompatible layout constraint ${constraintName}.`,
1326
+ )
1327
+ }
1328
+
1329
+ if (
1330
+ (kind === 'p' || kind === 'u') &&
1331
+ !matchesIndex(
1332
+ indexes.find((row) => row.name === constraintName),
1333
+ {
1334
+ table: name,
1335
+ columns: keyColumns,
1336
+ unique: true,
1337
+ primary: kind === 'p',
1338
+ },
1339
+ )
1340
+ ) {
1341
+ return yield* incompatible(
1342
+ legacy.version,
1343
+ `Missing or incompatible layout index ${constraintName}.`,
1344
+ )
1345
+ }
1346
+ }
1347
+ }
1348
+ for (const [name, expected] of Object.entries(layoutIndexes)) {
1349
+ if (legacy.version === 25 && Object.hasOwn(layout26IndexStatements, name)) continue
1350
+ if (name === 'effect_agent_canonical_batches_last' && legacy.version >= 28) {
1351
+ if (indexes.some((row) => row.name === name)) {
1352
+ return yield* incompatible(
1353
+ legacy.version,
1354
+ `Layout ${legacy.version} contains the retired batch-end index.`,
1355
+ )
1356
+ }
1357
+ continue
1358
+ }
1359
+ if (
1360
+ !matchesIndex(
1361
+ indexes.find((row) => row.name === name),
1362
+ expected,
1363
+ )
1364
+ ) {
1365
+ return yield* incompatible(legacy.version, `Missing or incompatible layout index ${name}.`)
1366
+ }
1367
+ }
1368
+
1369
+ const functions = yield* decode(
1370
+ Schema.Array(
1371
+ Schema.Struct({
1372
+ source: Schema.String,
1373
+ safe: Schema.Boolean,
1374
+ }),
1375
+ ),
1376
+ yield* execute(sql`
1377
+ SELECT p.prosrc AS source, (l.lanname='plpgsql' AND p.prorettype='pg_catalog.trigger'::regtype
1378
+ AND p.pronargs=0 AND NOT p.prosecdef AND p.proconfig IS NULL AND p.prokind='f') AS safe
1379
+ FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace JOIN pg_language l ON l.oid=p.prolang
1380
+ WHERE n.nspname=${namespace} AND p.proname='effect_agent_live_child_mutation'`),
1381
+ 'pg_proc',
1382
+ )
1383
+
1384
+ if (
1385
+ functions.length !== 1 ||
1386
+ !functions[0]?.safe ||
1387
+ functions[0].source !== qualify(liveChildFunctionBody, namespace)
1388
+ ) {
1389
+ return yield* incompatible(
1390
+ legacy.version,
1391
+ 'Missing or incompatible live child trigger function.',
1392
+ )
1393
+ }
1394
+
1395
+ const triggers = yield* decode(
1396
+ Schema.Array(
1397
+ Schema.Struct({
1398
+ name: Schema.String,
1399
+ table_name: Schema.String,
1400
+ type: SqlInteger,
1401
+ enabled: Schema.String,
1402
+ function_name: Schema.String,
1403
+ function_schema: Schema.String,
1404
+ arguments: Schema.String,
1405
+ safe: Schema.Boolean,
1406
+ }),
1407
+ ),
1408
+ yield* execute(sql`
1409
+ SELECT t.tgname AS name, c.relname AS table_name, t.tgtype::bigint AS type,
1410
+ t.tgenabled::text AS enabled, p.proname AS function_name, pn.nspname AS function_schema,
1411
+ encode(t.tgargs, 'hex') AS arguments,
1412
+ (NOT t.tgisinternal AND t.tgconstraint=0 AND NOT t.tgdeferrable AND NOT t.tginitdeferred
1413
+ AND t.tgqual IS NULL AND t.tgnargs=0 AND t.tgattr=''::int2vector) AS safe
1414
+ FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace
1415
+ JOIN pg_proc p ON p.oid=t.tgfoid JOIN pg_namespace pn ON pn.oid=p.pronamespace
1416
+ WHERE n.nspname=${namespace} AND (
1417
+ starts_with(t.tgname, 'effect_agent_live_child_') OR (
1418
+ ${legacy.version < CurrentPostgresStorageVersion} AND NOT t.tgisinternal
1419
+ AND c.relname IN ${sql.in(Object.keys(expectedShape))}
1420
+ )
1421
+ )`),
1422
+ 'pg_trigger',
1423
+ )
1424
+
1425
+ for (const expected of liveChildTriggers) {
1426
+ const actual = triggers.find((trigger) => trigger.name === expected.name)
1427
+
1428
+ if (
1429
+ actual === undefined ||
1430
+ !actual.safe ||
1431
+ actual.table_name !== expected.table ||
1432
+ actual.type !== (expected.event === 'INSERT' ? 5 : expected.event === 'UPDATE' ? 17 : 9) ||
1433
+ actual.enabled !== 'O' ||
1434
+ actual.function_name !== 'effect_agent_live_child_mutation' ||
1435
+ actual.function_schema !== namespace ||
1436
+ actual.arguments !== ''
1437
+ ) {
1438
+ return yield* incompatible(
1439
+ legacy.version,
1440
+ `Missing or incompatible live child trigger ${expected.name}.`,
1441
+ )
1442
+ }
1443
+ }
1444
+ // Backfill must not execute undeclared triggers that could rewrite retained evidence.
1445
+ if (triggers.length !== liveChildTriggers.length) {
1446
+ return yield* incompatible(legacy.version, 'Unexpected Thread storage triggers.')
1447
+ }
1448
+
1449
+ return header
1450
+ })
1451
+
1452
+ /** Export opening never creates a schema, runs layout steps, or initializes a journal. */
1453
+ export const readPostgresStorageHeader = Effect.fnUntraced(function*(namespace: string) {
1454
+ const header = yield* inspectPostgresStorage(namespace)
1455
+
1456
+ if (header === undefined) {
1457
+ return yield* incompatible(0, 'No initialized Thread storage to export.')
1458
+ }
1459
+
1460
+ return header
1461
+ })
1462
+
1463
+ /** The caller owns one writer transaction encompassing inspection, DDL, backfill, and both headers. */
1464
+ export const applyPostgresLayout = Effect.fnUntraced(function*(
1465
+ namespace: string,
1466
+ header: PostgresStorageHeader | undefined,
1467
+ ) {
1468
+ const sql = yield* SqlClient.SqlClient
1469
+ const { table, execute } = yield* makeSqlQuery(namespace)
1470
+
1471
+ if (header !== undefined) {
1472
+ if (header.layoutVersion === CurrentPostgresStorageVersion) return header
1473
+ if (
1474
+ header.layoutVersion !== 25 &&
1475
+ header.layoutVersion !== 26 &&
1476
+ header.layoutVersion !== 27 &&
1477
+ header.layoutVersion !== 28 &&
1478
+ header.layoutVersion !== 29 &&
1479
+ header.layoutVersion !== 30
1480
+ ) {
1481
+ return yield* incompatible(header.layoutVersion, 'Unsupported layout upgrade.')
1482
+ }
1483
+
1484
+ if (header.layoutVersion < 30) {
1485
+ yield* assertLegacyMessagePublicationDrained(namespace).pipe(
1486
+ Effect.mapError((cause) =>
1487
+ cause.reason === 'conflict'
1488
+ ? incompatible(
1489
+ header.layoutVersion,
1490
+ 'Recover work discovery and drain peer, report and update publication using the previous library version before upgrading.',
1491
+ )
1492
+ : PostgresStorageError.make({
1493
+ operation: cause.operation,
1494
+ message: cause.message,
1495
+ cause,
1496
+ })
1497
+ ),
1498
+ )
1499
+ }
1500
+
1501
+ yield* upgradeSqlThreadWorkIndex(namespace).pipe(
1502
+ Effect.mapError((cause) =>
1503
+ PostgresStorageError.make({ operation: cause.operation, message: cause.message, cause })
1504
+ ),
1505
+ )
1506
+
1507
+ // READ COMMITTED must observe in-flight writers before reading checkpoints for conversion.
1508
+ if (header.layoutVersion < 27) {
1509
+ yield* execute(
1510
+ sql`LOCK TABLE ${table('effect_agent_executions')} IN SHARE ROW EXCLUSIVE MODE`,
1511
+ )
1512
+ }
1513
+
1514
+ if (header.layoutVersion === 25) {
1515
+ yield* execute(
1516
+ sql`ALTER TABLE ${table('effect_agent_message_deliveries')} ADD COLUMN peer_retained_until_millis BIGINT`,
1517
+ )
1518
+ yield* backfillPeerMessageRetention(namespace).pipe(
1519
+ Effect.catchTag('MessageDeliveryError', (cause) =>
1520
+ PostgresStorageCorruptionError.make({
1521
+ table: 'effect_agent_message_deliveries',
1522
+ rowKey: 'layout-25-upgrade',
1523
+ message: `Invalid retained delivery during layout upgrade: ${cause.operation}.`,
1524
+ })),
1525
+ )
1526
+ for (const statement of Object.values(layout26IndexStatements)) {
1527
+ yield* sql.unsafe(qualify(statement, namespace)).withoutTransform
1528
+ }
1529
+ }
1530
+ if (header.layoutVersion < 27) {
1531
+ yield* upgradeExecutionCheckpoints(namespace).pipe(
1532
+ Effect.catchTag('ThreadStoreError', (cause) =>
1533
+ PostgresStorageCorruptionError.make({
1534
+ table: 'effect_agent_executions',
1535
+ rowKey: 'upgrade',
1536
+ message: `Invalid retained execution; upgrade rolled back: ${cause.message}`,
1537
+ })),
1538
+ )
1539
+ }
1540
+ if (header.layoutVersion < 30) {
1541
+ if (header.layoutVersion <= 27) {
1542
+ yield* execute(sql`DROP INDEX ${table('effect_agent_canonical_batches_last')}`)
1543
+ }
1544
+ // Retire only the derived generic snapshot cache. This step preserves the exact
1545
+ // canonical and operational bytes; earlier layout conversions remain independent.
1546
+ if (header.layoutVersion < 29) {
1547
+ yield* execute(sql`DROP TABLE ${table('effect_agent_checkpoints')}`)
1548
+ }
1549
+ yield* execute(
1550
+ sql`DROP INDEX IF EXISTS ${table('effect_agent_records_delivery_predecessor')}`,
1551
+ )
1552
+ yield* execute(sql`DROP INDEX IF EXISTS ${table('effect_agent_work_entries_message')}`)
1553
+ yield* execute(sql`DROP INDEX IF EXISTS ${table('effect_agent_work_entries_peer')}`)
1554
+ yield* createSqlThreadWorkTables(namespace).pipe(
1555
+ Effect.mapError((cause) =>
1556
+ PostgresStorageError.make({ operation: cause.operation, message: cause.message, cause })
1557
+ ),
1558
+ )
1559
+ }
1560
+ yield* execute(
1561
+ sql`UPDATE ${table('effect_agent_storage_version')} SET version=${CurrentPostgresStorageVersion} WHERE id=TRUE`,
1562
+ )
1563
+ yield* execute(
1564
+ sql`UPDATE ${table('effect_agent_schema')} SET layout_version=${CurrentPostgresStorageVersion} WHERE singleton=1`,
1565
+ )
1566
+
1567
+ // The enclosing transaction also rolls back DDL and backfill if final validation fails.
1568
+ return yield* readPostgresStorageHeader(namespace)
1569
+ }
1570
+ for (const statement of layoutStatements) {
1571
+ yield* sql.unsafe(qualify(statement, namespace)).withoutTransform
1572
+ }
1573
+ yield* createSqlThreadWorkTables(namespace).pipe(
1574
+ Effect.mapError((cause) =>
1575
+ PostgresStorageError.make({ operation: cause.operation, message: cause.message, cause })
1576
+ ),
1577
+ )
1578
+ yield* sql.unsafe(qualify(headerStatement, namespace)).withoutTransform
1579
+ yield* execute(
1580
+ sql`INSERT INTO ${
1581
+ table('effect_agent_storage_version')
1582
+ } (id, version) VALUES (TRUE, ${CurrentPostgresStorageVersion})`,
1583
+ )
1584
+ yield* execute(
1585
+ sql`INSERT INTO ${
1586
+ table('effect_agent_schema')
1587
+ } (singleton, layout_version, record_format) VALUES (1, ${CurrentPostgresStorageVersion}, ${CURRENT_RECORD_FORMAT})`,
1588
+ )
1589
+
1590
+ return yield* readPostgresStorageHeader(namespace)
1591
+ })