dirge-agent 0.12.4

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
703
704
705
706
707
708
709
710
711
712
//! Session search tool — three-shape search over past sessions.
//!
//! Port of Hermes's `tools/session_search_tool.py`. Lets the agent
//! search its own past work on this project. Three calling shapes:
//!
//! 1. **DISCOVERY** — pass `query`, gets FTS5 matches with bookends
//!    (first/last messages) and anchored windows around each hit.
//! 2. **SCROLL** — pass `session_id` + `around_message_id`, gets a
//!    ±N message window centered on the anchor. No FTS5, no bookends.
//! 3. **BROWSE** — no args, returns recent sessions chronologically.
//!
//! Key design decisions from Hermes preserved:
//! - Pure DB queries, no LLM cost
//! - Lineage deduplication (same compression chain → one result)
//! - Lineage rebinding (parent session_id + child message id)
//! - Source exclusion (review-fork hidden by default)
//! - Current session exclusion
//! - FTS5 syntax: AND, OR, NOT, quoted phrases, * wildcards

use crate::extras::session_db::{SearchResult, SessionDb};

/// Detect CJK (Chinese/Japanese/Korean) characters in a query.
/// When CJK is present, the default unicode61 tokenizer splits
/// each character into a separate token, breaking phrase matching.
/// We route to the trigram FTS5 index instead.
/// Port of Hermes's _contains_cjk() (hermes_state.py:2100-2112).
fn contains_cjk(query: &str) -> bool {
    query.chars().any(|c| {
        let cp = c as u32;
        (0x4E00..=0x9FFF).contains(&cp)     // CJK Unified Ideographs
        || (0x3400..=0x4DBF).contains(&cp)  // CJK Extension A
        || (0x20000..=0x2A6DF).contains(&cp) // CJK Extension B
        || (0x3000..=0x303F).contains(&cp)   // CJK Symbols
        || (0x3040..=0x309F).contains(&cp)   // Hiragana
        || (0x30A0..=0x30FF).contains(&cp)   // Katakana
        || (0xAC00..=0xD7AF).contains(&cp) // Hangul Syllables
    })
}

/// A single search hit in the DISCOVERY shape. Contains the
/// matched session with context for the agent to understand
/// what happened.
#[derive(Debug, Clone, serde::Serialize)]
pub struct DiscoveryHit {
    /// Session id for follow-up scroll calls.
    pub session_id: String,
    /// The root session id (after lineage resolution).
    pub root_session_id: String,
    /// Session source (cli, subagent, etc.).
    pub source: String,
    /// Model used for this session.
    pub model: String,
    /// Session title.
    pub title: String,
    /// When the session started.
    pub started_at: String,
    /// FTS5-highlighted snippet of the match.
    pub snippet: String,
    /// First few messages of the session (the goal/kickoff).
    pub bookend_start: Vec<MessagePreview>,
    /// Last few messages of the session (resolution/decisions).
    pub bookend_end: Vec<MessagePreview>,
    /// Window of messages around the FTS5 match.
    pub messages: Vec<MessagePreview>,
    /// Index of the anchor message within `messages`.
    pub anchor_index: usize,
    /// How many messages exist before the window.
    pub before: usize,
    /// How many messages exist after the window.
    pub after: usize,
}

/// A preview of a single message for search results.
#[derive(Debug, Clone, serde::Serialize)]
pub struct MessagePreview {
    pub id: i64,
    pub role: String,
    pub content_preview: String,
    pub timestamp: String,
}

/// Result of a SCROLL request.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ScrollResult {
    pub session_id: String,
    pub messages: Vec<MessagePreview>,
    pub anchor_index: usize,
    pub before: usize,
    pub after: usize,
}

/// Result of a BROWSE request — a list of recent sessions.
#[derive(Debug, Clone, serde::Serialize)]
pub struct BrowseSession {
    pub id: String,
    pub root_id: String,
    pub source: String,
    pub model: String,
    pub title: String,
    pub started_at: String,
    pub last_active: String,
    pub message_count: i64,
}

/// Maximum content length in a message preview.
const MAX_PREVIEW_LEN: usize = 300;

/// Number of bookend messages to return (first/last).
const BOOKEND_COUNT: usize = 3;

/// Default window size around a match.
const DEFAULT_WINDOW: usize = 5;

