luft-storage 0.3.2

SQLite persistence for Luft
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! UI-ready query API.
//!
//! All functions read from the global SQLite DB and return structs that map
//! directly to UI components (run list, conversation view, run tree).

use crate::error::StorageResult;
use crate::DbPool;
use luft_core::contract::ids::{AgentId, RunId};
use sqlx::Row;

/// Run summary for list views.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RunSummary {
    pub run_id: RunId,
    pub task: String,
    pub status: String,
    pub started_ts: String,
    pub finished_ts: Option<String>,
    pub elapsed_ms: i64,
    pub input_tokens: i64,
    pub output_tokens: i64,
}

/// Per-agent overview within a run.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AgentOverview {
    pub agent_id: AgentId,
    pub phase_id: Option<i64>,
    pub model: Option<String>,
    pub status: String,
    pub prompt_preview: Option<String>,
    pub input_tokens: i64,
    pub output_tokens: i64,
    pub elapsed_ms: i64,
    pub started_ts: String,
    pub done_ts: Option<String>,
    pub retry_count: i64,
}

/// One row of an agent's conversation stream.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TurnRow {
    pub seq: i64,
    pub ts: String,
    pub kind: String,
    pub role: Option<String>,
    pub text: Option<String>,
    pub tool_call_id: Option<String>,
    pub name: Option<String>,
    pub input: Option<String>,
    pub output: Option<String>,
    pub tool_status: Option<String>,
    pub file_path: Option<String>,
    pub file_op: Option<String>,
    pub diff: Option<String>,
}

/// Aggregated overview of a run.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RunOverview {
    pub run: RunSummary,
    pub agents: Vec<AgentOverview>,
    pub turn_counts: Vec<TurnKindCount>,
    pub total_messages: i64,
    pub total_tool_calls: i64,
    pub total_file_edits: i64,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TurnKindCount {
    pub kind: String,
    pub count: i64,
}

/// Span row used to build the run orchestration tree.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SpanRow {
    pub span_id: i64,
    pub kind: String,
    pub phase_id: Option<i64>,
    pub parent_span_id: Option<i64>,
    pub label: Option<String>,
    pub path: Option<String>,
    pub items: Option<i64>,
    pub max_rounds: Option<i64>,
    pub rounds: Option<i64>,
    pub converged: Option<i64>,
    pub ok: Option<i64>,
    pub failed: Option<i64>,
    pub result: Option<String>,
    pub error: Option<String>,
    pub started_ts: Option<String>,
    pub done_ts: Option<String>,
    pub elapsed_ms: i64,
}

// ---------------------------------------------------------------------------
// Queries
// ---------------------------------------------------------------------------

/// List recent runs, newest first. Paginated.
pub async fn list_runs(pool: &DbPool, limit: i64, offset: i64) -> StorageResult<Vec<RunSummary>> {
    let rows = sqlx::query(
        r#"SELECT run_id, task, status, started_ts, finished_ts, elapsed_ms,
                  input_tokens, output_tokens
           FROM runs
           ORDER BY started_ts DESC
           LIMIT ? OFFSET ?"#,
    )
    .bind(limit)
    .bind(offset)
    .fetch_all(pool)
    .await?;

    rows.into_iter()
        .map(|r| {
            Ok(RunSummary {
                run_id: r.try_get("run_id")?,
                task: r.try_get("task")?,
                status: r.try_get("status")?,
                started_ts: r.try_get("started_ts")?,
                finished_ts: r.try_get("finished_ts")?,
                elapsed_ms: r.try_get("elapsed_ms")?,
                input_tokens: r.try_get("input_tokens")?,
                output_tokens: r.try_get("output_tokens")?,
            })
        })
        .collect()
}

