frigg 0.6.0

Frigg gives AI agents local, source-backed code search and navigation without sending whole repositories through every prompt.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Storage initialization, verification, and vector-store lifecycle entry points.
//!
//! Coordinates schema init, vector extension readiness, verification, and auto-repair for
//! `.frigg/storage.sqlite3`; callers treat failures here as bootstrap blockers rather than
//! per-query errors.

use std::time::Duration;

use super::*;

fn vector_store_error_is_repairable(message: &str) -> bool {
    message.contains("missing vector table")
        || message.contains("vector table schema mismatch")
        || message.contains("legacy non-sqlite-vec schema")
}

impl Storage {
    pub fn new(db_path: impl Into<PathBuf>) -> Self {
        Self {
            db_path: db_path.into(),
        }
    }

    pub fn db_path(&self) -> &Path {
        &self.db_path
    }

    /// Opens storage, creates the current schema when empty, and initializes the vector extension.
    pub fn initialize(&self) -> FriggResult<()> {
        self.initialize_with_vector_store(true)
    }

    /// Initializes storage and auto-repairs regenerable invariants when verification fails.
    pub fn initialize_with_auto_repair(&self) -> FriggResult<Vec<String>> {
        match self.initialize() {
            Ok(()) => self.verify_with_auto_repair(),
            Err(original_err) => self.repair_then_verify(original_err),
        }
    }

    pub(crate) fn initialize_without_vector_store(&self) -> FriggResult<()> {
        self.initialize_with_vector_store(false)
    }

    fn incompatible_schema_error(&self, found_version: i64) -> FriggError {
        FriggError::StorageSchemaIncompatible {
            found_version,
            expected_version: CURRENT_SCHEMA_VERSION,
            db_path: self.db_path.clone(),
        }
    }

    fn uninitialized_schema_error(&self) -> FriggError {
        FriggError::Internal(format!(
            "storage schema is uninitialized: '{}' has no Frigg schema_version row; run `frigg init` or `frigg index` to create current storage, or delete the file first if it is not a Frigg database",
            self.db_path.display()
        ))
    }

    pub fn require_current_schema(&self) -> FriggResult<()> {
        let conn = open_existing_connection(&self.db_path)?;
        self.require_current_schema_on_connection(&conn)
    }

    pub(crate) fn open_current_schema_connection(&self) -> FriggResult<Connection> {
        let conn = open_existing_connection(&self.db_path)?;
        self.require_current_schema_on_connection(&conn)?;
        Ok(conn)
    }

    pub(crate) fn open_session(&self) -> FriggResult<StorageSession> {
        let conn = self.open_current_schema_connection()?;
        Ok(StorageSession {
            db_path: self.db_path.clone(),
            conn,
        })
    }

    pub(crate) fn require_current_schema_on_connection(
        &self,
        conn: &Connection,
    ) -> FriggResult<()> {
        if !table_exists(conn, "schema_version")? {
            if database_has_user_tables(conn)? {
                return Err(self.incompatible_schema_error(0));
            }
            return Err(self.uninitialized_schema_error());
        }

        let current_version = read_schema_version(conn)?;
        if current_version != CURRENT_SCHEMA_VERSION {
            return Err(self.incompatible_schema_error(current_version));
        }

        Ok(())
    }

    fn create_current_schema(&self, conn: &mut Connection) -> FriggResult<()> {
        let tx = conn.transaction().map_err(|err| {
            FriggError::Internal(format!(
                "failed to start current schema initialization transaction: {err}"
            ))
        })?;
        tx.execute_batch(CURRENT_SCHEMA_SQL).map_err(|err| {
            FriggError::Internal(format!(
                "failed to initialize current storage schema: {err}"
            ))
        })?;
        set_schema_version(&tx, CURRENT_SCHEMA_VERSION)?;
        tx.commit().map_err(|err| {
            FriggError::Internal(format!(
                "failed to commit current schema initialization transaction: {err}"
            ))
        })?;
        Ok(())
    }