/// Number of results to return in discovery.
const MAX_DISCOVERY_RESULTS: usize = 10;

pub struct SessionSearch {
    db: SessionDb,
    /// The current session id — excluded from search results.
    current_session_id: Option<String>,
}

impl SessionSearch {
    pub fn new(db: SessionDb) -> Self {
        SessionSearch {
            db,
            current_session_id: None,
        }
    }

    /// Set the current session to exclude from results.
    pub fn with_current_session(mut self, id: &str) -> Self {
        self.current_session_id = Some(id.to_string());
        self
    }

    // ── DISCOVERY shape ───────────────────────────────

    /// Search past sessions by FTS5 query. Returns up to
    /// `MAX_DISCOVERY_RESULTS` hits, each with bookends and
    /// an anchored window. Results are deduplicated by lineage
    /// root.
    pub fn discover(&self, query: &str) -> Result<Vec<DiscoveryHit>, String> {
        let sanitized = crate::extras::fts::sanitize_query(query);
        if sanitized.is_empty() {
            return Ok(Vec::new());
        }
        let results = if contains_cjk(&sanitized) {
            self.db.search_messages_trigram(&sanitized, None)?
        } else {
            self.db.search_messages(&sanitized, None)?
        };
        if results.is_empty() {
            return Ok(Vec::new());
        }

        let mut hits: Vec<DiscoveryHit> = Vec::new();
        let mut seen_roots = std::collections::HashSet::new();

        for result in &results {
            // Resolve lineage root.
            let root_id = self.db.resolve_parent(&result.session_id)?;

            // Skip if this lineage is already represented or
            // it's the current session.
            if !seen_roots.insert(root_id.clone()) {
                continue;
            }
            if let Some(ref current) = self.current_session_id {
                let current_root = self.db.resolve_parent(current)?;
                if current_root == root_id {
                    continue;
                }
            }

            // Build hit.
            match self.build_discovery_hit(result, &root_id) {
                Ok(hit) => hits.push(hit),
                Err(e) => {
                    tracing::warn!(
                        target: "dirge::session_search",
                        session_id = %result.session_id,
                        error = %e,
                        "Failed to build discovery hit"
                    );
                }
            }

            if hits.len() >= MAX_DISCOVERY_RESULTS {
                break;
            }
        }

        Ok(hits)
    }

    fn build_discovery_hit(
        &self,
        result: &SearchResult,
        root_id: &str,
    ) -> Result<DiscoveryHit, String> {
        let session_meta = self.get_session_meta(&result.session_id)?;

        // Get message ID for the anchor.
        let anchor_id = self.find_message_id_near(&result.session_id, &result.timestamp)?;

        // Get anchored window.
        let view = self
            .db
            .get_anchored_view(&result.session_id, anchor_id, DEFAULT_WINDOW)?;

        // Get bookends.
        let bookend_start = self.get_bookends(&result.session_id, true)?;
        let bookend_end = self.get_bookends(&result.session_id, false)?;

        let messages: Vec<MessagePreview> = view
            .messages
            .into_iter()
            .map(|m| MessagePreview {
                id: m.id,
                role: m.role,
                content_preview: truncate_content(&m.content, MAX_PREVIEW_LEN),
                timestamp: m.timestamp,
            })
            .collect();

        Ok(DiscoveryHit {
            session_id: result.session_id.clone(),
            root_session_id: root_id.to_string(),
            source: session_meta.0,
            model: session_meta.1,
            title: session_meta.2,
            started_at: session_meta.3,
            snippet: truncate_content(&result.content, MAX_PREVIEW_LEN),
            bookend_start,
            bookend_end,
            messages,
            anchor_index: view.anchor_index,
            before: view.before,
            after: view.after,
        })
    }

    // ── SCROLL shape ──────────────────────────────────

