lantern 0.3.0

Local-first, provenance-aware semantic search for agent activity
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
//! Session-grouped chunk listing.
//!
//! `list_sessions` reads the `session_id` column already populated by the
//! JSONL transcript extractor and aggregates chunks into one row per session.
//! Chunks without a `session_id` are excluded — this surface is intentionally
//! small and inspectable, not a session-inference layer.

use anyhow::{Context, Result};
use rusqlite::{Connection, params};
use serde::Serialize;

use crate::inspect::ago;

/// Filter / paging options for [`list_sessions`].
#[derive(Debug, Clone, Default)]
pub struct SessionListOptions {
    pub limit: Option<usize>,
}

/// One row in the session listing.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct SessionEntry {
    pub session_id: String,
    pub chunk_count: i64,
    pub source_count: i64,
    pub first_timestamp_unix: Option<i64>,
    pub last_timestamp_unix: Option<i64>,
    /// Representative project for this session: present only when every chunk
    /// in the session carries the same non-null `project`. Mixed or absent
    /// project values surface as `None` rather than guessing a "majority"
    /// project — this is an inspectable read surface, not an inference layer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    /// Representative user for this session, with the same all-or-nothing
    /// rule as `project`: surfaced only when every chunk shares the same
    /// non-null `user`, otherwise `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    /// Representative topic for this session, with the same all-or-nothing
    /// rule as `project` / `user`: surfaced only when every chunk shares the
    /// same non-null `topic`, otherwise `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub topic: Option<String>,
    /// Representative thread for this session, with the same all-or-nothing
    /// rule as `project` / `user` / `topic`: surfaced only when every chunk
    /// shares the same non-null `thread`, otherwise `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thread: Option<String>,
}

/// Listing result: the (possibly truncated) entries and the total session count.
#[derive(Debug, Clone, Serialize)]
pub struct SessionListReport {
    pub entries: Vec<SessionEntry>,
    pub total_sessions: i64,
}

/// Group chunks by `session_id` and return one row per session, ordered by
/// chunk count (descending) then session id (ascending). Chunks where
/// `session_id IS NULL` are excluded — they are not part of any session.
pub fn list_sessions(conn: &Connection, opts: &SessionListOptions) -> Result<SessionListReport> {
    let total_sessions: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM (
                 SELECT session_id FROM chunks
                 WHERE session_id IS NOT NULL
                 GROUP BY session_id
             )",
            [],
            |row| row.get(0),
        )
        .context("counting distinct sessions")?;

    let limit = opts.limit.unwrap_or(usize::MAX).min(i64::MAX as usize) as i64;
    let mut stmt = conn
        .prepare(
            "SELECT session_id,
                    COUNT(*)                          AS chunk_count,
                    COUNT(DISTINCT source_id)         AS source_count,
                    MIN(timestamp_unix)               AS first_ts,
                    MAX(timestamp_unix)               AS last_ts,
                    -- Representative project: surface a non-null value only
                    -- when every chunk in the session agrees on the same
                    -- project. `COUNT(project)` counts non-null rows; if it
                    -- equals the chunk count and MIN == MAX, all chunks
                    -- share one non-null project. Anything else (mixed
                    -- values or any nulls) collapses to NULL.
                    CASE
                        WHEN COUNT(project) = COUNT(*)
                         AND MIN(project) = MAX(project)
                        THEN MIN(project)
                        ELSE NULL
                    END                               AS project,
                    -- Same all-or-nothing rule for `user`.
                    CASE
                        WHEN COUNT(user) = COUNT(*)
                         AND MIN(user) = MAX(user)
                        THEN MIN(user)
                        ELSE NULL
                    END                               AS user,
                    -- Same all-or-nothing rule for `topic`.
                    CASE
                        WHEN COUNT(topic) = COUNT(*)
                         AND MIN(topic) = MAX(topic)
                        THEN MIN(topic)
                        ELSE NULL
                    END                               AS topic,
                    -- Same all-or-nothing rule for `thread`.
                    CASE
                        WHEN COUNT(thread) = COUNT(*)
                         AND MIN(thread) = MAX(thread)
                        THEN MIN(thread)
                        ELSE NULL
                    END                               AS thread
             FROM chunks
             WHERE session_id IS NOT NULL
             GROUP BY session_id
             ORDER BY chunk_count DESC, session_id ASC
             LIMIT ?1",
        )
        .context("preparing list_sessions query")?;
    let rows = stmt
        .query_map([limit], |row| {
            Ok(SessionEntry {
                session_id: row.get(0)?,
                chunk_count: row.get(1)?,
                source_count: row.get(2)?,
                first_timestamp_unix: row.get(3)?,
                last_timestamp_unix: row.get(4)?,
                project: row.get(5)?,
                user: row.get(6)?,
                topic: row.get(7)?,
                thread: row.get(8)?,
            })
        })
        .context("running list_sessions query")?;
    let entries = rows.collect::<Result<Vec<_>, _>>()?;

    Ok(SessionListReport {
        entries,
        total_sessions,
    })
}

