aegis-tools 1.0.1

Tool system for the Aegis agent runtime
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
//! `selfmod` tool — unified entry point for aegis self-modification.
//!
//! Two layers:
//! - Layer 1 (config): modify ~/.aegis/ files (SOUL.md, filters.toml, config.toml,
//!   tools.d/, strategies/, skills/, widgets.json, peers.json). All users.
//! - Layer 2 (source): locate/build/test/verify/rollback aegis source code.
//!   Only available when source checkout is present.

use crate::registry::{Tool, ToolContext};
use crate::tools::CheckpointManager;
use anyhow::Result;
use async_trait::async_trait;
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use std::process::Stdio;

pub struct SelfModTool;

fn is_aegis_workspace(path: &Path) -> bool {
    path.join("Cargo.toml").exists() && path.join("crates").is_dir()
}

fn config_dir() -> PathBuf {
    dirs_next::home_dir()
        .unwrap_or_default()
        .join(".aegis")
}

/// Discover aegis source root. Priority:
/// 1. AEGIS_SOURCE_DIR env var
/// 2. Walk CWD ancestors looking for aegis workspace (Cargo.toml + crates/)
/// 3. ~/src/aegis or ~/.aegis/source (convention paths)
/// 4. /workspace (dev container)
fn find_source_root() -> Option<PathBuf> {
    if let Ok(dir) = std::env::var("AEGIS_SOURCE_DIR") {
        let p = PathBuf::from(dir);
        if is_aegis_workspace(&p) {
            return Some(p);
        }
    }

    // Walk CWD ancestors (covers "user is developing aegis and CWD is inside repo")
    if let Ok(cwd) = std::env::current_dir() {
        let mut dir = cwd.as_path();
        loop {
            if is_aegis_workspace(dir) {
                return Some(dir.to_path_buf());
            }
            match dir.parent() {
                Some(parent) => dir = parent,
                None => break,
            }
        }
    }

    // Convention paths
    let home = dirs_next::home_dir().unwrap_or_default();
    for candidate in [
        home.join("src/aegis"),
        home.join(".aegis/source"),
        PathBuf::from("/workspace"),
    ] {
        if is_aegis_workspace(&candidate) {
            return Some(candidate);
        }
    }
    None
}

/// Create a backup of a config file before modification.
fn backup_config_file(path: &Path) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }
    let backup_dir = config_dir().join("backups");
    std::fs::create_dir_all(&backup_dir)?;
    let ts = chrono::Utc::now().format("%Y%m%d-%H%M%S").to_string();
    let fname = path.file_name().unwrap_or_default().to_string_lossy();
    let backup_path = backup_dir.join(format!("{fname}.{ts}"));
    std::fs::copy(path, &backup_path)?;

    // Keep max 5 backups per file
    let prefix = format!("{fname}.");
    let mut backups: Vec<_> = std::fs::read_dir(&backup_dir)?
        .flatten()
        .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
        .collect();
    backups.sort_by_key(|e| e.file_name());
    while backups.len() > 5 {
        let _ = std::fs::remove_file(backups[0].path());
        backups.remove(0);
    }
    Ok(())
}

/// List crates in source workspace.
fn list_crates(root: &Path) -> Vec<String> {
    let mut crates = Vec::new();
    for dir in ["crates", "bins"] {
        let base = root.join(dir);
        if let Ok(entries) = std::fs::read_dir(&base) {
            for entry in entries.flatten() {
                if entry.path().join("Cargo.toml").exists() {
                    crates.push(format!("{}/{}", dir, entry.file_name().to_string_lossy()));
                }
            }
        }
    }
    crates.sort();
    crates
}

