symbi 1.9.1

AI-native agent framework for building autonomous, policy-aware agents that can safely collaborate with humans, other agents, and large language models
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
use clap::parser::ValueSource;
use clap::ArgMatches;
use std::path::Path;

const DEFAULT_CEDAR_POLICY: &str = r#"// Default Symbiont policy — generated by `symbi init`
//
// Principle: deny by default, allow explicitly.
// Edit this file or add new .cedar files in policies/ to customize.

// Allow all read operations
permit(
    principal,
    action == Action::"read",
    resource
);

// Allow tool invocations that have been verified by SchemaPin
permit(
    principal,
    action == Action::"invoke_tool",
    resource
) when {
    resource.schema_verified == true
};

// Gate write operations on approval
forbid(
    principal,
    action == Action::"write",
    resource
) unless {
    principal.approved == true
};

// Require audit on all state-changing operations
permit(
    principal,
    action == Action::"audit",
    resource
);
"#;

const SYMBIONT_GITIGNORE_ENTRIES: &[&str] = &[
    "# Symbiont",
    ".symbiont/audit/*.jsonl",
    "symbi.db",
    "symbi.db-wal",
    "symbi.db-shm",
    "symbi.quick.toml",
];

const ASSISTANT_DSL: &str = r#"metadata {
    version = "1.0.0"
    description = "Default governed assistant"
    author = ""
}

agent assistant(input: Query) -> Response {
    capabilities = ["read", "analyze", "summarize"]

    policy default_access {
        allow: read(input) if true
        deny: write(any) if not approved
        deny: invoke_tool(any) if not schema_verified
        audit: all_operations
    }

    with memory = "session", sandbox = "tier1" {
        result = process(input)
        return result
    }
}
"#;

const DEV_AGENT_DSL: &str = r#"metadata {
    version = "1.0.0"
    description = "Governed development agent"
    author = ""
}

agent dev(task: String) -> Result {
    capabilities = ["read", "write", "execute", "test"]

    executor {
        type = "cli_executor"
        allowed_tools = ["Bash", "Read", "Write", "Edit"]
        model = "claude-sonnet-4-20250514"
    }

    policy dev_safety {
        allow: read(any) if true
        allow: write(file) if file.in_project == true
        deny: write(file) if file.path.starts_with("/etc")
        deny: write(file) if file.path.starts_with("/usr")
        deny: execute(cmd) if cmd.contains("--force") and cmd.contains("push")
        deny: execute(cmd) if cmd.contains("rm -rf /")
        audit: all_operations with signature
    }

    with memory = "persistent", sandbox = "tier1", timeout = "30m" {
        result = execute(task)
        return result
    }
}
"#;

const DEV_AGENT_CEDAR: &str = r#"// Development agent policies — require PR for production branches

// Allow writes to feature branches
permit(
    principal == Agent::"dev",
    action == Action::"write",
    resource
) when {
    resource.branch != "main" && resource.branch != "production"
};

// Require approval for main branch
forbid(
    principal == Agent::"dev",
    action == Action::"write",
    resource
) when {
    resource.branch == "main"
} unless {
    context.has_approved_pr == true
};
"#;

const COORDINATOR_DSL: &str = r#"metadata {
    version = "1.0.0"
    description = "Multi-agent coordinator"
    author = ""
}

agent coordinator(task: String) -> Result {
    capabilities = ["read", "delegate", "aggregate"]

    policy coordination {
        allow: delegate(agent) if agent.registered == true
        deny: delegate(agent) if agent.suspended == true
        audit: all_operations
    }

    with memory = "persistent", sandbox = "tier1" {
        subtasks = decompose(task)
        results = parallel_map(subtasks, delegate_to_worker)
        return aggregate(results)
    }
}
"#;

const WORKER_DSL: &str = r#"metadata {
    version = "1.0.0"
    description = "Multi-agent worker"
    author = ""
}

agent worker(subtask: String) -> Result {
    capabilities = ["read", "write", "analyze"]

    policy worker_limits {
        allow: read(any) if true
        deny: write(any) if not approved_by_coordinator
        audit: all_operations
    }

    with memory = "session", sandbox = "tier1", timeout = "10m" {
        result = process(subtask)
        return result
    }
}
"#;