pub fn print_text(report: &SessionListReport) {
    if report.entries.is_empty() {
        println!("no sessions found");
        return;
    }
    println!(
        "{} session{} ({} total)",
        report.entries.len(),
        if report.entries.len() == 1 { "" } else { "s" },
        report.total_sessions,
    );
    let now = crate::inspect::now_unix();
    for entry in &report.entries {
        let span = match (entry.first_timestamp_unix, entry.last_timestamp_unix) {
            (Some(first), Some(last)) if first == last => format!(" at={}", ago(now, first)),
            (Some(first), Some(last)) => {
                format!(" first={} last={}", ago(now, first), ago(now, last))
            }
            _ => String::new(),
        };
        let project = match &entry.project {
            Some(p) => format!(" project={p}"),
            None => String::new(),
        };
        let user = match &entry.user {
            Some(u) => format!(" user={u}"),
            None => String::new(),
        };
        let topic = match &entry.topic {
            Some(t) => format!(" topic={t}"),
            None => String::new(),
        };
        let thread = match &entry.thread {
            Some(t) => format!(" thread={t}"),
            None => String::new(),
        };
        println!(
            "  {session:<32} chunks={chunks:<4} sources={sources:<3}{span}{project}{user}{topic}{thread}",
            session = entry.session_id,
            chunks = entry.chunk_count,
            sources = entry.source_count,
        );
    }
}

pub fn print_json(report: &SessionListReport) -> Result<()> {
    println!("{}", serde_json::to_string_pretty(report)?);
    Ok(())
}

/// Filter / paging options for [`related_sessions`].
#[derive(Debug, Clone, Default)]
pub struct RelatedSessionsOptions {
    pub limit: Option<usize>,
    /// Include up to N sampled shared entities per related session. `None` (or
    /// zero) preserves the cheap count-only path.
    pub with_entities: Option<usize>,
}

/// One sampled shared entity linking the source session to a related session.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct RelatedSessionEntityEvidence {
    pub kind: String,
    pub value: String,
}

/// One session that shares entities with the source session.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct RelatedSession {
    pub session_id: String,
    /// Distinct entities the related session shares with the source session.
    /// Always >= 1 — sessions with no shared entity are not returned.
    pub shared_entity_count: i64,
    /// Chunks in the related session that touch at least one shared entity.
    /// Useful for telling "this session mentioned the topic once" apart from
    /// "this session mentioned it everywhere".
    pub shared_chunk_count: i64,
    /// Total chunks in the related session — the same denominator that
    /// `list_sessions` reports.
    pub chunk_count: i64,
    pub first_timestamp_unix: Option<i64>,
    pub last_timestamp_unix: Option<i64>,
    /// Representative project for the related session, with the same
    /// all-or-nothing rule as [`SessionEntry::project`]: surfaced only when
    /// every chunk in the related session carries the same non-null
    /// `project`, otherwise `None`. Lets a related-sessions caller see what
    /// project a neighbor session is about without a second
    /// `lantern sessions --session-id=...` lookup.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shared_entities: Option<Vec<RelatedSessionEntityEvidence>>,
}

/// Result of a [`related_sessions`] query: source-session context plus the
/// (possibly truncated) ranked list of sessions sharing entities with it.
#[derive(Debug, Clone, Serialize)]
pub struct RelatedSessionsReport {
    pub source_session_id: String,
    /// Total chunks in the source session — handy for callers that want to
    /// frame "shared with N% of the source's chunks" without a second query.
    pub source_chunk_count: i64,
    /// Distinct entities linked from the source session's chunks.
    pub source_entity_count: i64,
    pub sessions: Vec<RelatedSession>,
    pub total_related: i64,
}