/// Run a cargo command with timeout, returning (success, output).
async fn run_cargo(root: &Path, args: &[&str], timeout_secs: u64) -> (bool, String) {
    let result = tokio::time::timeout(
        std::time::Duration::from_secs(timeout_secs),
        tokio::process::Command::new("cargo")
            .args(args)
            .current_dir(root)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output(),
    )
    .await;

    match result {
        Ok(Ok(output)) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);
            let combined = if stdout.is_empty() {
                stderr.to_string()
            } else {
                format!("{stdout}\n{stderr}")
            };
            // Truncate to first 80 lines
            let truncated: String = combined.lines().take(80).collect::<Vec<_>>().join("\n");
            (output.status.success(), truncated)
        }
        Ok(Err(e)) => (false, format!("Failed to run cargo: {e}")),
        Err(_) => (false, format!("Timeout after {timeout_secs}s")),
    }
}

/// Check if git is available and we're in a repo.
fn has_git(root: &Path) -> bool {
    std::process::Command::new("git")
        .args(["rev-parse", "--git-dir"])
        .current_dir(root)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Get current git short hash.
fn git_short_hash(root: &Path) -> Option<String> {
    std::process::Command::new("git")
        .args(["rev-parse", "--short", "HEAD"])
        .current_dir(root)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}

/// Get dirty file list (modified + untracked in src dirs).
fn git_dirty_files(root: &Path) -> Vec<String> {
    let mut files = Vec::new();
    // Modified tracked files
    if let Ok(o) = std::process::Command::new("git")
        .args(["diff", "--name-only"])
        .current_dir(root)
        .output()
    {
        for line in String::from_utf8_lossy(&o.stdout).lines() {
            if !line.is_empty() {
                files.push(line.to_string());
            }
        }
    }
    // Staged but uncommitted
    if let Ok(o) = std::process::Command::new("git")
        .args(["diff", "--name-only", "--cached"])
        .current_dir(root)
        .output()
    {
        for line in String::from_utf8_lossy(&o.stdout).lines() {
            if !line.is_empty() && !files.contains(&line.to_string()) {
                files.push(line.to_string());
            }
        }
    }
    files
}

#[async_trait]
impl Tool for SelfModTool {
    fn name(&self) -> &str {
        "selfmod"
    }

    fn description(&self) -> &str {
        "Modify aegis's own behavior and source code. Layer 1 actions (config/soul/filter/script_tool) \
         work for all users — edit ~/.aegis/ config files. Layer 2 actions (locate/build/test/verify/status/rollback) \
         require aegis source checkout for source-level changes."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["config", "soul", "filter", "script_tool", "locate", "build", "test", "verify", "status", "rollback"],
                    "description": "Action to perform. config/soul/filter/script_tool = Layer 1 (all users). locate/build/test/verify/status/rollback = Layer 2 (source required)."
                },
                "target": {
                    "type": "string",
                    "description": "For locate/build/test: crate name (e.g. 'aegis-tools'). For config: config key path (e.g. 'upgrade.auto_apply'). For script_tool: tool name."
                },
                "value": {
                    "type": "string",
                    "description": "For config: new value to set. For soul: full new SOUL.md content (or 'read' to read current). For filter: TOML content to append. For script_tool: TOML content of the tool definition."
                },
                "message": {
                    "type": "string",
                    "description": "Commit message (for verify action)"
                }
            },
            "required": ["action"]
        })
    }

    async fn execute(&self, args: Value, ctx: &ToolContext<'_>) -> Result<String> {
        let action = args["action"].as_str().unwrap_or("");

        match action {
            // ═══ Layer 1: Config ═══
            "config" => self.action_config(&args).await,
            "soul" => self.action_soul(&args).await,
            "filter" => self.action_filter(&args).await,
            "script_tool" => self.action_script_tool(&args).await,

            // ═══ Layer 2: Source ═══
            "locate" => self.action_locate(&args).await,
            "build" => self.action_build(&args).await,
            "test" => self.action_test(&args).await,
            "verify" => self.action_verify(&args, ctx).await,
            "status" => self.action_status().await,
            "rollback" => self.action_rollback().await,

            _ => Ok(format!("Unknown action: '{action}'. Available: config, soul, filter, script_tool, locate, build, test, verify, status, rollback")),
        }
    }
}

impl SelfModTool {
    // ─── Layer 1 Actions ───

