Skip to main content

slabs_db/
lib.rs

1//! Raw-SQL database library for Slabs.
2//!
3//! This crate owns the tuned `SQLite` WAL wrapper ([`Db`]), the optional `PostgreSQL` wrapper ([`PgDb`]),
4//! URL engine detection ([`DbEngine`]), framework system schemas ([`SYSTEM_SCHEMA_SQL`], [`POSTGRES_SYSTEM_SCHEMA_SQL`]),
5//! and FTS5 query escaping ([`fts5_query`]). It also re-exports [`QueryBuilder`] for dynamic parameterized SQL.
6//!
7//! # Owned types and system tables
8//!
9//! Calling [`Db::init_system_tables`], [`Db::migrate`], or [`Db::migrate_dir`] (and the matching [`PgDb`] methods)
10//! creates these 12 framework tables if they do not exist:
11//!
12//! - `slabs_sessions`
13//! - `slabs_magic_links`
14//! - `slabs_access_tokens`
15//! - `slabs_jobs`
16//! - `slabs_cache`
17//! - `slabs_mail_outbox`
18//! - `slabs_blobs`
19//! - `slabs_webhooks`
20//! - `slabs_webhook_deliveries`
21//! - `slabs_idempotency_keys`
22//! - `slabs_audit_log`
23//! - `slabs_incidents`
24//!
25//! # Invariants
26//!
27//! - **Split WAL pools on file-backed `SQLite`**: [`Db::reader`] returns a read-only pool with up to 16 connections for concurrent `SELECT` queries. [`Db::writer`] and [`Db::pool`] return a dedicated single-connection writer pool (`max_connections(1)`).
28//! - **Explicit `BEGIN IMMEDIATE` transactions**: [`Db::begin`] opens a `BEGIN IMMEDIATE` transaction on the single writer pool. Use it for multi-step mutations so `SQLite` acquires the write lock up front and avoids `SQLITE_BUSY_SNAPSHOT` lock-upgrade failures.
29//! - **In-memory test databases share one connection**: when `database_url` is `"sqlite::memory:"` or contains `"mode=memory"`, [`Db::connect`] clones the single writer pool for [`Db::reader`] because `SQLite` isolates in-memory databases per connection.
30//! - **Tuned `SQLite` pragmas**: [`Db::connect`] sets `foreign_keys = ON`, `synchronous = NORMAL`, `cache_size = -64000`, `temp_store = MEMORY`, `trusted_schema = OFF`, `secure_delete = ON`, and `busy_timeout` (10s writer, 5s reader). File-backed databases also enable `journal_mode = WAL` and `mmap_size = 268435456` (256 MiB).
31//! - **Parameterized SQL only**: always bind untrusted input with `sqlx::query`, `sqlx::query_as`, or [`QueryBuilder`]. Never interpolate user strings into SQL text.
32//! - **FTS5 search escaping**: pass untrusted search strings through [`fts5_query`] before binding to an FTS5 `MATCH ?` clause. It strips double quotes and wraps each whitespace token as `"token"*` joined with `AND`.
33//!
34//! # Usage
35//!
36//! ```rust,no_run
37//! use slabs_core::SlabResult;
38//! use slabs_db::{fts5_query, Db};
39//!
40//! async fn example() -> SlabResult<()> {
41//!     let db = Db::connect("sqlite://app.db?mode=rwc").await?;
42//!     db.init_system_tables().await?;
43//!
44//!     // Concurrent SELECT on the read-only WAL pool.
45//!     let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM slabs_jobs")
46//!         .fetch_one(db.reader())
47//!         .await?;
48//!
49//!     // Multi-step write inside an explicit BEGIN IMMEDIATE transaction.
50//!     let mut tx = db.begin().await?;
51//!     sqlx::query("DELETE FROM slabs_cache WHERE cache_key = ?")
52//!         .bind("stale_key")
53//!         .execute(&mut *tx)
54//!         .await?;
55//!     tx.commit().await?;
56//!
57//!     // Safe FTS5 query construction for user input.
58//!     if let Some(match_expr) = fts5_query("deploy \"prod\"") {
59//!         assert_eq!(match_expr, "\"deploy\"* AND \"prod\"*");
60//!     }
61//!     let _ = count;
62//!     Ok(())
63//! }
64//! ```
65
66use slabs_core::{SlabError, SlabResult};
67use sqlx::{
68    migrate::Migrator,
69    postgres::PgPoolOptions,
70    sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
71    PgPool, Postgres, Sqlite, SqlitePool, Transaction,
72};
73use std::fmt::Write as _;
74use std::path::Path;
75use std::str::FromStr;
76use std::time::Duration;
77
78pub use sqlx::QueryBuilder;
79
80/// Database engine detected from a `DATABASE_URL` string.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum DbEngine {
83    /// Embedded `SQLite` database.
84    Sqlite,
85    /// Networked `PostgreSQL` database.
86    Postgres,
87}
88
89impl DbEngine {
90    /// Detects the [`DbEngine`] from a database connection URL.
91    ///
92    /// Returns [`DbEngine::Postgres`] when the trimmed, lowercased URL starts with
93    /// `"postgres://"` or `"postgresql://"`, and [`DbEngine::Sqlite`] otherwise.
94    #[must_use]
95    pub fn detect(database_url: &str) -> Self {
96        let lower = database_url.trim().to_ascii_lowercase();
97        if lower.starts_with("postgres://") || lower.starts_with("postgresql://") {
98            Self::Postgres
99        } else {
100            Self::Sqlite
101        }
102    }
103}
104
105/// Framework-owned `SQLite` DDL for the 12 system tables and their indexes.
106///
107/// Applied idempotently by [`Db::init_system_tables`], [`Db::migrate`], and [`Db::migrate_dir`].
108pub const SYSTEM_SCHEMA_SQL: &str = r"
109CREATE TABLE IF NOT EXISTS slabs_sessions (
110    id TEXT PRIMARY KEY NOT NULL,
111    user_id TEXT NOT NULL,
112    role TEXT NOT NULL DEFAULT 'member',
113    token_hash TEXT NOT NULL UNIQUE,
114    expires_at TEXT NOT NULL,
115    created_at TEXT NOT NULL
116);
117CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
118CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);
119
120CREATE TABLE IF NOT EXISTS slabs_magic_links (
121    id TEXT PRIMARY KEY NOT NULL,
122    email TEXT NOT NULL,
123    purpose TEXT NOT NULL DEFAULT 'sign_in',
124    code_hash TEXT NOT NULL UNIQUE,
125    expires_at TEXT NOT NULL,
126    created_at TEXT NOT NULL
127);
128CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);
129
130CREATE TABLE IF NOT EXISTS slabs_access_tokens (
131    id TEXT PRIMARY KEY NOT NULL,
132    user_id TEXT NOT NULL,
133    role TEXT NOT NULL DEFAULT 'member',
134    description TEXT NOT NULL DEFAULT '',
135    permission TEXT NOT NULL DEFAULT 'write',
136    token_hash TEXT NOT NULL UNIQUE,
137    last_used_at TEXT,
138    expires_at TEXT,
139    created_at TEXT NOT NULL
140);
141CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);
142
143CREATE TABLE IF NOT EXISTS slabs_jobs (
144    id TEXT PRIMARY KEY NOT NULL,
145    job_name TEXT NOT NULL,
146    queue TEXT NOT NULL DEFAULT 'default',
147    payload_json TEXT NOT NULL,
148    status TEXT NOT NULL DEFAULT 'pending',
149    attempts INTEGER NOT NULL DEFAULT 0,
150    max_attempts INTEGER NOT NULL DEFAULT 5,
151    run_at TEXT NOT NULL,
152    locked_until TEXT,
153    last_error TEXT,
154    created_at TEXT NOT NULL,
155    updated_at TEXT NOT NULL
156);
157CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);
158CREATE INDEX IF NOT EXISTS idx_slabs_jobs_locked_until ON slabs_jobs(status, locked_until);
159
160CREATE TABLE IF NOT EXISTS slabs_cache (
161    cache_key TEXT PRIMARY KEY NOT NULL,
162    value_text TEXT NOT NULL,
163    expires_at TEXT NOT NULL,
164    updated_at TEXT NOT NULL
165);
166CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);
167
168CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
169    id TEXT PRIMARY KEY NOT NULL,
170    from_addr TEXT NOT NULL,
171    to_addr TEXT NOT NULL,
172    subject TEXT NOT NULL,
173    text_body TEXT NOT NULL,
174    html_body TEXT,
175    sent_at TEXT NOT NULL
176);
177
178CREATE TABLE IF NOT EXISTS slabs_blobs (
179    id TEXT PRIMARY KEY NOT NULL,
180    filename TEXT NOT NULL,
181    content_type TEXT NOT NULL,
182    byte_size INTEGER NOT NULL,
183    checksum_sha256 TEXT NOT NULL,
184    storage_key TEXT NOT NULL UNIQUE,
185    scope TEXT,
186    created_at TEXT NOT NULL
187);
188
189CREATE TABLE IF NOT EXISTS slabs_webhooks (
190    id TEXT PRIMARY KEY NOT NULL,
191    scope_id TEXT NOT NULL,
192    name TEXT NOT NULL,
193    url TEXT NOT NULL,
194    signing_secret TEXT NOT NULL,
195    subscribed_actions_json TEXT NOT NULL,
196    active INTEGER NOT NULL DEFAULT 1,
197    created_at TEXT NOT NULL
198);
199CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);
200
201CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
202    id TEXT PRIMARY KEY NOT NULL,
203    webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
204    action TEXT NOT NULL,
205    payload_json TEXT NOT NULL,
206    signature TEXT NOT NULL,
207    status TEXT NOT NULL DEFAULT 'pending',
208    response_status INTEGER,
209    last_error TEXT,
210    created_at TEXT NOT NULL,
211    delivered_at TEXT
212);
213CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);
214
215CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
216    scope TEXT NOT NULL,
217    key TEXT NOT NULL,
218    response_json TEXT,
219    expires_at TEXT,
220    created_at TEXT NOT NULL,
221    PRIMARY KEY (scope, key)
222);
223CREATE INDEX IF NOT EXISTS idx_slabs_idempotency_keys_expires_at ON slabs_idempotency_keys(expires_at);
224
225CREATE TABLE IF NOT EXISTS slabs_audit_log (
226    id TEXT PRIMARY KEY NOT NULL,
227    actor_id TEXT,
228    action TEXT NOT NULL,
229    target_type TEXT NOT NULL,
230    target_id TEXT NOT NULL,
231    metadata_json TEXT NOT NULL DEFAULT '{}',
232    created_at TEXT NOT NULL
233);
234CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_id, created_at DESC);
235
236CREATE TABLE IF NOT EXISTS slabs_incidents (
237    id TEXT PRIMARY KEY,
238    fingerprint TEXT NOT NULL UNIQUE,
239    kind TEXT NOT NULL,
240    source_file TEXT NOT NULL,
241    route_pattern TEXT,
242    status_code INTEGER,
243    error_message TEXT NOT NULL,
244    detail TEXT,
245    context_json TEXT NOT NULL,
246    git_sha TEXT,
247    occurrences INTEGER NOT NULL DEFAULT 1,
248    status TEXT NOT NULL DEFAULT 'open',
249    resolved_in_sha TEXT,
250    assignee TEXT,
251    external_issue_key TEXT,
252    external_issue_url TEXT,
253    recent_occurrences_json TEXT NOT NULL DEFAULT '[]',
254    first_seen_at TEXT NOT NULL,
255    last_seen_at TEXT NOT NULL
256);
257CREATE INDEX IF NOT EXISTS idx_slabs_incidents_status_seen
258    ON slabs_incidents (status, last_seen_at DESC);
259";
260
261/// Framework-owned `PostgreSQL` DDL for the 12 system tables and their indexes.
262///
263/// Uses `TIMESTAMPTZ`, `JSONB`, `BIGINT`, and `BOOLEAN` column types.
264/// Applied idempotently by [`PgDb::init_system_tables`], [`PgDb::migrate`], and [`PgDb::migrate_dir`].
265pub const POSTGRES_SYSTEM_SCHEMA_SQL: &str = r"
266CREATE TABLE IF NOT EXISTS slabs_sessions (
267    id TEXT PRIMARY KEY NOT NULL,
268    user_id TEXT NOT NULL,
269    role TEXT NOT NULL DEFAULT 'member',
270    token_hash TEXT NOT NULL UNIQUE,
271    expires_at TIMESTAMPTZ NOT NULL,
272    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
273);
274CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
275CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);
276
277CREATE TABLE IF NOT EXISTS slabs_magic_links (
278    id TEXT PRIMARY KEY NOT NULL,
279    email TEXT NOT NULL,
280    purpose TEXT NOT NULL DEFAULT 'sign_in',
281    code_hash TEXT NOT NULL UNIQUE,
282    expires_at TIMESTAMPTZ NOT NULL,
283    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
284);
285CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);
286
287CREATE TABLE IF NOT EXISTS slabs_access_tokens (
288    id TEXT PRIMARY KEY NOT NULL,
289    user_id TEXT NOT NULL,
290    role TEXT NOT NULL DEFAULT 'member',
291    description TEXT NOT NULL DEFAULT '',
292    permission TEXT NOT NULL DEFAULT 'write',
293    token_hash TEXT NOT NULL UNIQUE,
294    last_used_at TIMESTAMPTZ,
295    expires_at TIMESTAMPTZ,
296    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
297);
298CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);
299
300CREATE TABLE IF NOT EXISTS slabs_jobs (
301    id TEXT PRIMARY KEY NOT NULL,
302    job_name TEXT NOT NULL,
303    queue TEXT NOT NULL DEFAULT 'default',
304    payload_json JSONB NOT NULL,
305    status TEXT NOT NULL DEFAULT 'pending',
306    attempts BIGINT NOT NULL DEFAULT 0,
307    max_attempts BIGINT NOT NULL DEFAULT 5,
308    run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
309    locked_until TIMESTAMPTZ,
310    last_error TEXT,
311    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
312    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
313);
314CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);
315CREATE INDEX IF NOT EXISTS idx_slabs_jobs_locked_until ON slabs_jobs(status, locked_until);
316
317CREATE TABLE IF NOT EXISTS slabs_cache (
318    cache_key TEXT PRIMARY KEY NOT NULL,
319    value_text TEXT NOT NULL,
320    expires_at TIMESTAMPTZ NOT NULL,
321    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
322);
323CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);
324
325CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
326    id TEXT PRIMARY KEY NOT NULL,
327    from_addr TEXT NOT NULL,
328    to_addr TEXT NOT NULL,
329    subject TEXT NOT NULL,
330    text_body TEXT NOT NULL,
331    html_body TEXT,
332    sent_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
333);
334
335CREATE TABLE IF NOT EXISTS slabs_blobs (
336    id TEXT PRIMARY KEY NOT NULL,
337    filename TEXT NOT NULL,
338    content_type TEXT NOT NULL,
339    byte_size BIGINT NOT NULL,
340    checksum_sha256 TEXT NOT NULL,
341    storage_key TEXT NOT NULL UNIQUE,
342    scope TEXT,
343    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
344);
345
346CREATE TABLE IF NOT EXISTS slabs_webhooks (
347    id TEXT PRIMARY KEY NOT NULL,
348    scope_id TEXT NOT NULL,
349    name TEXT NOT NULL,
350    url TEXT NOT NULL,
351    signing_secret TEXT NOT NULL,
352    subscribed_actions_json JSONB NOT NULL,
353    active BOOLEAN NOT NULL DEFAULT TRUE,
354    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
355);
356CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);
357
358CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
359    id TEXT PRIMARY KEY NOT NULL,
360    webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
361    action TEXT NOT NULL,
362    payload_json JSONB NOT NULL,
363    signature TEXT NOT NULL,
364    status TEXT NOT NULL DEFAULT 'pending',
365    response_status INTEGER,
366    last_error TEXT,
367    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
368    delivered_at TIMESTAMPTZ
369);
370CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);
371
372CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
373    scope TEXT NOT NULL,
374    key TEXT NOT NULL,
375    response_json TEXT,
376    expires_at TIMESTAMPTZ,
377    created_at TEXT NOT NULL,
378    PRIMARY KEY (scope, key)
379);
380CREATE INDEX IF NOT EXISTS idx_slabs_idempotency_keys_expires_at ON slabs_idempotency_keys(expires_at);
381
382CREATE TABLE IF NOT EXISTS slabs_audit_log (
383    id TEXT PRIMARY KEY NOT NULL,
384    actor_id TEXT,
385    action TEXT NOT NULL,
386    target_type TEXT NOT NULL,
387    target_id TEXT NOT NULL,
388    metadata_json TEXT NOT NULL DEFAULT '{}',
389    created_at TEXT NOT NULL
390);
391CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_id, created_at DESC);
392
393CREATE TABLE IF NOT EXISTS slabs_incidents (
394    id TEXT PRIMARY KEY,
395    fingerprint TEXT NOT NULL UNIQUE,
396    kind TEXT NOT NULL,
397    source_file TEXT NOT NULL,
398    route_pattern TEXT,
399    status_code INTEGER,
400    error_message TEXT NOT NULL,
401    detail TEXT,
402    context_json TEXT NOT NULL,
403    git_sha TEXT,
404    occurrences INTEGER NOT NULL DEFAULT 1,
405    status TEXT NOT NULL DEFAULT 'open',
406    resolved_in_sha TEXT,
407    assignee TEXT,
408    external_issue_key TEXT,
409    external_issue_url TEXT,
410    recent_occurrences_json TEXT NOT NULL DEFAULT '[]',
411    first_seen_at TEXT NOT NULL,
412    last_seen_at TEXT NOT NULL
413);
414CREATE INDEX IF NOT EXISTS idx_slabs_incidents_status_seen
415    ON slabs_incidents (status, last_seen_at DESC);
416";
417
418/// Converts untrusted user search text into an FTS5 prefix-AND `MATCH` expression.
419///
420/// Splits on whitespace, strips `"` and ASCII control characters (including `\0`), caps
421/// each token to 64 characters, keeps at most 16 tokens, wraps each remaining token as
422/// `"token"*`, and joins them with `AND`.
423/// Returns `None` when the input contains no non-empty tokens after sanitization.
424#[must_use]
425pub fn fts5_query(raw: &str) -> Option<String> {
426    let terms: Vec<String> = raw
427        .split_whitespace()
428        .map(|tok| {
429            tok.chars()
430                .filter(|&ch| ch != '"' && !ch.is_ascii_control())
431                .take(64)
432                .collect::<String>()
433        })
434        .filter(|tok| !tok.is_empty())
435        .take(16)
436        .map(|tok| format!("\"{tok}\"*"))
437        .collect();
438    if terms.is_empty() {
439        None
440    } else {
441        Some(terms.join(" AND "))
442    }
443}
444
445/// Query parameters for cursor-based (keyset) pagination.
446#[derive(Debug, Clone, Default, serde::Deserialize)]
447pub struct Pagination {
448    /// Requested maximum number of items per page.
449    pub limit: Option<u32>,
450    /// Opaque cursor returned as `next_cursor` by the previous page.
451    pub cursor: Option<String>,
452}
453
454impl Pagination {
455    /// Resolves the page size, clamping it between `1` and `max_limit.max(1)`.
456    ///
457    /// Falls back to `default_limit` when [`Pagination::limit`] is `None`.
458    #[must_use]
459    pub fn clamped_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
460        let upper = max_limit.max(1);
461        let raw = self.limit.unwrap_or(default_limit);
462        i64::from(raw.clamp(1, upper))
463    }
464
465    /// Returns `clamped_limit + 1` so callers can detect whether more rows exist without a `COUNT(*)`.
466    #[must_use]
467    pub fn fetch_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
468        self.clamped_limit(default_limit, max_limit) + 1
469    }
470}
471
472/// One page of cursor-paginated results.
473#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
474pub struct CursorPage<T> {
475    /// Items returned for the current page.
476    pub items: Vec<T>,
477    /// Cursor of the last item when more rows exist, or `None` on the final page.
478    pub next_cursor: Option<String>,
479    /// Whether additional rows exist beyond this page.
480    pub has_more: bool,
481}
482
483impl<T> CursorPage<T> {
484    /// Builds a [`CursorPage`] from rows fetched with `LIMIT (limit + 1)`.
485    ///
486    /// Truncates `rows` to `limit`, sets `has_more` when an extra row was present,
487    /// and computes `next_cursor` from the last retained row via `cursor_fn`.
488    #[must_use]
489    pub fn from_rows(mut rows: Vec<T>, limit: usize, cursor_fn: impl Fn(&T) -> String) -> Self {
490        let has_more = rows.len() > limit;
491        if has_more {
492            rows.truncate(limit);
493        }
494        let next_cursor = if has_more {
495            rows.last().map(cursor_fn)
496        } else {
497            None
498        };
499        Self {
500            items: rows,
501            next_cursor,
502            has_more,
503        }
504    }
505}
506
507/// Persisted audit event row stored in `slabs_audit_log`.
508#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
509pub struct AuditEntry {
510    /// Prefixed audit entry identifier (`aud_<ulid>`).
511    pub id: String,
512    /// Optional identifier of the user or service that performed the action.
513    pub actor_id: Option<String>,
514    /// Action name describing what happened (for example `"room.archived"`).
515    pub action: String,
516    /// Logical type of the affected resource (for example `"room"`).
517    pub target_type: String,
518    /// Identifier of the affected resource.
519    pub target_id: String,
520    /// JSON-serialized metadata payload attached to the audit event.
521    pub metadata_json: String,
522    /// RFC 3339 UTC timestamp when the audit entry was created.
523    pub created_at: String,
524}
525
526/// Transactional audit log backed by the `slabs_audit_log` system table.
527#[derive(Debug, Clone)]
528pub struct AuditLog {
529    db: Db,
530}
531
532impl AuditLog {
533    /// Creates an [`AuditLog`] handle backed by `db`.
534    #[must_use]
535    pub fn new(db: Db) -> Self {
536        Self { db }
537    }
538
539    /// Inserts an audit entry inside an open `SQLite` transaction so it commits or rolls back atomically.
540    ///
541    /// Returns the generated `aud_<ulid>` identifier.
542    pub async fn record_in_tx(
543        &self,
544        tx: &mut Transaction<'_, Sqlite>,
545        actor_id: Option<&str>,
546        action: &str,
547        target_type: &str,
548        target_id: &str,
549        metadata: &serde_json::Value,
550    ) -> SlabResult<String> {
551        let id = slabs_core::id::new("aud");
552        let created_at = chrono::Utc::now().to_rfc3339();
553        let metadata_json = serde_json::to_string(metadata)
554            .map_err(|e| SlabError::internal(format!("failed to serialize audit metadata: {e}")))?;
555
556        sqlx::query(
557            "INSERT INTO slabs_audit_log (id, actor_id, action, target_type, target_id, metadata_json, created_at)
558             VALUES (?, ?, ?, ?, ?, ?, ?)",
559        )
560        .bind(&id)
561        .bind(actor_id)
562        .bind(action)
563        .bind(target_type)
564        .bind(target_id)
565        .bind(&metadata_json)
566        .bind(&created_at)
567        .execute(&mut **tx)
568        .await?;
569
570        Ok(id)
571    }
572
573    /// Lists up to `limit` (clamped to `1..=500`) most recent audit entries for a specific
574    /// `(target_type, target_id)` on the read pool.
575    pub async fn list_for_target(
576        &self,
577        target_type: &str,
578        target_id: &str,
579        limit: i64,
580    ) -> SlabResult<Vec<AuditEntry>> {
581        let limit = limit.clamp(1, 500);
582        let rows: Vec<AuditEntry> = sqlx::query_as(
583            "SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
584             FROM slabs_audit_log
585             WHERE target_type = ? AND target_id = ?
586             ORDER BY created_at DESC, id DESC
587             LIMIT ?",
588        )
589        .bind(target_type)
590        .bind(target_id)
591        .bind(limit)
592        .fetch_all(self.db.reader())
593        .await?;
594        Ok(rows)
595    }
596
597    /// Lists up to `limit` (clamped to `1..=500`) most recent audit entries across all targets
598    /// on the read pool.
599    pub async fn list_recent(&self, limit: i64) -> SlabResult<Vec<AuditEntry>> {
600        let limit = limit.clamp(1, 500);
601        let rows: Vec<AuditEntry> = sqlx::query_as(
602            "SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
603             FROM slabs_audit_log
604             ORDER BY created_at DESC, id DESC
605             LIMIT ?",
606        )
607        .bind(limit)
608        .fetch_all(self.db.reader())
609        .await?;
610        Ok(rows)
611    }
612}
613
614const MAX_INCIDENT_ERROR_BYTES: usize = 1024;
615const MAX_INCIDENT_DETAIL_BYTES: usize = 4096;
616const MAX_RECENT_OCCURRENCES: usize = 10;
617
618fn append_recent_occurrence(existing_json: &str, snapshot: serde_json::Value) -> String {
619    let mut items =
620        serde_json::from_str::<Vec<serde_json::Value>>(existing_json).unwrap_or_default();
621    items.push(snapshot);
622    if items.len() > MAX_RECENT_OCCURRENCES {
623        let drain_count = items.len() - MAX_RECENT_OCCURRENCES;
624        items.drain(..drain_count);
625    }
626    serde_json::to_string(&items).unwrap_or_else(|_| "[]".to_owned())
627}
628
629fn truncate_utf8(input: &str, max_bytes: usize) -> &str {
630    if input.len() <= max_bytes {
631        return input;
632    }
633    let mut end = max_bytes;
634    while end > 0 && !input.is_char_boundary(end) {
635        end -= 1;
636    }
637    &input[..end]
638}
639
640fn format_utc_micros(dt: chrono::DateTime<chrono::Utc>) -> String {
641    dt.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)
642}
643
644/// Persisted runtime incident row stored in `slabs_incidents`.
645#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
646pub struct IncidentRecord {
647    /// Prefixed incident identifier (`inc_<ulid>`).
648    pub id: String,
649    /// Deterministic SHA-256 deduplication fingerprint.
650    pub fingerprint: String,
651    /// Incident category (for example `"panic"`, `"http_5xx"`, `"slow_request"`, `"job_dead"`, `"slow_job"`, or `"client_error"`).
652    pub kind: String,
653    /// Source file associated with the incident (for example `"slabs/rooms/send_message.rs"`, `"jobs/send_email.rs"`, or `"browser"`).
654    pub source_file: String,
655    /// Optional matched HTTP route pattern or job/browser path.
656    pub route_pattern: Option<String>,
657    /// Optional HTTP status code associated with the incident.
658    pub status_code: Option<i64>,
659    /// Truncated error summary (at most 1024 UTF-8 bytes).
660    pub error_message: String,
661    /// Optional extended diagnostic detail (at most 4096 UTF-8 bytes).
662    pub detail: Option<String>,
663    /// JSON-serialized redacted diagnostic context.
664    pub context_json: String,
665    /// Optional Git commit SHA active when the incident was last observed.
666    pub git_sha: Option<String>,
667    /// Number of times this fingerprinted incident has occurred.
668    pub occurrences: i64,
669    /// Lifecycle state (`"open"`, `"in_progress"`, `"resolved"`, or `"ignored"`).
670    pub status: String,
671    /// Optional Git commit SHA recorded when the incident was resolved.
672    pub resolved_in_sha: Option<String>,
673    /// Optional assignee name (agent or engineer) currently investigating the incident.
674    pub assignee: Option<String>,
675    /// Optional external tracker issue key (for example `"ENG-412"` or `"#42"`).
676    pub external_issue_key: Option<String>,
677    /// Optional external tracker issue URL (`http://` or `https://`).
678    pub external_issue_url: Option<String>,
679    /// JSON array of the last 10 occurrence snapshots (`seen_at`, `git_sha`, `request_id`, `latency_ms`).
680    pub recent_occurrences_json: String,
681    /// Fixed-width UTC RFC 3339 timestamp when the incident was first recorded.
682    pub first_seen_at: String,
683    /// Fixed-width UTC RFC 3339 timestamp when the incident was most recently updated.
684    pub last_seen_at: String,
685}
686
687/// Lifecycle outcome returned when recording an incident via [`Incidents::record_with_outcome`].
688#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
689#[serde(rename_all = "snake_case")]
690pub enum IncidentOutcome {
691    /// A brand-new incident row was inserted.
692    Opened,
693    /// A previously resolved incident recurred and was transitioned back to `"open"`.
694    Reopened,
695    /// An already-open incident matched the fingerprint and had its occurrence count incremented.
696    Incremented,
697}
698
699/// Input payload for recording a deduplicated runtime incident in `slabs_incidents`.
700#[derive(Debug, Clone)]
701pub struct IncidentInput {
702    /// Incident category (for example `"panic"`, `"http_5xx"`, `"slow_request"`, `"job_dead"`, `"slow_job"`, `"client_error"`, or `"user_bug_report"`).
703    pub kind: String,
704    /// Source file owning the failing or slow code path.
705    pub source_file: String,
706    /// Optional matched HTTP route pattern or path.
707    pub route_pattern: Option<String>,
708    /// Optional HTTP status code.
709    pub status_code: Option<i64>,
710    /// Error or bottleneck summary (truncated to 1024 UTF-8 bytes on persistence).
711    pub error_message: String,
712    /// Optional extended diagnostic detail (truncated to 4096 UTF-8 bytes on persistence).
713    pub detail: Option<String>,
714    /// Redacted structured JSON context attached to the incident.
715    pub context_json: serde_json::Value,
716    /// Optional Git commit SHA active when the incident occurred.
717    pub git_sha: Option<String>,
718    /// Optional explicit deduplication fingerprint override.
719    ///
720    /// When `None`, the fingerprint is derived deterministically from `(kind, source_file,
721    /// route_pattern, error_message)` — except for `"user_bug_report"`, which includes a unique
722    /// nonce so each user bug report creates a distinct open record unless explicitly fingerprinted.
723    pub custom_fingerprint: Option<String>,
724}
725
726/// Deduplicated runtime incident store backed by the `slabs_incidents` system table.
727#[derive(Debug, Clone)]
728pub struct Incidents {
729    db: Db,
730}
731
732impl Incidents {
733    /// Creates an [`Incidents`] handle backed by `db`.
734    #[must_use]
735    pub fn new(db: Db) -> Self {
736        Self { db }
737    }
738
739    /// Atomically records or deduplicates an incident and returns its exact [`IncidentOutcome`].
740    ///
741    /// Uses `input.custom_fingerprint` when provided (hashed under a domain prefix so fingerprints
742    /// remain fixed-width SHA-256 hex). Otherwise derives the fingerprint deterministically from
743    /// `(kind, source_file, route_pattern, error_message)`, appending a unique nonce when
744    /// `kind == "user_bug_report"` so individual user bug reports remain distinct.
745    ///
746    /// Truncates `error_message` to 1024 bytes and `detail` to 4096 bytes on UTF-8 character
747    /// boundaries, and upserts inside a `BEGIN IMMEDIATE` transaction.
748    pub async fn record_with_outcome(
749        &self,
750        input: IncidentInput,
751    ) -> SlabResult<(IncidentRecord, IncidentOutcome)> {
752        let fingerprint = if let Some(custom) = input
753            .custom_fingerprint
754            .as_deref()
755            .map(str::trim)
756            .filter(|s| !s.is_empty())
757        {
758            slabs_core::fingerprint(&["custom", custom])
759        } else if input.kind == "user_bug_report" {
760            let nonce = slabs_core::id::new("bug");
761            slabs_core::fingerprint(&[
762                &input.kind,
763                &input.source_file,
764                input.route_pattern.as_deref().unwrap_or(""),
765                &input.error_message,
766                &nonce,
767            ])
768        } else {
769            slabs_core::fingerprint(&[
770                &input.kind,
771                &input.source_file,
772                input.route_pattern.as_deref().unwrap_or(""),
773                &input.error_message,
774            ])
775        };
776        let error_message =
777            truncate_utf8(&input.error_message, MAX_INCIDENT_ERROR_BYTES).to_owned();
778        let detail = input
779            .detail
780            .as_deref()
781            .map(|d| truncate_utf8(d, MAX_INCIDENT_DETAIL_BYTES).to_owned());
782        let context_json = serde_json::to_string(&input.context_json).map_err(|e| {
783            SlabError::internal(format!("failed to serialize incident context: {e}"))
784        })?;
785        let now = format_utc_micros(chrono::Utc::now());
786        let occurrence_snapshot = serde_json::json!({
787            "seen_at": now,
788            "git_sha": input.git_sha,
789            "request_id": input.context_json.get("request_id"),
790            "latency_ms": input.context_json.get("latency_ms"),
791        });
792
793        let mut tx = self.db.begin().await?;
794        let existing: Option<IncidentRecord> = sqlx::query_as(
795            "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
796                    detail, context_json, git_sha, occurrences, status, resolved_in_sha,
797                    assignee, external_issue_key, external_issue_url, recent_occurrences_json,
798                    first_seen_at, last_seen_at
799             FROM slabs_incidents
800             WHERE fingerprint = ?",
801        )
802        .bind(&fingerprint)
803        .fetch_optional(&mut *tx)
804        .await?;
805
806        let (record, outcome) = if let Some(prev) = existing {
807            let reopened = prev.status == "resolved";
808            let next_status = if reopened {
809                "open".to_owned()
810            } else {
811                prev.status.clone()
812            };
813            let next_resolved_in_sha = if reopened {
814                None
815            } else {
816                prev.resolved_in_sha.clone()
817            };
818            let next_assignee = if reopened {
819                None
820            } else {
821                prev.assignee.clone()
822            };
823            let next_occurrences = prev.occurrences + 1;
824            let next_recent_occurrences_json =
825                append_recent_occurrence(&prev.recent_occurrences_json, occurrence_snapshot);
826
827            sqlx::query(
828                "UPDATE slabs_incidents
829                 SET occurrences = ?,
830                     last_seen_at = ?,
831                     detail = ?,
832                     context_json = ?,
833                     git_sha = ?,
834                     status = ?,
835                     resolved_in_sha = ?,
836                     assignee = ?,
837                     recent_occurrences_json = ?
838                 WHERE id = ?",
839            )
840            .bind(next_occurrences)
841            .bind(&now)
842            .bind(&detail)
843            .bind(&context_json)
844            .bind(&input.git_sha)
845            .bind(&next_status)
846            .bind(&next_resolved_in_sha)
847            .bind(&next_assignee)
848            .bind(&next_recent_occurrences_json)
849            .bind(&prev.id)
850            .execute(&mut *tx)
851            .await?;
852
853            let updated = IncidentRecord {
854                id: prev.id,
855                fingerprint: prev.fingerprint,
856                kind: prev.kind,
857                source_file: prev.source_file,
858                route_pattern: prev.route_pattern,
859                status_code: prev.status_code,
860                error_message: prev.error_message,
861                detail,
862                context_json,
863                git_sha: input.git_sha,
864                occurrences: next_occurrences,
865                status: next_status,
866                resolved_in_sha: next_resolved_in_sha,
867                assignee: next_assignee,
868                external_issue_key: prev.external_issue_key,
869                external_issue_url: prev.external_issue_url,
870                recent_occurrences_json: next_recent_occurrences_json,
871                first_seen_at: prev.first_seen_at,
872                last_seen_at: now,
873            };
874            let outcome = if reopened {
875                IncidentOutcome::Reopened
876            } else {
877                IncidentOutcome::Incremented
878            };
879            (updated, outcome)
880        } else {
881            let id = slabs_core::id::new("inc");
882            let recent_occurrences_json = append_recent_occurrence("[]", occurrence_snapshot);
883            sqlx::query(
884                "INSERT INTO slabs_incidents (
885                     id, fingerprint, kind, source_file, route_pattern, status_code,
886                     error_message, detail, context_json, git_sha, occurrences,
887                     status, resolved_in_sha, assignee, external_issue_key,
888                     external_issue_url, recent_occurrences_json, first_seen_at, last_seen_at
889                 )
890                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 'open', NULL, NULL, NULL, NULL, ?, ?, ?)",
891            )
892            .bind(&id)
893            .bind(&fingerprint)
894            .bind(&input.kind)
895            .bind(&input.source_file)
896            .bind(&input.route_pattern)
897            .bind(input.status_code)
898            .bind(&error_message)
899            .bind(&detail)
900            .bind(&context_json)
901            .bind(&input.git_sha)
902            .bind(&recent_occurrences_json)
903            .bind(&now)
904            .bind(&now)
905            .execute(&mut *tx)
906            .await?;
907
908            let inserted = IncidentRecord {
909                id,
910                fingerprint,
911                kind: input.kind,
912                source_file: input.source_file,
913                route_pattern: input.route_pattern,
914                status_code: input.status_code,
915                error_message,
916                detail,
917                context_json,
918                git_sha: input.git_sha,
919                occurrences: 1,
920                status: "open".to_owned(),
921                resolved_in_sha: None,
922                assignee: None,
923                external_issue_key: None,
924                external_issue_url: None,
925                recent_occurrences_json,
926                first_seen_at: now.clone(),
927                last_seen_at: now,
928            };
929            (inserted, IncidentOutcome::Opened)
930        };
931
932        tx.commit().await?;
933        Ok((record, outcome))
934    }
935
936    /// Atomically records or deduplicates an incident by deterministic fingerprint.
937    ///
938    /// Delegates to [`Incidents::record_with_outcome`], returning `(record, is_new_or_reopened)`,
939    /// where the boolean is `true` for [`IncidentOutcome::Opened`] or [`IncidentOutcome::Reopened`].
940    pub async fn record(&self, input: IncidentInput) -> SlabResult<(IncidentRecord, bool)> {
941        let (record, outcome) = self.record_with_outcome(input).await?;
942        Ok((
943            record,
944            matches!(outcome, IncidentOutcome::Opened | IncidentOutcome::Reopened),
945        ))
946    }
947
948    /// Lists up to `limit` (clamped to `1..=500`) incidents ordered by `last_seen_at DESC` on the read pool.
949    ///
950    /// Pass `status = Some("open")`, `Some("in_progress")`, `Some("resolved")`, or `Some("ignored")`
951    /// to filter by lifecycle state, or `None` / `Some("all")` to return all incidents.
952    pub async fn list(&self, status: Option<&str>, limit: i64) -> SlabResult<Vec<IncidentRecord>> {
953        let limit = limit.clamp(1, 500);
954        let filter = status
955            .map(str::trim)
956            .filter(|s| !s.is_empty() && !s.eq_ignore_ascii_case("all"));
957
958        let rows: Vec<IncidentRecord> = if let Some(st) = filter {
959            sqlx::query_as(
960                "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
961                        detail, context_json, git_sha, occurrences, status, resolved_in_sha,
962                        assignee, external_issue_key, external_issue_url, recent_occurrences_json,
963                        first_seen_at, last_seen_at
964                 FROM slabs_incidents
965                 WHERE status = ?
966                 ORDER BY last_seen_at DESC, id DESC
967                 LIMIT ?",
968            )
969            .bind(st)
970            .bind(limit)
971            .fetch_all(self.db.reader())
972            .await?
973        } else {
974            sqlx::query_as(
975                "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
976                        detail, context_json, git_sha, occurrences, status, resolved_in_sha,
977                        assignee, external_issue_key, external_issue_url, recent_occurrences_json,
978                        first_seen_at, last_seen_at
979                 FROM slabs_incidents
980                 ORDER BY last_seen_at DESC, id DESC
981                 LIMIT ?",
982            )
983            .bind(limit)
984            .fetch_all(self.db.reader())
985            .await?
986        };
987        Ok(rows)
988    }
989
990    /// Fetches a single incident by its `inc_<ulid>` identifier on the read pool.
991    pub async fn get(&self, id: &str) -> SlabResult<Option<IncidentRecord>> {
992        let row: Option<IncidentRecord> = sqlx::query_as(
993            "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
994                    detail, context_json, git_sha, occurrences, status, resolved_in_sha,
995                    assignee, external_issue_key, external_issue_url, recent_occurrences_json,
996                    first_seen_at, last_seen_at
997             FROM slabs_incidents
998             WHERE id = ?",
999        )
1000        .bind(id)
1001        .fetch_optional(self.db.reader())
1002        .await?;
1003        Ok(row)
1004    }
1005
1006    /// Atomically claims an `"open"` incident for `assignee`, transitioning it to `"in_progress"`.
1007    ///
1008    /// Returns `true` when the incident was open and claimed, or `false` if it does not exist,
1009    /// was already claimed, or is not in the `"open"` state.
1010    pub async fn claim(&self, id: &str, assignee: &str) -> SlabResult<bool> {
1011        let trimmed = assignee.trim();
1012        if trimmed.is_empty() {
1013            return Err(SlabError::validation("assignee", "cannot be empty"));
1014        }
1015        let clean_assignee = truncate_utf8(trimmed, 128);
1016        let now = format_utc_micros(chrono::Utc::now());
1017        let res = sqlx::query(
1018            "UPDATE slabs_incidents
1019             SET status = 'in_progress',
1020                 assignee = ?,
1021                 last_seen_at = ?
1022             WHERE id = ? AND status = 'open'",
1023        )
1024        .bind(clean_assignee)
1025        .bind(&now)
1026        .bind(id)
1027        .execute(self.db.writer())
1028        .await?;
1029        Ok(res.rows_affected() > 0)
1030    }
1031
1032    /// Links an external issue tracker key and `http://` or `https://` URL to an incident.
1033    ///
1034    /// Returns `true` if a matching row was updated, or `false` if `id` does not exist.
1035    pub async fn link_external(&self, id: &str, key: &str, url: &str) -> SlabResult<bool> {
1036        let clean_key = key.trim();
1037        if clean_key.is_empty() {
1038            return Err(SlabError::validation(
1039                "external_issue_key",
1040                "cannot be empty",
1041            ));
1042        }
1043        let clean_url = url.trim();
1044        let valid_scheme = clean_url.starts_with("https://") || clean_url.starts_with("http://");
1045        if !valid_scheme
1046            || clean_url.len() <= "http://".len()
1047            || clean_url
1048                .chars()
1049                .any(|c| c.is_whitespace() || c.is_control())
1050        {
1051            return Err(SlabError::validation(
1052                "external_issue_url",
1053                "must be a valid http:// or https:// URL",
1054            ));
1055        }
1056        let clean_key = truncate_utf8(clean_key, 128);
1057        let clean_url = truncate_utf8(clean_url, 1024);
1058        let now = format_utc_micros(chrono::Utc::now());
1059        let res = sqlx::query(
1060            "UPDATE slabs_incidents
1061             SET external_issue_key = ?,
1062                 external_issue_url = ?,
1063                 last_seen_at = ?
1064             WHERE id = ?",
1065        )
1066        .bind(clean_key)
1067        .bind(clean_url)
1068        .bind(&now)
1069        .bind(id)
1070        .execute(self.db.writer())
1071        .await?;
1072        Ok(res.rows_affected() > 0)
1073    }
1074
1075    /// Marks an incident as `"ignored"` and updates `last_seen_at`.
1076    ///
1077    /// Future occurrences increment the counter and append to `recent_occurrences_json` without
1078    /// reopening the incident or firing alert webhooks.
1079    pub async fn ignore(&self, id: &str) -> SlabResult<bool> {
1080        let now = format_utc_micros(chrono::Utc::now());
1081        let res = sqlx::query(
1082            "UPDATE slabs_incidents
1083             SET status = 'ignored',
1084                 last_seen_at = ?
1085             WHERE id = ?",
1086        )
1087        .bind(&now)
1088        .bind(id)
1089        .execute(self.db.writer())
1090        .await?;
1091        Ok(res.rows_affected() > 0)
1092    }
1093
1094    /// Marks an incident as `"resolved"` with an optional `resolved_in_sha`, updating `last_seen_at`.
1095    ///
1096    /// Returns `true` if a matching row was updated, or `false` if `id` does not exist.
1097    pub async fn resolve(&self, id: &str, resolved_in_sha: Option<&str>) -> SlabResult<bool> {
1098        let now = format_utc_micros(chrono::Utc::now());
1099        let res = sqlx::query(
1100            "UPDATE slabs_incidents
1101             SET status = 'resolved',
1102                 resolved_in_sha = ?,
1103                 last_seen_at = ?
1104             WHERE id = ?",
1105        )
1106        .bind(resolved_in_sha)
1107        .bind(&now)
1108        .bind(id)
1109        .execute(self.db.writer())
1110        .await?;
1111        Ok(res.rows_affected() > 0)
1112    }
1113
1114    /// Re-opens an incident by setting `status = 'open'`, clearing `resolved_in_sha` and `assignee`,
1115    /// and updating `last_seen_at`.
1116    ///
1117    /// Returns `true` if a matching row was updated, or `false` if `id` does not exist.
1118    pub async fn reopen(&self, id: &str) -> SlabResult<bool> {
1119        let now = format_utc_micros(chrono::Utc::now());
1120        let res = sqlx::query(
1121            "UPDATE slabs_incidents
1122             SET status = 'open',
1123                 resolved_in_sha = NULL,
1124                 assignee = NULL,
1125                 last_seen_at = ?
1126             WHERE id = ?",
1127        )
1128        .bind(&now)
1129        .bind(id)
1130        .execute(self.db.writer())
1131        .await?;
1132        Ok(res.rows_affected() > 0)
1133    }
1134
1135    /// Returns the number of currently open incidents on the read pool.
1136    pub async fn count_open(&self) -> SlabResult<i64> {
1137        let (count,): (i64,) =
1138            sqlx::query_as("SELECT COUNT(*) FROM slabs_incidents WHERE status = 'open'")
1139                .fetch_one(self.db.reader())
1140                .await?;
1141        Ok(count)
1142    }
1143}
1144
1145/// Raw-SQL `SQLite` database wrapper tuned for concurrent WAL workloads.
1146///
1147/// Holds two pools on file-backed databases:
1148/// - A single-connection writer pool (`max_connections(1)`) used by [`Db::writer`], [`Db::pool`], and [`Db::begin`] (`BEGIN IMMEDIATE`).
1149/// - A 16-connection read-only pool used by [`Db::reader`] for parallel `SELECT` queries.
1150///
1151/// In-memory databases (`sqlite::memory:` or `mode=memory`) share the single writer pool for both reads and writes.
1152#[derive(Debug, Clone)]
1153pub struct Db {
1154    read_pool: SqlitePool,
1155    write_pool: SqlitePool,
1156}
1157
1158impl Db {
1159    /// Connects to a `SQLite` database with tuned WAL pragmas and split read/write pools.
1160    ///
1161    /// Creates the database file when missing and enables `foreign_keys = ON`, `synchronous = NORMAL`,
1162    /// `cache_size = -64000`, and `temp_store = MEMORY`. File-backed databases also enable
1163    /// `journal_mode = WAL`, `mmap_size = 268435456`, and a separate 16-connection read-only pool.
1164    /// Returns [`SlabError::Internal`] if `database_url` cannot be parsed.
1165    pub async fn connect(database_url: &str) -> SlabResult<Self> {
1166        let is_memory = database_url == "sqlite::memory:" || database_url.contains("mode=memory");
1167
1168        let mut write_opts = SqliteConnectOptions::from_str(database_url)
1169            .map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
1170            .create_if_missing(true)
1171            .foreign_keys(true)
1172            .busy_timeout(Duration::from_secs(10))
1173            .synchronous(SqliteSynchronous::Normal)
1174            .pragma("cache_size", "-64000")
1175            .pragma("temp_store", "MEMORY")
1176            .pragma("trusted_schema", "OFF")
1177            .pragma("secure_delete", "ON");
1178
1179        if !is_memory {
1180            write_opts = write_opts
1181                .journal_mode(SqliteJournalMode::Wal)
1182                .pragma("mmap_size", "268435456");
1183        }
1184
1185        // Single dedicated writer guarantees serialized writes without SQLITE_BUSY thrashing.
1186        let write_pool = SqlitePoolOptions::new()
1187            .max_connections(1)
1188            .acquire_timeout(Duration::from_secs(10))
1189            .connect_with(write_opts)
1190            .await?;
1191
1192        let read_pool = if is_memory {
1193            // In-memory SQLite databases are per-connection, so share the single pool in tests.
1194            write_pool.clone()
1195        } else {
1196            let read_opts = SqliteConnectOptions::from_str(database_url)
1197                .map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
1198                .read_only(true)
1199                .foreign_keys(true)
1200                .busy_timeout(Duration::from_secs(5))
1201                .pragma("cache_size", "-64000")
1202                .pragma("temp_store", "MEMORY")
1203                .pragma("trusted_schema", "OFF")
1204                .pragma("mmap_size", "268435456");
1205
1206            SqlitePoolOptions::new()
1207                .max_connections(16)
1208                .acquire_timeout(Duration::from_secs(5))
1209                .connect_with(read_opts)
1210                .await?
1211        };
1212
1213        Ok(Self {
1214            read_pool,
1215            write_pool,
1216        })
1217    }
1218
1219    /// Returns the default pool, which aliases the single-connection writer pool.
1220    ///
1221    /// Prefer [`Db::reader`] for read-only `SELECT` queries so reads run concurrently on file-backed databases.
1222    #[must_use]
1223    pub fn pool(&self) -> &SqlitePool {
1224        &self.write_pool
1225    }
1226
1227    /// Returns the concurrent read-only WAL pool (up to 16 connections on file-backed databases).
1228    ///
1229    /// Use this pool for `SELECT` queries. Executing write statements on a file-backed reader pool fails.
1230    #[must_use]
1231    pub fn reader(&self) -> &SqlitePool {
1232        &self.read_pool
1233    }
1234
1235    /// Returns the dedicated single-connection writer pool (`max_connections(1)`).
1236    ///
1237    /// Serializes writes in-process with a 10-second `busy_timeout` to prevent `SQLITE_BUSY` thrashing.
1238    #[must_use]
1239    pub fn writer(&self) -> &SqlitePool {
1240        &self.write_pool
1241    }
1242
1243    /// Opens an explicit `BEGIN IMMEDIATE` transaction on the single writer connection.
1244    ///
1245    /// Acquires the write lock at transaction start, avoiding deferred lock-upgrade `SQLITE_BUSY_SNAPSHOT` errors.
1246    pub async fn begin(&self) -> SlabResult<Transaction<'_, Sqlite>> {
1247        Ok(self.write_pool.begin_with("BEGIN IMMEDIATE").await?)
1248    }
1249
1250    /// Ensures an existing `SQLite` system table has `column` (adding it if absent).
1251    async fn ensure_sqlite_column(
1252        &self,
1253        table: &str,
1254        column: &str,
1255        column_def: &str,
1256    ) -> SlabResult<()> {
1257        let query = format!("SELECT name FROM pragma_table_info('{table}')");
1258        let cols: Vec<(String,)> = sqlx::query_as(&query).fetch_all(&self.write_pool).await?;
1259        if !cols.is_empty() && !cols.iter().any(|(name,)| name == column) {
1260            let alter = format!("ALTER TABLE {table} ADD COLUMN {column} {column_def}");
1261            sqlx::raw_sql(&alter).execute(&self.write_pool).await?;
1262        }
1263        Ok(())
1264    }
1265
1266    /// Executes [`SYSTEM_SCHEMA_SQL`] against the writer pool to create all 12 system tables idempotently,
1267    /// upgrading legacy `slabs_jobs`, `slabs_idempotency_keys`, `slabs_blobs`, and `slabs_incidents`
1268    /// tables in place when needed.
1269    pub async fn init_system_tables(&self) -> SlabResult<()> {
1270        self.ensure_sqlite_column("slabs_jobs", "locked_until", "TEXT")
1271            .await?;
1272        self.ensure_sqlite_column("slabs_idempotency_keys", "expires_at", "TEXT")
1273            .await?;
1274        self.ensure_sqlite_column("slabs_blobs", "scope", "TEXT")
1275            .await?;
1276        self.ensure_sqlite_column("slabs_incidents", "assignee", "TEXT")
1277            .await?;
1278        self.ensure_sqlite_column("slabs_incidents", "external_issue_key", "TEXT")
1279            .await?;
1280        self.ensure_sqlite_column("slabs_incidents", "external_issue_url", "TEXT")
1281            .await?;
1282        self.ensure_sqlite_column(
1283            "slabs_incidents",
1284            "recent_occurrences_json",
1285            "TEXT NOT NULL DEFAULT '[]'",
1286        )
1287        .await?;
1288        sqlx::raw_sql(SYSTEM_SCHEMA_SQL)
1289            .execute(&self.write_pool)
1290            .await?;
1291        Ok(())
1292    }
1293
1294    /// Creates system tables if missing and runs all pending migrations from `migrator` on the writer pool.
1295    ///
1296    /// Wraps migration failures in [`SlabError::Internal`].
1297    pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
1298        self.init_system_tables().await?;
1299        migrator
1300            .run(&self.write_pool)
1301            .await
1302            .map_err(|e| SlabError::internal(format!("migration failed: {e}")))?;
1303        Ok(())
1304    }
1305
1306    /// Creates system tables if missing and runs all SQL migrations located in `dir` on the writer pool.
1307    ///
1308    /// Wraps directory load and migration failures in [`SlabError::Internal`].
1309    pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
1310        self.init_system_tables().await?;
1311        let migrator = Migrator::new(dir)
1312            .await
1313            .map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
1314        self.migrate(&migrator).await
1315    }
1316
1317    /// Exports the current `SQLite` schema DDL from `sqlite_master` on the read pool.
1318    ///
1319    /// Excludes internal `sqlite_%` and `_sqlx_%` objects and orders statements by table, index, trigger, then view.
1320    pub async fn dump_schema_sql(&self) -> SlabResult<String> {
1321        let rows: Vec<(String, String, Option<String>)> = sqlx::query_as(
1322            "SELECT type, name, sql
1323             FROM sqlite_master
1324             WHERE sql IS NOT NULL
1325               AND name NOT LIKE 'sqlite_%'
1326               AND name NOT LIKE '_sqlx_%'
1327             ORDER BY
1328               CASE type
1329                 WHEN 'table' THEN 1
1330                 WHEN 'index' THEN 2
1331                 WHEN 'trigger' THEN 3
1332                 WHEN 'view' THEN 4
1333                 ELSE 5
1334               END,
1335               name ASC",
1336        )
1337        .fetch_all(&self.read_pool)
1338        .await?;
1339
1340        let mut out = String::from(
1341            "-- Auto-generated by slabs-db (SQLite). Single-file schema truth for humans and agents.\n\n",
1342        );
1343        for (_kind, _name, sql) in rows {
1344            if let Some(stmt) = sql {
1345                out.push_str(stmt.trim());
1346                if !stmt.trim_end().ends_with(';') {
1347                    out.push(';');
1348                }
1349                out.push_str("\n\n");
1350            }
1351        }
1352        Ok(out)
1353    }
1354
1355    /// Reads a `.sql` file from disk and executes its statements atomically inside a `SQLite` transaction.
1356    ///
1357    /// Intended for seed scripts such as `slabs db seed`. Empty or whitespace-only files are a no-op.
1358    pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
1359        let sql = std::fs::read_to_string(path).map_err(|e| {
1360            SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
1361        })?;
1362        if sql.trim().is_empty() {
1363            return Ok(());
1364        }
1365        let mut tx = self.begin().await?;
1366        sqlx::raw_sql(&sql).execute(&mut *tx).await?;
1367        tx.commit().await?;
1368        Ok(())
1369    }
1370
1371    /// Executes `SELECT 1` against the read pool to verify database connectivity.
1372    pub async fn ping(&self) -> SlabResult<()> {
1373        let _: (i64,) = sqlx::query_as("SELECT 1")
1374            .fetch_one(&self.read_pool)
1375            .await?;
1376        Ok(())
1377    }
1378
1379    /// Runs `SQLite` `EXPLAIN QUERY PLAN` for a single read-only `SELECT` or `WITH` statement
1380    /// against the read pool and returns each plan `detail` line.
1381    ///
1382    /// Rejects empty SQL, queries containing `;`, and statements not starting with `SELECT` or
1383    /// `WITH` (case-insensitive) with [`SlabError::BadRequest`].
1384    pub async fn explain_query_plan(&self, sql: &str) -> SlabResult<Vec<String>> {
1385        let trimmed = sql.trim();
1386        if trimmed.is_empty() {
1387            return Err(SlabError::bad_request("SQL query cannot be empty"));
1388        }
1389        if trimmed.contains(';') {
1390            return Err(SlabError::bad_request(
1391                "SQL query must be a single statement without semicolons",
1392            ));
1393        }
1394
1395        let starts_select = trimmed.len() > 6
1396            && trimmed
1397                .get(..6)
1398                .is_some_and(|p| p.eq_ignore_ascii_case("SELECT"))
1399            && trimmed
1400                .as_bytes()
1401                .get(6)
1402                .is_some_and(u8::is_ascii_whitespace);
1403        let starts_with = trimmed.len() > 4
1404            && trimmed
1405                .get(..4)
1406                .is_some_and(|p| p.eq_ignore_ascii_case("WITH"))
1407            && trimmed
1408                .as_bytes()
1409                .get(4)
1410                .is_some_and(u8::is_ascii_whitespace);
1411
1412        if !starts_select && !starts_with {
1413            return Err(SlabError::bad_request(
1414                "only read-only SELECT or WITH queries can be explained",
1415            ));
1416        }
1417
1418        let explain_sql = format!("EXPLAIN QUERY PLAN {trimmed}");
1419        let rows: Vec<(i64, i64, i64, String)> = sqlx::query_as(&explain_sql)
1420            .fetch_all(self.reader())
1421            .await?;
1422        Ok(rows.into_iter().map(|(_, _, _, detail)| detail).collect())
1423    }
1424}
1425
1426fn quote_pg_ident(ident: &str) -> String {
1427    format!("\"{}\"", ident.replace('"', "\"\""))
1428}
1429
1430/// Raw-SQL `PostgreSQL` database wrapper for multi-node deployments.
1431#[derive(Debug, Clone)]
1432pub struct PgDb {
1433    pool: PgPool,
1434}
1435
1436impl PgDb {
1437    /// Connects to a `PostgreSQL` database with up to 20 pooled connections, a 5-second acquire
1438    /// timeout, a 5-minute idle timeout, and a 30-minute maximum connection lifetime.
1439    pub async fn connect(database_url: &str) -> SlabResult<Self> {
1440        let pool = PgPoolOptions::new()
1441            .max_connections(20)
1442            .acquire_timeout(Duration::from_secs(5))
1443            .idle_timeout(Duration::from_secs(300))
1444            .max_lifetime(Duration::from_secs(1800))
1445            .connect(database_url)
1446            .await?;
1447        Ok(Self { pool })
1448    }
1449
1450    /// Returns the underlying `sqlx` `PostgreSQL` connection pool.
1451    #[must_use]
1452    pub fn pool(&self) -> &PgPool {
1453        &self.pool
1454    }
1455
1456    /// Begins a new `PostgreSQL` transaction on the pool.
1457    pub async fn begin(&self) -> SlabResult<Transaction<'_, Postgres>> {
1458        Ok(self.pool.begin().await?)
1459    }
1460
1461    /// Executes [`POSTGRES_SYSTEM_SCHEMA_SQL`] to create all 12 system tables idempotently,
1462    /// upgrading legacy `slabs_jobs`, `slabs_idempotency_keys`, `slabs_blobs`, and `slabs_incidents`
1463    /// tables in place when needed.
1464    pub async fn init_system_tables(&self) -> SlabResult<()> {
1465        sqlx::raw_sql(
1466            "ALTER TABLE IF EXISTS slabs_jobs ADD COLUMN IF NOT EXISTS locked_until TIMESTAMPTZ;
1467             ALTER TABLE IF EXISTS slabs_idempotency_keys ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;
1468             ALTER TABLE IF EXISTS slabs_blobs ADD COLUMN IF NOT EXISTS scope TEXT;
1469             ALTER TABLE IF EXISTS slabs_incidents ADD COLUMN IF NOT EXISTS assignee TEXT;
1470             ALTER TABLE IF EXISTS slabs_incidents ADD COLUMN IF NOT EXISTS external_issue_key TEXT;
1471             ALTER TABLE IF EXISTS slabs_incidents ADD COLUMN IF NOT EXISTS external_issue_url TEXT;
1472             ALTER TABLE IF EXISTS slabs_incidents ADD COLUMN IF NOT EXISTS recent_occurrences_json TEXT NOT NULL DEFAULT '[]';",
1473        )
1474        .execute(&self.pool)
1475        .await?;
1476        sqlx::raw_sql(POSTGRES_SYSTEM_SCHEMA_SQL)
1477            .execute(&self.pool)
1478            .await?;
1479        Ok(())
1480    }
1481
1482    /// Creates system tables if missing and runs all pending migrations from `migrator`.
1483    ///
1484    /// Wraps migration failures in [`SlabError::Internal`].
1485    pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
1486        self.init_system_tables().await?;
1487        migrator
1488            .run(&self.pool)
1489            .await
1490            .map_err(|e| SlabError::internal(format!("postgres migration failed: {e}")))?;
1491        Ok(())
1492    }
1493
1494    /// Creates system tables if missing and runs all SQL migrations located in `dir`.
1495    ///
1496    /// Wraps directory load and migration failures in [`SlabError::Internal`].
1497    pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
1498        self.init_system_tables().await?;
1499        let migrator = Migrator::new(dir)
1500            .await
1501            .map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
1502        self.migrate(&migrator).await
1503    }
1504
1505    /// Exports `public` schema tables and indexes from `information_schema.columns` and `pg_indexes`.
1506    ///
1507    /// Excludes `_sqlx_%` internal migration tables.
1508    pub async fn dump_schema_sql(&self) -> SlabResult<String> {
1509        let cols: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
1510            "SELECT table_name, column_name, data_type, is_nullable, column_default
1511             FROM information_schema.columns
1512             WHERE table_schema = 'public'
1513               AND table_name NOT LIKE '_sqlx_%'
1514             ORDER BY table_name ASC, ordinal_position ASC",
1515        )
1516        .fetch_all(&self.pool)
1517        .await?;
1518
1519        let indexes: Vec<(String,)> = sqlx::query_as(
1520            "SELECT indexdef
1521             FROM pg_indexes
1522             WHERE schemaname = 'public'
1523               AND tablename NOT LIKE '_sqlx_%'
1524             ORDER BY tablename ASC, indexname ASC",
1525        )
1526        .fetch_all(&self.pool)
1527        .await?;
1528
1529        let mut out = String::from(
1530            "-- Auto-generated by slabs-db (PostgreSQL). Single-file schema truth for humans and agents.\n\n",
1531        );
1532
1533        let mut current_table: Option<String> = None;
1534        for (table, col, dtype, nullable, default) in cols {
1535            if current_table.as_deref() == Some(table.as_str()) {
1536                out.push_str(",\n");
1537            } else {
1538                if current_table.is_some() {
1539                    out.push_str(");\n\n");
1540                }
1541                let quoted_table = quote_pg_ident(&table);
1542                let _ = writeln!(out, "CREATE TABLE {quoted_table} (");
1543                current_table = Some(table);
1544            }
1545            let quoted_col = quote_pg_ident(&col);
1546            let _ = write!(out, "    {quoted_col} {dtype}");
1547            if nullable == "NO" {
1548                out.push_str(" NOT NULL");
1549            }
1550            if let Some(def) = default {
1551                let _ = write!(out, " DEFAULT {def}");
1552            }
1553        }
1554        if current_table.is_some() {
1555            out.push_str("\n);\n\n");
1556        }
1557
1558        for (indexdef,) in indexes {
1559            out.push_str(&indexdef);
1560            if !indexdef.ends_with(';') {
1561                out.push(';');
1562            }
1563            out.push_str("\n\n");
1564        }
1565
1566        Ok(out)
1567    }
1568
1569    /// Reads a `.sql` file from disk and executes its statements against the `PostgreSQL` pool.
1570    ///
1571    /// Intended for seed scripts such as `slabs db seed`. Empty or whitespace-only files are a no-op.
1572    pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
1573        let sql = std::fs::read_to_string(path).map_err(|e| {
1574            SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
1575        })?;
1576        if sql.trim().is_empty() {
1577            return Ok(());
1578        }
1579        sqlx::raw_sql(&sql).execute(&self.pool).await?;
1580        Ok(())
1581    }
1582
1583    /// Executes `SELECT 1` against the `PostgreSQL` pool to verify database connectivity.
1584    pub async fn ping(&self) -> SlabResult<()> {
1585        let _: (i32,) = sqlx::query_as("SELECT 1").fetch_one(&self.pool).await?;
1586        Ok(())
1587    }
1588}
1589
1590#[cfg(test)]
1591mod tests {
1592    use super::*;
1593
1594    #[test]
1595    fn detects_sqlite_and_postgres_urls() {
1596        assert_eq!(DbEngine::detect("sqlite::memory:"), DbEngine::Sqlite);
1597        assert_eq!(
1598            DbEngine::detect("sqlite://app.db?mode=rwc"),
1599            DbEngine::Sqlite
1600        );
1601        assert_eq!(
1602            DbEngine::detect("postgres://user:pass@localhost:5432/slabs"),
1603            DbEngine::Postgres
1604        );
1605        assert_eq!(
1606            DbEngine::detect("postgresql://localhost/slabs"),
1607            DbEngine::Postgres
1608        );
1609    }
1610
1611    #[test]
1612    fn fts5_query_safely_quotes_user_input() {
1613        assert_eq!(
1614            fts5_query(r#"hello "world" fts5"#),
1615            Some(r#""hello"* AND "world"* AND "fts5"*"#.to_string())
1616        );
1617        assert_eq!(fts5_query("   "), None);
1618    }
1619
1620    #[tokio::test]
1621    async fn split_wal_pools_handle_concurrent_writers_and_readers_without_sqlite_busy() {
1622        let path =
1623            std::env::temp_dir().join(format!("slabs_wal_stress_{}.db", slabs_core::id::new("db")));
1624        let url = format!("sqlite://{}", path.display());
1625        let db = Db::connect(&url).await.unwrap();
1626        sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT NOT NULL)")
1627            .execute(db.writer())
1628            .await
1629            .unwrap();
1630
1631        let mut handles = Vec::new();
1632        // 24 concurrent writers using BEGIN IMMEDIATE + 24 concurrent readers on WAL read_pool
1633        for i in 0..24 {
1634            let db_w = db.clone();
1635            handles.push(tokio::spawn(async move {
1636                let mut tx = db_w.begin().await.unwrap();
1637                sqlx::query("INSERT INTO items (val) VALUES (?)")
1638                    .bind(format!("item-{i}"))
1639                    .execute(&mut *tx)
1640                    .await
1641                    .unwrap();
1642                tx.commit().await.unwrap();
1643            }));
1644
1645            let db_r = db.clone();
1646            handles.push(tokio::spawn(async move {
1647                let _count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
1648                    .fetch_one(db_r.reader())
1649                    .await
1650                    .unwrap();
1651            }));
1652        }
1653
1654        for h in handles {
1655            h.await.unwrap();
1656        }
1657
1658        let (total,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
1659            .fetch_one(db.reader())
1660            .await
1661            .unwrap();
1662        assert_eq!(total, 24);
1663
1664        let _ = std::fs::remove_file(&path);
1665        let _ = std::fs::remove_file(format!("{}-wal", path.display()));
1666        let _ = std::fs::remove_file(format!("{}-shm", path.display()));
1667    }
1668
1669    #[test]
1670    fn pagination_clamps_limits_and_computes_fetch_limit() {
1671        let default_page = Pagination::default();
1672        assert_eq!(default_page.clamped_limit(20, 100), 20);
1673        assert_eq!(default_page.fetch_limit(20, 100), 21);
1674
1675        let zero_page = Pagination {
1676            limit: Some(0),
1677            cursor: None,
1678        };
1679        assert_eq!(zero_page.clamped_limit(20, 100), 1);
1680        assert_eq!(zero_page.fetch_limit(20, 100), 2);
1681
1682        let huge_page = Pagination {
1683            limit: Some(500),
1684            cursor: Some("cur_1".into()),
1685        };
1686        assert_eq!(huge_page.clamped_limit(20, 100), 100);
1687        assert_eq!(huge_page.fetch_limit(20, 100), 101);
1688        assert_eq!(huge_page.cursor.as_deref(), Some("cur_1"));
1689    }
1690
1691    #[test]
1692    fn cursor_page_from_rows_truncates_and_sets_next_cursor() {
1693        let page = CursorPage::from_rows(vec![10, 20, 30], 2, ToString::to_string);
1694        assert_eq!(page.items, vec![10, 20]);
1695        assert!(page.has_more);
1696        assert_eq!(page.next_cursor.as_deref(), Some("20"));
1697
1698        let exact = CursorPage::from_rows(vec![10, 20], 2, ToString::to_string);
1699        assert_eq!(exact.items, vec![10, 20]);
1700        assert!(!exact.has_more);
1701        assert!(exact.next_cursor.is_none());
1702
1703        let empty = CursorPage::from_rows(Vec::<i32>::new(), 2, ToString::to_string);
1704        assert_eq!(empty.items, Vec::<i32>::new());
1705        assert!(!empty.has_more);
1706        assert!(empty.next_cursor.is_none());
1707    }
1708
1709    #[tokio::test]
1710    async fn audit_log_commits_and_rolls_back_atomically_with_tx() {
1711        let db = Db::connect("sqlite::memory:").await.unwrap();
1712        db.init_system_tables().await.unwrap();
1713        let audit = AuditLog::new(db.clone());
1714
1715        // Committed transaction persists audit entry
1716        let mut tx = db.begin().await.unwrap();
1717        let entry_id = audit
1718            .record_in_tx(
1719                &mut tx,
1720                Some("usr_1"),
1721                "room.created",
1722                "room",
1723                "room_1",
1724                &serde_json::json!({ "name": "Lobby" }),
1725            )
1726            .await
1727            .unwrap();
1728        assert!(entry_id.starts_with("aud_"));
1729        tx.commit().await.unwrap();
1730
1731        // Rolled back transaction does not persist audit entry
1732        let mut rollback_tx = db.begin().await.unwrap();
1733        let _rolled_back_id = audit
1734            .record_in_tx(
1735                &mut rollback_tx,
1736                Some("usr_2"),
1737                "room.deleted",
1738                "room",
1739                "room_1",
1740                &serde_json::json!({ "reason": "rolled back" }),
1741            )
1742            .await
1743            .unwrap();
1744        rollback_tx.rollback().await.unwrap();
1745
1746        // Second committed entry on another target to verify filtering
1747        let mut tx2 = db.begin().await.unwrap();
1748        let _other_id = audit
1749            .record_in_tx(
1750                &mut tx2,
1751                None,
1752                "user.invited",
1753                "user",
1754                "usr_9",
1755                &serde_json::json!({}),
1756            )
1757            .await
1758            .unwrap();
1759        tx2.commit().await.unwrap();
1760
1761        let room_entries = audit.list_for_target("room", "room_1", 10).await.unwrap();
1762        assert_eq!(room_entries.len(), 1);
1763        assert_eq!(room_entries[0].id, entry_id);
1764        assert_eq!(room_entries[0].actor_id.as_deref(), Some("usr_1"));
1765        assert_eq!(room_entries[0].action, "room.created");
1766        assert_eq!(room_entries[0].target_type, "room");
1767        assert_eq!(room_entries[0].target_id, "room_1");
1768        assert_eq!(room_entries[0].metadata_json, r#"{"name":"Lobby"}"#);
1769
1770        let recent = audit.list_recent(10).await.unwrap();
1771        assert_eq!(recent.len(), 2);
1772
1773        let recent_limited = audit.list_recent(1).await.unwrap();
1774        assert_eq!(recent_limited.len(), 1);
1775    }
1776
1777    #[tokio::test]
1778    async fn execute_sql_file_runs_seed_statements_and_handles_empty_or_missing() {
1779        let db = Db::connect("sqlite::memory:").await.unwrap();
1780        db.init_system_tables().await.unwrap();
1781
1782        let seed_path = std::env::temp_dir().join(format!(
1783            "slabs_seed_test_{}.sql",
1784            slabs_core::id::new("sql")
1785        ));
1786        std::fs::write(
1787            &seed_path,
1788            "CREATE TABLE widgets (id TEXT PRIMARY KEY, name TEXT NOT NULL);\n\
1789             INSERT INTO widgets (id, name) VALUES ('w_1', 'Alpha');\n\
1790             INSERT INTO widgets (id, name) VALUES ('w_2', 'Beta');\n",
1791        )
1792        .unwrap();
1793
1794        db.execute_sql_file(&seed_path).await.unwrap();
1795        let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM widgets")
1796            .fetch_one(db.reader())
1797            .await
1798            .unwrap();
1799        assert_eq!(count, 2);
1800
1801        // Blank seed file is a no-op
1802        std::fs::write(&seed_path, "   \n\t  ").unwrap();
1803        db.execute_sql_file(&seed_path).await.unwrap();
1804        let _ = std::fs::remove_file(&seed_path);
1805
1806        // Missing file returns an internal error
1807        let missing = std::env::temp_dir().join("slabs_definitely_missing_seed.sql");
1808        assert!(db.execute_sql_file(&missing).await.is_err());
1809
1810        // Both system schemas declare the new v0.2.0 system tables
1811        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
1812        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
1813        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
1814        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
1815    }
1816
1817    #[test]
1818    fn fts5_query_strips_control_chars_and_caps_tokens_and_lengths() {
1819        assert_eq!(
1820            fts5_query("hello\x00world \x07foo\x7fbar"),
1821            Some("\"helloworld\"* AND \"foobar\"*".to_string())
1822        );
1823        assert_eq!(fts5_query("\0\x01\x1f\x7f"), None);
1824
1825        // Cap at 16 tokens
1826        let many_tokens = (1..=25)
1827            .map(|i| format!("tok{i}"))
1828            .collect::<Vec<_>>()
1829            .join(" ");
1830        let rendered = fts5_query(&many_tokens).unwrap();
1831        assert_eq!(rendered.split(" AND ").count(), 16);
1832        assert!(rendered.contains("\"tok16\"*"));
1833        assert!(!rendered.contains("\"tok17\"*"));
1834
1835        // Cap each token to 64 chars
1836        let huge_token = "a".repeat(100);
1837        let rendered_long = fts5_query(&huge_token).unwrap();
1838        assert_eq!(rendered_long, format!("\"{}\"*", "a".repeat(64)));
1839    }
1840
1841    #[tokio::test]
1842    async fn init_system_tables_adds_locked_until_and_expires_at_and_upgrades_legacy_tables() {
1843        let db = Db::connect("sqlite::memory:").await.unwrap();
1844
1845        // Simulate legacy v0.2.0 tables without locked_until / expires_at
1846        sqlx::raw_sql(
1847            "CREATE TABLE slabs_jobs (
1848                id TEXT PRIMARY KEY NOT NULL,
1849                job_name TEXT NOT NULL,
1850                queue TEXT NOT NULL DEFAULT 'default',
1851                payload_json TEXT NOT NULL,
1852                status TEXT NOT NULL DEFAULT 'pending',
1853                attempts INTEGER NOT NULL DEFAULT 0,
1854                max_attempts INTEGER NOT NULL DEFAULT 5,
1855                run_at TEXT NOT NULL,
1856                last_error TEXT,
1857                created_at TEXT NOT NULL,
1858                updated_at TEXT NOT NULL
1859            );
1860            CREATE TABLE slabs_idempotency_keys (
1861                scope TEXT NOT NULL,
1862                key TEXT NOT NULL,
1863                response_json TEXT,
1864                created_at TEXT NOT NULL,
1865                PRIMARY KEY (scope, key)
1866            );
1867            CREATE TABLE slabs_blobs (
1868                id TEXT PRIMARY KEY NOT NULL,
1869                filename TEXT NOT NULL,
1870                content_type TEXT NOT NULL,
1871                byte_size INTEGER NOT NULL,
1872                checksum_sha256 TEXT NOT NULL,
1873                storage_key TEXT NOT NULL UNIQUE,
1874                created_at TEXT NOT NULL
1875            );
1876            CREATE TABLE slabs_incidents (
1877                id TEXT PRIMARY KEY,
1878                fingerprint TEXT NOT NULL UNIQUE,
1879                kind TEXT NOT NULL,
1880                source_file TEXT NOT NULL,
1881                route_pattern TEXT,
1882                status_code INTEGER,
1883                error_message TEXT NOT NULL,
1884                detail TEXT,
1885                context_json TEXT NOT NULL,
1886                git_sha TEXT,
1887                occurrences INTEGER NOT NULL DEFAULT 1,
1888                status TEXT NOT NULL DEFAULT 'open',
1889                resolved_in_sha TEXT,
1890                first_seen_at TEXT NOT NULL,
1891                last_seen_at TEXT NOT NULL
1892            );",
1893        )
1894        .execute(db.writer())
1895        .await
1896        .unwrap();
1897
1898        // Running init_system_tables twice should upgrade once and stay idempotent
1899        db.init_system_tables().await.unwrap();
1900        db.init_system_tables().await.unwrap();
1901
1902        let job_cols: Vec<(String,)> =
1903            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_jobs')")
1904                .fetch_all(db.reader())
1905                .await
1906                .unwrap();
1907        assert!(job_cols.iter().any(|(c,)| c == "locked_until"));
1908
1909        let idem_cols: Vec<(String,)> =
1910            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_idempotency_keys')")
1911                .fetch_all(db.reader())
1912                .await
1913                .unwrap();
1914        assert!(idem_cols.iter().any(|(c,)| c == "expires_at"));
1915
1916        let blob_cols: Vec<(String,)> =
1917            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_blobs')")
1918                .fetch_all(db.reader())
1919                .await
1920                .unwrap();
1921        assert!(blob_cols.iter().any(|(c,)| c == "scope"));
1922        assert!(SYSTEM_SCHEMA_SQL.contains("scope TEXT"));
1923        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("scope TEXT"));
1924
1925        let incident_cols: Vec<(String,)> =
1926            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_incidents')")
1927                .fetch_all(db.reader())
1928                .await
1929                .unwrap();
1930        for col in [
1931            "assignee",
1932            "external_issue_key",
1933            "external_issue_url",
1934            "recent_occurrences_json",
1935        ] {
1936            assert!(
1937                incident_cols.iter().any(|(c,)| c == col),
1938                "missing upgraded column {col}"
1939            );
1940            assert!(SYSTEM_SCHEMA_SQL.contains(col));
1941            assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains(col));
1942        }
1943
1944        // Verify security pragmas
1945        let (trusted_schema,): (i64,) = sqlx::query_as("PRAGMA trusted_schema")
1946            .fetch_one(db.writer())
1947            .await
1948            .unwrap();
1949        assert_eq!(trusted_schema, 0);
1950
1951        let (secure_delete,): (i64,) = sqlx::query_as("PRAGMA secure_delete")
1952            .fetch_one(db.writer())
1953            .await
1954            .unwrap();
1955        assert_eq!(secure_delete, 1);
1956    }
1957
1958    #[tokio::test]
1959    async fn audit_log_clamps_limits_to_1_through_500() {
1960        let db = Db::connect("sqlite::memory:").await.unwrap();
1961        db.init_system_tables().await.unwrap();
1962        let audit = AuditLog::new(db.clone());
1963
1964        let mut tx = db.begin().await.unwrap();
1965        for i in 0..3 {
1966            audit
1967                .record_in_tx(
1968                    &mut tx,
1969                    Some("usr_1"),
1970                    "item.updated",
1971                    "item",
1972                    "item_1",
1973                    &serde_json::json!({ "n": i }),
1974                )
1975                .await
1976                .unwrap();
1977        }
1978        tx.commit().await.unwrap();
1979
1980        // Non-positive limits clamp up to 1 (never SQLite's unlimited -1)
1981        assert_eq!(audit.list_recent(-1).await.unwrap().len(), 1);
1982        assert_eq!(audit.list_recent(0).await.unwrap().len(), 1);
1983        assert_eq!(
1984            audit
1985                .list_for_target("item", "item_1", -5)
1986                .await
1987                .unwrap()
1988                .len(),
1989            1
1990        );
1991        assert_eq!(
1992            audit
1993                .list_for_target("item", "item_1", 0)
1994                .await
1995                .unwrap()
1996                .len(),
1997            1
1998        );
1999        // Huge limit clamps to 500 and still succeeds
2000        assert_eq!(audit.list_recent(10_000).await.unwrap().len(), 3);
2001    }
2002
2003    #[tokio::test]
2004    async fn execute_sql_file_rolls_back_on_error() {
2005        let db = Db::connect("sqlite::memory:").await.unwrap();
2006        sqlx::query("CREATE TABLE items (id TEXT PRIMARY KEY)")
2007            .execute(db.writer())
2008            .await
2009            .unwrap();
2010
2011        let seed_path = std::env::temp_dir().join(format!(
2012            "slabs_seed_rollback_{}.sql",
2013            slabs_core::id::new("sql")
2014        ));
2015        std::fs::write(
2016            &seed_path,
2017            "INSERT INTO items (id) VALUES ('ok_1');\n\
2018             INSERT INTO items (id) VALUES ('ok_1');\n",
2019        )
2020        .unwrap();
2021
2022        assert!(db.execute_sql_file(&seed_path).await.is_err());
2023        let _ = std::fs::remove_file(&seed_path);
2024
2025        let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
2026            .fetch_one(db.reader())
2027            .await
2028            .unwrap();
2029        assert_eq!(count, 0);
2030    }
2031
2032    #[test]
2033    fn quote_pg_ident_escapes_double_quotes() {
2034        assert_eq!(quote_pg_ident("users"), "\"users\"");
2035        assert_eq!(quote_pg_ident("weird\"name"), "\"weird\"\"name\"");
2036    }
2037
2038    #[tokio::test]
2039    async fn incidents_record_deduplicate_list_get_resolve_and_reopen() {
2040        let db = Db::connect("sqlite::memory:").await.unwrap();
2041        db.init_system_tables().await.unwrap();
2042        let incidents = Incidents::new(db.clone());
2043
2044        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_incidents"));
2045        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_incidents"));
2046
2047        // Multibyte UTF-8 strings exceeding limits truncate cleanly on char boundaries
2048        let long_msg = "é".repeat(700); // 1400 bytes > 1024
2049        let long_detail = "€".repeat(2000); // 6000 bytes > 4096
2050
2051        let input = IncidentInput {
2052            kind: "panic".into(),
2053            source_file: "slabs/rooms/send_message.rs".into(),
2054            route_pattern: Some("/api/rooms/{room_id}/messages".into()),
2055            status_code: Some(500),
2056            error_message: long_msg.clone(),
2057            detail: Some(long_detail),
2058            context_json: serde_json::json!({ "request_id": "req_1" }),
2059            git_sha: Some("sha_aaa".into()),
2060            custom_fingerprint: None,
2061        };
2062
2063        let (first, is_new) = incidents.record(input.clone()).await.unwrap();
2064        assert!(is_new);
2065        assert!(first.id.starts_with("inc_"));
2066        assert_eq!(first.occurrences, 1);
2067        assert_eq!(first.status, "open");
2068        assert!(first.error_message.len() <= MAX_INCIDENT_ERROR_BYTES);
2069        assert!(first.detail.as_deref().unwrap().len() <= MAX_INCIDENT_DETAIL_BYTES);
2070        assert_eq!(incidents.count_open().await.unwrap(), 1);
2071
2072        // Second identical incident deduplicates and increments occurrences
2073        let mut second_input = input.clone();
2074        second_input.detail = Some("updated detail".into());
2075        second_input.git_sha = Some("sha_bbb".into());
2076        let (second, is_new_second) = incidents.record(second_input).await.unwrap();
2077        assert!(!is_new_second);
2078        assert_eq!(second.id, first.id);
2079        assert_eq!(second.occurrences, 2);
2080        assert_eq!(second.status, "open");
2081        assert_eq!(second.detail.as_deref(), Some("updated detail"));
2082        assert_eq!(second.git_sha.as_deref(), Some("sha_bbb"));
2083
2084        // Fetch by id
2085        let fetched = incidents.get(&first.id).await.unwrap().unwrap();
2086        assert_eq!(fetched.id, first.id);
2087        assert_eq!(fetched.occurrences, 2);
2088        assert!(incidents.get("inc_missing").await.unwrap().is_none());
2089
2090        // Resolve incident
2091        assert!(incidents.resolve(&first.id, Some("sha_fix")).await.unwrap());
2092        assert!(!incidents.resolve("inc_missing", None).await.unwrap());
2093        assert_eq!(incidents.count_open().await.unwrap(), 0);
2094        assert!(incidents.list(Some("open"), 10).await.unwrap().is_empty());
2095        let resolved_list = incidents.list(Some("resolved"), 10).await.unwrap();
2096        assert_eq!(resolved_list.len(), 1);
2097        assert_eq!(resolved_list[0].resolved_in_sha.as_deref(), Some("sha_fix"));
2098
2099        // Re-occurring resolved incident re-opens and returns is_new = true
2100        let (reopened, is_reopened) = incidents.record(input).await.unwrap();
2101        assert!(is_reopened);
2102        assert_eq!(reopened.id, first.id);
2103        assert_eq!(reopened.status, "open");
2104        assert_eq!(reopened.occurrences, 3);
2105        assert!(reopened.resolved_in_sha.is_none());
2106        assert_eq!(incidents.count_open().await.unwrap(), 1);
2107
2108        // Listing with None / "all" returns the row and clamps limits
2109        assert_eq!(incidents.list(None, -1).await.unwrap().len(), 1);
2110        assert_eq!(incidents.list(Some("all"), 999).await.unwrap().len(), 1);
2111    }
2112
2113    #[tokio::test]
2114    async fn incidents_record_with_outcome_lifecycle_reopen_and_user_bug_reports() {
2115        let db = Db::connect("sqlite::memory:").await.unwrap();
2116        db.init_system_tables().await.unwrap();
2117        let incidents = Incidents::new(db);
2118
2119        let base = IncidentInput {
2120            kind: "http_5xx".into(),
2121            source_file: "slabs/rooms/show.rs".into(),
2122            route_pattern: Some("/rooms/{id}".into()),
2123            status_code: Some(500),
2124            error_message: "boom".into(),
2125            detail: None,
2126            context_json: serde_json::json!({}),
2127            git_sha: Some("sha_1".into()),
2128            custom_fingerprint: None,
2129        };
2130
2131        let (rec1, outcome1) = incidents.record_with_outcome(base.clone()).await.unwrap();
2132        assert_eq!(outcome1, IncidentOutcome::Opened);
2133        assert_eq!(rec1.occurrences, 1);
2134
2135        let (rec2, outcome2) = incidents.record_with_outcome(base.clone()).await.unwrap();
2136        assert_eq!(outcome2, IncidentOutcome::Incremented);
2137        assert_eq!(rec2.id, rec1.id);
2138        assert_eq!(rec2.occurrences, 2);
2139
2140        assert!(incidents.resolve(&rec1.id, Some("sha_fix")).await.unwrap());
2141        let (rec3, outcome3) = incidents.record_with_outcome(base).await.unwrap();
2142        assert_eq!(outcome3, IncidentOutcome::Reopened);
2143        assert_eq!(rec3.id, rec1.id);
2144        assert_eq!(rec3.status, "open");
2145        assert_eq!(rec3.occurrences, 3);
2146        assert!(rec3.resolved_in_sha.is_none());
2147
2148        // Explicit reopen helper works on resolved incidents and returns false when missing
2149        assert!(incidents.resolve(&rec1.id, Some("sha_fix2")).await.unwrap());
2150        assert!(incidents.reopen(&rec1.id).await.unwrap());
2151        assert!(!incidents.reopen("inc_missing").await.unwrap());
2152        let reopened_row = incidents.get(&rec1.id).await.unwrap().unwrap();
2153        assert_eq!(reopened_row.status, "open");
2154        assert!(reopened_row.resolved_in_sha.is_none());
2155
2156        // User bug reports without custom_fingerprint create distinct open incidents
2157        let bug = IncidentInput {
2158            kind: "user_bug_report".into(),
2159            source_file: "slabs/rooms/show.rs".into(),
2160            route_pattern: Some("/rooms/1".into()),
2161            status_code: None,
2162            error_message: "Button does not respond".into(),
2163            detail: Some("Button does not respond".into()),
2164            context_json: serde_json::json!({ "reporter_user_id": "usr_1" }),
2165            git_sha: None,
2166            custom_fingerprint: None,
2167        };
2168        let (bug1, first_bug_outcome) = incidents.record_with_outcome(bug.clone()).await.unwrap();
2169        let (bug2, second_bug_outcome) = incidents.record_with_outcome(bug).await.unwrap();
2170        assert_eq!(first_bug_outcome, IncidentOutcome::Opened);
2171        assert_eq!(second_bug_outcome, IncidentOutcome::Opened);
2172        assert_ne!(bug1.id, bug2.id);
2173
2174        // Explicit custom_fingerprint deduplicates deterministically when reused
2175        let mut custom = IncidentInput {
2176            kind: "user_bug_report".into(),
2177            source_file: "slabs/rooms/show.rs".into(),
2178            route_pattern: None,
2179            status_code: None,
2180            error_message: "Grouped bug".into(),
2181            detail: None,
2182            context_json: serde_json::json!({}),
2183            git_sha: None,
2184            custom_fingerprint: Some("bug_group_key".into()),
2185        };
2186        let (c1, grouped_first) = incidents.record_with_outcome(custom.clone()).await.unwrap();
2187        let (c2, grouped_second) = incidents.record_with_outcome(custom.clone()).await.unwrap();
2188        assert_eq!(grouped_first, IncidentOutcome::Opened);
2189        assert_eq!(grouped_second, IncidentOutcome::Incremented);
2190        assert_eq!(c1.id, c2.id);
2191        assert_eq!(c2.occurrences, 2);
2192
2193        custom.custom_fingerprint = Some(slabs_core::id::new("bug"));
2194        let (c3, unique_custom) = incidents.record_with_outcome(custom).await.unwrap();
2195        assert_eq!(unique_custom, IncidentOutcome::Opened);
2196        assert_ne!(c3.id, c1.id);
2197    }
2198
2199    #[tokio::test]
2200    async fn explain_query_plan_detects_scan_vs_index_and_rejects_non_select_sql() {
2201        let db = Db::connect("sqlite::memory:").await.unwrap();
2202        sqlx::raw_sql(
2203            "CREATE TABLE messages (
2204                id TEXT PRIMARY KEY NOT NULL,
2205                room_id TEXT NOT NULL,
2206                body TEXT NOT NULL
2207            );
2208            CREATE INDEX idx_messages_room ON messages(room_id);",
2209        )
2210        .execute(db.writer())
2211        .await
2212        .unwrap();
2213
2214        // Unindexed filter -> full table SCAN
2215        let scan_plan = db
2216            .explain_query_plan("SELECT id FROM messages WHERE body = 'hello'")
2217            .await
2218            .unwrap();
2219        assert!(
2220            scan_plan.iter().any(|line| line.contains("SCAN messages")),
2221            "expected SCAN in plan: {scan_plan:?}"
2222        );
2223
2224        // Indexed filter -> SEARCH ... USING INDEX
2225        let index_plan = db
2226            .explain_query_plan("SELECT id FROM messages WHERE room_id = 'room_1'")
2227            .await
2228            .unwrap();
2229        assert!(
2230            index_plan
2231                .iter()
2232                .any(|line| line.contains("USING INDEX idx_messages_room")
2233                    || line.contains("USING COVERING INDEX idx_messages_room")),
2234            "expected USING INDEX in plan: {index_plan:?}"
2235        );
2236
2237        // CTE WITH query is permitted
2238        let cte_plan = db
2239            .explain_query_plan(
2240                "WITH r AS (SELECT id FROM messages WHERE room_id = 'r1') SELECT id FROM r",
2241            )
2242            .await
2243            .unwrap();
2244        assert!(
2245            cte_plan
2246                .iter()
2247                .any(|line| line.contains("idx_messages_room")),
2248            "expected idx_messages_room in CTE plan: {cte_plan:?}"
2249        );
2250
2251        // Reject empty, semicolons, and non-SELECT statements
2252        assert!(db.explain_query_plan("   ").await.is_err());
2253        assert!(db
2254            .explain_query_plan("SELECT 1; DROP TABLE messages")
2255            .await
2256            .is_err());
2257        assert!(db.explain_query_plan("DELETE FROM messages").await.is_err());
2258        assert!(db
2259            .explain_query_plan("UPDATE messages SET body = 'x'")
2260            .await
2261            .is_err());
2262        assert!(db
2263            .explain_query_plan("INSERT INTO messages VALUES ('1','r','b')")
2264            .await
2265            .is_err());
2266        assert!(db.explain_query_plan("DROP TABLE messages").await.is_err());
2267        assert!(db
2268            .explain_query_plan("PRAGMA table_info(messages)")
2269            .await
2270            .is_err());
2271    }
2272
2273    #[tokio::test]
2274    async fn incidents_claim_link_ignore_reopen_and_occurrence_ring_buffer() {
2275        let db = Db::connect("sqlite::memory:").await.unwrap();
2276        db.init_system_tables().await.unwrap();
2277        let incidents = Incidents::new(db);
2278
2279        // Record 12 occurrences of the same fingerprinted incident; ring buffer keeps last 10
2280        let mut inc_id = String::new();
2281        for idx in 1..=12 {
2282            let input = IncidentInput {
2283                kind: "http_5xx".into(),
2284                source_file: "slabs/orders/charge.rs".into(),
2285                route_pattern: Some("/api/orders/charge".into()),
2286                status_code: Some(500),
2287                error_message: "gateway timeout".into(),
2288                detail: Some(format!("attempt {idx}")),
2289                context_json: serde_json::json!({
2290                    "request_id": format!("req_{idx}"),
2291                    "latency_ms": idx * 100,
2292                }),
2293                git_sha: Some(format!("sha_{idx:02}")),
2294                custom_fingerprint: None,
2295            };
2296            let (rec, outcome) = incidents.record_with_outcome(input).await.unwrap();
2297            if idx == 1 {
2298                assert_eq!(outcome, IncidentOutcome::Opened);
2299                inc_id = rec.id.clone();
2300            } else {
2301                assert_eq!(outcome, IncidentOutcome::Incremented);
2302            }
2303            if idx == 12 {
2304                let history: Vec<serde_json::Value> =
2305                    serde_json::from_str(&rec.recent_occurrences_json).unwrap();
2306                assert_eq!(history.len(), 10);
2307                assert_eq!(history[0]["git_sha"], "sha_03");
2308                assert_eq!(history[0]["request_id"], "req_3");
2309                assert_eq!(history[0]["latency_ms"], 300);
2310                assert_eq!(history[9]["git_sha"], "sha_12");
2311                assert_eq!(history[9]["request_id"], "req_12");
2312                assert_eq!(history[9]["latency_ms"], 1200);
2313                assert!(history[9]["seen_at"].as_str().is_some());
2314            }
2315        }
2316
2317        // Atomic claim transitions open -> in_progress and blocks concurrent second claim
2318        assert!(incidents.claim(&inc_id, "   ").await.is_err());
2319        assert!(incidents.claim(&inc_id, "agent-alpha").await.unwrap());
2320        assert!(!incidents.claim(&inc_id, "agent-beta").await.unwrap());
2321
2322        let claimed = incidents.get(&inc_id).await.unwrap().unwrap();
2323        assert_eq!(claimed.status, "in_progress");
2324        assert_eq!(claimed.assignee.as_deref(), Some("agent-alpha"));
2325        assert_eq!(
2326            incidents.list(Some("in_progress"), 10).await.unwrap().len(),
2327            1
2328        );
2329
2330        // External tracker linking validates URL scheme and persists key/url
2331        assert!(incidents
2332            .link_external(&inc_id, "ENG-42", "javascript:alert(1)")
2333            .await
2334            .is_err());
2335        assert!(incidents
2336            .link_external(&inc_id, "", "https://linear.app/team/issue/ENG-42")
2337            .await
2338            .is_err());
2339        assert!(incidents
2340            .link_external(&inc_id, "ENG-42", "https://linear.app/team/issue/ENG-42")
2341            .await
2342            .unwrap());
2343        assert!(!incidents
2344            .link_external(
2345                "inc_missing",
2346                "ENG-42",
2347                "https://linear.app/team/issue/ENG-42"
2348            )
2349            .await
2350            .unwrap());
2351
2352        // Resolve then recur -> reopens to open, clears assignee, preserves external issue link
2353        assert!(incidents.resolve(&inc_id, Some("sha_fix")).await.unwrap());
2354        let recur_input = IncidentInput {
2355            kind: "http_5xx".into(),
2356            source_file: "slabs/orders/charge.rs".into(),
2357            route_pattern: Some("/api/orders/charge".into()),
2358            status_code: Some(500),
2359            error_message: "gateway timeout".into(),
2360            detail: None,
2361            context_json: serde_json::json!({ "request_id": "req_13", "latency_ms": 1300 }),
2362            git_sha: Some("sha_13".into()),
2363            custom_fingerprint: None,
2364        };
2365        let (reopened, outcome) = incidents
2366            .record_with_outcome(recur_input.clone())
2367            .await
2368            .unwrap();
2369        assert_eq!(outcome, IncidentOutcome::Reopened);
2370        assert_eq!(reopened.status, "open");
2371        assert!(reopened.assignee.is_none());
2372        assert!(reopened.resolved_in_sha.is_none());
2373        assert_eq!(reopened.external_issue_key.as_deref(), Some("ENG-42"));
2374        assert_eq!(
2375            reopened.external_issue_url.as_deref(),
2376            Some("https://linear.app/team/issue/ENG-42")
2377        );
2378
2379        // Ignore -> stays ignored on recurrence, increments occurrences & recent history, returns Incremented
2380        assert!(incidents.ignore(&inc_id).await.unwrap());
2381        assert!(!incidents.ignore("inc_missing").await.unwrap());
2382        assert_eq!(incidents.list(Some("ignored"), 10).await.unwrap().len(), 1);
2383
2384        let (still_ignored, ignored_outcome) =
2385            incidents.record_with_outcome(recur_input).await.unwrap();
2386        assert_eq!(ignored_outcome, IncidentOutcome::Incremented);
2387        assert_eq!(still_ignored.status, "ignored");
2388        assert_eq!(still_ignored.occurrences, 14);
2389        let history: Vec<serde_json::Value> =
2390            serde_json::from_str(&still_ignored.recent_occurrences_json).unwrap();
2391        assert_eq!(history.len(), 10);
2392        assert_eq!(history[9]["git_sha"], "sha_13");
2393    }
2394}