    fn ensure_current_schema(&self, conn: &mut Connection) -> FriggResult<()> {
        if !table_exists(conn, "schema_version")? {
            if database_has_user_tables(conn)? {
                return Err(self.incompatible_schema_error(0));
            }
            return self.create_current_schema(conn);
        }

        let current_version = read_schema_version(conn)?;
        if current_version != CURRENT_SCHEMA_VERSION {
            return Err(self.incompatible_schema_error(current_version));
        }

        Ok(())
    }

    fn initialize_with_vector_store(&self, initialize_vector_store: bool) -> FriggResult<()> {
        let mut conn = open_connection(&self.db_path)?;

        conn.execute_batch(
            r#"
            PRAGMA journal_mode = WAL;
            PRAGMA synchronous = NORMAL;
            "#,
        )
        .map_err(|err| {
            FriggError::Internal(format!("failed to configure sqlite pragmas: {err}"))
        })?;

        self.ensure_current_schema(&mut conn)?;

        if initialize_vector_store {
            initialize_vector_store_on_connection(&conn, DEFAULT_VECTOR_DIMENSIONS)?;
        }

        Ok(())
    }

    pub fn schema_version(&self) -> FriggResult<i64> {
        let conn = open_existing_connection(&self.db_path)?;
        if !table_exists(&conn, "schema_version")? {
            return Ok(0);
        }

        read_schema_version(&conn)
    }

    /// Verifies schema version, required tables, and storage invariants.
    pub fn verify(&self) -> FriggResult<()> {
        let mut conn = open_existing_connection(&self.db_path)?;
        self.require_current_schema_on_connection(&conn)?;
        self.verify_required_tables_on_connection(&conn)?;

        run_repository_roundtrip_probe(&mut conn)?;
        verify_vector_store_on_connection(&conn, DEFAULT_VECTOR_DIMENSIONS)?;
        self.verify_storage_invariants_with_connection(&conn)?;

        Ok(())
    }

    /// Verifies storage invariants and attempts one repair pass before surfacing the original error.
    pub fn verify_with_auto_repair(&self) -> FriggResult<Vec<String>> {
        match self.verify() {
            Ok(()) => Ok(Vec::new()),
            Err(original_err) => self.repair_then_verify(original_err),
        }
    }

    fn repair_then_verify(&self, original_err: FriggError) -> FriggResult<Vec<String>> {
        let repair_summary = self.repair_storage_invariants()?;
        match self.verify() {
            Ok(()) => Ok(repair_summary.repaired_categories),
            Err(_) if repair_summary.repaired_categories.is_empty() => Err(original_err),
            Err(err) => Err(err),
        }
    }

    pub fn verify_relational_schema(&self) -> FriggResult<()> {
        let mut conn = open_existing_connection(&self.db_path)?;
        self.require_current_schema_on_connection(&conn)?;
        self.verify_required_tables_on_connection(&conn)?;
        run_repository_roundtrip_probe(&mut conn)?;
        self.verify_storage_invariants_with_connection(&conn)?;
        Ok(())
    }

    fn verify_required_tables_on_connection(&self, conn: &Connection) -> FriggResult<()> {
        for table in REQUIRED_TABLES {
            if !table_exists(conn, table)? {
                return Err(FriggError::Internal(format!(
                    "storage verification failed: missing required table '{table}' in '{}'; delete the storage DB and run `frigg index` to rebuild current storage",
                    self.db_path.display()
                )));
            }
        }

        let version = read_schema_version(conn)?;
        if version != CURRENT_SCHEMA_VERSION {
            return Err(FriggError::Internal(format!(
                "storage verification failed: schema version mismatch (found {version}, expected {CURRENT_SCHEMA_VERSION}); automatic schema migrations are disabled; delete '{}' and run `frigg index` to rebuild current storage",
                self.db_path.display()
            )));
        }
        Ok(())
    }

