dx-driven 0.1.0

Professional AI-assisted development orchestrator with binary-first architecture
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
//! # Obsidian Integration
//!
//! Obsidian vault file operations and search.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use driven::integrations::obsidian::{ObsidianVault, ObsidianConfig};
//!
//! let config = ObsidianConfig::from_file("~/.dx/config/obsidian.sr")?;
//! let vault = ObsidianVault::new(&config)?;
//!
//! // Create a note
//! vault.create_note("My Note", "# Hello\n\nContent here.").await?;
//!
//! // Search notes
//! let results = vault.search("keyword").await?;
//! ```

use crate::error::{DrivenError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Obsidian configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObsidianConfig {
    /// Whether Obsidian integration is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Vault path
    pub vault_path: PathBuf,
    /// Default folder for new notes
    #[serde(default)]
    pub default_folder: String,
    /// Daily notes folder
    #[serde(default = "default_daily_folder")]
    pub daily_folder: String,
    /// Daily note format
    #[serde(default = "default_daily_format")]
    pub daily_format: String,
    /// Template folder
    pub template_folder: Option<String>,
}

fn default_true() -> bool {
    true
}

fn default_daily_folder() -> String {
    "Daily".to_string()
}

fn default_daily_format() -> String {
    "%Y-%m-%d".to_string()
}

impl Default for ObsidianConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            vault_path: PathBuf::new(),
            default_folder: String::new(),
            daily_folder: default_daily_folder(),
            daily_format: default_daily_format(),
            template_folder: None,
        }
    }
}

impl ObsidianConfig {
    /// Load from .sr config file
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
        let content = std::fs::read_to_string(path.as_ref())
            .map_err(|e| DrivenError::Io(e))?;
        Self::parse_sr(&content)
    }

    fn parse_sr(_content: &str) -> Result<Self> {
        Ok(Self::default())
    }

    /// Resolve environment variables
    pub fn resolve_env_vars(&mut self) {
        if let Ok(path) = std::env::var("OBSIDIAN_VAULT_PATH") {
            self.vault_path = PathBuf::from(path);
        }
    }
}

/// Obsidian note
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObsidianNote {
    /// Note title (filename without .md)
    pub title: String,
    /// Full path to the note
    pub path: PathBuf,
    /// Note content
    pub content: String,
    /// Frontmatter (YAML)
    pub frontmatter: Option<HashMap<String, serde_yaml::Value>>,
    /// Tags found in the note
    pub tags: Vec<String>,
    /// Links to other notes
    pub links: Vec<String>,
    /// Backlinks (notes that link to this one)
    pub backlinks: Vec<String>,
    /// Created time
    pub created: Option<chrono::DateTime<chrono::Utc>>,
    /// Modified time
    pub modified: Option<chrono::DateTime<chrono::Utc>>,
}

/// Search result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
    /// Note
    pub note: ObsidianNote,
    /// Match score
    pub score: f32,
    /// Matched lines
    pub matches: Vec<SearchMatch>,
}

/// Search match in a note
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchMatch {
    /// Line number (1-indexed)
    pub line: usize,
    /// Line content
    pub content: String,
    /// Match start position in line
    pub start: usize,
    /// Match end position in line
    pub end: usize,
}

/// Obsidian vault
pub struct ObsidianVault {
    config: ObsidianConfig,
    /// Cache of note metadata
    note_cache: HashMap<PathBuf, NoteCacheEntry>,
}

#[derive(Debug, Clone)]
struct NoteCacheEntry {
    title: String,
    tags: Vec<String>,
    links: Vec<String>,
    modified: std::time::SystemTime,
}

impl ObsidianVault {
    /// Create a new vault instance
    pub fn new(config: &ObsidianConfig) -> Result<Self> {
        let mut config = config.clone();
        config.resolve_env_vars();

        if !config.vault_path.exists() {
            return Err(DrivenError::NotFound(format!(
                "Vault not found: {}",
                config.vault_path.display()
            )));
        }

        Ok(Self {
            config,
            note_cache: HashMap::new(),
        })
    }

    /// Check if vault is configured
    pub fn is_configured(&self) -> bool {
        self.config.enabled && self.config.vault_path.exists()
    }

    /// Get vault path
    pub fn vault_path(&self) -> &Path {
        &self.config.vault_path
    }

    /// Create a new note
    pub async fn create_note(&self, title: &str, content: &str) -> Result<ObsidianNote> {
        let filename = self.sanitize_filename(title);
        let folder = if self.config.default_folder.is_empty() {
            self.config.vault_path.clone()
        } else {
            self.config.vault_path.join(&self.config.default_folder)
        };

        // Ensure folder exists
        tokio::fs::create_dir_all(&folder)
            .await
            .map_err(|e| DrivenError::Io(e))?;

        let path = folder.join(format!("{}.md", filename));

        if path.exists() {
            return Err(DrivenError::Conflict(format!(
                "Note already exists: {}",
                path.display()
            )));
        }

        tokio::fs::write(&path, content)
            .await
            .map_err(|e| DrivenError::Io(e))?;

        self.get_note(&path).await
    }

