coding-agent-search 0.6.0

Unified TUI search over local coding agent histories
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
//! Provenance types for tracking conversation origins.
//!
//! This module defines the data model for tracking where conversations come from.
//! These types are used throughout cass: storage, indexing, search, CLI, TUI.
//!
//! # Key Types
//!
//! - [`SourceKind`]: The type of source (local, SSH, etc.)
//! - [`Source`]: A registered source in the system (stored in SQLite)
//! - [`Origin`]: Per-conversation provenance metadata
//!
//! # Example
//!
//! ```rust
//! use coding_agent_search::sources::provenance::{Origin, SourceKind, LOCAL_SOURCE_ID};
//!
//! // Create origin for a local conversation
//! let local_origin = Origin::local();
//! assert_eq!(local_origin.source_id, LOCAL_SOURCE_ID);
//!
//! // Create origin for a remote conversation
//! let remote_origin = Origin::remote("work-laptop");
//! assert!(remote_origin.is_remote());
//! ```

use serde::{Deserialize, Serialize};

// Re-export core provenance types from franken_agent_detection.
pub use franken_agent_detection::{LOCAL_SOURCE_ID, Origin, SourceKind};

const SOURCE_FILTER_ALL: &str = "all";
const SOURCE_FILTER_LOCAL: &str = "local";
const SOURCE_FILTER_REMOTE: &str = "remote";

/// A registered source in the system.
///
/// This struct represents a source record as stored in SQLite.
/// It's different from [`super::config::SourceDefinition`] which is
/// the user-facing configuration for how to connect to a source.
///
/// # Fields
///
/// - `id`: Stable, user-friendly identifier (e.g., "local", "work-laptop")
/// - `kind`: The type of source (local, ssh, etc.)
/// - `host_label`: Display label for UI (often SSH alias or hostname)
/// - `machine_id`: Optional stable machine identifier
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Source {
    /// Stable, user-friendly identifier.
    /// Examples: "local", "work-laptop", "home-server"
    pub id: String,

    /// What type of source this is.
    pub kind: SourceKind,

    /// Display label for UI (often SSH alias or hostname).
    /// May be None for local source.
    pub host_label: Option<String>,

    /// Optional stable machine identifier (can be hashed for privacy).
    pub machine_id: Option<String>,

    /// Platform hint (macos, linux, windows).
    pub platform: Option<String>,

    /// Extra configuration as JSON (SSH params, path rewrites, etc.).
    pub config_json: Option<serde_json::Value>,

    /// When this source was first registered.
    pub created_at: Option<i64>,

    /// When this source was last updated.
    pub updated_at: Option<i64>,
}

impl Source {
    /// Create a new local source.
    pub fn local() -> Self {
        Self {
            id: LOCAL_SOURCE_ID.to_string(),
            kind: SourceKind::Local,
            host_label: None,
            machine_id: None,
            platform: None,
            config_json: None,
            created_at: None,
            updated_at: None,
        }
    }

    /// Create a new remote source.
    pub fn remote(id: impl Into<String>, host_label: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            kind: SourceKind::Ssh,
            host_label: Some(host_label.into()),
            machine_id: None,
            platform: None,
            config_json: None,
            created_at: None,
            updated_at: None,
        }
    }

    /// Check if this is a remote source.
    pub fn is_remote(&self) -> bool {
        self.kind.is_remote()
    }

    /// Check if this is the local source.
    pub fn is_local(&self) -> bool {
        self.id == LOCAL_SOURCE_ID && self.kind == SourceKind::Local
    }

    /// Get a display label for this source.
    pub fn display_label(&self) -> &str {
        self.host_label.as_deref().unwrap_or(&self.id)
    }
}

impl Default for Source {
    fn default() -> Self {
        Self::local()
    }
}

/// Filter for searching by source.
///
/// Used in search queries to filter results by their origin.
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceFilter {
    /// Match all sources (no filtering).
    #[default]
    All,
    /// Match only local sources.
    Local,
    /// Match only remote sources (any SSH source).
    Remote,
    /// Match a specific source by ID.
    SourceId(String),
}