/// Find sessions that share at least one entity with `source_session_id`,
/// ranked by the count of shared distinct entities (descending), with
/// `session_id` ascending as a deterministic tiebreaker. The source session
/// is excluded from the results, as are chunks where `session_id IS NULL`.
///
/// Returns `Err` when no chunk carries `source_session_id`, so callers (CLI /
/// MCP) can surface a clear "unknown session" message instead of an empty
/// result that would be indistinguishable from "session exists but has no
/// shared entities".
pub fn related_sessions(
    conn: &Connection,
    source_session_id: &str,
    opts: &RelatedSessionsOptions,
) -> Result<RelatedSessionsReport> {
    let source_chunk_count: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM chunks WHERE session_id = ?1",
            params![source_session_id],
            |row| row.get(0),
        )
        .context("counting chunks in source session")?;
    if source_chunk_count == 0 {
        anyhow::bail!("no session with id '{source_session_id}'");
    }
    let source_entity_count: i64 = conn
        .query_row(
            "SELECT COUNT(DISTINCT ce.entity_id)
             FROM chunk_entities ce
             JOIN chunks c ON c.id = ce.chunk_id
             WHERE c.session_id = ?1",
            params![source_session_id],
            |row| row.get(0),
        )
        .context("counting distinct entities in source session")?;

    let total_related: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM (
                 SELECT c.session_id
                 FROM chunks c
                 JOIN chunk_entities ce ON ce.chunk_id = c.id
                 WHERE ce.entity_id IN (
                     SELECT DISTINCT ce2.entity_id
                     FROM chunk_entities ce2
                     JOIN chunks src ON src.id = ce2.chunk_id
                     WHERE src.session_id = ?1
                 )
                   AND c.session_id IS NOT NULL
                   AND c.session_id != ?1
                 GROUP BY c.session_id
             )",
            params![source_session_id],
            |row| row.get(0),
        )
        .context("counting related sessions")?;

    let limit = opts.limit.unwrap_or(usize::MAX).min(i64::MAX as usize) as i64;
    let mut stmt = conn
        .prepare(
            "SELECT c.session_id                          AS session_id,
                    COUNT(DISTINCT ce.entity_id)          AS shared_entity_count,
                    COUNT(DISTINCT c.id)                  AS shared_chunk_count,
                    (SELECT COUNT(*)
                     FROM chunks c2
                     WHERE c2.session_id = c.session_id)  AS chunk_count,
                    (SELECT MIN(timestamp_unix)
                     FROM chunks c2
                     WHERE c2.session_id = c.session_id)  AS first_ts,
                    (SELECT MAX(timestamp_unix)
                     FROM chunks c2
                     WHERE c2.session_id = c.session_id)  AS last_ts,
                    -- Representative project for the related session: same
                    -- all-or-nothing rule as `list_sessions` — surface only
                    -- when every chunk in the session agrees on one non-null
                    -- project. Scoped to the full session, not just the
                    -- shared-entity-touching chunks, so the field matches
                    -- what `lantern sessions` would report.
                    (SELECT CASE
                                WHEN COUNT(project) = COUNT(*)
                                 AND MIN(project) = MAX(project)
                                THEN MIN(project)
                                ELSE NULL
                            END
                     FROM chunks c2
                     WHERE c2.session_id = c.session_id)  AS project
             FROM chunks c
             JOIN chunk_entities ce ON ce.chunk_id = c.id
             WHERE ce.entity_id IN (
                 SELECT DISTINCT ce2.entity_id
                 FROM chunk_entities ce2
                 JOIN chunks src ON src.id = ce2.chunk_id
                 WHERE src.session_id = ?1
             )
               AND c.session_id IS NOT NULL
               AND c.session_id != ?1
             GROUP BY c.session_id
             ORDER BY shared_entity_count DESC, c.session_id ASC
             LIMIT ?2",
        )
        .context("preparing related_sessions query")?;
    let rows = stmt
        .query_map(params![source_session_id, limit], |row| {
            Ok(RelatedSession {
                session_id: row.get(0)?,
                shared_entity_count: row.get(1)?,
                shared_chunk_count: row.get(2)?,
                chunk_count: row.get(3)?,
                first_timestamp_unix: row.get(4)?,
                last_timestamp_unix: row.get(5)?,
                project: row.get(6)?,
                shared_entities: None,
            })
        })
        .context("running related_sessions query")?;
    let mut sessions = rows.collect::<Result<Vec<_>, _>>()?;

    if let Some(entity_limit) = opts.with_entities.filter(|n| *n > 0) {
        for session in &mut sessions {
            session.shared_entities = Some(load_related_session_entities(
                conn,
                source_session_id,
                &session.session_id,
                entity_limit,
            )?);
        }
    }

    Ok(RelatedSessionsReport {
        source_session_id: source_session_id.to_string(),
        source_chunk_count,
        source_entity_count,
        sessions,
        total_related,
    })
}