    pub fn repair_storage_invariants(&self) -> FriggResult<StorageInvariantRepairSummary> {
        let conn = self.open_current_schema_connection()?;
        let mut repaired_categories = Vec::new();

        match verify_vector_store_on_connection(&conn, DEFAULT_VECTOR_DIMENSIONS) {
            Ok(_) => {}
            Err(err) if vector_store_error_is_repairable(&err.to_string()) => {
                drop(conn);
                self.repair_semantic_vector_store()?;
                repaired_categories.push(INVARIANT_SEMANTIC_VECTOR_PARTITION_IN_SYNC.to_string());
                return Ok(StorageInvariantRepairSummary {
                    repaired_categories,
                });
            }
            Err(err) => return Err(err),
        }

        let inconsistent_partitions = self.semantic_vector_partition_violations(&conn)?;
        if !inconsistent_partitions.is_empty() {
            self.repair_semantic_vector_store()?;
            repaired_categories.push(INVARIANT_SEMANTIC_VECTOR_PARTITION_IN_SYNC.to_string());
        }

        Ok(StorageInvariantRepairSummary {
            repaired_categories,
        })
    }

    fn verify_storage_invariants_with_connection(&self, conn: &Connection) -> FriggResult<()> {
        let invalid_manifest_rows: i64 = conn
            .query_row(
                r#"
                SELECT COUNT(*)
                FROM file_manifest AS manifest
                INNER JOIN snapshot ON snapshot.snapshot_id = manifest.snapshot_id
                WHERE snapshot.kind != ?1
                "#,
                [SNAPSHOT_KIND_MANIFEST],
                |row| row.get(0),
            )
            .map_err(|err| {
                FriggError::Internal(format!(
                    "storage verification failed: invariant={} error=failed to count invalid manifest rows: {err}",
                    INVARIANT_MANIFEST_ROWS_REQUIRE_MANIFEST_SNAPSHOTS
                ))
            })?;
        if invalid_manifest_rows > 0 {
            return Err(FriggError::Internal(format!(
                "storage verification failed: invariant={} count={invalid_manifest_rows}",
                INVARIANT_MANIFEST_ROWS_REQUIRE_MANIFEST_SNAPSHOTS
            )));
        }

        let invalid_semantic_heads: i64 = conn
            .query_row(
                r#"
                SELECT COUNT(*)
                FROM semantic_head
                LEFT JOIN snapshot
                  ON snapshot.snapshot_id = semantic_head.covered_snapshot_id
                 AND snapshot.repository_id = semantic_head.repository_id
                WHERE snapshot.snapshot_id IS NULL OR snapshot.kind != ?1
                "#,
                [SNAPSHOT_KIND_MANIFEST],
                |row| row.get(0),
            )
            .map_err(|err| {
                FriggError::Internal(format!(
                    "storage verification failed: invariant={} error=failed to count invalid semantic heads: {err}",
                    INVARIANT_SEMANTIC_HEAD_REQUIRES_MANIFEST_SNAPSHOT
                ))
            })?;
        if invalid_semantic_heads > 0 {
            return Err(FriggError::Internal(format!(
                "storage verification failed: invariant={} count={invalid_semantic_heads}",
                INVARIANT_SEMANTIC_HEAD_REQUIRES_MANIFEST_SNAPSHOT
            )));
        }

        let inconsistent_partitions = self.semantic_vector_partition_violations(conn)?;
        if !inconsistent_partitions.is_empty() {
            return Err(FriggError::Internal(format!(
                "storage verification failed: invariant={} count={} partitions={}",
                INVARIANT_SEMANTIC_VECTOR_PARTITION_IN_SYNC,
                inconsistent_partitions.len(),
                inconsistent_partitions.join(",")
            )));
        }

        Ok(())
    }