    async fn action_config(&self, args: &Value) -> Result<String> {
        let config_path = config_dir().join("config.toml");
        let key = args["target"].as_str().unwrap_or("");
        let value = args["value"].as_str().unwrap_or("");

        if key.is_empty() {
            // Read mode: return current config
            let content = std::fs::read_to_string(&config_path).unwrap_or_default();
            if content.is_empty() {
                return Ok("No config.toml found. Use with target='section.key' and value='...' to set.".into());
            }
            return Ok(format!("Current config (~/.aegis/config.toml):\n```toml\n{content}\n```"));
        }

        if value.is_empty() {
            // Read specific key
            let content = std::fs::read_to_string(&config_path).unwrap_or_default();
            let table: toml::Table = content.parse().unwrap_or_default();
            let parts: Vec<&str> = key.split('.').collect();
            let result = match parts.as_slice() {
                [section, field] => table
                    .get(*section)
                    .and_then(|s| s.get(*field))
                    .map(|v| v.to_string())
                    .unwrap_or_else(|| "(not set)".to_string()),
                [field] => table
                    .get(*field)
                    .map(|v| v.to_string())
                    .unwrap_or_else(|| "(not set)".to_string()),
                _ => "(invalid key path)".to_string(),
            };
            return Ok(format!("{key} = {result}"));
        }

        // Write mode
        backup_config_file(&config_path)?;
        let content = std::fs::read_to_string(&config_path).unwrap_or_default();
        let mut table: toml::Table = content.parse().unwrap_or_default();

        let parts: Vec<&str> = key.split('.').collect();
        let toml_value: toml::Value = if value == "true" {
            toml::Value::Boolean(true)
        } else if value == "false" {
            toml::Value::Boolean(false)
        } else if let Ok(n) = value.parse::<i64>() {
            toml::Value::Integer(n)
        } else {
            toml::Value::String(value.to_string())
        };

        match parts.as_slice() {
            [section, field] => {
                let section_table = table
                    .entry(section.to_string())
                    .or_insert_with(|| toml::Value::Table(toml::Table::new()));
                if let Some(t) = section_table.as_table_mut() {
                    t.insert(field.to_string(), toml_value);
                }
            }
            [field] => {
                table.insert(field.to_string(), toml_value);
            }
            _ => return Ok("Invalid key path. Use 'section.key' or 'key'.".into()),
        }

        let new_content = toml::to_string_pretty(&table)?;
        std::fs::write(&config_path, &new_content)?;
        Ok(format!("Set {key} = {value} in config.toml. Backup saved."))
    }

    async fn action_soul(&self, args: &Value) -> Result<String> {
        let soul_path = config_dir().join("SOUL.md");
        let value = args["value"].as_str().unwrap_or("read");

        if value == "read" {
            let content = std::fs::read_to_string(&soul_path).unwrap_or_else(|_| "(no SOUL.md found)".into());
            return Ok(format!("Current SOUL.md:\n\n{content}"));
        }

        backup_config_file(&soul_path)?;
        std::fs::create_dir_all(config_dir())?;
        std::fs::write(&soul_path, value)?;
        Ok("SOUL.md updated. Changes take effect next turn.".into())
    }

    async fn action_filter(&self, args: &Value) -> Result<String> {
        let filter_path = config_dir().join("filters.toml");
        let value = args["value"].as_str().unwrap_or("read");

        if value == "read" {
            let content = std::fs::read_to_string(&filter_path).unwrap_or_else(|_| "(no filters.toml found)".into());
            return Ok(format!("Current filters.toml:\n```toml\n{content}\n```"));
        }

        backup_config_file(&filter_path)?;
        let mut current = std::fs::read_to_string(&filter_path).unwrap_or_default();
        if !current.is_empty() && !current.ends_with('\n') {
            current.push('\n');
        }
        current.push_str(value);
        current.push('\n');
        std::fs::write(&filter_path, &current)?;
        Ok("Filter rule appended to filters.toml. Takes effect next turn.".into())
    }