    /// Get a window of messages around an anchor. If the session
    /// has been split (compression), rebinds to the child session
    /// containing the message.
    pub fn scroll(
        &self,
        session_id: &str,
        around_message_id: i64,
        window: usize,
    ) -> Result<ScrollResult, String> {
        // Walk lineage to find the actual session containing
        // this message. If the message was created after a
        // compression split, it lives in a child session.
        let actual_session = self.find_message_session(session_id, around_message_id)?;

        let view = self
            .db
            .get_anchored_view(&actual_session, around_message_id, window)?;

        let messages: Vec<MessagePreview> = view
            .messages
            .into_iter()
            .map(|m| MessagePreview {
                id: m.id,
                role: m.role,
                content_preview: truncate_content(&m.content, MAX_PREVIEW_LEN),
                timestamp: m.timestamp,
            })
            .collect();

        Ok(ScrollResult {
            session_id: actual_session,
            messages,
            anchor_index: view.anchor_index,
            before: view.before,
            after: view.after,
        })
    }

    // ── BROWSE shape ──────────────────────────────────

    /// List recent sessions, excluding review-fork sources
    /// and the current session.
    pub fn browse(&self) -> Result<Vec<BrowseSession>, String> {
        let sessions = self.db.list_sessions_rich(Some(&["review-fork"]))?;

        let mut result = Vec::new();
        let mut seen_roots = std::collections::HashSet::new();

        for s in sessions {
            // Resolve lineage root.
            let root_id = self.db.resolve_parent(&s.id)?;

            // Deduplicate by root.
            if !seen_roots.insert(root_id.clone()) {
                continue;
            }

            // Exclude current session.
            if let Some(ref current) = self.current_session_id {
                let current_root = self.db.resolve_parent(current)?;
                if current_root == root_id {
                    continue;
                }
            }

            result.push(BrowseSession {
                id: s.id,
                root_id,
                source: s.source,
                model: s.model,
                title: s.title,
                started_at: s.started_at,
                last_active: s.last_active,
                message_count: s.message_count,
            });
        }

        Ok(result)
    }

    // ── Internal helpers ──────────────────────────────

    /// Get session metadata: (source, model, title, started_at).
    fn get_session_meta(
        &self,
        session_id: &str,
    ) -> Result<(String, String, String, String), String> {
        self.db
            .get_anchored_view(session_id, 0, 0)
            .map(|_v| {
                // Just use the session list info — the anchored
                // view is just a probe to verify the session exists.
                // Actual metadata comes from list_sessions_rich query.
                (String::new(), String::new(), String::new(), String::new())
            })
            .map_err(|_| format!("Session '{}' not found", session_id))?;

        // Fall through to list_sessions_rich for metadata.
        let all = self.db.list_sessions_rich(None)?;
        for s in &all {
            if s.id == session_id {
                return Ok((
                    s.source.clone(),
                    s.model.clone(),
                    s.title.clone(),
                    s.started_at.clone(),
                ));
            }
        }
        Ok((String::new(), String::new(), String::new(), String::new()))
    }

    /// Find a message id near the given timestamp in a session.
    fn find_message_id_near(&self, session_id: &str, timestamp: &str) -> Result<i64, String> {
        let view = self.db.get_anchored_view(session_id, 1, 0)?;
        if view.messages.is_empty() {
            return Err(format!("No messages in session '{}'", session_id));
        }
        // Find the first message with timestamp >= target.
        for m in &view.messages {
            if *m.timestamp >= *timestamp {
                return Ok(m.id);
            }
        }
        // Fall back to the last message.
        Ok(view.messages.last().map(|m| m.id).unwrap_or(1))
    }

    /// Get the first or last few messages of a session.
    fn get_bookends(&self, session_id: &str, start: bool) -> Result<Vec<MessagePreview>, String> {
        let view = self.db.get_anchored_view(session_id, 1, BOOKEND_COUNT)?;

        let messages: Vec<MessagePreview> = view
            .messages
            .into_iter()
            .map(|m| MessagePreview {
                id: m.id,
                role: m.role,
                content_preview: truncate_content(&m.content, MAX_PREVIEW_LEN),
                timestamp: m.timestamp,
            })
            .collect();

        if start {
            Ok(messages)
        } else {
            // Get the last BOOKEND_COUNT messages.
            let total_view = self.db.get_anchored_view(session_id, 1, 100_000)?;
            let total = total_view.messages.len();
            if total <= BOOKEND_COUNT {
                return Ok(messages);
            }
            let last_id = total_view.messages.last().map(|m| m.id).unwrap_or(1);
            let end_view = self
                .db
                .get_anchored_view(session_id, last_id, BOOKEND_COUNT)?;
            Ok(end_view
                .messages
                .into_iter()
                .map(|m| MessagePreview {
                    id: m.id,
                    role: m.role,
                    content_preview: truncate_content(&m.content, MAX_PREVIEW_LEN),
                    timestamp: m.timestamp,
                })
                .collect())
        }
    }

