opencrabs 0.3.55

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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
//! 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();

tokio::task_local! {
    static PROFILE_HOME_OVERRIDE: PathBuf;
    // The profile NAME for the current task, set alongside the home override.
    // Lets `current_profile_name()` attribute data (e.g. a cron job's
    // profile_name) to the profile actually running, not the process global.
    static PROFILE_NAME_OVERRIDE: String;
}

/// Resolve the home directory for an explicit profile name, WITHOUT reading the
/// process-global active profile.
///
/// - `None` / `"default"` → `~/.opencrabs/`
/// - `"ops"` → `~/.opencrabs/profiles/ops/`
pub fn home_for_profile(name: Option<&str>) -> PathBuf {
    let base = base_opencrabs_dir();
    match name {
        None | Some("default") => base,
        Some(n) => base.join("profiles").join(n),
    }
}

/// Run an async future with the profile home pointed at `profile`'s directory.
///
/// The override is a `tokio::task_local!`, so it lives for the entire duration
/// of `fut` including across every `.await`. It is scoped to this one tokio task
/// only, it never leaks to sibling tasks or other jobs on the scheduler. Every
/// call to `opencrabs_home()` / `resolve_profile_home()` inside `fut` (including
/// deep inside tools like memory writes, config reads, brain file ops) resolves
/// to the correct profile home.
pub async fn with_profile_home_async<F, T>(profile: Option<&str>, fut: F) -> T
where
    F: std::future::Future<Output = T>,
{
    let home = home_for_profile(profile);
    let name = profile.unwrap_or("default").to_string();
    PROFILE_NAME_OVERRIDE
        .scope(name, PROFILE_HOME_OVERRIDE.scope(home, fut))
        .await
}

/// The profile name for the CURRENT task. Returns the task-local name set by
/// `with_profile_home_async`/`with_profile_home` when present, otherwise the
/// process-global active profile (or "default"). Use this when stamping data
/// (like a cron job's `profile_name`) so it attributes to the profile actually
/// executing, not the process default.
pub fn current_profile_name() -> String {
    if let Ok(name) = PROFILE_NAME_OVERRIDE.try_with(|n| n.clone()) {
        return name;
    }
    active_profile().unwrap_or("default").to_string()
}

/// Run a sync closure with the profile home pointed at `profile`'s directory.
///
/// Convenience wrapper for synchronous loads (Config::load(), BrainLoader, etc.)
/// that don't have an async context. Internally blocks on the task-local scope.
pub fn with_profile_home<T>(profile: Option<&str>, f: impl FnOnce() -> T) -> T {
    let home = home_for_profile(profile);
    let name = profile.unwrap_or("default").to_string();
    // Use a minimal tokio runtime to host the task-local scope for sync callers.
    // This is only used for initial config/brain materialization before the
    // async agent runs.
    PROFILE_NAME_OVERRIDE.sync_scope(name, || PROFILE_HOME_OVERRIDE.sync_scope(home, f))
}