const INTER_AGENT_CEDAR: &str = r#"// Inter-agent communication policies

// Coordinator can delegate to any registered worker
permit(
    principal == Agent::"coordinator",
    action == Action::"delegate",
    resource
) when {
    resource.type == "agent" && resource.registered == true
};

// Workers can only respond to their coordinator
permit(
    principal == Agent::"worker",
    action == Action::"respond",
    resource
) when {
    resource.requester == "coordinator"
};

// Workers cannot invoke other workers directly
forbid(
    principal == Agent::"worker",
    action == Action::"delegate",
    resource
);
"#;

struct CatalogEntry {
    name: &'static str,
    description: &'static str,
    dsl: &'static str,
    cedar: Option<&'static str>,
}

const CATALOG: &[CatalogEntry] = &[
    CatalogEntry {
        name: "assistant",
        description: "Default governed assistant",
        dsl: ASSISTANT_DSL,
        cedar: None,
    },
    CatalogEntry {
        name: "dev",
        description: "CliExecutor agent for Claude Code / Gemini CLI",
        dsl: DEV_AGENT_DSL,
        cedar: Some(DEV_AGENT_CEDAR),
    },
    CatalogEntry {
        name: "coordinator",
        description: "Multi-agent coordinator with message passing",
        dsl: COORDINATOR_DSL,
        cedar: Some(INTER_AGENT_CEDAR),
    },
    CatalogEntry {
        name: "worker",
        description: "Multi-agent worker",
        dsl: WORKER_DSL,
        cedar: None,
    },
];

fn list_catalog() {
    println!("\nAvailable agents:");
    for entry in CATALOG {
        println!("  {:<20} {}", entry.name, entry.description);
    }
    println!();
}

fn import_catalog_agents(dir: &Path, names: &[&str]) {
    std::fs::create_dir_all(dir.join("agents")).expect("Failed to create agents/");

    for name in names {
        match CATALOG.iter().find(|e| e.name == *name) {
            Some(entry) => {
                let dsl_path = dir.join(format!("agents/{}.dsl", entry.name));
                if dsl_path.exists() {
                    println!(
                        "  \u{26a0} Skipping agents/{}.dsl (already exists)",
                        entry.name
                    );
                } else {
                    std::fs::write(&dsl_path, entry.dsl)
                        .unwrap_or_else(|_| panic!("Failed to write {}.dsl", entry.name));
                    println!("\u{2713} Created agents/{}.dsl", entry.name);
                    validate_dsl(&format!("agents/{}.dsl", entry.name), entry.dsl);
                }

                if let Some(cedar) = entry.cedar {
                    let cedar_path = dir.join(format!("policies/{}.cedar", entry.name));
                    if cedar_path.exists() {
                        println!(
                            "  \u{26a0} Skipping policies/{}.cedar (already exists)",
                            entry.name
                        );
                    } else {
                        std::fs::create_dir_all(dir.join("policies")).ok();
                        std::fs::write(&cedar_path, cedar)
                            .unwrap_or_else(|_| panic!("Failed to write {}.cedar", entry.name));
                        println!("\u{2713} Created policies/{}.cedar", entry.name);
                    }
                }
            }
            None => {
                eprintln!("\u{2717} Unknown catalog agent: {}", name);
                eprintln!("  Run `symbi init --catalog list` to see available agents");
            }
        }
    }
}

fn generate_toml(profile: &str, schemapin: &str, sandbox: &str) -> String {
    format!(
        r#"# Generated by `symbi init` — profile: {profile}
# Docs: https://docs.symbiont.dev/configuration

[runtime]
mode = "dev"
hot_reload = true
log_level = "info"

[policy]
engine = "cedar"
enforcement = "strict"
policy_dir = "policies"

[schemapin]
mode = "{schemapin}"

[sandbox]
tier = "{sandbox}"

[storage]
type = "sqlite"
path = "./symbi.db"

[http]
enabled = true
port = 8081
bind = "127.0.0.1"
"#
    )
}

