opencrabs 0.3.43

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
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
//! File Service
//!
//! Provides business logic for file tracking operations.

use crate::db::{models::File, repository::FileRepository};
use crate::services::ServiceContext;
use anyhow::{Context, Result};
use chrono::Utc;
use std::path::{Path, PathBuf};
use uuid::Uuid;

/// Whether `path` lives inside a git repository — walk up its parents looking
/// for a `.git` entry. Repository code is excluded from project archiving: it's
/// already version-controlled and changes on the repo, so copying it elsewhere
/// is pointless. Everything outside a repo (shared uploads, generated artifacts)
/// is fair game to archive.
fn is_inside_git_repo(path: &Path) -> bool {
    let mut dir = path.parent();
    while let Some(d) = dir {
        if d.join(".git").exists() {
            return true;
        }
        dir = d.parent();
    }
    false
}

/// Turn a project name into a filesystem-safe directory slug
/// (lowercase alphanumerics, runs of other chars collapsed to a single dash).
pub(crate) fn slugify_project_name(name: &str) -> String {
    let mut slug = String::with_capacity(name.len());
    let mut prev_dash = false;
    for c in name.chars() {
        if c.is_ascii_alphanumeric() {
            slug.push(c.to_ascii_lowercase());
            prev_dash = false;
        } else if !prev_dash {
            slug.push('-');
            prev_dash = true;
        }
    }
    let trimmed = slug.trim_matches('-');
    if trimmed.is_empty() {
        "project".to_string()
    } else {
        trimmed.to_string()
    }
}

/// Service for managing file tracking
#[derive(Clone)]
pub struct FileService {
    context: ServiceContext,
}

impl FileService {
    /// Create a new file service
    pub fn new(context: ServiceContext) -> Self {
        Self { context }
    }