impl SourceFilter {
    /// Parse a source filter from a string.
    ///
    /// - "all" or "*" → All
    /// - "local" → Local
    /// - "remote" → Remote
    /// - anything else → SourceId
    pub fn parse(s: &str) -> Self {
        let trimmed = s.trim();
        match trimmed.to_ascii_lowercase().as_str() {
            "" | SOURCE_FILTER_ALL | "*" => Self::All,
            SOURCE_FILTER_LOCAL => Self::Local,
            SOURCE_FILTER_REMOTE => Self::Remote,
            _ => Self::SourceId(trimmed.to_string()),
        }
    }

    /// Check if an origin matches this filter.
    pub fn matches(&self, origin: &Origin) -> bool {
        match self {
            Self::All => true,
            Self::Local => origin.is_local(),
            Self::Remote => origin.is_remote(),
            Self::SourceId(id) => {
                let filter_id = id.trim();
                !filter_id.is_empty() && origin.source_id.trim() == filter_id
            }
        }
    }

    /// Check if this filter allows any source.
    pub fn is_all(&self) -> bool {
        matches!(self, Self::All)
    }

    /// Cycle to the next filter in sequence (for F11 hotkey).
    ///
    /// Cycle order: All → Local → Remote → All
    /// SourceId variants reset to All.
    pub fn cycle(&self) -> Self {
        match self {
            Self::All => Self::Local,
            Self::Local => Self::Remote,
            Self::Remote => Self::All,
            Self::SourceId(_) => Self::All,
        }
    }
}

