opencrabs 0.3.36

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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! Profile management — multi-instance isolated OpenCrabs environments.
//!
//! Each profile gets its own `config.toml`, `keys.toml`, `opencrabs.db`,
//! `memory/`, brain files, and `layout.json`. The "default" profile maps
//! to `~/.opencrabs/` for backward compatibility; named profiles live
//! under `~/.opencrabs/profiles/<name>/`.
//!
//! Selection priority (first wins):
//! 1. `set_active_profile()` (called from CLI `-p` flag)
//! 2. `OPENCRABS_PROFILE` environment variable
//! 3. Falls back to "default"
//!
//! ## TUI footer display
//!
//! The status bar in `src/tui/render/input.rs::render_status_bar` shows
//! a `profile: <name>` chip ONLY when `active_profile()` returns
//! `Some(name)` (issue #167). When it returns `None` (no `-p`, no env)
//! the chip is omitted entirely — there is no real profile by that name
//! on disk, so the footer would otherwise have to invent a `default`
//! label that doesn't exist anywhere. Named profiles always show up;
//! the base directory stays unannotated.

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use anyhow::{Context, Result, bail};
use chrono::Utc;
use serde::{Deserialize, Serialize};

/// Global active profile name. Set once at startup before anything calls `opencrabs_home()`.
static ACTIVE_PROFILE: OnceLock<Option<String>> = OnceLock::new();

/// Set the active profile. Must be called before any `opencrabs_home()` call.
/// Returns `Err` if called more than once (OnceLock semantics).
pub fn set_active_profile(name: Option<String>) -> Result<()> {
    ACTIVE_PROFILE
        .set(name)
        .map_err(|_| anyhow::anyhow!("active profile already set"))
}

/// Get the active profile name, or `None` for default.
pub fn active_profile() -> Option<&'static str> {
    ACTIVE_PROFILE.get().and_then(|opt| opt.as_deref())
}

/// Resolve the home directory for the active profile.
///
/// - `None` / `"default"` → `~/.opencrabs/`
/// - `"hermes"` → `~/.opencrabs/profiles/hermes/`
pub fn resolve_profile_home() -> PathBuf {
    let base = base_opencrabs_dir();

    let profile_name = active_profile().map(String::from).or_else(|| {
        std::env::var("OPENCRABS_PROFILE")
            .ok()
            .filter(|s| !s.is_empty())
    });

    match profile_name.as_deref() {
        None | Some("default") => base,
        Some(name) => base.join("profiles").join(name),
    }
}

/// The raw `~/.opencrabs/` directory (profile-agnostic).
pub fn base_opencrabs_dir() -> PathBuf {
    let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
    home.join(".opencrabs")
}

// ─── Profile Registry ────────────────────────────────────────────────

/// Metadata for a single profile.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileEntry {
    pub name: String,
    pub description: Option<String>,
    pub created_at: String,
    pub last_used: Option<String>,
}

/// Registry of all profiles, stored at `~/.opencrabs/profiles.toml`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProfileRegistry {
    #[serde(default)]
    pub profiles: HashMap<String, ProfileEntry>,
}

impl ProfileRegistry {
    fn path() -> PathBuf {
        base_opencrabs_dir().join("profiles.toml")
    }

    pub fn load() -> Result<Self> {
        let path = Self::path();
        if !path.exists() {
            return Ok(Self::default());
        }
        let contents = fs::read_to_string(&path)
            .with_context(|| format!("failed to read {}", path.display()))?;
        toml::from_str(&contents).with_context(|| format!("failed to parse {}", path.display()))
    }

    pub fn save(&self) -> Result<()> {
        let path = Self::path();
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let contents = toml::to_string_pretty(self)?;
        // Atomic write: write to temp file then rename to prevent concurrent
        // readers from seeing a partially-written file.
        let tmp = path.with_extension("toml.tmp");
        fs::write(&tmp, &contents).with_context(|| format!("failed to write {}", tmp.display()))?;
        fs::rename(&tmp, &path)
            .with_context(|| format!("failed to rename {} -> {}", tmp.display(), path.display()))
    }