fn update_gitignore(dir: &Path) -> std::io::Result<()> {
    let gitignore_path = dir.join(".gitignore");
    let existing = if gitignore_path.exists() {
        std::fs::read_to_string(&gitignore_path)?
    } else {
        String::new()
    };
    let mut lines_to_add = Vec::new();
    for entry in SYMBIONT_GITIGNORE_ENTRIES {
        if !existing.contains(entry) {
            lines_to_add.push(*entry);
        }
    }
    if lines_to_add.is_empty() {
        return Ok(());
    }
    let mut content = existing;
    if !content.is_empty() && !content.ends_with('\n') {
        content.push('\n');
    }
    if !content.is_empty() {
        content.push('\n');
    }
    for line in &lines_to_add {
        content.push_str(line);
        content.push('\n');
    }
    std::fs::write(&gitignore_path, content)
}

fn should_proceed(dir: &Path, force: bool) -> Result<(), String> {
    if dir.join("symbiont.toml").exists() && !force {
        return Err("symbiont.toml already exists".into());
    }
    Ok(())
}

#[cfg(feature = "interactive")]
fn select_profile_interactive() -> String {
    use dialoguer::{theme::ColorfulTheme, Select};

    let profiles = &[
        "minimal      \u{2014} symbiont.toml + default Cedar policy (add agents later)",
        "assistant     \u{2014} single governed assistant agent",
        "dev-agent     \u{2014} CliExecutor agent for coding tasks (Claude Code / Gemini CLI)",
        "multi-agent   \u{2014} coordinator + worker pattern with inter-agent policies",
    ];
    let profile_values = &["minimal", "assistant", "dev-agent", "multi-agent"];

    let selection = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("Select a project profile")
        .items(profiles)
        .default(1)
        .interact()
        .expect("Failed to select profile");

    profile_values[selection].to_string()
}

#[cfg(feature = "interactive")]
fn select_schemapin_interactive() -> String {
    use dialoguer::{theme::ColorfulTheme, Select};

    let modes = &[
        "tofu          \u{2014} Trust-On-First-Use (pin on first verify)",
        "strict        \u{2014} require pre-configured trust bundles",
        "disabled      \u{2014} no MCP tool verification",
    ];
    let mode_values = &["tofu", "strict", "disabled"];

    let selection = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("SchemaPin mode")
        .items(modes)
        .default(0)
        .interact()
        .expect("Failed to select SchemaPin mode");

    mode_values[selection].to_string()
}

#[cfg(feature = "interactive")]
fn select_sandbox_interactive() -> String {
    use dialoguer::{theme::ColorfulTheme, Select};

    let tiers = &[
        "tier1         \u{2014} Docker isolation (recommended)",
        "tier2         \u{2014} gVisor hardened sandbox",
        "tier0         \u{2014} no sandbox (development only)",
    ];
    let tier_values = &["tier1", "tier2", "tier0"];

    let selection = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("Sandbox tier")
        .items(tiers)
        .default(0)
        .interact()
        .expect("Failed to select sandbox tier");

    tier_values[selection].to_string()
}

fn validate_dsl(filename: &str, source: &str) {
    match dsl::parse_dsl(source) {
        Ok(tree) if !tree.root_node().has_error() => {}
        Ok(_) => println!("  \u{26a0} Warning: {} has parse warnings", filename),
        Err(e) => println!("  \u{26a0} Warning: {} parse error: {}", filename, e),
    }
}

fn generate_agents_md(dir: &Path) {
    let agents_dir = dir.join("agents");
    if !agents_dir.exists() {
        return;
    }
    let mut content = String::from("# AGENTS.md\n\n");
    content.push_str("<!-- agents-md:auto-start -->\n");
    content.push_str("<!-- This section is auto-generated. Do not edit manually. -->\n\n");
    content.push_str("| Agent | Description |\n");
    content.push_str("|-------|-------------|\n");
    if let Ok(entries) = std::fs::read_dir(&agents_dir) {
        let mut entries: Vec<_> = entries.flatten().collect();
        entries.sort_by_key(|e| e.file_name());
        for entry in entries {
            let path = entry.path();
            if path.extension().map(|e| e == "dsl").unwrap_or(false) {
                if let Ok(source) = std::fs::read_to_string(&path) {
                    if let Ok(tree) = dsl::parse_dsl(&source) {
                        let meta = dsl::extract_metadata(&tree, &source);
                        let name = path.file_stem().unwrap_or_default().to_string_lossy();
                        let desc = meta.get("description").cloned().unwrap_or_default();
                        content.push_str(&format!("| {} | {} |\n", name, desc));
                    }
                }
            }
        }
    }
    content.push_str("\n<!-- agents-md:auto-end -->\n");
    std::fs::write(dir.join("AGENTS.md"), content).ok();
    println!("\u{2713} Created AGENTS.md");
}