fn load_related_session_entities(
    conn: &Connection,
    source_session_id: &str,
    related_session_id: &str,
    limit: usize,
) -> Result<Vec<RelatedSessionEntityEvidence>> {
    let limit = limit.min(i64::MAX as usize) as i64;
    let mut stmt = conn
        .prepare(
            "SELECT e.kind,
                    e.value
             FROM chunk_entities ce
             JOIN entities e ON e.id = ce.entity_id
             JOIN chunks c ON c.id = ce.chunk_id
             WHERE c.session_id = ?2
               AND ce.entity_id IN (
                   SELECT DISTINCT ce2.entity_id
                   FROM chunk_entities ce2
                   JOIN chunks src ON src.id = ce2.chunk_id
                   WHERE src.session_id = ?1
               )
             GROUP BY e.id, e.kind, e.value
             ORDER BY COUNT(DISTINCT c.id) DESC, e.kind ASC, e.value ASC
             LIMIT ?3",
        )
        .context("preparing related-session shared-entity query")?;
    let rows = stmt
        .query_map(
            params![source_session_id, related_session_id, limit],
            |row| {
                Ok(RelatedSessionEntityEvidence {
                    kind: row.get(0)?,
                    value: row.get(1)?,
                })
            },
        )
        .context("running related-session shared-entity query")?;
    rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
}

pub fn print_related_text(report: &RelatedSessionsReport) {
    println!(
        "{} (chunks={} entities={}) — {} related session{}",
        report.source_session_id,
        report.source_chunk_count,
        report.source_entity_count,
        report.total_related,
        if report.total_related == 1 { "" } else { "s" },
    );
    if report.sessions.is_empty() {
        println!("  (no sessions share entities with this one)");
        return;
    }
    let now = crate::inspect::now_unix();
    for s in &report.sessions {
        let span = match (s.first_timestamp_unix, s.last_timestamp_unix) {
            (Some(first), Some(last)) if first == last => format!(" at={}", ago(now, first)),
            (Some(first), Some(last)) => {
                format!(" first={} last={}", ago(now, first), ago(now, last))
            }
            _ => String::new(),
        };
        let project = match &s.project {
            Some(p) => format!(" project={p}"),
            None => String::new(),
        };
        println!(
            "  {session:<32} shared_entities={se:<3} shared_chunks={sc:<3} chunks={total:<4}{span}{project}",
            session = s.session_id,
            se = s.shared_entity_count,
            sc = s.shared_chunk_count,
            total = s.chunk_count,
        );
        if let Some(shared_entities) = &s.shared_entities {
            for entity in shared_entities {
                println!(
                    "    - [{kind}] {value}",
                    kind = entity.kind,
                    value = entity.value
                );
            }
        }
    }
}

pub fn print_related_json(report: &RelatedSessionsReport) -> Result<()> {
    println!("{}", serde_json::to_string_pretty(report)?);
    Ok(())
}

/// Filter / paging options for [`temporally_related_sessions`].
#[derive(Debug, Clone, Default)]
pub struct TemporallyRelatedSessionsOptions {
    pub limit: Option<usize>,
    /// Only include sessions whose temporal gap to the source is at most this
    /// many seconds. `None` means no window filter — all sessions with at
    /// least one timestamped chunk are scored and ranked.
    pub window_secs: Option<i64>,
}