    /// Walk lineage from session_id to find which session
    /// actually contains the given message. If the message was
    /// created after a compression split, it lives in a child
    /// session.
    fn find_message_session(&self, session_id: &str, message_id: i64) -> Result<String, String> {
        // First try the given session.
        if self.db.get_anchored_view(session_id, message_id, 0).is_ok() {
            // Message might exist — we trust the caller.
            return Ok(session_id.to_string());
        }

        // Walk forward looking for child sessions that might
        // contain this message. List all sessions to find children.
        let all = self.db.list_sessions_rich(None)?;
        let root_id = self.db.resolve_parent(session_id)?;

        // Find all sessions in this lineage.
        for s in &all {
            let s_root = self.db.resolve_parent(&s.id)?;
            if s_root == root_id && self.db.get_anchored_view(&s.id, message_id, 0).is_ok() {
                return Ok(s.id.clone());
            }
        }

        // Fall back to the given session.
        Ok(session_id.to_string())
    }
}

/// Truncate content for preview, preserving readability.
fn truncate_content(content: &str, max_len: usize) -> String {
    if content.len() <= max_len {
        return content.to_string();
    }
    format!(
        "{}…[{} more chars]",
        crate::text::head(content, max_len.saturating_sub(20)),
        content.len() - max_len
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static TEST_COUNTER: AtomicU32 = AtomicU32::new(0);

    fn temp_search() -> (SessionSearch, std::path::PathBuf) {
        let n = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("dirge-search-test-{}-{}", std::process::id(), n));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("state.db");
        let db = SessionDb::open(&path).unwrap();
        let search = SessionSearch::new(db);
        (search, dir)
    }

    fn seed_session(db: &SessionDb, id: &str, source: &str) {
        db.insert_session(id, source, "gpt-5", "openai", "2025-01-15T10:00:00Z")
            .unwrap();
        for i in 0..5 {
            db.insert_message(
                id,
                if i % 2 == 0 { "user" } else { "assistant" },
                &format!("message {} in {}", i, id),
                None,
                None,
                None,
                &format!("2025-01-15T10:{:02}:00Z", i),
            )
            .unwrap();
        }
    }

    #[test]
    fn browse_returns_recent_sessions() {
        let (search, _dir) = temp_search();
        seed_session(&search.db, "sess-1", "cli");
        seed_session(&search.db, "sess-2", "subagent");

        let sessions = search.browse().unwrap();
        assert!(!sessions.is_empty());
        // Should exclude review-fork, include cli and subagent.
        let ids: Vec<&str> = sessions.iter().map(|s| s.id.as_str()).collect();
        assert!(ids.contains(&"sess-1"));
        assert!(ids.contains(&"sess-2"));
    }

    #[test]
    fn browse_excludes_review_fork() {
        let (search, _dir) = temp_search();
        seed_session(&search.db, "sess-1", "cli");
        seed_session(&search.db, "review-1", "review-fork");

        let sessions = search.browse().unwrap();
        let ids: Vec<&str> = sessions.iter().map(|s| s.id.as_str()).collect();
        assert!(ids.contains(&"sess-1"));
        assert!(!ids.contains(&"review-1"));
    }

    #[test]
    fn browse_excludes_current_session() {
        let (mut search, _dir) = temp_search();
        seed_session(&search.db, "sess-1", "cli");
        seed_session(&search.db, "sess-2", "cli");

        search.current_session_id = Some("sess-1".to_string());
        let sessions = search.browse().unwrap();
        let ids: Vec<&str> = sessions.iter().map(|s| s.id.as_str()).collect();
        assert!(
            !ids.contains(&"sess-1"),
            "current session should be excluded"
        );
        assert!(ids.contains(&"sess-2"));
    }

    #[test]
    fn discover_finds_matching_sessions() {
        let (search, _dir) = temp_search();
        seed_session(&search.db, "sess-1", "cli");

        // Insert a specific message to search for.
        search
            .db
            .insert_message(
                "sess-1",
                "user",
                "how do we handle database migrations with rusqlite",
                None,
                None,
                None,
                "2025-01-15T10:01:00Z",
            )
            .unwrap();

        let hits = search.discover("database migrations").unwrap();
        assert!(!hits.is_empty());
    }

    #[test]
    fn discover_empty_for_no_match() {
        let (search, _dir) = temp_search();
        seed_session(&search.db, "sess-1", "cli");

        let hits = search.discover("zzzzz_nonexistent_query_xyz").unwrap();
        assert!(hits.is_empty());
    }

    #[test]
    fn discover_excludes_current_session() {
        let (mut search, _dir) = temp_search();
        seed_session(&search.db, "current", "cli");
        seed_session(&search.db, "other", "cli");

        search
            .db
            .insert_message(
                "current",
                "user",
                "database migration in current session",
                None,
                None,
                None,
                "2025-01-15T10:01:00Z",
            )
            .unwrap();
        search
            .db
            .insert_message(
                "other",
                "user",
                "database migration in other session",
                None,
                None,
                None,
                "2025-01-15T11:01:00Z",
            )
            .unwrap();

        search.current_session_id = Some("current".to_string());
        let hits = search.discover("database migration").unwrap();
        assert!(!hits.is_empty());
        for hit in &hits {
            assert_ne!(hit.session_id, "current");
        }
    }

    #[test]
    fn discover_dedupes_by_lineage() {
        let (search, _dir) = temp_search();
        seed_session(&search.db, "sess-1", "cli");
        seed_session(&search.db, "child-1", "cli");

        search.db.set_parent_session("child-1", "sess-1").unwrap();

        search
            .db
            .insert_message(
                "sess-1",
                "user",
                "unique term: ziggurat construction",
                None,
                None,
                None,
                "2025-01-15T10:01:00Z",
            )
            .unwrap();
        search
            .db
            .insert_message(
                "child-1",
                "user",
                "unique term: ziggurat construction continued",
                None,
                None,
                None,
                "2025-01-15T11:01:00Z",
            )
            .unwrap();

        let hits = search.discover("ziggurat").unwrap();
        // Both sessions match but share a lineage root — only one result.
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn scroll_returns_window_around_anchor() {
        let (search, _dir) = temp_search();
        search
            .db
            .insert_session("sess-1", "cli", "gpt-5", "openai", "2025-01-15T10:00:00Z")
            .unwrap();

        // Insert 20 messages.
        for i in 0..20 {
            search
                .db
                .insert_message(
                    "sess-1",
                    if i % 2 == 0 { "user" } else { "assistant" },
                    &format!("message {}", i),
                    None,
                    None,
                    None,
                    &format!("2025-01-15T10:{:02}:00Z", i),
                )
                .unwrap();
        }

        let result = search.scroll("sess-1", 10, 3).unwrap();
        assert!(!result.messages.is_empty());
        // Should have anchor at index 3 (3 before) and 3 after.
        assert_eq!(result.before, 3);
        assert_eq!(result.after, 3);
    }

    #[test]
    fn truncate_preserves_short_content() {
        let result = truncate_content("hello", 300);
        assert_eq!(result, "hello");
    }

    #[test]
    fn truncate_shortens_long_content() {
        let long = "a".repeat(500);
        let result = truncate_content(&long, 200);
        assert!(result.len() < 300);
        assert!(result.ends_with("more chars]"));
    }

    #[test]
    fn browse_dedupes_by_lineage() {
        let (search, _dir) = temp_search();
        seed_session(&search.db, "sess-1", "cli");
        seed_session(&search.db, "child-1", "cli");
        search.db.set_parent_session("child-1", "sess-1").unwrap();

        let sessions = search.browse().unwrap();
        // Same lineage → only one result.
        let ids: Vec<&str> = sessions.iter().map(|s| s.id.as_str()).collect();
        assert_eq!(ids.len(), 1, "should dedupe by lineage");
    }

    #[test]
    fn find_message_session_falls_back_to_given() {
        let (search, _dir) = temp_search();
        search
            .db
            .insert_session("sess-1", "cli", "gpt-5", "openai", "2025-01-15T10:00:00Z")
            .unwrap();
        // Message doesn't exist, but we trust the caller.
        let session = search.find_message_session("sess-1", 999).unwrap();
        assert_eq!(session, "sess-1");
    }
}