    fn semantic_vector_partition_violations(&self, conn: &Connection) -> FriggResult<Vec<String>> {
        let mut stmt = conn
            .prepare(
                r#"
                SELECT repository_id, provider, model
                FROM semantic_head
                ORDER BY repository_id, provider, model
                "#,
            )
            .map_err(|err| {
                FriggError::Internal(format!(
                    "storage verification failed: invariant={} error=failed to prepare semantic partition scan: {err}",
                    INVARIANT_SEMANTIC_VECTOR_PARTITION_IN_SYNC
                ))
            })?;
        let rows = stmt
            .query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                ))
            })
            .map_err(|err| {
                FriggError::Internal(format!(
                    "storage verification failed: invariant={} error=failed to iterate semantic partitions: {err}",
                    INVARIANT_SEMANTIC_VECTOR_PARTITION_IN_SYNC
                ))
            })?;

        let mut partitions = Vec::new();
        for row in rows {
            let (repository_id, provider, model) = row.map_err(|err| {
                FriggError::Internal(format!(
                    "storage verification failed: invariant={} error=failed to decode semantic partition row: {err}",
                    INVARIANT_SEMANTIC_VECTOR_PARTITION_IN_SYNC
                ))
            })?;
            let health = self.collect_semantic_storage_health_for_repository_model(
                &repository_id,
                &provider,
                &model,
            )?;
            if !health.vector_consistent {
                partitions.push(format!("{repository_id}:{provider}:{model}"));
            }
        }

        Ok(partitions)
    }

    pub fn initialize_vector_store(
        &self,
        expected_dimensions: usize,
    ) -> FriggResult<VectorStoreStatus> {
        let conn = open_connection(&self.db_path)?;
        initialize_vector_store_on_connection(&conn, expected_dimensions)
    }

    pub fn verify_vector_store(
        &self,
        expected_dimensions: usize,
    ) -> FriggResult<VectorStoreStatus> {
        let conn = open_existing_connection(&self.db_path)?;
        verify_vector_store_on_connection(&conn, expected_dimensions)
    }
}

impl StorageSession {
    pub(crate) fn checkpoint_wal_truncate(&self) -> FriggResult<()> {
        checkpoint_wal_truncate_on_connection(&self.conn, &self.db_path)
    }
}

fn checkpoint_wal_truncate_on_connection(conn: &Connection, db_path: &Path) -> FriggResult<()> {
    let previous_busy_timeout_ms: i64 = conn
        .query_row("PRAGMA busy_timeout", [], |row| row.get(0))
        .map_err(|err| {
            FriggError::Internal(format!(
                "failed to read sqlite busy timeout before WAL checkpoint for '{}': {err}",
                db_path.display()
            ))
        })?;
    let previous_busy_timeout_ms = u64::try_from(previous_busy_timeout_ms).map_err(|err| {
        FriggError::Internal(format!(
            "invalid sqlite busy timeout before WAL checkpoint for '{}': {err}",
            db_path.display()
        ))
    })?;

    conn.busy_timeout(Duration::from_millis(0)).map_err(|err| {
        FriggError::Internal(format!(
            "failed to disable sqlite busy timeout for WAL checkpoint on '{}': {err}",
            db_path.display()
        ))
    })?;
    let checkpoint_result = conn.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
        Ok((
            row.get::<_, i64>(0)?,
            row.get::<_, i64>(1)?,
            row.get::<_, i64>(2)?,
        ))
    });
    let restore_result = conn.busy_timeout(Duration::from_millis(previous_busy_timeout_ms));

    restore_result.map_err(|err| {
        FriggError::Internal(format!(
            "failed to restore sqlite busy timeout after WAL checkpoint for '{}': {err}",
            db_path.display()
        ))
    })?;

    let (busy, _log_pages, _checkpointed_pages) = checkpoint_result.map_err(|err| {
        FriggError::Internal(format!(
            "failed to checkpoint sqlite WAL for '{}': {err}",
            db_path.display()
        ))
    })?;
    if busy > 0 {
        return Err(FriggError::Internal(format!(
            "sqlite WAL checkpoint for '{}' skipped because {busy} connection(s) were busy",
            db_path.display()
        )));
    }
    Ok(())
}