    /// Track a new file
    pub async fn track_file(
        &self,
        session_id: Uuid,
        path: PathBuf,
        content: Option<String>,
    ) -> Result<File> {
        let repo = FileRepository::new(self.context.pool());

        // Determine file size from disk if available
        let size = std::fs::metadata(&path).ok().map(|m| m.len() as i64);

        let file = File {
            id: Uuid::new_v4(),
            session_id,
            path: path.clone(),
            content,
            size,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        repo.create(&file).await.context("Failed to track file")?;

        tracing::debug!("Tracked new file: {:?} in session {}", path, session_id);
        Ok(file)
    }

    /// Get a file by ID
    pub async fn get_file(&self, id: Uuid) -> Result<Option<File>> {
        let repo = FileRepository::new(self.context.pool());
        repo.find_by_id(id).await.context("Failed to get file")
    }

    /// Get a file by ID, returning an error if not found
    pub async fn get_file_required(&self, id: Uuid) -> Result<File> {
        self.get_file(id)
            .await?
            .ok_or_else(|| anyhow::anyhow!("File not found: {}", id))
    }

    /// List all files for a session
    pub async fn list_files_for_session(&self, session_id: Uuid) -> Result<Vec<File>> {
        let repo = FileRepository::new(self.context.pool());
        repo.find_by_session(session_id)
            .await
            .context("Failed to list files for session")
    }

    /// Find a file by path in a session
    pub async fn find_file_by_path(&self, session_id: Uuid, path: &Path) -> Result<Option<File>> {
        let repo = FileRepository::new(self.context.pool());
        repo.find_by_path(session_id, path)
            .await
            .context("Failed to find file by path")
    }

    /// Update a file
    pub async fn update_file(&self, file: &File) -> Result<()> {
        let repo = FileRepository::new(self.context.pool());

        // Update the updated_at timestamp
        let mut updated_file = file.clone();
        updated_file.updated_at = Utc::now();

        repo.update(&updated_file)
            .await
            .context("Failed to update file")?;

        tracing::debug!("Updated file: {:?}", file.path);
        Ok(())
    }

    /// Update file content
    pub async fn update_file_content(&self, id: Uuid, content: Option<String>) -> Result<()> {
        let mut file = self.get_file_required(id).await?;
        file.content = content;
        file.updated_at = Utc::now();

        let repo = FileRepository::new(self.context.pool());
        repo.update(&file)
            .await
            .context("Failed to update file content")?;

        tracing::debug!("Updated file content: {:?}", file.path);
        Ok(())
    }

    /// Delete a file
    pub async fn delete_file(&self, id: Uuid) -> Result<()> {
        let repo = FileRepository::new(self.context.pool());
        repo.delete(id).await.context("Failed to delete file")?;

        tracing::debug!("Deleted file: {}", id);
        Ok(())
    }

    /// Delete all files for a session
    pub async fn delete_files_for_session(&self, session_id: Uuid) -> Result<()> {
        let repo = FileRepository::new(self.context.pool());
        repo.delete_by_session(session_id)
            .await
            .context("Failed to delete files for session")?;

        tracing::info!("Deleted files for session {}", session_id);
        Ok(())
    }

    /// Count files in a session
    pub async fn count_files_in_session(&self, session_id: Uuid) -> Result<i64> {
        let repo = FileRepository::new(self.context.pool());
        repo.count_by_session(session_id)
            .await
            .context("Failed to count files in session")
    }

    /// Check if a file is tracked in a session
    pub async fn is_file_tracked(&self, session_id: Uuid, path: &Path) -> Result<bool> {
        let file = self.find_file_by_path(session_id, path).await?;
        Ok(file.is_some())
    }

    /// Get or create a file entry
    pub async fn get_or_create_file(
        &self,
        session_id: Uuid,
        path: PathBuf,
        content: Option<String>,
    ) -> Result<File> {
        // If the session belongs to a project, archive the file under
        // `projects/<name>/files/` so a project's artifacts live together.
        // Dedup + tracking then key off the archived path.
        let path = self.archive_into_project(session_id, path).await;

        // Try to find existing file
        if let Some(file) = self.find_file_by_path(session_id, &path).await? {
            return Ok(file);
        }

        // Create new file if not found
        self.track_file(session_id, path, content).await
    }

    /// `~/.opencrabs/projects/<slug>/files/` for the session's project, or
    /// `None` when the session has no project. Creates the directory.
    pub async fn project_files_dir(&self, session_id: Uuid) -> Option<PathBuf> {
        use crate::db::repository::{ProjectRepository, SessionRepository};
        let session = SessionRepository::new(self.context.pool())
            .find_by_id(session_id)
            .await
            .ok()??;
        let project_id = session.project_id?;
        let project = ProjectRepository::new(self.context.pool())
            .find_by_id(project_id)
            .await
            .ok()??;
        let dir = crate::services::ProjectService::projects_dir()
            .join(slugify_project_name(&project.name))
            .join("files");
        std::fs::create_dir_all(&dir).ok()?;
        Some(dir)
    }

    /// Copy `path` into the session's project files dir (best-effort). Returns
    /// the archived path on success, otherwise the original path unchanged.
    ///
    /// Archive everything that's a project ARTIFACT — files the user shares
    /// (photos, documents, videos, audio) and files the agent produces
    /// (generated images, PDFs, research, `.md`, plans) — so a project's
    /// deliverables live together. The ONE exclusion is **repository code**:
    /// a file inside a git repo loads from and changes on the repo (already
    /// persistent + version-controlled), so copying it just duplicates it and
    /// points the tracked path at a stale copy. Repo files are tracked at their
    /// real path, never archived.
    async fn archive_into_project(&self, session_id: Uuid, path: PathBuf) -> PathBuf {
        if is_inside_git_repo(&path) {
            return path;
        }
        let Some(dir) = self.project_files_dir(session_id).await else {
            return path;
        };
        if !path.is_file() || path.starts_with(&dir) {
            return path;
        }
        let Some(name) = path.file_name() else {
            return path;
        };
        let dest = dir.join(name);
        match std::fs::copy(&path, &dest) {
            Ok(_) => {
                tracing::info!(
                    "Archived file to project: {} -> {}",
                    path.display(),
                    dest.display()
                );
                dest
            }
            Err(e) => {
                tracing::warn!("Failed to archive file to project dir: {e}");
                path
            }
        }
    }

    /// Get files with content
    pub async fn get_files_with_content(&self, session_id: Uuid) -> Result<Vec<File>> {
        let files = self.list_files_for_session(session_id).await?;
        Ok(files.into_iter().filter(|f| f.content.is_some()).collect())
    }

    /// Get files without content
    pub async fn get_files_without_content(&self, session_id: Uuid) -> Result<Vec<File>> {
        let files = self.list_files_for_session(session_id).await?;
        Ok(files.into_iter().filter(|f| f.content.is_none()).collect())
    }
}

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