fn write_agent_if_not_exists(dir: &Path, filename: &str, content: &str) -> bool {
    let path = dir.join("agents").join(filename);
    if path.exists() {
        println!("  \u{26a0} Skipping agents/{} (already exists)", filename);
        return false;
    }
    std::fs::write(&path, content)
        .unwrap_or_else(|_| panic!("Failed to write agents/{}", filename));
    println!("\u{2713} Created agents/{}", filename);
    validate_dsl(&format!("agents/{}", filename), content);
    true
}

fn write_policy_if_not_exists(dir: &Path, filename: &str, content: &str) -> bool {
    let path = dir.join("policies").join(filename);
    if path.exists() {
        println!("  \u{26a0} Skipping policies/{} (already exists)", filename);
        return false;
    }
    std::fs::write(&path, content)
        .unwrap_or_else(|_| panic!("Failed to write policies/{}", filename));
    println!("\u{2713} Created policies/{}", filename);
    true
}

fn detect_project_hints(dir: &Path) -> Vec<&'static str> {
    let mut hints = Vec::new();
    if dir.join(".claude").exists() || dir.join("CLAUDE.md").exists() {
        hints.push("Detected Claude Code project \u{2014} consider `--profile dev-agent`");
    }
    if dir.join("GEMINI.md").exists() || dir.join(".gemini").exists() {
        hints.push("Detected Gemini CLI project \u{2014} consider `--profile dev-agent`");
    }
    if dir.join("Cargo.toml").exists() {
        hints.push("Detected Rust project");
    }
    if dir.join("package.json").exists() {
        hints.push("Detected Node.js project");
    }
    if dir.join("pyproject.toml").exists() || dir.join("requirements.txt").exists() {
        hints.push("Detected Python project");
    }
    hints
}

fn init_project(dir: &Path, profile: &str, schemapin: &str, sandbox: &str) {
    let toml = generate_toml(profile, schemapin, sandbox);
    std::fs::write(dir.join("symbiont.toml"), toml).expect("Failed to write symbiont.toml");
    println!("\u{2713} Created symbiont.toml");

    std::fs::create_dir_all(dir.join("policies")).expect("Failed to create policies/");
    std::fs::write(dir.join("policies/default.cedar"), DEFAULT_CEDAR_POLICY)
        .expect("Failed to write default.cedar");
    println!("\u{2713} Created policies/default.cedar");

    std::fs::create_dir_all(dir.join(".symbiont/audit"))
        .expect("Failed to create .symbiont/audit/");
    println!("\u{2713} Created .symbiont/audit/");

    update_gitignore(dir).expect("Failed to update .gitignore");
    println!("\u{2713} Updated .gitignore");

    match profile {
        "minimal" => {}
        "assistant" => {
            std::fs::create_dir_all(dir.join("agents")).expect("Failed to create agents/");
            write_agent_if_not_exists(dir, "assistant.dsl", ASSISTANT_DSL);
            generate_agents_md(dir);
        }
        "dev-agent" => {
            std::fs::create_dir_all(dir.join("agents")).expect("Failed to create agents/");
            write_agent_if_not_exists(dir, "dev.dsl", DEV_AGENT_DSL);
            write_policy_if_not_exists(dir, "dev-agent.cedar", DEV_AGENT_CEDAR);
            generate_agents_md(dir);
        }
        "multi-agent" => {
            std::fs::create_dir_all(dir.join("agents")).expect("Failed to create agents/");
            write_agent_if_not_exists(dir, "coordinator.dsl", COORDINATOR_DSL);
            write_agent_if_not_exists(dir, "worker.dsl", WORKER_DSL);
            write_policy_if_not_exists(dir, "inter-agent.cedar", INTER_AGENT_CEDAR);
            generate_agents_md(dir);
        }
        "import" => {}
        _ => unreachable!("profile validated before reaching init_project"),
    }

    println!();
    println!("Next steps:");
    match profile {
        "minimal" | "import" => {}
        "dev-agent" => println!("  symbi dsl -f agents/dev.dsl          # validate your agent"),
        "multi-agent" => {
            println!("  symbi dsl -f agents/coordinator.dsl  # validate your agents");
        }
        _ => println!("  symbi dsl -f agents/assistant.dsl   # validate your agent"),
    }
    println!("  symbi up                             # start the runtime");
    if profile != "minimal" && profile != "import" {
        println!("  symbi agents-md generate             # regenerate AGENTS.md after changes");
    }
}