/// One session whose chunk-timestamp range is close to the source session's.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct TemporallyRelatedSession {
    pub session_id: String,
    /// 0 if the source and target time-spans overlap; otherwise the gap
    /// between their nearest endpoints, in seconds.
    pub gap_secs: i64,
    /// 0 when the spans are disjoint; otherwise the duration of their
    /// intersection in seconds.
    pub overlap_secs: i64,
    /// Total chunks in the related session (includes chunks without
    /// timestamps), matching [`RelatedSession::chunk_count`].
    pub chunk_count: i64,
    /// Earliest non-NULL `timestamp_unix` among the related session's chunks.
    /// Always populated — sessions with no timestamped chunks are excluded.
    pub first_timestamp_unix: i64,
    /// Latest non-NULL `timestamp_unix` among the related session's chunks.
    pub last_timestamp_unix: i64,
}

/// Result of a [`temporally_related_sessions`] query: source-session timing
/// context plus the (possibly truncated) ranked list.
#[derive(Debug, Clone, Serialize)]
pub struct TemporallyRelatedSessionsReport {
    pub source_session_id: String,
    pub source_first_timestamp_unix: i64,
    pub source_last_timestamp_unix: i64,
    /// Window applied (in seconds), or `None` if every timestamped session was
    /// considered. Echoed so callers can see the exact filter the report used.
    pub window_secs: Option<i64>,
    pub sessions: Vec<TemporallyRelatedSession>,
    pub total_related: i64,
}

/// Find sessions whose chunk-timestamp range is close to the source session's,
/// ranked by ascending temporal gap (overlap → 0) with `session_id` ascending
/// as a deterministic tiebreaker. The source session is excluded, as are
/// sessions where every chunk has `timestamp_unix IS NULL`.
///
/// Errors when the source `session_id` has no chunks, or when it has chunks
/// but none of them carry a timestamp — temporal proximity is undefined in
/// those cases, so callers (CLI / MCP) can surface a clear message instead of
/// returning an empty list that would be indistinguishable from "exists, but
/// nothing nearby."
pub fn temporally_related_sessions(
    conn: &Connection,
    source_session_id: &str,
    opts: &TemporallyRelatedSessionsOptions,
) -> Result<TemporallyRelatedSessionsReport> {
    let source_chunk_count: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM chunks WHERE session_id = ?1",
            params![source_session_id],
            |row| row.get(0),
        )
        .context("counting chunks in source session")?;
    if source_chunk_count == 0 {
        anyhow::bail!("no session with id '{source_session_id}'");
    }
    let (s_first, s_last): (Option<i64>, Option<i64>) = conn
        .query_row(
            "SELECT MIN(timestamp_unix), MAX(timestamp_unix)
             FROM chunks
             WHERE session_id = ?1 AND timestamp_unix IS NOT NULL",
            params![source_session_id],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .context("aggregating source session timestamps")?;
    let (source_first, source_last) = match (s_first, s_last) {
        (Some(first), Some(last)) => (first, last),
        _ => anyhow::bail!("session '{source_session_id}' has no chunks with a timestamp"),
    };

    // Pull per-session min/max for every other session that has at least one
    // timestamped chunk, then compute gap/overlap and apply window+limit in
    // Rust. The query stays simple and read-only; ranking and filtering live
    // alongside the score formulas instead of being smeared across SQL.
    let mut stmt = conn
        .prepare(
            "SELECT c.session_id,
                    (SELECT COUNT(*) FROM chunks c2 WHERE c2.session_id = c.session_id) AS chunk_count,
                    MIN(c.timestamp_unix) AS o_first,
                    MAX(c.timestamp_unix) AS o_last
             FROM chunks c
             WHERE c.session_id IS NOT NULL
               AND c.session_id != ?1
               AND c.timestamp_unix IS NOT NULL
             GROUP BY c.session_id",
        )
        .context("preparing temporally_related_sessions query")?;
    let rows = stmt
        .query_map(params![source_session_id], |row| {
            let session_id: String = row.get(0)?;
            let chunk_count: i64 = row.get(1)?;
            let o_first: i64 = row.get(2)?;
            let o_last: i64 = row.get(3)?;
            Ok((session_id, chunk_count, o_first, o_last))
        })
        .context("running temporally_related_sessions query")?;

    let mut scored: Vec<TemporallyRelatedSession> = Vec::new();
    for row in rows {
        let (session_id, chunk_count, o_first, o_last) = row?;
        let (gap_secs, overlap_secs) =
            score_temporal_proximity((source_first, source_last), (o_first, o_last));
        if let Some(window) = opts.window_secs
            && gap_secs > window
        {
            continue;
        }
        scored.push(TemporallyRelatedSession {
            session_id,
            gap_secs,
            overlap_secs,
            chunk_count,
            first_timestamp_unix: o_first,
            last_timestamp_unix: o_last,
        });
    }
    scored.sort_by(|a, b| {
        a.gap_secs
            .cmp(&b.gap_secs)
            .then_with(|| a.session_id.cmp(&b.session_id))
    });
    let total_related = scored.len() as i64;
    if let Some(limit) = opts.limit {
        scored.truncate(limit);
    }

    Ok(TemporallyRelatedSessionsReport {
        source_session_id: source_session_id.to_string(),
        source_first_timestamp_unix: source_first,
        source_last_timestamp_unix: source_last,
        window_secs: opts.window_secs,
        sessions: scored,
        total_related,
    })
}