    async fn action_script_tool(&self, args: &Value) -> Result<String> {
        let tools_dir = config_dir().join("tools.d");
        let name = args["target"].as_str().unwrap_or("");
        let value = args["value"].as_str().unwrap_or("");

        if name.is_empty() && value.is_empty() {
            // List existing script tools
            let mut tools = Vec::new();
            if let Ok(entries) = std::fs::read_dir(&tools_dir) {
                for entry in entries.flatten() {
                    let fname = entry.file_name().to_string_lossy().to_string();
                    if fname.ends_with(".toml") {
                        tools.push(fname.trim_end_matches(".toml").to_string());
                    }
                }
            }
            if tools.is_empty() {
                return Ok("No script tools defined. Create one with target='name' and value='<toml content>'.".into());
            }
            tools.sort();
            return Ok(format!("Script tools in ~/.aegis/tools.d/:\n{}", tools.iter().map(|t| format!("- {t}")).collect::<Vec<_>>().join("\n")));
        }

        if name.is_empty() {
            return Ok("Error: 'target' (tool name) is required for script_tool action.".into());
        }

        if value == "read" {
            let path = tools_dir.join(format!("{name}.toml"));
            let content = std::fs::read_to_string(&path)
                .unwrap_or_else(|_| format!("(tool '{name}' not found)"));
            return Ok(content);
        }

        if value == "remove" {
            let path = tools_dir.join(format!("{name}.toml"));
            if path.exists() {
                std::fs::remove_file(&path)?;
                return Ok(format!("Removed script tool '{name}'."));
            }
            return Ok(format!("Tool '{name}' not found."));
        }

        // Create/update tool
        std::fs::create_dir_all(&tools_dir)?;
        let path = tools_dir.join(format!("{name}.toml"));
        if path.exists() {
            backup_config_file(&path)?;
        }
        std::fs::write(&path, value)?;
        Ok(format!("Script tool '{name}' saved to ~/.aegis/tools.d/{name}.toml. Available next turn."))
    }

    // ─── Layer 2 Actions ───

