agent-atlas 0.1.2

Deterministic knowledge base indexer for AI 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
//! Core data types for the indexer

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;

/// File fingerprint for change detection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Fingerprint {
    /// Relative path from knowledge base root
    pub path: PathBuf,
    /// Last modification time (Unix timestamp)
    pub mtime: u64,
    /// File size in bytes
    pub size: u64,
    /// Content hash (Blake3, computed on demand)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_hash: Option<String>,
}

/// Type of file being indexed
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FileType {
    Markdown,
    PlainText,
    Pdf,
    Rst,
    Org,
    Rust,
    JavaScript,
    Jsx,
    TypeScript,
    Tsx,
    Unknown,
}

impl FileType {
    pub fn from_extension(ext: &str) -> Self {
        match ext.to_lowercase().as_str() {
            "md" | "markdown" => Self::Markdown,
            "txt" | "text" | "json" | "yml" | "yaml" | "toml" | "sh" | "sql" => Self::PlainText,
            "pdf" => Self::Pdf,
            "rst" => Self::Rst,
            "org" => Self::Org,
            "rs" => Self::Rust,
            "js" | "mjs" | "cjs" => Self::JavaScript,
            "jsx" => Self::Jsx,
            "ts" => Self::TypeScript,
            "tsx" => Self::Tsx,
            _ => Self::Unknown,
        }
    }

    /// Check if this file type is source code
    pub fn is_code(&self) -> bool {
        matches!(
            self,
            Self::Rust | Self::JavaScript | Self::Jsx | Self::TypeScript | Self::Tsx
        )
    }

    pub fn search_term(&self) -> &'static str {
        match self {
            Self::Markdown => "markdown",
            Self::PlainText => "plaintext",
            Self::Pdf => "pdf",
            Self::Rst => "rst",
            Self::Org => "org",
            Self::Rust => "rust",
            Self::JavaScript => "javascript",
            Self::Jsx => "jsx",
            Self::TypeScript => "typescript",
            Self::Tsx => "tsx",
            Self::Unknown => "unknown",
        }
    }

    pub fn normalize_search_term(term: &str) -> String {
        term.trim()
            .chars()
            .filter(|ch| ch.is_ascii_alphanumeric())
            .collect::<String>()
            .to_ascii_lowercase()
    }
}

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

    #[test]
    fn maps_javascript_and_common_text_extensions() {
        assert_eq!(FileType::from_extension("js"), FileType::JavaScript);
        assert_eq!(FileType::from_extension("mjs"), FileType::JavaScript);
        assert_eq!(FileType::from_extension("cjs"), FileType::JavaScript);
        assert_eq!(FileType::from_extension("jsx"), FileType::Jsx);
        assert_eq!(FileType::from_extension("json"), FileType::PlainText);
        assert_eq!(FileType::from_extension("yaml"), FileType::PlainText);
        assert_eq!(FileType::from_extension("toml"), FileType::PlainText);
        assert_eq!(FileType::from_extension("sh"), FileType::PlainText);
        assert_eq!(FileType::from_extension("sql"), FileType::PlainText);
    }

    #[test]
    fn javascript_family_is_treated_as_code() {
        assert!(FileType::JavaScript.is_code());
        assert!(FileType::Jsx.is_code());
        assert!(!FileType::PlainText.is_code());
    }

    #[test]
    fn normalizes_search_terms_for_filters() {
        assert_eq!(FileType::normalize_search_term("plain-text"), "plaintext");
        assert_eq!(FileType::normalize_search_term("Type_Script"), "typescript");
        assert_eq!(FileType::Markdown.search_term(), "markdown");
    }
}