impl std::fmt::Display for SourceFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::All => f.write_str(SOURCE_FILTER_ALL),
            Self::Local => f.write_str(SOURCE_FILTER_LOCAL),
            Self::Remote => f.write_str(SOURCE_FILTER_REMOTE),
            Self::SourceId(id) => f.write_str(id),
        }
    }
}

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

    #[test]
    fn test_source_kind_default() {
        assert_eq!(SourceKind::default(), SourceKind::Local);
    }

    #[test]
    fn test_source_kind_is_remote() {
        assert!(!SourceKind::Local.is_remote());
        assert!(SourceKind::Ssh.is_remote());
    }

    #[test]
    fn test_source_kind_display() {
        assert_eq!(SourceKind::Local.to_string(), "local");
        assert_eq!(SourceKind::Ssh.to_string(), "ssh");
    }

    #[test]
    fn test_source_kind_parse() {
        assert_eq!(SourceKind::parse("local"), Some(SourceKind::Local));
        assert_eq!(SourceKind::parse("LOCAL"), Some(SourceKind::Local));
        assert_eq!(SourceKind::parse("ssh"), Some(SourceKind::Ssh));
        assert_eq!(SourceKind::parse("SSH"), Some(SourceKind::Ssh));
        assert_eq!(SourceKind::parse("unknown"), None);
    }

    #[test]
    fn test_source_kind_serialization() {
        assert_eq!(
            serde_json::to_string(&SourceKind::Local).unwrap(),
            "\"local\""
        );
        assert_eq!(serde_json::to_string(&SourceKind::Ssh).unwrap(), "\"ssh\"");
    }

    #[test]
    fn test_source_kind_deserialization() {
        assert_eq!(
            serde_json::from_str::<SourceKind>("\"local\"").unwrap(),
            SourceKind::Local
        );
        assert_eq!(
            serde_json::from_str::<SourceKind>("\"ssh\"").unwrap(),
            SourceKind::Ssh
        );
    }

    #[test]
    fn test_source_local() {
        let source = Source::local();
        assert_eq!(source.id, LOCAL_SOURCE_ID);
        assert_eq!(source.kind, SourceKind::Local);
        assert!(source.is_local());
        assert!(!source.is_remote());
    }

    #[test]
    fn test_source_remote() {
        let source = Source::remote("laptop", "user@laptop.local");
        assert_eq!(source.id, "laptop");
        assert_eq!(source.kind, SourceKind::Ssh);
        assert_eq!(source.host_label, Some("user@laptop.local".to_string()));
        assert!(source.is_remote());
        assert!(!source.is_local());
    }

    #[test]
    fn test_source_display_label() {
        let local = Source::local();
        assert_eq!(local.display_label(), "local");

        let remote = Source::remote("laptop", "user@laptop.local");
        assert_eq!(remote.display_label(), "user@laptop.local");
    }

    #[test]
    fn test_source_default() {
        let source = Source::default();
        assert!(source.is_local());
    }

    #[test]
    fn test_origin_local() {
        let origin = Origin::local();
        assert_eq!(origin.source_id, LOCAL_SOURCE_ID);
        assert_eq!(origin.kind, SourceKind::Local);
        assert!(origin.is_local());
        assert!(!origin.is_remote());
    }

    #[test]
    fn test_origin_remote() {
        let origin = Origin::remote("laptop");
        assert_eq!(origin.source_id, "laptop");
        assert_eq!(origin.kind, SourceKind::Ssh);
        assert!(origin.is_remote());
        assert!(!origin.is_local());
    }

    #[test]
    fn test_origin_remote_with_host() {
        let origin = Origin::remote_with_host("laptop", "user@laptop.local");
        assert_eq!(origin.source_id, "laptop");
        assert_eq!(origin.host, Some("user@laptop.local".to_string()));
    }

    #[test]
    fn test_origin_display_label() {
        let local = Origin::local();
        assert_eq!(local.display_label(), "local");

        let remote = Origin::remote("laptop");
        assert_eq!(remote.display_label(), "laptop (remote)");

        let remote_with_host = Origin::remote_with_host("laptop", "user@laptop.local");
        assert_eq!(
            remote_with_host.display_label(),
            "user@laptop.local (remote)"
        );
    }

    #[test]
    fn test_origin_short_label() {
        let local = Origin::local();
        assert_eq!(local.short_label(), "local");

        let remote = Origin::remote_with_host("laptop", "user@laptop.local");
        assert_eq!(remote.short_label(), "user@laptop.local");
    }

    #[test]
    fn test_origin_default() {
        let origin = Origin::default();
        assert!(origin.is_local());
    }

    #[test]
    fn test_origin_equality() {
        let a = Origin::local();
        let b = Origin::local();
        assert_eq!(a, b);

        let c = Origin::remote("laptop");
        let d = Origin::remote("laptop");
        assert_eq!(c, d);

        assert_ne!(a, c);
    }

    #[test]
    fn test_origin_serialization_roundtrip() {
        let original = Origin::remote_with_host("laptop", "user@host");
        let json = serde_json::to_string(&original).unwrap();
        let deserialized: Origin = serde_json::from_str(&json).unwrap();
        assert_eq!(original, deserialized);
    }

    #[test]
    fn test_source_filter_parse() {
        assert_eq!(SourceFilter::parse(SOURCE_FILTER_ALL), SourceFilter::All);
        assert_eq!(SourceFilter::parse("ALL"), SourceFilter::All);
        assert_eq!(SourceFilter::parse("*"), SourceFilter::All);
        assert_eq!(
            SourceFilter::parse(SOURCE_FILTER_LOCAL),
            SourceFilter::Local
        );
        assert_eq!(SourceFilter::parse("LOCAL"), SourceFilter::Local);
        assert_eq!(
            SourceFilter::parse(SOURCE_FILTER_REMOTE),
            SourceFilter::Remote
        );
        assert_eq!(SourceFilter::parse("REMOTE"), SourceFilter::Remote);
        assert_eq!(
            SourceFilter::parse("laptop"),
            SourceFilter::SourceId("laptop".to_string())
        );
    }

    #[test]
    fn test_source_filter_parse_trims_whitespace() {
        assert_eq!(SourceFilter::parse("   local   "), SourceFilter::Local);
        assert_eq!(SourceFilter::parse("   REMOTE	"), SourceFilter::Remote);
        assert_eq!(
            SourceFilter::parse("   laptop-01   "),
            SourceFilter::SourceId("laptop-01".to_string())
        );
        assert_eq!(SourceFilter::parse("   	  "), SourceFilter::All);
    }

    #[test]
    fn test_source_filter_matches() {
        let local = Origin::local();
        let remote = Origin::remote("laptop");
        let mut whitespace_remote = Origin::remote("laptop");
        whitespace_remote.source_id = "  laptop  ".to_string();

        assert!(SourceFilter::All.matches(&local));
        assert!(SourceFilter::All.matches(&remote));

        assert!(SourceFilter::Local.matches(&local));
        assert!(!SourceFilter::Local.matches(&remote));

        assert!(!SourceFilter::Remote.matches(&local));
        assert!(SourceFilter::Remote.matches(&remote));

        assert!(SourceFilter::SourceId("laptop".to_string()).matches(&remote));
        assert!(SourceFilter::SourceId("  laptop  ".to_string()).matches(&whitespace_remote));
        assert!(!SourceFilter::SourceId("laptop".to_string()).matches(&local));
        assert!(!SourceFilter::SourceId("other".to_string()).matches(&remote));
        assert!(!SourceFilter::SourceId("   ".to_string()).matches(&remote));
    }

    #[test]
    fn test_source_filter_display() {
        assert_eq!(SourceFilter::All.to_string(), SOURCE_FILTER_ALL);
        assert_eq!(SourceFilter::Local.to_string(), SOURCE_FILTER_LOCAL);
        assert_eq!(SourceFilter::Remote.to_string(), SOURCE_FILTER_REMOTE);
        assert_eq!(
            SourceFilter::SourceId("laptop".to_string()).to_string(),
            "laptop"
        );
    }

    #[test]
    fn test_source_filter_default() {
        assert_eq!(SourceFilter::default(), SourceFilter::All);
    }

    // =================================================================
    // F11 Source Filter Cycle Tests (P4.3 TUI behavior)
    // =================================================================

    #[test]
    fn test_source_filter_cycle_transitions() {
        for (case, filter, expected) in [
            ("all to local", SourceFilter::All, SourceFilter::Local),
            ("local to remote", SourceFilter::Local, SourceFilter::Remote),
            ("remote to all", SourceFilter::Remote, SourceFilter::All),
            (
                "specific to all",
                SourceFilter::SourceId("laptop".to_string()),
                SourceFilter::All,
            ),
        ] {
            assert_eq!(filter.cycle(), expected, "{case}");
        }
    }

    #[test]
    fn test_source_filter_full_cycle() {
        // Complete F11 cycle: All → Local → Remote → All
        let filter = SourceFilter::All;
        let after_one = filter.cycle();
        let after_two = after_one.cycle();
        let after_three = after_two.cycle();

        assert_eq!(after_one, SourceFilter::Local);
        assert_eq!(after_two, SourceFilter::Remote);
        assert_eq!(after_three, SourceFilter::All);
    }

    #[test]
    fn test_source_filter_cycle_is_idempotent_for_specific() {
        // Multiple cycles from SourceId should always go to All first
        let filter = SourceFilter::SourceId("work-laptop".to_string());
        let cycled = filter.cycle();
        assert_eq!(cycled, SourceFilter::All);

        // Then continue normal cycle
        assert_eq!(cycled.cycle(), SourceFilter::Local);
    }

    #[test]
    fn test_source_filter_cycle_preserves_type_invariants() {
        // Cycling should never produce a SourceId variant
        let filters = [
            SourceFilter::All,
            SourceFilter::Local,
            SourceFilter::Remote,
            SourceFilter::SourceId("test".to_string()),
        ];

        for filter in filters {
            let cycled = filter.cycle();
            assert!(
                !matches!(cycled, SourceFilter::SourceId(_)),
                "Cycle should never produce SourceId variant, got {:?}",
                cycled
            );
        }
    }
}