sifs 0.3.3

SIFS Is Fast Search: instant local code search for agents
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
use crate::index::CacheConfig;
use crate::model2vec::{EncoderSpec, ModelLoadPolicy, ModelOptions};
use crate::types::{Chunk, IndexStats, IndexWarning, SearchMode, SearchOptions, SearchResult};
use crate::utils::is_git_url;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::{Path, PathBuf};

pub const DAEMON_PROTOCOL_VERSION: u32 = 1;

pub fn daemon_version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceKind {
    LocalPath,
    GitUrl,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SourceSpec {
    pub kind: SourceKind,
    pub source: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ref_name: Option<String>,
}

impl SourceSpec {
    pub fn resolve(
        source: impl AsRef<str>,
        ref_name: Option<String>,
        offline: bool,
    ) -> Result<Self> {
        let source = source.as_ref();
        if is_git_url(source) {
            if offline {
                bail!("--offline does not allow remote Git sources");
            }
            return Ok(Self {
                kind: SourceKind::GitUrl,
                source: source.to_owned(),
                ref_name,
            });
        }

        let path = PathBuf::from(source);
        if !path.exists() {
            bail!("local source does not exist: {}", path.display());
        }
        if !path.is_dir() {
            bail!("local source is not a directory: {}", path.display());
        }
        Ok(Self {
            kind: SourceKind::LocalPath,
            source: path
                .canonicalize()
                .with_context(|| format!("canonicalize source {}", path.display()))?
                .to_string_lossy()
                .into_owned(),
            ref_name: None,
        })
    }

    pub fn current_dir(offline: bool) -> Result<Self> {
        let cwd = std::env::current_dir().context("resolve current directory")?;
        Self::resolve(cwd.to_string_lossy(), None, offline)
    }

    pub fn cache_key(&self) -> String {
        match (&self.kind, &self.ref_name) {
            (SourceKind::LocalPath, _) => format!("path:{}", self.source),
            (SourceKind::GitUrl, Some(ref_name)) => format!("git:{}@{}", self.source, ref_name),
            (SourceKind::GitUrl, None) => format!("git:{}", self.source),
        }
    }

    pub fn display(&self) -> String {
        match &self.ref_name {
            Some(ref_name) => format!("{}@{}", self.source, ref_name),
            None => self.source.clone(),
        }
    }

    pub fn as_path(&self) -> Option<&Path> {
        matches!(self.kind, SourceKind::LocalPath).then(|| Path::new(&self.source))
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CacheConfigSpec {
    Platform,
    Project,
    Custom { path: PathBuf },
    Disabled,
}

impl From<&CacheConfig> for CacheConfigSpec {
    fn from(value: &CacheConfig) -> Self {
        match value {
            CacheConfig::Platform => Self::Platform,
            CacheConfig::Project => Self::Project,
            CacheConfig::Custom(path) => Self::Custom { path: path.clone() },
            CacheConfig::Disabled => Self::Disabled,
        }
    }
}

impl From<CacheConfigSpec> for CacheConfig {
    fn from(value: CacheConfigSpec) -> Self {
        match value {
            CacheConfigSpec::Platform => Self::Platform,
            CacheConfigSpec::Project => Self::Project,
            CacheConfigSpec::Custom { path } => Self::Custom(path),
            CacheConfigSpec::Disabled => Self::Disabled,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EncoderSpecWire {
    Model2Vec {
        model: String,
        policy: ModelLoadPolicyWire,
    },
    Hashing {
        dim: usize,
    },
    Sparse,
}

impl EncoderSpecWire {
    pub fn from_encoder_spec(spec: Option<&EncoderSpec>) -> Self {
        match spec {
            Some(EncoderSpec::Model2Vec(options)) => Self::Model2Vec {
                model: options.model.clone(),
                policy: ModelLoadPolicyWire::from(options.policy),
            },
            Some(EncoderSpec::Hashing { dim }) => Self::Hashing { dim: *dim },
            None => Self::Sparse,
        }
    }

    pub fn into_encoder_spec(self) -> Option<EncoderSpec> {
        match self {
            Self::Model2Vec { model, policy } => Some(EncoderSpec::Model2Vec(ModelOptions {
                model,
                policy: policy.into(),
            })),
            Self::Hashing { dim } => Some(EncoderSpec::Hashing { dim }),
            Self::Sparse => None,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModelLoadPolicyWire {
    AllowDownload,
    NoDownload,
    Offline,
}

impl From<ModelLoadPolicy> for ModelLoadPolicyWire {
    fn from(value: ModelLoadPolicy) -> Self {
        match value {
            ModelLoadPolicy::AllowDownload => Self::AllowDownload,
            ModelLoadPolicy::NoDownload => Self::NoDownload,
            ModelLoadPolicy::Offline => Self::Offline,
        }
    }
}

impl From<ModelLoadPolicyWire> for ModelLoadPolicy {
    fn from(value: ModelLoadPolicyWire) -> Self {
        match value {
            ModelLoadPolicyWire::AllowDownload => Self::AllowDownload,
            ModelLoadPolicyWire::NoDownload => Self::NoDownload,
            ModelLoadPolicyWire::Offline => Self::Offline,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct IndexRuntimeOptions {
    pub encoder: EncoderSpecWire,
    pub cache: CacheConfigSpec,
    pub extensions: Option<Vec<String>>,
    pub ignore: Option<Vec<String>>,
    pub include_text_files: bool,
}

impl Default for IndexRuntimeOptions {
    fn default() -> Self {
        Self {
            encoder: EncoderSpecWire::Model2Vec {
                model: ModelOptions::default().model,
                policy: ModelLoadPolicyWire::AllowDownload,
            },
            cache: CacheConfigSpec::Platform,
            extensions: None,
            ignore: None,
            include_text_files: false,
        }
    }
}

impl IndexRuntimeOptions {
    pub fn sparse(cache: CacheConfig) -> Self {
        Self {
            encoder: EncoderSpecWire::Sparse,
            cache: CacheConfigSpec::from(&cache),
            extensions: None,
            ignore: None,
            include_text_files: false,
        }
    }

    pub fn with_encoder(encoder: EncoderSpec, cache: CacheConfig) -> Self {
        Self {
            encoder: EncoderSpecWire::from_encoder_spec(Some(&encoder)),
            cache: CacheConfigSpec::from(&cache),
            extensions: None,
            ignore: None,
            include_text_files: false,
        }
    }

    pub fn extensions_set(&self) -> Option<HashSet<String>> {
        self.extensions
            .as_ref()
            .map(|items| items.iter().cloned().collect())
    }

    pub fn ignore_set(&self) -> Option<HashSet<String>> {
        self.ignore
            .as_ref()
            .map(|items| items.iter().cloned().collect())
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct IndexIdentity {
    pub source: SourceSpec,
    pub encoder_key: String,
    pub cache_key: String,
    pub extensions: Option<Vec<String>>,
    pub ignore: Option<Vec<String>>,
    pub include_text_files: bool,
}

impl IndexIdentity {
    pub fn new(source: SourceSpec, options: &IndexRuntimeOptions) -> Self {
        Self {
            source,
            encoder_key: encoder_key(&options.encoder),
            cache_key: cache_key(&options.cache),
            extensions: normalized_vec(options.extensions.clone()),
            ignore: normalized_vec(options.ignore.clone()),
            include_text_files: options.include_text_files,
        }
    }

    pub fn key(&self) -> String {
        serde_json::to_string(self).expect("index identity is serializable")
    }
}

fn encoder_key(encoder: &EncoderSpecWire) -> String {
    match encoder {
        EncoderSpecWire::Model2Vec { model, policy } => {
            format!("model2vec:{model}:{}", policy_key(*policy))
        }
        EncoderSpecWire::Hashing { dim } => format!("hashing:{dim}"),
        EncoderSpecWire::Sparse => "sparse".to_owned(),
    }
}

fn policy_key(policy: ModelLoadPolicyWire) -> &'static str {
    match policy {
        ModelLoadPolicyWire::AllowDownload => "allow-download",
        ModelLoadPolicyWire::NoDownload => "no-download",
        ModelLoadPolicyWire::Offline => "offline",
    }
}

fn cache_key(cache: &CacheConfigSpec) -> String {
    match cache {
        CacheConfigSpec::Platform => "platform".to_owned(),
        CacheConfigSpec::Project => "project".to_owned(),
        CacheConfigSpec::Custom { path } => format!("custom:{}", path.display()),
        CacheConfigSpec::Disabled => "disabled".to_owned(),
    }
}

fn normalized_vec(items: Option<Vec<String>>) -> Option<Vec<String>> {
    let mut items = items?;
    items.sort();
    items.dedup();
    Some(items)
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DaemonRequestEnvelope {
    pub protocol_version: u32,
    pub request_id: String,
    pub request: DaemonRequest,
}

impl DaemonRequestEnvelope {
    pub fn new(request_id: impl Into<String>, request: DaemonRequest) -> Self {
        Self {
            protocol_version: DAEMON_PROTOCOL_VERSION,
            request_id: request_id.into(),
            request,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum DaemonRequest {
    Ping,
    Status,
    IndexStatus {
        source: SourceSpec,
        options: IndexRuntimeOptions,
    },
    Search {
        source: SourceSpec,
        options: IndexRuntimeOptions,
        query: String,
        search: SearchOptionsWire,
    },
    FindRelated {
        source: SourceSpec,
        options: IndexRuntimeOptions,
        file_path: String,
        line: usize,
        top_k: usize,
    },
    ListFiles {
        source: SourceSpec,
        options: IndexRuntimeOptions,
        limit: usize,
    },
    GetChunk {
        source: SourceSpec,
        options: IndexRuntimeOptions,
        file_path: String,
        line: usize,
    },
    Refresh {
        source: SourceSpec,
        options: IndexRuntimeOptions,
    },
    Clear {
        source: SourceSpec,
        options: IndexRuntimeOptions,
    },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SearchOptionsWire {
    pub top_k: usize,
    pub mode: SearchMode,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alpha: Option<f32>,
    pub filter_languages: Vec<String>,
    pub filter_paths: Vec<String>,
    pub use_query_cache: bool,
    #[serde(default)]
    pub explain: bool,
}

impl From<SearchOptions> for SearchOptionsWire {
    fn from(value: SearchOptions) -> Self {
        Self {
            top_k: value.top_k,
            mode: value.mode,
            alpha: value.alpha,
            filter_languages: value.filter_languages,
            filter_paths: value.filter_paths,
            use_query_cache: value.use_query_cache,
            explain: value.explain,
        }
    }
}

impl From<SearchOptionsWire> for SearchOptions {
    fn from(value: SearchOptionsWire) -> Self {
        Self {
            top_k: value.top_k,
            mode: value.mode,
            alpha: value.alpha,
            filter_languages: value.filter_languages,
            filter_paths: value.filter_paths,
            use_query_cache: value.use_query_cache,
            explain: value.explain,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DaemonResponseEnvelope {
    pub protocol_version: u32,
    pub request_id: String,
    #[serde(flatten)]
    pub result: ResultEnvelope,
}

impl DaemonResponseEnvelope {
    pub fn ok(request_id: impl Into<String>, result: DaemonResult) -> Self {
        Self {
            protocol_version: DAEMON_PROTOCOL_VERSION,
            request_id: request_id.into(),
            result: ResultEnvelope::Ok { result },
        }
    }

    pub fn error(request_id: impl Into<String>, error: DaemonError) -> Self {
        Self {
            protocol_version: DAEMON_PROTOCOL_VERSION,
            request_id: request_id.into(),
            result: ResultEnvelope::Error { error },
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResultEnvelope {
    Ok { result: DaemonResult },
    Error { error: DaemonError },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum DaemonResult {
    Pong {
        version: String,
    },
    Status(DaemonStatus),
    IndexStatus(IndexStatusResult),
    Search(SearchResultSet),
    FindRelated(SearchResultSet),
    ListFiles {
        source: SourceSpec,
        total: usize,
        files: Vec<String>,
    },
    GetChunk {
        source: SourceSpec,
        chunk: Chunk,
    },
    Refresh(IndexStatusResult),
    Clear {
        source: SourceSpec,
        removed: bool,
    },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DaemonStatus {
    pub version: String,
    pub protocol_version: u32,
    pub pid: u32,
    pub indexes: Vec<CachedIndexStatus>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CachedIndexStatus {
    pub source: SourceSpec,
    pub stats: IndexStats,
    pub semantic_loaded: bool,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IndexStatusResult {
    pub source: SourceSpec,
    pub stats: IndexStats,
    pub semantic_loaded: bool,
    pub warnings: Vec<IndexWarning>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SearchResultSet {
    pub source: SourceSpec,
    pub query: String,
    pub mode: SearchMode,
    pub stats: IndexStats,
    pub elapsed_ms: u64,
    pub results: Vec<SearchResult>,
    pub warnings: Vec<IndexWarning>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DaemonError {
    pub code: String,
    pub message: String,
}

impl DaemonError {
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
        }
    }
}