pub async fn run(matches: &ArgMatches) {
    let force = matches.get_flag("force");
    let no_interact = matches.get_flag("no-interact");
    let cwd = std::env::current_dir().expect("Failed to get current directory");

    if !no_interact {
        let hints = detect_project_hints(&cwd);
        if !hints.is_empty() {
            for hint in &hints {
                println!("\u{2139} {}", hint);
            }
            println!();
        }
    }

    let profile = match matches.get_one::<String>("profile") {
        Some(p) => p.clone(),
        None if no_interact => "assistant".to_string(),
        #[cfg(feature = "interactive")]
        None => select_profile_interactive(),
        #[cfg(not(feature = "interactive"))]
        None => {
            println!("No --profile specified, using default: assistant");
            "assistant".to_string()
        }
    };

    let schemapin = match matches.value_source("schemapin") {
        Some(ValueSource::CommandLine) => matches.get_one::<String>("schemapin").unwrap().clone(),
        _ if no_interact => "tofu".to_string(),
        #[cfg(feature = "interactive")]
        _ => select_schemapin_interactive(),
        #[cfg(not(feature = "interactive"))]
        _ => "tofu".to_string(),
    };

    let sandbox = match matches.value_source("sandbox") {
        Some(ValueSource::CommandLine) => matches.get_one::<String>("sandbox").unwrap().clone(),
        _ if no_interact => "tier1".to_string(),
        #[cfg(feature = "interactive")]
        _ => select_sandbox_interactive(),
        #[cfg(not(feature = "interactive"))]
        _ => "tier1".to_string(),
    };

    if !["minimal", "assistant", "dev-agent", "multi-agent", "import"].contains(&profile.as_str()) {
        eprintln!("\u{2717} Unknown profile: {}", profile);
        eprintln!("  Available: minimal, assistant, dev-agent, multi-agent, import");
        std::process::exit(1);
    }
    if profile == "import" {
        let catalog_arg = matches.get_one::<String>("catalog");
        if catalog_arg.is_none() || catalog_arg.map(|s| s.as_str()) == Some("list") {
            eprintln!("\u{2717} --profile import requires --catalog <agent1,agent2,...>");
            eprintln!("  Run `symbi init --catalog list` to see available agents");
            std::process::exit(1);
        }
    }

    if !["tofu", "strict", "disabled"].contains(&schemapin.as_str()) {
        eprintln!("\u{2717} Unknown schemapin mode: {}", schemapin);
        std::process::exit(1);
    }
    if !["tier0", "tier1", "tier2"].contains(&sandbox.as_str()) {
        eprintln!("\u{2717} Unknown sandbox tier: {}", sandbox);
        std::process::exit(1);
    }

    // Handle --catalog list
    if let Some(catalog_arg) = matches.get_one::<String>("catalog") {
        if catalog_arg == "list" {
            list_catalog();
            return;
        }
    }

    if should_proceed(&cwd, force).is_err() {
        eprintln!("\u{2717} symbiont.toml already exists. Use --force to overwrite.");
        std::process::exit(1);
    }

    init_project(&cwd, &profile, &schemapin, &sandbox);

    // Import catalog agents if --catalog was provided alongside a profile
    if let Some(catalog_arg) = matches.get_one::<String>("catalog") {
        let names: Vec<&str> = catalog_arg.split(',').map(|s| s.trim()).collect();
        import_catalog_agents(&cwd, &names);
        generate_agents_md(&cwd);
    }
}

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

    #[test]
    fn test_generate_toml_minimal() {
        let toml = generate_toml("minimal", "tofu", "tier1");
        assert!(toml.contains("profile: minimal"));
        assert!(toml.contains(r#"mode = "tofu""#));
        assert!(toml.contains(r#"tier = "tier1""#));
        assert!(toml.contains(r#"mode = "dev""#));
        assert!(toml.contains("policy_dir = \"policies\""));
    }

    #[test]
    fn test_generate_toml_custom_options() {
        let toml = generate_toml("assistant", "strict", "tier2");
        assert!(toml.contains("profile: assistant"));
        assert!(toml.contains(r#"mode = "strict""#));
        assert!(toml.contains(r#"tier = "tier2""#));
    }

    #[test]
    fn test_default_cedar_policy_content() {
        assert!(DEFAULT_CEDAR_POLICY.contains("deny by default"));
        assert!(DEFAULT_CEDAR_POLICY.contains("schema_verified"));
        assert!(DEFAULT_CEDAR_POLICY.contains("Action::\"read\""));
        assert!(DEFAULT_CEDAR_POLICY.contains("Action::\"audit\""));
    }

    #[test]
    fn test_update_gitignore_creates_new() {
        let dir = tempfile::tempdir().unwrap();
        update_gitignore(dir.path()).unwrap();
        let content = std::fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(content.contains("# Symbiont"));
        assert!(content.contains("symbi.db"));
        assert!(content.contains(".symbiont/audit/*.jsonl"));
        assert!(content.contains("symbi.quick.toml"));
    }

    #[test]
    fn test_update_gitignore_appends_to_existing() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(".gitignore"), "node_modules/\n").unwrap();
        update_gitignore(dir.path()).unwrap();
        let content = std::fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(content.starts_with("node_modules/"));
        assert!(content.contains("symbi.db"));
    }

    #[test]
    fn test_update_gitignore_no_duplicates() {
        let dir = tempfile::tempdir().unwrap();
        update_gitignore(dir.path()).unwrap();
        update_gitignore(dir.path()).unwrap();
        let content = std::fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert_eq!(content.matches("symbi.db\n").count(), 1);
    }

    #[test]
    fn test_assistant_dsl_has_metadata() {
        match dsl::parse_dsl(ASSISTANT_DSL) {
            Ok(tree) => {
                let meta = dsl::extract_metadata(&tree, ASSISTANT_DSL);
                match meta.get("description").map(|s| s.as_str()) {
                    Some("Default governed assistant") => {} // grammar supports full extraction
                    _ => {
                        // Grammar parsed but didn't extract metadata; check content instead
                        assert!(ASSISTANT_DSL.contains("Default governed assistant"));
                        assert!(ASSISTANT_DSL.contains("agent assistant"));
                    }
                }
            }
            Err(_) => {
                assert!(ASSISTANT_DSL.contains("Default governed assistant"));
                assert!(ASSISTANT_DSL.contains("agent assistant"));
            }
        }
    }

    #[test]
    fn test_init_project_minimal() {
        let dir = tempfile::tempdir().unwrap();
        init_project(dir.path(), "minimal", "tofu", "tier1");
        assert!(dir.path().join("symbiont.toml").exists());
        assert!(dir.path().join("policies/default.cedar").exists());
        assert!(dir.path().join(".symbiont/audit").exists());
        assert!(dir.path().join(".gitignore").exists());
        assert!(!dir.path().join("agents").exists());
        assert!(!dir.path().join("AGENTS.md").exists());
    }

    #[test]
    fn test_init_project_assistant() {
        let dir = tempfile::tempdir().unwrap();
        init_project(dir.path(), "assistant", "strict", "tier2");
        assert!(dir.path().join("symbiont.toml").exists());
        assert!(dir.path().join("policies/default.cedar").exists());
        assert!(dir.path().join("agents/assistant.dsl").exists());
        assert!(dir.path().join("AGENTS.md").exists());
        assert!(dir.path().join(".symbiont/audit").exists());
        let toml = std::fs::read_to_string(dir.path().join("symbiont.toml")).unwrap();
        assert!(toml.contains(r#"mode = "strict""#));
        assert!(toml.contains(r#"tier = "tier2""#));
    }

    #[test]
    fn test_should_proceed_blocks_without_force() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("symbiont.toml"), "existing").unwrap();
        assert!(should_proceed(dir.path(), false).is_err());
        assert!(should_proceed(dir.path(), true).is_ok());
    }

    #[test]
    fn test_should_proceed_allows_fresh_dir() {
        let dir = tempfile::tempdir().unwrap();
        assert!(should_proceed(dir.path(), false).is_ok());
    }

    #[test]
    fn test_dev_agent_dsl_has_metadata() {
        assert!(DEV_AGENT_DSL.contains("Governed development agent"));
        assert!(DEV_AGENT_DSL.contains("agent dev"));
        assert!(DEV_AGENT_DSL.contains("cli_executor"));
    }

    #[test]
    fn test_coordinator_dsl_has_metadata() {
        assert!(COORDINATOR_DSL.contains("Multi-agent coordinator"));
        assert!(COORDINATOR_DSL.contains("agent coordinator"));
    }

    #[test]
    fn test_worker_dsl_has_metadata() {
        assert!(WORKER_DSL.contains("Multi-agent worker"));
        assert!(WORKER_DSL.contains("agent worker"));
    }

    #[test]
    fn test_init_project_dev_agent() {
        let dir = tempfile::tempdir().unwrap();
        init_project(dir.path(), "dev-agent", "tofu", "tier1");
        assert!(dir.path().join("agents/dev.dsl").exists());
        assert!(dir.path().join("policies/default.cedar").exists());
        assert!(dir.path().join("policies/dev-agent.cedar").exists());
        assert!(dir.path().join("AGENTS.md").exists());
    }

    #[test]
    fn test_init_project_multi_agent() {
        let dir = tempfile::tempdir().unwrap();
        init_project(dir.path(), "multi-agent", "tofu", "tier1");
        assert!(dir.path().join("agents/coordinator.dsl").exists());
        assert!(dir.path().join("agents/worker.dsl").exists());
        assert!(dir.path().join("policies/default.cedar").exists());
        assert!(dir.path().join("policies/inter-agent.cedar").exists());
    }

    #[test]
    fn test_catalog_has_entries() {
        assert!(!CATALOG.is_empty());
        assert!(CATALOG.iter().any(|e| e.name == "assistant"));
        assert!(CATALOG.iter().any(|e| e.name == "dev"));
        assert!(CATALOG.iter().any(|e| e.name == "coordinator"));
        assert!(CATALOG.iter().any(|e| e.name == "worker"));
    }

    #[test]
    fn test_import_catalog_agents() {
        let dir = tempfile::tempdir().unwrap();
        import_catalog_agents(dir.path(), &["assistant", "dev"]);
        assert!(dir.path().join("agents/assistant.dsl").exists());
        assert!(dir.path().join("agents/dev.dsl").exists());
        assert!(dir.path().join("policies/dev.cedar").exists());
    }

    #[test]
    fn test_import_catalog_skips_existing() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("agents")).unwrap();
        std::fs::write(dir.path().join("agents/assistant.dsl"), "custom content").unwrap();
        import_catalog_agents(dir.path(), &["assistant"]);
        let content = std::fs::read_to_string(dir.path().join("agents/assistant.dsl")).unwrap();
        assert_eq!(content, "custom content");
    }

    #[test]
    fn test_init_preserves_existing_agents() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("agents")).unwrap();
        std::fs::write(dir.path().join("agents/assistant.dsl"), "my custom agent").unwrap();
        init_project(dir.path(), "assistant", "tofu", "tier1");
        let content = std::fs::read_to_string(dir.path().join("agents/assistant.dsl")).unwrap();
        assert_eq!(content, "my custom agent");
    }

    #[test]
    fn test_detect_project_hints() {
        let dir = tempfile::tempdir().unwrap();
        assert!(detect_project_hints(dir.path()).is_empty());

        std::fs::create_dir(dir.path().join(".claude")).unwrap();
        let hints = detect_project_hints(dir.path());
        assert!(hints.iter().any(|h| h.contains("dev-agent")));
    }
}