/// List turns for an agent, in seq order. Paginated.
pub async fn get_agent_turns(
    pool: &DbPool,
    run_id: RunId,
    agent_id: AgentId,
    limit: i64,
    offset: i64,
) -> StorageResult<Vec<TurnRow>> {
    let rows = sqlx::query(
        r#"SELECT seq, ts, kind, role, text, tool_call_id, name, input, output,
                  tool_status, file_path, file_op, diff
           FROM turns
           WHERE run_id = ? AND agent_id = ?
           ORDER BY seq
           LIMIT ? OFFSET ?"#,
    )
    .bind(run_id)
    .bind(agent_id)
    .bind(limit)
    .bind(offset)
    .fetch_all(pool)
    .await?;

    rows.into_iter()
        .map(|r| {
            Ok(TurnRow {
                seq: r.try_get("seq")?,
                ts: r.try_get("ts")?,
                kind: r.try_get("kind")?,
                role: r.try_get("role")?,
                text: r.try_get("text")?,
                tool_call_id: r.try_get("tool_call_id")?,
                name: r.try_get("name")?,
                input: r.try_get("input")?,
                output: r.try_get("output")?,
                tool_status: r.try_get("tool_status")?,
                file_path: r.try_get("file_path")?,
                file_op: r.try_get("file_op")?,
                diff: r.try_get("diff")?,
            })
        })
        .collect()
}

/// Single-agent overview (status, tokens, model).
pub async fn get_agent_overview(
    pool: &DbPool,
    run_id: RunId,
    agent_id: AgentId,
) -> StorageResult<AgentOverview> {
    let r = sqlx::query(
        r#"SELECT agent_id, phase_id, model, status, prompt_preview,
                  input_tokens, output_tokens, elapsed_ms, started_ts, done_ts,
                  retry_count
           FROM agents WHERE run_id = ? AND agent_id = ?"#,
    )
    .bind(run_id)
    .bind(agent_id)
    .fetch_one(pool)
    .await?;

    Ok(AgentOverview {
        agent_id: r.try_get("agent_id")?,
        phase_id: r.try_get("phase_id")?,
        model: r.try_get("model")?,
        status: r.try_get("status")?,
        prompt_preview: r.try_get("prompt_preview")?,
        input_tokens: r.try_get("input_tokens")?,
        output_tokens: r.try_get("output_tokens")?,
        elapsed_ms: r.try_get("elapsed_ms")?,
        started_ts: r.try_get("started_ts")?,
        done_ts: r.try_get("done_ts")?,
        retry_count: r.try_get("retry_count")?,
    })
}

/// All agents for a run.
pub async fn get_run_agents(pool: &DbPool, run_id: RunId) -> StorageResult<Vec<AgentOverview>> {
    let rows = sqlx::query(
        r#"SELECT agent_id, phase_id, model, status, prompt_preview,
                  input_tokens, output_tokens, elapsed_ms, started_ts, done_ts,
                  retry_count
           FROM agents
           WHERE run_id = ?
           ORDER BY started_ts"#,
    )
    .bind(run_id)
    .fetch_all(pool)
    .await?;

    rows.into_iter()
        .map(|r| {
            Ok(AgentOverview {
                agent_id: r.try_get("agent_id")?,
                phase_id: r.try_get("phase_id")?,
                model: r.try_get("model")?,
                status: r.try_get("status")?,
                prompt_preview: r.try_get("prompt_preview")?,
                input_tokens: r.try_get("input_tokens")?,
                output_tokens: r.try_get("output_tokens")?,
                elapsed_ms: r.try_get("elapsed_ms")?,
                started_ts: r.try_get("started_ts")?,
                done_ts: r.try_get("done_ts")?,
                retry_count: r.try_get("retry_count")?,
            })
        })
        .collect()
}