    /// Atomically load, modify, and save the registry under a file lock.
    /// Prevents concurrent load+save races (e.g. two `create_profile` calls).
    pub fn modify<F>(f: F) -> Result<Self>
    where
        F: FnOnce(&mut Self),
    {
        let path = Self::path();
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }

        // Advisory lock file — prevents concurrent modify() calls
        let lock_path = path.with_extension("toml.lock");
        let lock_file = fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&lock_path)
            .with_context(|| format!("failed to open lock {}", lock_path.display()))?;

        // Platform-specific exclusive lock
        #[cfg(unix)]
        {
            use std::os::unix::io::AsRawFd;
            let fd = lock_file.as_raw_fd();
            let ret = unsafe { libc::flock(fd, libc::LOCK_EX) };
            if ret != 0 {
                bail!(
                    "failed to lock {}: {}",
                    lock_path.display(),
                    std::io::Error::last_os_error()
                );
            }
        }
        #[cfg(windows)]
        {
            use std::os::windows::io::AsRawHandle;
            // On Windows, opening with write + no sharing provides exclusion
            let _ = lock_file.as_raw_handle();
        }

        // Load current state under lock
        let mut registry = Self::load()?;
        f(&mut registry);
        registry.save()?;

        // Lock released when lock_file drops
        // Explicitly flush to keep the borrow checker happy
        let _ = lock_file;

        Ok(registry)
    }

    pub fn register(&mut self, name: &str, description: Option<&str>) {
        self.profiles.insert(
            name.to_string(),
            ProfileEntry {
                name: name.to_string(),
                description: description.map(String::from),
                created_at: Utc::now().to_rfc3339(),
                last_used: None,
            },
        );
    }

    pub fn touch(&mut self, name: &str) {
        if let Some(entry) = self.profiles.get_mut(name) {
            entry.last_used = Some(Utc::now().to_rfc3339());
        }
    }
}

// ─── Profile CRUD ────────────────────────────────────────────────────

/// Create a new named profile with its directory structure AND the
/// default brain-file templates seeded into the profile's root.
///
/// Without seeding, a freshly created profile starts with an empty
/// brain dir. `RsiSync::sync_templates` skips files that don't exist
/// locally (by design — it never CREATES brain files, only updates
/// existing ones), so the empty state was sticky: no SOUL.md, no
/// TOOLS.md, no SECURITY.md, etc. until the user manually copied them
/// or re-ran the full onboarding wizard with the profile active.
/// Issue noticed during the audit of #120's `ops` profile breakdown.
///
/// starts with a working brain identical to a fresh default install.
pub fn create_profile(name: &str, description: Option<&str>) -> Result<PathBuf> {
    validate_profile_name(name)?;

    let profile_dir = base_opencrabs_dir().join("profiles").join(name);
    if profile_dir.exists() {
        bail!(
            "profile '{}' already exists at {}",
            name,
            profile_dir.display()
        );
    }

    // Create directory structure
    fs::create_dir_all(&profile_dir)?;
    fs::create_dir_all(profile_dir.join("memory"))?;
    fs::create_dir_all(profile_dir.join("logs"))?;

    // Seed the default brain-file templates so the profile starts with
    // a working brain. Errors here are logged but non-fatal — the
    // profile still gets registered; the user can re-seed by running
    // the onboarding wizard with the profile active.
    seed_brain_templates(&profile_dir);

    // Register under file lock to prevent concurrent write races
    let name_owned = name.to_string();
    let desc_owned = description.map(|s| s.to_string());
    ProfileRegistry::modify(|reg| {
        reg.register(&name_owned, desc_owned.as_deref());
    })?;

    tracing::info!("Created profile '{}' at {}", name, profile_dir.display());
    Ok(profile_dir)
}