    async fn create_test_service() -> (FileService, SessionService) {
        use crate::db::Database;

        let db = Database::connect_in_memory().await.unwrap();
        db.run_migrations().await.unwrap();
        let pool = db.pool().clone();

        let context = ServiceContext::new(pool);
        (
            FileService::new(context.clone()),
            SessionService::new(context),
        )
    }

    #[tokio::test]
    async fn test_track_file() {
        let (file_service, session_service) = create_test_service().await;
        let session = session_service
            .create_session(Some("Test".to_string()))
            .await
            .unwrap();

        let file = file_service
            .track_file(
                session.id,
                PathBuf::from("/test/file.txt"),
                Some("content".to_string()),
            )
            .await
            .unwrap();

        assert_eq!(file.session_id, session.id);
        assert_eq!(file.path, PathBuf::from("/test/file.txt"));
        assert_eq!(file.content, Some("content".to_string()));
    }

    #[tokio::test]
    async fn test_get_file() {
        let (file_service, session_service) = create_test_service().await;
        let session = session_service
            .create_session(Some("Test".to_string()))
            .await
            .unwrap();

        let created = file_service
            .track_file(session.id, PathBuf::from("/test/file.txt"), None)
            .await
            .unwrap();

        let found = file_service.get_file(created.id).await.unwrap();
        assert!(found.is_some());
        assert_eq!(found.unwrap().id, created.id);
    }

    #[tokio::test]
    async fn test_list_files_for_session() {
        let (file_service, session_service) = create_test_service().await;
        let session = session_service
            .create_session(Some("Test".to_string()))
            .await
            .unwrap();

        file_service
            .track_file(session.id, PathBuf::from("/test/file1.txt"), None)
            .await
            .unwrap();
        file_service
            .track_file(session.id, PathBuf::from("/test/file2.txt"), None)
            .await
            .unwrap();

        let files = file_service
            .list_files_for_session(session.id)
            .await
            .unwrap();
        assert_eq!(files.len(), 2);
    }

    #[tokio::test]
    async fn test_find_file_by_path() {
        let (file_service, session_service) = create_test_service().await;
        let session = session_service
            .create_session(Some("Test".to_string()))
            .await
            .unwrap();

        let path = PathBuf::from("/test/file.txt");
        file_service
            .track_file(session.id, path.clone(), None)
            .await
            .unwrap();

        let found = file_service
            .find_file_by_path(session.id, &path)
            .await
            .unwrap();
        assert!(found.is_some());
        assert_eq!(found.unwrap().path, path);
    }

    #[tokio::test]
    async fn test_update_file_content() {
        let (file_service, session_service) = create_test_service().await;
        let session = session_service
            .create_session(Some("Test".to_string()))
            .await
            .unwrap();

        let file = file_service
            .track_file(session.id, PathBuf::from("/test/file.txt"), None)
            .await
            .unwrap();

        file_service
            .update_file_content(file.id, Some("new content".to_string()))
            .await
            .unwrap();

        let updated = file_service.get_file_required(file.id).await.unwrap();
        assert_eq!(updated.content, Some("new content".to_string()));
    }