pub const SEARCH_RESULTS_CONTRACT_VERSION: u32 = 2;
pub const SCAN_RESULTS_CONTRACT_VERSION: u32 = 1;
pub const DOCTOR_RESULTS_CONTRACT_VERSION: u32 = 1;
pub const LAST_BUILD_MANIFEST_VERSION: u32 = 1;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ScanDeltaGroup {
    pub count: usize,
    pub paths: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ScanDeltaGroups {
    pub new_files: ScanDeltaGroup,
    pub modified_files: ScanDeltaGroup,
    pub deleted_files: ScanDeltaGroup,
    pub unchanged_files: ScanDeltaGroup,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ScanDeltaSummary {
    pub changed_files: usize,
    pub new_files: usize,
    pub modified_files: usize,
    pub deleted_files: usize,
    pub unchanged_files: usize,
    pub requires_build: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ScanDeltaReport {
    pub version: u32,
    pub read_only: bool,
    pub indexed_candidates: usize,
    pub summary: ScanDeltaSummary,
    pub groups: ScanDeltaGroups,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum BuildFileIssueReason {
    FileTooLarge,
    MetadataUnreadable,
    ExtractionFailed,
    PdftotextUnavailable,
}

impl BuildFileIssueReason {
    pub fn label(&self) -> &'static str {
        match self {
            Self::FileTooLarge => "file_too_large",
            Self::MetadataUnreadable => "metadata_unreadable",
            Self::ExtractionFailed => "extraction_failed",
            Self::PdftotextUnavailable => "pdftotext_unavailable",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BuildFileIssue {
    pub path: String,
    pub reason: BuildFileIssueReason,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LastBuildManifest {
    pub version: u32,
    pub index_version: String,
    pub indexed_candidates: usize,
    pub indexed_documents: usize,
    pub processed_files: usize,
    pub full_reindex: bool,
    pub skipped: Vec<BuildFileIssue>,
    pub failed: Vec<BuildFileIssue>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DoctorState {
    Clean,
    Stale,
    Broken,
}

impl DoctorState {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Clean => "clean",
            Self::Stale => "stale",
            Self::Broken => "broken",
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DoctorSeverity {
    Error,
    Warning,
    Info,
}

impl DoctorSeverity {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Warning => "warning",
            Self::Info => "info",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DoctorCheck {
    pub id: String,
    pub label: String,
    pub severity: DoctorSeverity,
    pub summary: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub details: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DoctorSeverityCounts {
    pub error: usize,
    pub warning: usize,
    pub info: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DoctorSummary {
    pub indexed_candidates: usize,
    pub index_documents: usize,
    pub requires_build: bool,
    pub changed_files: usize,
    pub skipped_files: usize,
    pub failed_files: usize,
    pub severity_counts: DoctorSeverityCounts,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct DoctorCheckGroups {
    pub error: Vec<DoctorCheck>,
    pub warning: Vec<DoctorCheck>,
    pub info: Vec<DoctorCheck>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DoctorReport {
    pub version: u32,
    pub state: DoctorState,
    pub summary: DoctorSummary,
    pub checks: DoctorCheckGroups,
}

/// Per-file extracted features
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileFeatures {
    /// Unique identifier (content hash)
    pub id: String,
    /// Relative path from knowledge base root
    pub path: PathBuf,
    /// Detected file type
    pub file_type: FileType,
    /// Extracted or derived title
    pub title: String,
    /// First paragraph or ~400 chars
    pub snippet: String,
    /// Total word count
    pub word_count: usize,
    /// Total character count
    pub char_count: usize,
    /// Unique term count before truncation
    #[serde(default)]
    pub unique_term_count: usize,
    /// Top terms by TF-IDF (after global pass)
    pub top_terms: Vec<TermScore>,
    /// Top bigrams/trigrams
    pub top_phrases: Vec<PhraseScore>,
    /// Top RAKE phrases
    #[serde(default)]
    pub rake_phrases: Vec<PhraseScore>,
    /// Top YAKE keywords (lower score = more important)
    #[serde(default)]
    pub yake_keywords: Vec<KeywordScore>,
    /// Extracted links (internal/external)
    pub links_out: Vec<Link>,
    /// Extracted headings (if available)
    pub headings: Vec<String>,
    /// Did extraction succeed?
    pub extraction_ok: bool,
    /// Unix timestamp of extraction
    pub extracted_at: u64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchFilters {
    pub paths: Vec<String>,
    pub types: Vec<String>,
    pub extensions: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchQueryMetadata {
    pub text: String,
    pub limit: usize,
    pub filters: SearchFilters,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SearchResultItem {
    pub score: f32,
    pub path: String,
    pub file_type: FileType,
    pub extension: String,
    pub title: String,
    pub snippet: String,
    pub matched_fields: Vec<String>,
    pub highlight: SearchHighlight,
    pub reasons: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub explanation: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SearchResultsEnvelope {
    pub version: u32,
    pub index_version: String,
    pub query: SearchQueryMetadata,
    pub result_count: usize,
    pub results: Vec<SearchResultItem>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchHighlight {
    pub field: String,
    pub text: String,
    pub html: String,
    pub ranges: Vec<SearchHighlightRange>,
    #[serde(default)]
    pub fallback: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchHighlightRange {
    pub start: usize,
    pub end: usize,
}

/// Term with TF-IDF score
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TermScore {
    /// The term (lowercase, normalized)
    pub term: String,
    /// Term frequency in this document
    pub tf: f32,
    /// TF-IDF score (computed after global pass)
    #[serde(default)]
    pub tfidf: f32,
}

/// Phrase with score
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhraseScore {
    /// The phrase (normalized)
    pub phrase: String,
    /// Phrase score (RAKE or frequency-based)
    #[serde(default, alias = "count")]
    pub score: f32,
}

/// Keyword with YAKE score
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeywordScore {
    /// The keyword or phrase
    pub keyword: String,
    /// YAKE score (lower is better)
    pub score: f32,
}

/// Link type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LinkType {
    /// Internal link (relative path or wiki-link)
    Internal,
    /// External URL
    External,
    /// Citation (DOI, arXiv, ISBN, etc.)
    Citation,
}

/// Extracted link
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Link {
    /// Link target (path or URL)
    pub target: String,
    /// Type of link
    pub link_type: LinkType,
}

/// Global term document frequency index
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GlobalTermIndex {
    /// Total number of documents indexed
    pub total_docs: usize,
    /// Term -> stats mapping
    pub terms: BTreeMap<String, TermStats>,
}

/// Statistics for a single term across the corpus
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TermStats {
    /// Document frequency (number of docs containing this term)
    pub df: usize,
    /// Top documents by TF-IDF for this term (file IDs)
    pub top_docs: Vec<String>,
}

/// Folder signature (aggregate stats for a folder)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FolderSignature {
    /// Relative path from knowledge base root
    pub path: PathBuf,
    /// Number of indexed files in this folder (recursive)
    pub file_count: usize,
    /// Top distinctive terms for this folder
    pub top_terms: Vec<String>,
    /// Top distinctive phrases for this folder
    pub top_phrases: Vec<String>,
}

/// Change status for a file
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeStatus {
    /// File is new (not in previous fingerprints)
    New,
    /// File was modified (mtime or size changed)
    Modified,
    /// File was deleted (in previous fingerprints, not on disk)
    Deleted,
    /// File is unchanged
    Unchanged,
}

/// Result of scanning for changes
#[derive(Debug, Clone, Default)]
pub struct ScanResult {
    /// All current fingerprints
    pub fingerprints: Vec<Fingerprint>,
    /// Files that are new
    pub new_files: Vec<PathBuf>,
    /// Files that were modified
    pub modified_files: Vec<PathBuf>,
    /// Files that were deleted
    pub deleted_files: Vec<PathBuf>,
    /// Total files scanned
    pub total_files: usize,
}