/// Write the default brain-file templates into `profile_dir`. The exact
/// same list the onboarding wizard's `seed_templates` path writes, so
/// CLI `profile create` and TUI onboarding produce identical brain
/// starting states. Files already present in `profile_dir` are NOT
/// overwritten (defensive — this function is also safe to call from
/// the template-sync recovery path).
pub(crate) fn seed_brain_templates(profile_dir: &Path) {
    // Inline the canonical template set rather than reaching into the
    // TUI module — `config` must not depend on `tui`. The templates
    // are baked into the binary at compile time via `include_str!`,
    // so this list and the TUI's `TEMPLATE_FILES` stay in lockstep
    // because both reference the same files under
    // `src/docs/reference/templates/`.
    const TEMPLATES: &[(&str, &str)] = &[
        (
            "SOUL.md",
            include_str!("../docs/reference/templates/SOUL.md"),
        ),
        (
            "USER.md",
            include_str!("../docs/reference/templates/USER.md"),
        ),
        (
            "AGENTS.md",
            include_str!("../docs/reference/templates/AGENTS.md"),
        ),
        (
            "TOOLS.md",
            include_str!("../docs/reference/templates/TOOLS.md"),
        ),
        (
            "MEMORY.md",
            include_str!("../docs/reference/templates/MEMORY.md"),
        ),
        (
            "CODE.md",
            include_str!("../docs/reference/templates/CODE.md"),
        ),
        (
            "SECURITY.md",
            include_str!("../docs/reference/templates/SECURITY.md"),
        ),
    ];

    for (filename, content) in TEMPLATES {
        let target = profile_dir.join(filename);
        if target.exists() {
            continue;
        }
        if let Err(e) = fs::write(&target, content) {
            tracing::warn!(
                "create_profile: failed to seed {} in {}: {e}",
                filename,
                profile_dir.display(),
            );
        }
    }
}

/// List all profiles (always includes "default").
pub fn list_profiles() -> Result<Vec<ProfileEntry>> {
    let registry = ProfileRegistry::load()?;

    let mut profiles = vec![ProfileEntry {
        name: "default".to_string(),
        description: Some("Default profile (~/.opencrabs/)".to_string()),
        created_at: String::new(),
        last_used: None,
    }];

    let mut named: Vec<_> = registry.profiles.values().cloned().collect();
    named.sort_by(|a, b| a.name.cmp(&b.name));
    profiles.extend(named);

    Ok(profiles)
}

/// Delete a named profile and its directory.
pub fn delete_profile(name: &str) -> Result<()> {
    if name == "default" {
        bail!("cannot delete the default profile");
    }

    let profile_dir = base_opencrabs_dir().join("profiles").join(name);
    if !profile_dir.exists() {
        bail!("profile '{}' does not exist", name);
    }

    fs::remove_dir_all(&profile_dir).with_context(|| {
        format!(
            "failed to delete profile directory: {}",
            profile_dir.display()
        )
    })?;

    let name_owned = name.to_string();
    ProfileRegistry::modify(|reg| {
        reg.profiles.remove(&name_owned);
    })?;

    tracing::info!("Deleted profile '{}'", name);
    Ok(())
}

/// Export a profile as a tar.gz archive.
pub fn export_profile(name: &str, output: &Path) -> Result<()> {
    let profile_dir = if name == "default" {
        base_opencrabs_dir()
    } else {
        let dir = base_opencrabs_dir().join("profiles").join(name);
        if !dir.exists() {
            bail!("profile '{}' does not exist", name);
        }
        dir
    };

    use flate2::Compression;
    use flate2::write::GzEncoder;
    use tar::Builder;

    let file = fs::File::create(output)
        .with_context(|| format!("failed to create {}", output.display()))?;
    let enc = GzEncoder::new(file, Compression::default());
    let mut tar = Builder::new(enc);

    // Add profile directory contents
    tar.append_dir_all(name, &profile_dir)
        .with_context(|| "failed to add profile to archive")?;

    tar.finish()?;
    tracing::info!("Exported profile '{}' to {}", name, output.display());
    Ok(())
}