    #[tokio::test]
    async fn test_delete_file() {
        let (file_service, session_service) = create_test_service().await;
        let session = session_service
            .create_session(Some("Test".to_string()))
            .await
            .unwrap();

        let file = file_service
            .track_file(session.id, PathBuf::from("/test/file.txt"), None)
            .await
            .unwrap();

        file_service.delete_file(file.id).await.unwrap();

        let result = file_service.get_file(file.id).await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_delete_files_for_session() {
        let (file_service, session_service) = create_test_service().await;
        let session = session_service
            .create_session(Some("Test".to_string()))
            .await
            .unwrap();

        file_service
            .track_file(session.id, PathBuf::from("/test/file1.txt"), None)
            .await
            .unwrap();
        file_service
            .track_file(session.id, PathBuf::from("/test/file2.txt"), None)
            .await
            .unwrap();

        file_service
            .delete_files_for_session(session.id)
            .await
            .unwrap();

        let files = file_service
            .list_files_for_session(session.id)
            .await
            .unwrap();
        assert_eq!(files.len(), 0);
    }

    #[tokio::test]
    async fn test_count_files_in_session() {
        let (file_service, session_service) = create_test_service().await;
        let session = session_service
            .create_session(Some("Test".to_string()))
            .await
            .unwrap();

        file_service
            .track_file(session.id, PathBuf::from("/test/file1.txt"), None)
            .await
            .unwrap();
        file_service
            .track_file(session.id, PathBuf::from("/test/file2.txt"), None)
            .await
            .unwrap();

        let count = file_service
            .count_files_in_session(session.id)
            .await
            .unwrap();
        assert_eq!(count, 2);
    }

    #[tokio::test]
    async fn test_is_file_tracked() {
        let (file_service, session_service) = create_test_service().await;
        let session = session_service
            .create_session(Some("Test".to_string()))
            .await
            .unwrap();

        let path = PathBuf::from("/test/file.txt");
        file_service
            .track_file(session.id, path.clone(), None)
            .await
            .unwrap();

        let is_tracked = file_service
            .is_file_tracked(session.id, &path)
            .await
            .unwrap();
        assert!(is_tracked);

        let not_tracked = file_service
            .is_file_tracked(session.id, &PathBuf::from("/test/other.txt"))
            .await
            .unwrap();
        assert!(!not_tracked);
    }

    #[tokio::test]
    async fn test_get_or_create_file() {
        let (file_service, session_service) = create_test_service().await;
        let session = session_service
            .create_session(Some("Test".to_string()))
            .await
            .unwrap();

        let path = PathBuf::from("/test/file.txt");

        // First call should create
        let file1 = file_service
            .get_or_create_file(session.id, path.clone(), Some("content".to_string()))
            .await
            .unwrap();

        // Second call should return existing
        let file2 = file_service
            .get_or_create_file(session.id, path.clone(), None)
            .await
            .unwrap();

        assert_eq!(file1.id, file2.id);
    }

    #[tokio::test]
    async fn test_get_files_with_content() {
        let (file_service, session_service) = create_test_service().await;
        let session = session_service
            .create_session(Some("Test".to_string()))
            .await
            .unwrap();

        file_service
            .track_file(
                session.id,
                PathBuf::from("/test/file1.txt"),
                Some("content".to_string()),
            )
            .await
            .unwrap();
        file_service
            .track_file(session.id, PathBuf::from("/test/file2.txt"), None)
            .await
            .unwrap();

        let with_content = file_service
            .get_files_with_content(session.id)
            .await
            .unwrap();
        let without_content = file_service
            .get_files_without_content(session.id)
            .await
            .unwrap();

        assert_eq!(with_content.len(), 1);
        assert_eq!(without_content.len(), 1);
    }
}