/// Aggregated run overview with turn counts.
pub async fn get_run_overview(pool: &DbPool, run_id: RunId) -> StorageResult<RunOverview> {
    let run_row = sqlx::query(
        r#"SELECT run_id, task, status, started_ts, finished_ts, elapsed_ms,
                  input_tokens, output_tokens
           FROM runs WHERE run_id = ?"#,
    )
    .bind(run_id)
    .fetch_one(pool)
    .await?;

    let run = RunSummary {
        run_id: run_row.try_get("run_id")?,
        task: run_row.try_get("task")?,
        status: run_row.try_get("status")?,
        started_ts: run_row.try_get("started_ts")?,
        finished_ts: run_row.try_get("finished_ts")?,
        elapsed_ms: run_row.try_get("elapsed_ms")?,
        input_tokens: run_row.try_get("input_tokens")?,
        output_tokens: run_row.try_get("output_tokens")?,
    };

    let agents = get_run_agents(pool, run_id).await?;

    let count_rows =
        sqlx::query("SELECT kind, COUNT(*) AS c FROM turns WHERE run_id = ? GROUP BY kind")
            .bind(run_id)
            .fetch_all(pool)
            .await?;

    let mut turn_counts = Vec::new();
    let mut total_messages = 0i64;
    let mut total_tool_calls = 0i64;
    let mut total_file_edits = 0i64;
    for r in count_rows {
        let kind: String = r.try_get("kind")?;
        let count: i64 = r.try_get("c")?;
        match kind.as_str() {
            "message" => total_messages = count,
            "tool_call" | "tool_result" => total_tool_calls += count,
            "file_edit" => total_file_edits = count,
            _ => {}
        }
        turn_counts.push(TurnKindCount { kind, count });
    }

    Ok(RunOverview {
        run,
        agents,
        turn_counts,
        total_messages,
        total_tool_calls,
        total_file_edits,
    })
}

/// Orchestration spans for a run (caller assembles into a tree).
pub async fn get_run_spans(pool: &DbPool, run_id: RunId) -> StorageResult<Vec<SpanRow>> {
    let rows = sqlx::query(
        r#"SELECT span_id, kind, phase_id, parent_span_id, label, path,
                  items, max_rounds, rounds, converged, ok, failed,
                  result, error, started_ts, done_ts, elapsed_ms
           FROM spans WHERE run_id = ? ORDER BY span_id"#,
    )
    .bind(run_id)
    .fetch_all(pool)
    .await?;

    rows.into_iter()
        .map(|r| {
            Ok(SpanRow {
                span_id: r.try_get("span_id")?,
                kind: r.try_get("kind")?,
                phase_id: r.try_get("phase_id")?,
                parent_span_id: r.try_get("parent_span_id")?,
                label: r.try_get("label")?,
                path: r.try_get("path")?,
                items: r.try_get("items")?,
                max_rounds: r.try_get("max_rounds")?,
                rounds: r.try_get("rounds")?,
                converged: r.try_get("converged")?,
                ok: r.try_get("ok")?,
                failed: r.try_get("failed")?,
                result: r.try_get("result")?,
                error: r.try_get("error")?,
                started_ts: r.try_get("started_ts")?,
                done_ts: r.try_get("done_ts")?,
                elapsed_ms: r.try_get("elapsed_ms")?,
            })
        })
        .collect()
}

/// Alias for backwards-compat with the design doc.
pub async fn get_run_tree(pool: &DbPool, run_id: RunId) -> StorageResult<Vec<SpanRow>> {
    get_run_spans(pool, run_id).await
}