/// Import a profile from a tar.gz archive.
pub fn import_profile(archive: &Path) -> Result<String> {
    use flate2::read::GzDecoder;
    use tar::Archive;

    if !archive.exists() {
        bail!("archive not found: {}", archive.display());
    }

    let file = fs::File::open(archive)?;
    let dec = GzDecoder::new(file);
    let mut ar = Archive::new(dec);

    // Peek at the first entry to get the profile name
    let profile_name = {
        let file = fs::File::open(archive)?;
        let dec = GzDecoder::new(file);
        let mut ar = Archive::new(dec);
        let first = ar.entries()?.next();
        match first {
            Some(Ok(entry)) => {
                let path = entry.path()?;
                path.components()
                    .next()
                    .map(|c| c.as_os_str().to_string_lossy().to_string())
                    .unwrap_or_default()
            }
            _ => bail!("archive is empty"),
        }
    };

    if profile_name.is_empty() {
        bail!("could not determine profile name from archive");
    }

    let target = base_opencrabs_dir().join("profiles");
    fs::create_dir_all(&target)?;

    ar.unpack(&target)
        .with_context(|| "failed to extract archive")?;

    // Register the imported profile under file lock
    let pname = profile_name.clone();
    ProfileRegistry::modify(|reg| {
        if !reg.profiles.contains_key(&pname) {
            reg.register(&pname, Some("Imported profile"));
        }
    })?;

    tracing::info!(
        "Imported profile '{}' from {}",
        profile_name,
        archive.display()
    );
    Ok(profile_name)
}

// ─── Profile Migration ───────────────────────────────────────────────

/// Migrate config and brain files from one profile to another.
/// Copies `*.md`, `*.toml`, and `memory/` directory.
/// Does NOT copy database, sessions, logs, locks, or layout.
pub fn migrate_profile(from: &str, to: &str, force: bool) -> Result<Vec<String>> {
    let base = base_opencrabs_dir();

    let src_dir = if from == "default" {
        base.clone()
    } else {
        let dir = base.join("profiles").join(from);
        if !dir.exists() {
            bail!("source profile '{}' does not exist", from);
        }
        dir
    };

    let dst_dir = if to == "default" {
        base.clone()
    } else {
        let dir = base.join("profiles").join(to);
        if !dir.exists() {
            bail!(
                "destination profile '{}' does not exist. Create it first with: opencrabs profile create {}",
                to,
                to
            );
        }
        dir
    };

    if src_dir == dst_dir {
        bail!("source and destination profiles are the same");
    }

    let mut migrated = Vec::new();

    // Copy top-level *.md and *.toml files (config, keys, brain files)
    // Skip: profiles.toml (registry), layout.json, locks, DB
    let skip_files = ["profiles.toml", "layout.json"];

    for entry in fs::read_dir(&src_dir)? {
        let entry = entry?;
        let path = entry.path();
        let name = entry.file_name();
        let name_str = name.to_string_lossy();

        if path.is_file() {
            let dominated = name_str.ends_with(".md") || name_str.ends_with(".toml");
            if !dominated || skip_files.contains(&name_str.as_ref()) {
                continue;
            }

            let dst_path = dst_dir.join(&name);
            if dst_path.exists() && !force {
                tracing::warn!(
                    "Skipping '{}' — already exists in '{}' (use --force to overwrite)",
                    name_str,
                    to
                );
                continue;
            }

            fs::copy(&path, &dst_path).with_context(|| {
                format!(
                    "failed to copy {} to {}",
                    path.display(),
                    dst_path.display()
                )
            })?;
            migrated.push(name_str.to_string());
        }
    }

    // Copy memory/ directory
    let src_memory = src_dir.join("memory");
    if src_memory.exists() && src_memory.is_dir() {
        let dst_memory = dst_dir.join("memory");
        fs::create_dir_all(&dst_memory)?;

        for entry in fs::read_dir(&src_memory)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() {
                let name = entry.file_name();
                let name_str = name.to_string_lossy();
                let dst_path = dst_memory.join(&name);

                if dst_path.exists() && !force {
                    tracing::warn!(
                        "Skipping memory/'{}' — already exists (use --force to overwrite)",
                        name_str
                    );
                    continue;
                }

                fs::copy(&path, &dst_path)?;
                migrated.push(format!("memory/{}", name_str));
            }
        }
    }

    tracing::info!(
        "Migrated {} files from profile '{}' to '{}'",
        migrated.len(),
        from,
        to
    );
    Ok(migrated)
}

// ─── Token Lock ──────────────────────────────────────────────────────