/// Compute `(gap_secs, overlap_secs)` between two `[first, last]` time spans.
/// Both values are >= 0; at most one is non-zero.
fn score_temporal_proximity(src: (i64, i64), other: (i64, i64)) -> (i64, i64) {
    let (s_first, s_last) = src;
    let (o_first, o_last) = other;
    if o_last < s_first {
        (s_first - o_last, 0)
    } else if o_first > s_last {
        (o_first - s_last, 0)
    } else {
        let overlap = s_last.min(o_last) - s_first.max(o_first);
        (0, overlap.max(0))
    }
}

pub fn print_temporally_related_text(report: &TemporallyRelatedSessionsReport) {
    let now = crate::inspect::now_unix();
    let window = match report.window_secs {
        Some(w) => format!(" window={w}s"),
        None => String::new(),
    };
    println!(
        "{src} (first={first} last={last}){window}{total} related session{plural}",
        src = report.source_session_id,
        first = ago(now, report.source_first_timestamp_unix),
        last = ago(now, report.source_last_timestamp_unix),
        total = report.total_related,
        plural = if report.total_related == 1 { "" } else { "s" },
    );
    if report.sessions.is_empty() {
        println!("  (no other sessions in range)");
        return;
    }
    for s in &report.sessions {
        println!(
            "  {session:<32} gap={gap:<7} overlap={overlap:<7} chunks={chunks:<4} first={first} last={last}",
            session = s.session_id,
            gap = format!("{}s", s.gap_secs),
            overlap = format!("{}s", s.overlap_secs),
            chunks = s.chunk_count,
            first = ago(now, s.first_timestamp_unix),
            last = ago(now, s.last_timestamp_unix),
        );
    }
}

pub fn print_temporally_related_json(report: &TemporallyRelatedSessionsReport) -> Result<()> {
    println!("{}", serde_json::to_string_pretty(report)?);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::score_temporal_proximity;

    #[test]
    fn scoring_overlap_returns_zero_gap_and_intersection_length() {
        // src [10..20], other [15..25] → overlap [15..20] = 5
        assert_eq!(score_temporal_proximity((10, 20), (15, 25)), (0, 5));
        // contained spans: src [10..20], other [12..18] → overlap = 6
        assert_eq!(score_temporal_proximity((10, 20), (12, 18)), (0, 6));
        // identical spans → overlap == length
        assert_eq!(score_temporal_proximity((10, 20), (10, 20)), (0, 10));
        // touching at the boundary still counts as overlap (gap = 0, overlap = 0)
        assert_eq!(score_temporal_proximity((10, 20), (20, 30)), (0, 0));
    }

    #[test]
    fn scoring_disjoint_returns_gap_and_zero_overlap() {
        // other strictly before src → gap = s_first - o_last
        assert_eq!(score_temporal_proximity((100, 200), (10, 50)), (50, 0));
        // other strictly after src → gap = o_first - s_last
        assert_eq!(score_temporal_proximity((100, 200), (300, 400)), (100, 0));
    }
}