    /// Get a note by path or title
    pub async fn get_note(&self, path: &Path) -> Result<ObsidianNote> {
        let full_path = if path.is_absolute() {
            path.to_path_buf()
        } else {
            self.config.vault_path.join(path)
        };

        let content = tokio::fs::read_to_string(&full_path)
            .await
            .map_err(|e| DrivenError::Io(e))?;

        let metadata = tokio::fs::metadata(&full_path)
            .await
            .map_err(|e| DrivenError::Io(e))?;

        let title = full_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or_default()
            .to_string();

        let (frontmatter, body) = self.parse_frontmatter(&content);
        let tags = self.extract_tags(&content);
        let links = self.extract_links(&content);

        Ok(ObsidianNote {
            title,
            path: full_path,
            content,
            frontmatter,
            tags,
            links,
            backlinks: Vec::new(), // Would need to scan vault
            created: metadata.created().ok().map(|t| t.into()),
            modified: metadata.modified().ok().map(|t| t.into()),
        })
    }

    /// Update a note
    pub async fn update_note(&self, path: &Path, content: &str) -> Result<ObsidianNote> {
        let full_path = if path.is_absolute() {
            path.to_path_buf()
        } else {
            self.config.vault_path.join(path)
        };

        if !full_path.exists() {
            return Err(DrivenError::NotFound(format!(
                "Note not found: {}",
                full_path.display()
            )));
        }

        tokio::fs::write(&full_path, content)
            .await
            .map_err(|e| DrivenError::Io(e))?;

        self.get_note(&full_path).await
    }

    /// Delete a note
    pub async fn delete_note(&self, path: &Path) -> Result<()> {
        let full_path = if path.is_absolute() {
            path.to_path_buf()
        } else {
            self.config.vault_path.join(path)
        };

        tokio::fs::remove_file(&full_path)
            .await
            .map_err(|e| DrivenError::Io(e))
    }

    /// Create or get today's daily note
    pub async fn daily_note(&self) -> Result<ObsidianNote> {
        let today = chrono::Local::now().format(&self.config.daily_format).to_string();
        let folder = self.config.vault_path.join(&self.config.daily_folder);
        let path = folder.join(format!("{}.md", today));

        if path.exists() {
            return self.get_note(&path).await;
        }

        // Create daily note with template
        let content = format!("# {}\n\n", today);
        
        tokio::fs::create_dir_all(&folder)
            .await
            .map_err(|e| DrivenError::Io(e))?;

        tokio::fs::write(&path, &content)
            .await
            .map_err(|e| DrivenError::Io(e))?;

        self.get_note(&path).await
    }

    /// Append to today's daily note
    pub async fn append_to_daily(&self, content: &str) -> Result<ObsidianNote> {
        let note = self.daily_note().await?;
        let new_content = format!("{}\n{}", note.content.trim_end(), content);
        self.update_note(&note.path, &new_content).await
    }