    async fn action_locate(&self, args: &Value) -> Result<String> {
        let root = match find_source_root() {
            Some(r) => r,
            None => return Ok(
                "Source not available. Set AEGIS_SOURCE_DIR or clone to ~/src/aegis.\n\
                 For config-layer changes (SOUL.md, filters, script tools), use the config/soul/filter/script_tool actions instead."
                    .into(),
            ),
        };

        let target = args["target"].as_str().unwrap_or("");
        if target.is_empty() {
            let crates = list_crates(&root);
            return Ok(format!(
                "Source root: {}\nCrates ({}):\n{}",
                root.display(),
                crates.len(),
                crates.iter().map(|c| format!("  {c}")).collect::<Vec<_>>().join("\n")
            ));
        }

        // Find specific crate
        for dir in ["crates", "bins"] {
            let candidate = root.join(dir).join(target);
            if candidate.exists() {
                let files: Vec<String> = walkdir_simple(&candidate.join("src"));
                return Ok(format!(
                    "source_root: {}\ncrate_path: {}/{target}/src/\nfiles:\n{}",
                    root.display(),
                    dir,
                    files.iter().map(|f| format!("  {f}")).collect::<Vec<_>>().join("\n")
                ));
            }
        }
        // Try partial match
        let crates = list_crates(&root);
        let matches: Vec<&String> = crates.iter().filter(|c| c.contains(target)).collect();
        if matches.is_empty() {
            Ok(format!("Crate '{target}' not found. Available: {}", crates.join(", ")))
        } else {
            Ok(format!("Partial matches for '{target}': {}", matches.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")))
        }
    }

    async fn action_build(&self, args: &Value) -> Result<String> {
        let root = match find_source_root() {
            Some(r) => r,
            None => return Ok("Source not available. Set AEGIS_SOURCE_DIR.".into()),
        };

        let target = args["target"].as_str().unwrap_or("");
        let cargo_args = if target.is_empty() || target == "all" {
            vec!["check", "--workspace"]
        } else {
            vec!["check", "-p", target]
        };

        let (success, output) = run_cargo(&root, &cargo_args, 60).await;
        if success {
            Ok(format!("cargo check: OK\n{output}"))
        } else {
            Ok(format!("cargo check: FAILED\n{output}"))
        }
    }

    async fn action_test(&self, args: &Value) -> Result<String> {
        let root = match find_source_root() {
            Some(r) => r,
            None => return Ok("Source not available. Set AEGIS_SOURCE_DIR.".into()),
        };

        let target = args["target"].as_str().unwrap_or("");
        let cargo_args = if target.is_empty() || target == "all" {
            vec!["test", "--workspace"]
        } else {
            vec!["test", "-p", target]
        };

        let (success, output) = run_cargo(&root, &cargo_args, 120).await;
        if success {
            Ok(format!("cargo test: OK\n{output}"))
        } else {
            Ok(format!("cargo test: FAILED\n{output}"))
        }
    }

    async fn action_verify(&self, args: &Value, ctx: &ToolContext<'_>) -> Result<String> {
        let root = match find_source_root() {
            Some(r) => r,
            None => return Ok("Source not available. Set AEGIS_SOURCE_DIR.".into()),
        };

        if !has_git(&root) {
            return Ok("verify requires git. Source directory is not a git repository.".into());
        }

        let message = args["message"].as_str().unwrap_or("selfmod: auto-commit");

        // Approval gate (unless yolo)
        if !ctx.yolo {
            let dirty = git_dirty_files(&root);
            if dirty.len() > 5 {
                return Ok(format!(
                    "Too many changed files ({}). selfmod limits to 5 files per verify for safety. Changed: {}",
                    dirty.len(),
                    dirty.join(", ")
                ));
            }
        }

        // Step 1: cargo check
        let (check_ok, check_out) = run_cargo(&root, &["check", "--workspace"], 60).await;
        if !check_ok {
            // Auto-rollback
            let _ = std::process::Command::new("git")
                .args(["checkout", "."])
                .current_dir(&root)
                .status();
            return Ok(format!("Build FAILED — auto-rolled back.\n{check_out}"));
        }

        // Step 2: cargo test
        let (test_ok, test_out) = run_cargo(&root, &["test", "--workspace"], 120).await;
        if !test_ok {
            let _ = std::process::Command::new("git")
                .args(["checkout", "."])
                .current_dir(&root)
                .status();
            return Ok(format!("Tests FAILED — auto-rolled back.\n{test_out}"));
        }

        // Step 3: commit
        let _ = std::process::Command::new("git")
            .args(["add", "-A"])
            .current_dir(&root)
            .status();
        let commit_result = std::process::Command::new("git")
            .args(["commit", "-m", message])
            .current_dir(&root)
            .output();

        match commit_result {
            Ok(output) if output.status.success() => {
                let hash = git_short_hash(&root).unwrap_or_default();
                Ok(format!("Build: OK. Tests: OK. Committed as {hash}.\nNote: source committed but binary not replaced. Use `aegis evolve` to deploy."))
            }
            Ok(output) => {
                let err = String::from_utf8_lossy(&output.stderr);
                Ok(format!("Build/test passed but commit failed: {err}"))
            }
            Err(e) => Ok(format!("Build/test passed but git commit error: {e}")),
        }
    }

    async fn action_status(&self) -> Result<String> {
        let root = match find_source_root() {
            Some(r) => r,
            None => {
                // Show Layer 1 status only
                let soul_exists = config_dir().join("SOUL.md").exists();
                let filter_exists = config_dir().join("filters.toml").exists();
                let tools_dir = config_dir().join("tools.d");
                let tool_count = std::fs::read_dir(&tools_dir)
                    .map(|rd| rd.flatten().count())
                    .unwrap_or(0);
                return Ok(format!(
                    "Source: not available\nConfig dir: {}\nSOUL.md: {}\nfilters.toml: {}\nScript tools: {}",
                    config_dir().display(),
                    if soul_exists { "present" } else { "absent" },
                    if filter_exists { "present" } else { "absent" },
                    tool_count
                ));
            }
        };

        let dirty = git_dirty_files(&root);
        let hash = git_short_hash(&root).unwrap_or_else(|| "unknown".into());
        let soul_exists = config_dir().join("SOUL.md").exists();
        let tools_dir = config_dir().join("tools.d");
        let tool_count = std::fs::read_dir(&tools_dir)
            .map(|rd| rd.flatten().count())
            .unwrap_or(0);

        let checkpoints = CheckpointManager::list().unwrap_or_default();
        let recent_cp = checkpoints.first().map(|(name, _)| name.as_str()).unwrap_or("none");

        Ok(format!(
            "Source root: {}\nGit HEAD: {hash}\nDirty files: {}\nSOUL.md: {}\nScript tools: {}\nLast checkpoint: {recent_cp}{}",
            root.display(),
            if dirty.is_empty() { "clean".to_string() } else { format!("{}\n  {}", dirty.len(), dirty.join("\n  ")) },
            if soul_exists { "present" } else { "absent" },
            tool_count,
            if dirty.is_empty() { String::new() } else { "\n\nUse 'rollback' to revert uncommitted changes.".to_string() }
        ))
    }

    async fn action_rollback(&self) -> Result<String> {
        let root = match find_source_root() {
            Some(r) => r,
            None => return Ok("Source not available. For config rollback, use checkpoints.".into()),
        };

        if !has_git(&root) {
            return Ok("rollback requires git.".into());
        }

        let dirty = git_dirty_files(&root);
        if dirty.is_empty() {
            return Ok("Nothing to rollback — working directory is clean.".into());
        }

        let _ = std::process::Command::new("git")
            .args(["checkout", "."])
            .current_dir(&root)
            .status();

        // Clean untracked files in src directories only
        let _ = std::process::Command::new("git")
            .args(["clean", "-fd", "crates/", "bins/"])
            .current_dir(&root)
            .status();

        Ok(format!("Rolled back {} dirty file(s). Working directory is clean.", dirty.len()))
    }
}

/// Simple recursive file listing (no external crate needed).
fn walkdir_simple(dir: &Path) -> Vec<String> {
    let mut files = Vec::new();
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                files.extend(walkdir_simple(&path));
            } else {
                let name = path.file_name().unwrap_or_default().to_string_lossy().to_string();
                files.push(name);
            }
        }
    }
    files.sort();
    files
}

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

    #[test]
    fn test_is_aegis_workspace() {
        // Current workspace should be detected
        let workspace = PathBuf::from("/workspace");
        if workspace.join("Cargo.toml").exists() {
            assert!(is_aegis_workspace(&workspace));
        }
        // Random path should not
        assert!(!is_aegis_workspace(Path::new("/tmp")));
    }

    #[test]
    fn test_config_dir() {
        let dir = config_dir();
        assert!(dir.to_string_lossy().contains(".aegis"));
    }

    #[test]
    fn test_find_source_root() {
        // In CI/dev container, /workspace should be found
        if PathBuf::from("/workspace").join("Cargo.toml").exists() {
            assert!(find_source_root().is_some());
        }
    }

    #[test]
    fn test_list_crates() {
        if let Some(root) = find_source_root() {
            let crates = list_crates(&root);
            assert!(!crates.is_empty());
            assert!(crates.iter().any(|c| c.contains("aegis-tools")));
        }
    }

    #[test]
    fn test_backup_config_file_nonexistent() {
        // Backing up a nonexistent file should be a no-op
        let result = backup_config_file(Path::new("/tmp/nonexistent-aegis-test-file"));
        assert!(result.is_ok());
    }

    #[test]
    fn test_walkdir_simple_empty() {
        let files = walkdir_simple(Path::new("/tmp/nonexistent-dir-aegis-test"));
        assert!(files.is_empty());
    }
}