1use sqlx::postgres::PgPoolOptions;
22use sqlx::{Executor as _, Row as _};
23
24use super::{Error, Pool};
25
26const SCHEMA: &str = r#"
32-- Every base objectiveai table lives in the `objectiveai` schema —
33-- one namespace for what used to be split across `public` and
34-- `logs`. Plugin/tool compartments (see `db::compartment`) get
35-- readonly over exactly this schema and never touch `public`.
36CREATE SCHEMA IF NOT EXISTS objectiveai;
37
38-- `tag_groups`: explicit grouping container that lets many tags
39-- share one resolved `AgentSpec` + parent lineage. The cli's
40-- `agents tags apply` either creates a group on the fly (for the
41-- `--agent` arm) or joins the new tag into an existing group (for
42-- the `--agent-tag` arm). When any one tag in a group is picked
43-- up by a live spawn, the conduit-driven upgrade flips every tag
44-- in the group from `tag_group` to `agent_instance_hierarchy` in
45-- one UPDATE inside the read transaction — see
46-- `db::message_queue::read_pending_and_upgrade_tag`.
47CREATE TABLE IF NOT EXISTS objectiveai.tag_groups (
48 id BIGSERIAL PRIMARY KEY,
49 -- Resolved `agents::spawn::AgentSpec`; serialized
50 -- as JSONB. References are resolved at apply-time, never at
51 -- spawn-time, so this column is always inline-or-remote.
52 agent_spec JSONB NOT NULL,
53 -- The lineage prefix the spawn-by-tag will compose its AIH
54 -- against. NOT NULL: callers (CLI handlers) substitute the
55 -- cli's own `Config.agent_instance_hierarchy` when the user
56 -- omits the argument.
57 parent_agent_instance_hierarchy TEXT NOT NULL,
58 created_at BIGINT NOT NULL
59);
60
61CREATE TABLE IF NOT EXISTS objectiveai.tags (
62 name TEXT PRIMARY KEY NOT NULL,
63 -- BOUND when set: this tag resolves to a live AIH.
64 agent_instance_hierarchy TEXT,
65 -- GROUPED when set: this tag's resolution is the tag_group
66 -- row's (agent_spec, parent). Exactly one of the two columns
67 -- is non-null at any time.
68 tag_group BIGINT,
69 updated_at BIGINT NOT NULL,
70 CHECK (
71 (agent_instance_hierarchy IS NOT NULL AND tag_group IS NULL)
72 OR
73 (agent_instance_hierarchy IS NULL AND tag_group IS NOT NULL)
74 ),
75 FOREIGN KEY (tag_group) REFERENCES objectiveai.tag_groups(id) ON DELETE CASCADE
76);
77CREATE INDEX IF NOT EXISTS tags_hierarchy_idx
78 ON objectiveai.tags(agent_instance_hierarchy);
79CREATE INDEX IF NOT EXISTS tags_tag_group_idx
80 ON objectiveai.tags(tag_group);
81
82-- `laboratory_attachments`: laboratory IDs attached to an agent target.
83-- The target is EITHER an `agent_instance_hierarchy` (AIH) OR a `tag`
84-- (never both — same exclusivity CHECK as `tags`/`message_queue`). A
85-- given laboratory is attached at most once per target, enforced by a
86-- partial unique index per target column. `laboratory_id` is an opaque
87-- external identifier (no labs table, no FK).
88CREATE TABLE IF NOT EXISTS objectiveai.laboratory_attachments (
89 id BIGSERIAL PRIMARY KEY,
90 agent_instance_hierarchy TEXT,
91 tag TEXT,
92 laboratory_id TEXT NOT NULL,
93 created_at BIGINT NOT NULL,
94 CHECK (
95 (agent_instance_hierarchy IS NOT NULL AND tag IS NULL)
96 OR
97 (agent_instance_hierarchy IS NULL AND tag IS NOT NULL)
98 )
99);
100CREATE UNIQUE INDEX IF NOT EXISTS laboratory_attachments_tag_unique_idx
101 ON objectiveai.laboratory_attachments(tag, laboratory_id)
102 WHERE tag IS NOT NULL;
103CREATE UNIQUE INDEX IF NOT EXISTS laboratory_attachments_aih_unique_idx
104 ON objectiveai.laboratory_attachments(agent_instance_hierarchy, laboratory_id)
105 WHERE agent_instance_hierarchy IS NOT NULL;
106
107-- Latest continuation token per agent_instance_hierarchy. Upserted
108-- per streamed chunk by the chunk-yielder loops in `agents spawn`
109-- and `functions execute`. No GC, no history — querying it gives
110-- the single most recent continuation for that AIH.
111CREATE TABLE IF NOT EXISTS objectiveai.agent_continuations (
112 agent_instance_hierarchy TEXT PRIMARY KEY NOT NULL,
113 continuation TEXT NOT NULL,
114 updated_at BIGINT NOT NULL
115);
116
117CREATE TABLE IF NOT EXISTS objectiveai.message_queue (
118 id BIGSERIAL PRIMARY KEY,
119 agent_instance_hierarchy TEXT,
120 agent_tag TEXT,
121 -- AIH of the caller who enqueued this row (sourced from
122 -- `ctx.config.agent_instance_hierarchy` at enqueue time).
123 -- Surfaced on `agents queue read pending` so callers can
124 -- audit "who asked for this" without a join.
125 sender_agent_instance_hierarchy TEXT NOT NULL,
126 -- Content rows live in `message_queue_contents` (PK
127 -- `id BIGSERIAL`, FK `message_queue_id` → here). Readers
128 -- JOIN; no denormalized JSON shadow column lives here.
129 enqueued_at BIGINT NOT NULL,
130 key TEXT,
131 -- Soft-delete marker. Rows start at TRUE and flip to FALSE
132 -- when consumed (either via the LogWriter's MessageQueue row
133 -- write or via `db::message_queue::delete_by_id`'s in-flight
134 -- lock-race-released path). Every reader filters
135 -- `WHERE active = TRUE`, so flipped rows are invisible.
136 -- Content stays around in `message_queue_contents` (the old
137 -- `ON DELETE CASCADE` chain no longer fires because we don't
138 -- DELETE).
139 active BOOLEAN NOT NULL DEFAULT TRUE,
140 CHECK (
141 (agent_instance_hierarchy IS NOT NULL AND agent_tag IS NULL)
142 OR
143 (agent_instance_hierarchy IS NULL AND agent_tag IS NOT NULL)
144 )
145);
146CREATE INDEX IF NOT EXISTS message_queue_hierarchy_idx
147 ON objectiveai.message_queue(agent_instance_hierarchy, id)
148 WHERE agent_instance_hierarchy IS NOT NULL;
149CREATE INDEX IF NOT EXISTS message_queue_tag_idx
150 ON objectiveai.message_queue(agent_tag, id)
151 WHERE agent_tag IS NOT NULL;
152-- Per-target idempotency keys. The `AND active = TRUE` clause
153-- means inactive prior rows don't count toward uniqueness — an
154-- `agents message --enqueue-with-key k` after a prior consumption
155-- inserts cleanly without UNIQUE-violating the soft-flipped row.
156CREATE UNIQUE INDEX IF NOT EXISTS message_queue_key_hierarchy_unique_idx
157 ON objectiveai.message_queue(agent_instance_hierarchy, key)
158 WHERE agent_instance_hierarchy IS NOT NULL
159 AND key IS NOT NULL
160 AND active = TRUE;
161CREATE UNIQUE INDEX IF NOT EXISTS message_queue_key_tag_unique_idx
162 ON objectiveai.message_queue(agent_tag, key)
163 WHERE agent_tag IS NOT NULL
164 AND key IS NOT NULL
165 AND active = TRUE;
166
167CREATE TABLE IF NOT EXISTS objectiveai.message_queue_contents (
168 id BIGSERIAL PRIMARY KEY,
169 message_queue_id BIGINT NOT NULL,
170 kind TEXT NOT NULL
171 CHECK (kind IN ('text','image','audio','video','file')),
172 FOREIGN KEY (message_queue_id) REFERENCES objectiveai.message_queue(id) ON DELETE CASCADE
173);
174CREATE INDEX IF NOT EXISTS message_queue_contents_parent_idx
175 ON objectiveai.message_queue_contents(message_queue_id);
176
177CREATE TABLE IF NOT EXISTS objectiveai.message_queue_texts (
178 id BIGINT PRIMARY KEY,
179 text TEXT NOT NULL,
180 FOREIGN KEY (id) REFERENCES objectiveai.message_queue_contents(id) ON DELETE CASCADE
181);
182
183CREATE TABLE IF NOT EXISTS objectiveai.message_queue_images (
184 id BIGINT PRIMARY KEY,
185 url TEXT NOT NULL,
186 detail TEXT,
187 FOREIGN KEY (id) REFERENCES objectiveai.message_queue_contents(id) ON DELETE CASCADE
188);
189
190CREATE TABLE IF NOT EXISTS objectiveai.message_queue_audios (
191 id BIGINT PRIMARY KEY,
192 data TEXT NOT NULL,
193 format TEXT NOT NULL,
194 FOREIGN KEY (id) REFERENCES objectiveai.message_queue_contents(id) ON DELETE CASCADE
195);
196
197CREATE TABLE IF NOT EXISTS objectiveai.message_queue_videos (
198 id BIGINT PRIMARY KEY,
199 url TEXT NOT NULL,
200 FOREIGN KEY (id) REFERENCES objectiveai.message_queue_contents(id) ON DELETE CASCADE
201);
202
203CREATE TABLE IF NOT EXISTS objectiveai.message_queue_files (
204 id BIGINT PRIMARY KEY,
205 file_data TEXT,
206 file_id TEXT,
207 filename TEXT,
208 file_url TEXT,
209 FOREIGN KEY (id) REFERENCES objectiveai.message_queue_contents(id) ON DELETE CASCADE
210);
211
212-- AFTER-UPDATE trigger on `message_queue.active`: every soft-flip
213-- (TRUE → FALSE) emits a `NOTIFY message_queue_inactive '<id>'`
214-- so the cli's `db::message_queue::subscribe_delivered` listener
215-- wakes up the instant a consumption flip lands. Pure native
216-- LISTEN/NOTIFY — no polling. We no longer hard-delete, so the
217-- prior AFTER DELETE trigger is gone.
218CREATE OR REPLACE FUNCTION objectiveai.notify_message_queue_inactive()
219RETURNS trigger AS $$
220BEGIN
221 IF OLD.active = TRUE AND NEW.active = FALSE THEN
222 PERFORM pg_notify('message_queue_inactive', NEW.id::text);
223 END IF;
224 RETURN NEW;
225END;
226$$ LANGUAGE plpgsql;
227CREATE OR REPLACE TRIGGER message_queue_inactive_notify
228AFTER UPDATE OF active ON objectiveai.message_queue
229FOR EACH ROW EXECUTE FUNCTION objectiveai.notify_message_queue_inactive();
230
231"#;
232
233const LOGS_SCHEMA: &str = include_str!("logs/schema.sql");
238
239const READER_GROUP: &str = r#"
249DO $$
250BEGIN
251 CREATE ROLE objectiveai_read NOLOGIN;
252EXCEPTION WHEN duplicate_object THEN
253 NULL;
254END
255$$;
256GRANT USAGE ON SCHEMA objectiveai TO objectiveai_read;
257GRANT SELECT ON ALL TABLES IN SCHEMA objectiveai TO objectiveai_read;
258ALTER DEFAULT PRIVILEGES IN SCHEMA objectiveai GRANT SELECT ON TABLES TO objectiveai_read;
259"#;
260
261pub async fn init(url: &str, database: &str) -> Result<Pool, Error> {
268 let app_url = format!(
269 "{}/{}",
270 url.trim_end_matches('/'),
271 percent_encoding::utf8_percent_encode(database, percent_encoding::NON_ALPHANUMERIC),
272 );
273
274 let admin = PgPoolOptions::new()
278 .max_connections(1)
279 .connect(url)
280 .await
281 .map_err(|e| unreachable_hint(url, e))?;
282 let exists: bool = {
283 let row = sqlx::query("SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)")
284 .bind(database)
285 .fetch_one(&admin)
286 .await?;
287 row.try_get::<bool, _>(0)?
288 };
289 if !exists {
290 let quoted = database.replace('"', "\"\"");
300 match admin
301 .execute(format!("CREATE DATABASE \"{quoted}\"").as_str())
302 .await
303 {
304 Ok(_) => {}
305 Err(sqlx::Error::Database(db))
312 if matches!(db.code().as_deref(), Some("42P04") | Some("23505")) => {}
313 Err(e) => return Err(e.into()),
314 }
315 }
316 admin.close().await;
317
318 let pool = PgPoolOptions::new()
331 .max_connections(8)
332 .connect(&app_url)
333 .await
334 .map_err(|e| unreachable_hint(&app_url, e))?;
335 {
336 const SCHEMA_LOCK_KEY: i64 = 0x0B7EC71AE_15CBE_AA_i64;
341 let mut conn = pool.acquire().await?;
342 sqlx::query("SELECT pg_advisory_lock($1)")
343 .bind(SCHEMA_LOCK_KEY)
344 .execute(&mut *conn)
345 .await?;
346 let apply_result: Result<(), Error> = async {
347 conn.execute(SCHEMA).await?;
348 conn.execute(LOGS_SCHEMA).await?;
349 conn.execute(READER_GROUP).await?;
350 Ok(())
351 }
352 .await;
353 let _ = sqlx::query("SELECT pg_advisory_unlock($1)")
356 .bind(SCHEMA_LOCK_KEY)
357 .execute(&mut *conn)
358 .await;
359 apply_result?;
360 }
361
362 Ok(Pool(pool))
363}
364
365pub(crate) fn config_url(address: &str, user: &str, password: &str) -> String {
372 let user =
373 percent_encoding::utf8_percent_encode(user, percent_encoding::NON_ALPHANUMERIC);
374 let password =
375 percent_encoding::utf8_percent_encode(password, percent_encoding::NON_ALPHANUMERIC);
376 format!("postgres://{user}:{password}@{address}")
377}
378
379fn unreachable_hint(url: &str, source: sqlx::Error) -> Error {
386 Error::DbUnreachable {
387 url: redact_url_password(url),
388 source: Box::new(source),
389 }
390}
391
392fn redact_url_password(url: &str) -> String {
397 let Some(scheme_end) = url.find("://") else {
398 return url.to_string();
399 };
400 let rest = &url[scheme_end + 3..];
401 let authority = &rest[..rest.find('/').unwrap_or(rest.len())];
402 let Some(at) = authority.rfind('@') else {
403 return url.to_string();
404 };
405 let userinfo = &authority[..at];
406 let Some(colon) = userinfo.find(':') else {
407 return url.to_string();
408 };
409 format!(
410 "{}:***{}",
411 &url[..scheme_end + 3 + colon],
412 &url[scheme_end + 3 + at..],
413 )
414}
415
416#[cfg(test)]
417mod tests {
418 use super::redact_url_password;
419
420 #[test]
421 fn redact_url_password_cases() {
422 assert_eq!(
423 redact_url_password("postgresql://postgres:s3cr%40t@127.0.0.1:5432"),
424 "postgresql://postgres:***@127.0.0.1:5432",
425 );
426 assert_eq!(
427 redact_url_password("postgres://u:p@h:5432/objectiveai"),
428 "postgres://u:***@h:5432/objectiveai",
429 );
430 assert_eq!(
432 redact_url_password("postgres://postgres@127.0.0.1:5432"),
433 "postgres://postgres@127.0.0.1:5432",
434 );
435 assert_eq!(
437 redact_url_password("postgres://127.0.0.1:5432/db"),
438 "postgres://127.0.0.1:5432/db",
439 );
440 assert_eq!(redact_url_password("127.0.0.1:5432"), "127.0.0.1:5432");
442 }
443}