    /// Search notes
    pub async fn search(&self, query: &str) -> Result<Vec<SearchResult>> {
        let query_lower = query.to_lowercase();
        let mut results = Vec::new();

        // Walk vault directory
        let mut entries = tokio::fs::read_dir(&self.config.vault_path)
            .await
            .map_err(|e| DrivenError::Io(e))?;

        while let Some(entry) = entries.next_entry().await.map_err(|e| DrivenError::Io(e))? {
            let path = entry.path();
            if path.extension().map(|e| e == "md").unwrap_or(false) {
                if let Ok(note) = self.get_note(&path).await {
                    let matches = self.find_matches(&note.content, &query_lower);
                    if !matches.is_empty() {
                        let score = matches.len() as f32 / note.content.len() as f32;
                        results.push(SearchResult {
                            note,
                            score,
                            matches,
                        });
                    }
                }
            }
        }

        // Sort by score descending
        results.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));

        Ok(results)
    }

    /// List all notes
    pub async fn list_notes(&self) -> Result<Vec<ObsidianNote>> {
        let mut notes = Vec::new();

        fn walk_dir(dir: &Path, notes: &mut Vec<PathBuf>) -> std::io::Result<()> {
            if dir.is_dir() {
                for entry in std::fs::read_dir(dir)? {
                    let entry = entry?;
                    let path = entry.path();
                    if path.is_dir() {
                        walk_dir(&path, notes)?;
                    } else if path.extension().map(|e| e == "md").unwrap_or(false) {
                        notes.push(path);
                    }
                }
            }
            Ok(())
        }

        let mut paths = Vec::new();
        walk_dir(&self.config.vault_path, &mut paths)
            .map_err(|e| DrivenError::Io(e))?;

        for path in paths {
            if let Ok(note) = self.get_note(&path).await {
                notes.push(note);
            }
        }

        Ok(notes)
    }

    /// Get backlinks for a note
    pub async fn get_backlinks(&self, title: &str) -> Result<Vec<ObsidianNote>> {
        let notes = self.list_notes().await?;
        let link_pattern = format!("[[{}]]", title);
        let link_pattern_alias = format!("[[{}|", title);

        Ok(notes
            .into_iter()
            .filter(|n| {
                n.content.contains(&link_pattern) || n.content.contains(&link_pattern_alias)
            })
            .collect())
    }

    /// Parse frontmatter from content
    fn parse_frontmatter(&self, content: &str) -> (Option<HashMap<String, serde_yaml::Value>>, String) {
        if !content.starts_with("---") {
            return (None, content.to_string());
        }

        if let Some(end) = content[3..].find("---") {
            let frontmatter_str = &content[3..end + 3];
            let body = &content[end + 6..];

            let frontmatter: Result<HashMap<String, serde_yaml::Value>, _> =
                serde_yaml::from_str(frontmatter_str.trim());

            (frontmatter.ok(), body.trim_start().to_string())
        } else {
            (None, content.to_string())
        }
    }

    /// Extract tags from content
    fn extract_tags(&self, content: &str) -> Vec<String> {
        let mut tags = Vec::new();

        // Tags in frontmatter are handled separately
        // Find inline tags (#tag)
        for word in content.split_whitespace() {
            if word.starts_with('#') && word.len() > 1 {
                let tag = word[1..]
                    .trim_end_matches(|c: char| !c.is_alphanumeric() && c != '/' && c != '-');
                if !tag.is_empty() {
                    tags.push(tag.to_string());
                }
            }
        }

        tags.sort();
        tags.dedup();
        tags
    }

    /// Extract wiki links from content
    fn extract_links(&self, content: &str) -> Vec<String> {
        let mut links = Vec::new();
        let mut remaining = content;

        while let Some(start) = remaining.find("[[") {
            if let Some(end) = remaining[start..].find("]]") {
                let link = &remaining[start + 2..start + end];
                // Handle aliases [[Note|Alias]]
                let note_name = link.split('|').next().unwrap_or(link);
                links.push(note_name.to_string());
                remaining = &remaining[start + end + 2..];
            } else {
                break;
            }
        }

        links.sort();
        links.dedup();
        links
    }

    /// Find matches in content
    fn find_matches(&self, content: &str, query: &str) -> Vec<SearchMatch> {
        let mut matches = Vec::new();
        let content_lower = content.to_lowercase();

        for (line_idx, line) in content.lines().enumerate() {
            let line_lower = line.to_lowercase();
            let mut start = 0;

            while let Some(pos) = line_lower[start..].find(query) {
                matches.push(SearchMatch {
                    line: line_idx + 1,
                    content: line.to_string(),
                    start: start + pos,
                    end: start + pos + query.len(),
                });
                start = start + pos + 1;
            }
        }

        matches
    }

    /// Sanitize filename
    fn sanitize_filename(&self, name: &str) -> String {
        name.chars()
            .map(|c| match c {
                '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
                _ => c,
            })
            .collect()
    }
}

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

    #[test]
    fn test_extract_tags() {
        let config = ObsidianConfig::default();
        let vault = ObsidianVault {
            config,
            note_cache: HashMap::new(),
        };

        let content = "This is a note with #tag1 and #tag2/nested tags.";
        let tags = vault.extract_tags(content);
        assert!(tags.contains(&"tag1".to_string()));
        assert!(tags.contains(&"tag2/nested".to_string()));
    }

    #[test]
    fn test_extract_links() {
        let config = ObsidianConfig::default();
        let vault = ObsidianVault {
            config,
            note_cache: HashMap::new(),
        };

        let content = "Link to [[Note A]] and [[Note B|alias]].";
        let links = vault.extract_links(content);
        assert!(links.contains(&"Note A".to_string()));
        assert!(links.contains(&"Note B".to_string()));
    }

    #[test]
    fn test_sanitize_filename() {
        let config = ObsidianConfig::default();
        let vault = ObsidianVault {
            config,
            note_cache: HashMap::new(),
        };

        assert_eq!(vault.sanitize_filename("My Note: Test"), "My Note_ Test");
        assert_eq!(vault.sanitize_filename("A/B\\C"), "A_B_C");
    }
}