/// Search turns by free-text query (basic LIKE-based, sufficient for now;
/// will be upgraded to FTS5 in P4).
pub async fn search_turns(
    pool: &DbPool,
    run_id: RunId,
    query: &str,
    limit: i64,
) -> StorageResult<Vec<TurnRow>> {
    let like = format!("%{query}%");
    let rows = sqlx::query(
        r#"SELECT seq, ts, kind, role, text, tool_call_id, name, input, output,
                  tool_status, file_path, file_op, diff
           FROM turns
           WHERE run_id = ? AND text LIKE ?
           ORDER BY seq
           LIMIT ?"#,
    )
    .bind(run_id)
    .bind(like)
    .bind(limit)
    .fetch_all(pool)
    .await?;

    rows.into_iter()
        .map(|r| {
            Ok(TurnRow {
                seq: r.try_get("seq")?,
                ts: r.try_get("ts")?,
                kind: r.try_get("kind")?,
                role: r.try_get("role")?,
                text: r.try_get("text")?,
                tool_call_id: r.try_get("tool_call_id")?,
                name: r.try_get("name")?,
                input: r.try_get("input")?,
                output: r.try_get("output")?,
                tool_status: r.try_get("tool_status")?,
                file_path: r.try_get("file_path")?,
                file_op: r.try_get("file_op")?,
                diff: r.try_get("diff")?,
            })
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::open_db;
    use crate::EventWriter;
    use chrono::Utc;
    use luft_core::contract::backend::AgentStatus;
    use luft_core::contract::event::{AgentEvent, ProgressDelta, RunStatus};
    use luft_core::contract::ids::TokenUsage;
    use std::path::PathBuf;
    use tempfile::tempdir;

    async fn setup() -> (tempfile::TempDir, DbPool, EventWriter) {
        let dir = tempdir().unwrap();
        let pool = open_db(&dir.path().join("test.db")).await.unwrap();
        let writer = EventWriter::new(pool.clone());
        (dir, pool, writer)
    }

    async fn seed_run_with_agent(
        w: &EventWriter,
        task: &str,
        agent_count: usize,
        msg_per_agent: usize,
    ) -> (RunId, Vec<AgentId>) {
        let run_id = uuid::Uuid::now_v7();
        w.write_event(&AgentEvent::RunStarted {
            run_id,
            task: task.into(),
            ts: Utc::now(),
        })
        .await
        .unwrap();

        let mut agents = Vec::new();
        for i in 0..agent_count {
            let agent_id = uuid::Uuid::now_v7();
            agents.push(agent_id);
            w.write_event(&AgentEvent::AgentStarted {
                run_id,
                phase_id: 0,
                agent_id,
                prompt_preview: format!("task {i}"),
                model: Some("claude-sonnet-4".into()),
                description: None,
                role: None,
                name: None,
                agent_seq: 0,
            })
            .await
            .unwrap();
            for j in 0..msg_per_agent {
                w.write_event(&AgentEvent::AgentProgress {
                    run_id,
                    agent_id,
                    delta: ProgressDelta::Message {
                        text: format!("agent {i} msg {j}"),
                    },
                })
                .await
                .unwrap();
            }
            w.write_event(&AgentEvent::AgentDone {
                run_id,
                agent_id,
                status: AgentStatus::Ok,
                tokens: TokenUsage {
                    input: 10,
                    output: 5,
                    cache_read: 0,
                    cache_write: 0,
                },
                elapsed_ms: 100,
                name: None,
                agent_seq: 0,
                output: serde_json::Value::Null,
                findings: Vec::new(),
                prompt: String::new(),
                retry_count: 0,
            })
            .await
            .unwrap();
        }

        w.write_event(&AgentEvent::RunDone {
            run_id,
            status: RunStatus::Completed,
            total_tokens: TokenUsage {
                input: 10,
                output: 5,
                cache_read: 0,
                cache_write: 0,
            },
            report: serde_json::json!({}),
            ts: chrono::Utc::now(),
        })
        .await
        .unwrap();

        (run_id, agents)
    }

    #[tokio::test]
    async fn list_runs_returns_seeded_runs() {
        let (_dir, pool, writer) = setup().await;
        for i in 0..3 {
            seed_run_with_agent(&writer, &format!("task {i}"), 1, 1).await;
        }

        let runs = list_runs(&pool, 10, 0).await.unwrap();
        assert_eq!(runs.len(), 3);
        assert!(runs.iter().all(|r| r.status == "completed"));
    }

    #[tokio::test]
    async fn list_runs_pagination() {
        let (_dir, pool, writer) = setup().await;
        for i in 0..5 {
            seed_run_with_agent(&writer, &format!("t{i}"), 1, 0).await;
        }

        let page1 = list_runs(&pool, 2, 0).await.unwrap();
        let page2 = list_runs(&pool, 2, 2).await.unwrap();
        let page3 = list_runs(&pool, 2, 4).await.unwrap();
        assert_eq!(page1.len(), 2);
        assert_eq!(page2.len(), 2);
        assert_eq!(page3.len(), 1);

        // Pages must not overlap.
        let ids: std::collections::HashSet<_> = page1
            .iter()
            .chain(&page2)
            .chain(&page3)
            .map(|r| r.run_id)
            .collect();
        assert_eq!(ids.len(), 5);
    }

    #[tokio::test]
    async fn get_agent_turns_preserves_order() {
        let (_dir, pool, writer) = setup().await;
        let (run_id, agents) = seed_run_with_agent(&writer, "t", 1, 4).await;
        let agent_id = agents[0];

        let turns = get_agent_turns(&pool, run_id, agent_id, 100, 0)
            .await
            .unwrap();
        assert_eq!(turns.len(), 4);
        let seqs: Vec<i64> = turns.iter().map(|t| t.seq).collect();
        assert!(seqs.windows(2).all(|w| w[0] < w[1]));
        for (i, t) in turns.iter().enumerate() {
            assert_eq!(t.kind, "message");
            assert_eq!(t.text.as_deref(), Some(format!("agent 0 msg {i}").as_str()));
        }
    }

    #[tokio::test]
    async fn get_agent_overview_returns_tokens() {
        let (_dir, pool, writer) = setup().await;
        let (run_id, agents) = seed_run_with_agent(&writer, "t", 1, 0).await;
        let agent_id = agents[0];

        let overview = get_agent_overview(&pool, run_id, agent_id).await.unwrap();
        assert_eq!(overview.status, "ok");
        assert_eq!(overview.input_tokens, 10);
        assert_eq!(overview.output_tokens, 5);
        assert_eq!(overview.model.as_deref(), Some("claude-sonnet-4"));
    }

    #[tokio::test]
    async fn get_run_overview_aggregates_turns() {
        let (_dir, pool, writer) = setup().await;
        let (run_id, _) = seed_run_with_agent(&writer, "t", 2, 3).await;

        let overview = get_run_overview(&pool, run_id).await.unwrap();
        assert_eq!(overview.run.task, "t");
        assert_eq!(overview.agents.len(), 2);
        assert_eq!(overview.total_messages, 6); // 2 agents × 3 messages
        assert_eq!(overview.turn_counts.len(), 1);
        assert_eq!(overview.turn_counts[0].kind, "message");
        assert_eq!(overview.turn_counts[0].count, 6);
    }

    #[tokio::test]
    async fn get_run_spans_returns_empty_when_no_spans() {
        let (_dir, pool, writer) = setup().await;
        let (run_id, _) = seed_run_with_agent(&writer, "t", 1, 1).await;

        let spans = get_run_spans(&pool, run_id).await.unwrap();
        assert!(spans.is_empty());
    }

    #[tokio::test]
    async fn search_turns_finds_matching_text() {
        let (_dir, pool, writer) = setup().await;
        let (run_id, agents) = seed_run_with_agent(&writer, "t", 1, 3).await;
        let agent_id = agents[0];

        // Add a distinctive message.
        writer
            .write_event(&AgentEvent::AgentProgress {
                run_id,
                agent_id,
                delta: ProgressDelta::Message {
                    text: "the quick brown fox jumps".into(),
                },
            })
            .await
            .unwrap();

        let results = search_turns(&pool, run_id, "fox", 10).await.unwrap();
        assert_eq!(results.len(), 1);
        assert!(results[0].text.as_ref().unwrap().contains("fox"));
    }

    #[tokio::test]
    async fn file_edit_turns_appear_in_conversation() {
        let (_dir, pool, writer) = setup().await;
        let run_id = uuid::Uuid::now_v7();
        let agent_id = uuid::Uuid::now_v7();

        writer
            .write_event(&AgentEvent::AgentStarted {
                run_id,
                phase_id: 0,
                agent_id,
                prompt_preview: "".into(),
                model: None,
                description: None,
                role: None,
                name: None,
                agent_seq: 0,
            })
            .await
            .unwrap();

        writer
            .write_event(&AgentEvent::AgentProgress {
                run_id,
                agent_id,
                delta: ProgressDelta::FileEdit {
                    path: PathBuf::from("src/lib.rs"),
                },
            })
            .await
            .unwrap();

        let turns = get_agent_turns(&pool, run_id, agent_id, 100, 0)
            .await
            .unwrap();
        assert_eq!(turns.len(), 1);
        assert_eq!(turns[0].kind, "file_edit");
        assert_eq!(turns[0].file_path.as_deref(), Some("src/lib.rs"));
    }
}