/// 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/`
///
/// A task-local override wins when set (cron job running under a foreign
/// profile, #182). It persists across every `.await` inside the task, so
/// all tool calls during agent execution see the right home.
pub fn resolve_profile_home() -> PathBuf {
    // Task-local override: set by with_profile_home_async() for the entire
    // lifetime of a cron job's tokio task. Every opencrabs_home() call inside
    // tools (memory writes, config reads, file ops) resolves here first.
    if let Ok(home) = PROFILE_HOME_OVERRIDE.try_with(|h| h.clone()) {
        return home;
    }

    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"),
        ),
        (
            "BOOT.md",
            include_str!("../docs/reference/templates/BOOT.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 ──────────────────────────────────────────────────────

/// Parse the owner PID from the second field of a lock file (`profile:pid`).
///
/// Returns `None` when the field names no live owner: a missing/zero PID, or a
/// corrupted value (e.g. an external in-place edit concatenated entries, so the
/// field is `"101528ops:103104"`). Callers treat `None` as a stale lock to take
/// over, rather than coercing it to PID 0 (issue #192).
pub(crate) fn parse_lock_owner_pid(field: &str) -> Option<u32> {
    field.trim().parse::<u32>().ok().filter(|&p| p != 0)
}

/// 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];
            // A lock whose PID doesn't parse to a real process names no live
            // owner. This happens when the file is corrupted — e.g. an external
            // in-place edit concatenated several entries, so `parts[1]` is
            // something like "101528ops:103104family" — or when it's literally
            // 0. Treat that as a stale lock and take it over, rather than
            // coercing it to PID 0 and depending on is_pid_alive(0) (issue #192).
            match parse_lock_owner_pid(parts[1]) {
                None => {
                    tracing::warn!(
                        "lock file {} has an invalid owner PID ({:?}) — treating as stale and taking over",
                        lock_file.display(),
                        parts[1]
                    );
                    // fall through to overwrite
                }
                Some(locked_pid) => {
                    if locked_profile == current_profile {
                        // Same profile — only one instance per profile allowed.
                        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 if is_pid_alive(locked_pid) {
                        // Different profile holds it with a live process.
                        bail!(
                            "channel '{}' token is locked by profile '{}' (PID {}). \
                             Two profiles cannot share the same bot credential.",
                            channel,
                            locked_profile,
                            locked_pid
                        );
                        // else: stale lock from a 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())
}

/// A live, OTHER instance of the active profile that was holding channel
/// token locks when the interactive TUI started.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreemptedInstance {
    /// PID of the background instance (e.g. an `opencrabs daemon`).
    pub pid: u32,
    /// Channels whose token lock it was holding (e.g. `["telegram"]`).
    pub channels: Vec<String>,
    /// Whether it had released its locks (process gone) by the time we
    /// stopped waiting. `false` means it may still contend for the
    /// credential — the caller should say so in the warning.
    pub stopped: bool,
}

/// Map every *live, foreign* lock owner for the active profile to the
/// channels it holds, reading lock files from `lock_dir`. "Foreign" = a PID
/// other than this process. Pure file inspection, no side effects. The dir is
/// a parameter so tests can point it at a TempDir and never read the real
/// workspace.
fn foreign_lock_owners(lock_dir: &Path) -> std::collections::BTreeMap<u32, Vec<String>> {
    let current_profile = active_profile().unwrap_or("default");
    let self_pid = std::process::id();
    let mut owners: std::collections::BTreeMap<u32, Vec<String>> = Default::default();

    let entries = match fs::read_dir(lock_dir) {
        Ok(e) => e,
        Err(_) => return owners,
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let fname = match path.file_name().and_then(|n| n.to_str()) {
            Some(f) if f.ends_with(".lock") => f.to_string(),
            _ => continue,
        };
        let contents = match fs::read_to_string(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let (profile, pid_field) = match contents.trim().split_once(':') {
            Some(p) => p,
            None => continue,
        };
        if profile != current_profile {
            continue;
        }
        let pid = match parse_lock_owner_pid(pid_field) {
            Some(p) => p,
            None => continue,
        };
        if pid == self_pid || !is_pid_alive(pid) {
            continue;
        }
        // Lock file is `<channel>_<hash>.lock` — channel is everything
        // before the final '_'.
        let channel = fname
            .strip_suffix(".lock")
            .and_then(|s| s.rsplit_once('_'))
            .map(|(c, _)| c.to_string())
            .unwrap_or(fname);
        owners.entry(pid).or_default().push(channel);
    }
    owners
}

/// TUI priority: shut down any OTHER live instance of the active profile
/// that currently holds channel token locks, so the interactive session
/// can take over the channels.
///
/// When a user opens the TUI while a background `opencrabs daemon` (or
/// systemd service) for the same profile is already running, both try to
/// own the same bot credentials. Only one process can hold a Telegram
/// `getUpdates` long-poll, so they fight (HTTP 409) and the channel keeps
/// dropping. The interactive session is the one the user is looking at,
/// so it wins.
///
/// We ask the other instance to stop two ways, then wait briefly for it
/// to release its locks:
///   * stop its systemd unit (`systemctl [--user] stop opencrabs*.service`)
///     so a `Restart=always` policy doesn't immediately resurrect it;
///   * SIGTERM the PID directly, covering a bare `opencrabs daemon`
///     launched in a terminal with no systemd unit behind it.
///
/// Per the chosen behavior we do NOT restart the daemon afterwards — it
/// stays down until the user starts it again. Best-effort and quick
/// (~3s cap); returns the instances we preempted so the caller can warn
/// the user. Blocks while waiting, so callers on an async runtime should
/// invoke it via `spawn_blocking`.
pub fn preempt_other_profile_instances() -> Vec<PreemptedInstance> {
    // The ONLY caller that may touch the real lock dir and real services.
    preempt_instances_in(&base_opencrabs_dir().join("locks"), true)
}

/// Core of [`preempt_other_profile_instances`], parameterized by the lock
/// directory and whether to stop systemd services. This separation exists for
/// SAFETY: this function sends real SIGTERM/SIGKILL to whatever live PIDs it
/// finds in `lock_dir`, so it must NEVER run against the real
/// `~/.opencrabs/locks/` from a test (doing so kills the user's running
/// instances). Tests call this with a TempDir and `stop_services = false`.
pub(crate) fn preempt_instances_in(lock_dir: &Path, stop_services: bool) -> Vec<PreemptedInstance> {
    let owners = foreign_lock_owners(lock_dir);
    if owners.is_empty() {
        return Vec::new();
    }

    // Stop a systemd-managed daemon first, so its unit's Restart policy
    // doesn't bring it straight back after the SIGTERM. The glob covers
    // every profile's unit; harmless (just non-zero exit) when there's no
    // systemd or no matching unit. Both scopes, since the daemon may be a
    // system OR a user service. Skipped under tests (`stop_services = false`)
    // so a test can never stop a real service on a CI host.
    if stop_services {
        for user in [false, true] {
            let mut cmd = std::process::Command::new("systemctl");
            if user {
                cmd.arg("--user");
            }
            cmd.arg("stop")
                .arg("opencrabs*.service")
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null());
            if let Err(e) = cmd.status() {
                tracing::debug!(user, error = %e, "preempt: systemctl stop spawn failed (likely no systemd)");
            }
        }
    }

    // SIGTERM each foreign PID directly — covers a bare `opencrabs daemon`
    // running in a terminal with no unit behind it.
    #[cfg(unix)]
    for &pid in owners.keys() {
        let ret = unsafe { libc::kill(pid as i32, libc::SIGTERM) };
        if ret != 0 {
            let err = std::io::Error::last_os_error();
            tracing::debug!(pid, error = %err, "preempt: SIGTERM to background instance failed");
        }
    }

    let mut results: Vec<PreemptedInstance> = owners
        .into_iter()
        .map(|(pid, mut channels)| {
            channels.sort();
            channels.dedup();
            PreemptedInstance {
                pid,
                channels,
                stopped: false,
            }
        })
        .collect();

    // Wait up to ~3s for the instances to exit and release their locks.
    for _ in 0..30 {
        if results.iter().all(|r| !is_pid_alive(r.pid)) {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    // Escalate to SIGKILL for anything that ignored SIGTERM. The TUI must
    // win the credential outright: if a stubborn daemon stays alive, its
    // same-profile lock would still block `acquire_token_lock` and the TUI
    // would silently get no Telegram — the exact "I had to reconnect"
    // symptom we're fixing. A cross-user daemon (root vs user) may still
    // resist (EPERM); that we can only warn about.
    #[cfg(unix)]
    {
        let stragglers: Vec<u32> = results
            .iter()
            .filter(|r| is_pid_alive(r.pid))
            .map(|r| r.pid)
            .collect();
        if !stragglers.is_empty() {
            for pid in &stragglers {
                let ret = unsafe { libc::kill(*pid as i32, libc::SIGKILL) };
                if ret != 0 {
                    let err = std::io::Error::last_os_error();
                    tracing::warn!(pid = *pid, error = %err, "preempt: SIGKILL to stubborn instance failed");
                }
            }
            for _ in 0..10 {
                if stragglers.iter().all(|p| !is_pid_alive(*p)) {
                    break;
                }
                std::thread::sleep(std::time::Duration::from_millis(100));
            }
        }
    }

    for r in &mut results {
        r.stopped = !is_pid_alive(r.pid);
        if r.stopped {
            tracing::info!(
                pid = r.pid,
                channels = ?r.channels,
                "TUI priority: stopped background instance that held channel locks"
            );
        } else {
            tracing::warn!(
                pid = r.pid,
                channels = ?r.channels,
                "TUI priority: background instance still alive after stop request — its channel locks may still contend"
            );
        }
    }
    results
}

// ─── 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(())
}

pub(crate) fn is_pid_alive(pid: u32) -> bool {
    // PID 0 is never a real process that could own a lock. Critically, on Unix
    // `kill(0, 0)` does NOT probe "process 0" — it signals the CALLING process's
    // entire process group and always succeeds, so without this guard a lock
    // file whose PID parsed to 0 (corruption) would look alive forever and wedge
    // the channel that owns that credential (issue #192). Guard it on every
    // platform.
    if pid == 0 {
        return false;
    }
    #[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
    }
}