/// Check and acquire a token lock for a channel credential.
/// Returns `Err` if another profile holds the lock.
pub fn acquire_token_lock(channel: &str, token_hash: &str) -> Result<()> {
    let lock_dir = base_opencrabs_dir().join("locks");
    fs::create_dir_all(&lock_dir)?;

    let lock_file = lock_dir.join(format!("{}_{}.lock", channel, token_hash));
    let current_profile = active_profile().unwrap_or("default");
    let pid = std::process::id();

    if lock_file.exists() {
        let contents = fs::read_to_string(&lock_file).unwrap_or_default();
        let parts: Vec<&str> = contents.splitn(2, ':').collect();
        if parts.len() == 2 {
            let locked_profile = parts[0];
            let locked_pid: u32 = parts[1].parse().unwrap_or(0);

            // Same profile — check if PID is still alive
            if locked_profile == current_profile {
                if is_pid_alive(locked_pid) && locked_pid != pid {
                    bail!(
                        "profile '{}' already running (PID {}). Only one instance per profile allowed.",
                        current_profile,
                        locked_pid
                    );
                }
                // Stale lock from same profile — overwrite
            } else {
                // Different profile — check PID
                if is_pid_alive(locked_pid) {
                    bail!(
                        "channel '{}' token is locked by profile '{}' (PID {}). \
                         Two profiles cannot share the same bot credential.",
                        channel,
                        locked_profile,
                        locked_pid
                    );
                }
                // Stale lock from dead process — overwrite
            }
        }
    }

    fs::write(&lock_file, format!("{}:{}", current_profile, pid))?;
    Ok(())
}

/// Release a token lock.
pub fn release_token_lock(channel: &str, token_hash: &str) {
    let lock_file = base_opencrabs_dir()
        .join("locks")
        .join(format!("{}_{}.lock", channel, token_hash));
    let _ = fs::remove_file(lock_file);
}

/// Release all locks held by this process.
pub fn release_all_locks() {
    let lock_dir = base_opencrabs_dir().join("locks");
    let pid = std::process::id();
    let current_profile = active_profile().unwrap_or("default");
    let expected = format!("{}:{}", current_profile, pid);

    if let Ok(entries) = fs::read_dir(&lock_dir) {
        for entry in entries.flatten() {
            if let Ok(contents) = fs::read_to_string(entry.path())
                && contents.trim() == expected
            {
                let _ = fs::remove_file(entry.path());
            }
        }
    }
}

/// Hash a token for lock file naming (no raw secrets on disk).
pub fn hash_token(token: &str) -> String {
    use std::hash::{DefaultHasher, Hash, Hasher};
    let mut hasher = DefaultHasher::new();
    token.hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

// ─── Helpers ─────────────────────────────────────────────────────────

pub fn validate_profile_name(name: &str) -> Result<()> {
    if name == "default" {
        bail!("'default' is reserved — the default profile is ~/.opencrabs/");
    }
    if name.is_empty() || name.len() > 64 {
        bail!("profile name must be 1-64 characters");
    }
    if !name
        .chars()
        .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
    {
        bail!("profile name can only contain alphanumeric, hyphens, and underscores");
    }
    Ok(())
}

fn is_pid_alive(pid: u32) -> bool {
    #[cfg(unix)]
    {
        // kill(pid, 0) returns 0 if we can signal the process.
        // If it returns -1, check errno: ESRCH means the process doesn't exist,
        // EPERM means it exists but we lack permission (still alive).
        let ret = unsafe { libc::kill(pid as i32, 0) };
        if ret == 0 {
            return true;
        }
        // EPERM = process exists but owned by another user (e.g. PID 1 = launchd)
        std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
    }
    #[cfg(windows)]
    {
        unsafe extern "system" {
            fn OpenProcess(dwDesiredAccess: u32, bInheritHandle: i32, dwProcessId: u32) -> isize;
            fn CloseHandle(hObject: isize) -> i32;
        }
        const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
        let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
        if handle == 0 {
            false
        } else {
            unsafe { CloseHandle(handle) };
            true
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = pid;
        false
    }
}