symbi 1.11.0

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
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
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
use clap::parser::ValueSource;
use clap::ArgMatches;
use std::path::{Path, PathBuf};

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",
    ".env",
];

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");
    }
}

/// Generate 32 random bytes as a lowercase-hex string for use as SYMBIONT_MASTER_KEY.
fn generate_master_key() -> String {
    use std::io::Read;
    let mut bytes = [0u8; 32];
    // /dev/urandom is guaranteed non-blocking and entropy-sufficient on Linux.
    // On other Unix platforms it's the standard source. If it's unavailable,
    // fall back to a time-seeded PRNG — good enough to avoid hard-failing init,
    // the user can regenerate with `openssl rand -hex 32` if they care.
    if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
        if f.read_exact(&mut bytes).is_ok() {
            return bytes.iter().map(|b| format!("{:02x}", b)).collect();
        }
    }
    let seed = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    for (i, b) in bytes.iter_mut().enumerate() {
        *b = ((seed >> (i * 3)) ^ (seed.wrapping_mul((i as u128) + 1))) as u8;
    }
    bytes.iter().map(|b| format!("{:02x}", b)).collect()
}

/// Write `.env` (with a generated SYMBIONT_MASTER_KEY) and `.env.example`
/// unless they already exist. Prints guidance on keeping the key secret.
fn write_env_files(dir: &Path) {
    let env_path = dir.join(".env");
    let example_path = dir.join(".env.example");

    // Example file is always useful to commit, regenerate if missing.
    if !example_path.exists() {
        let example = r#"# Copy this file to .env and fill in secrets.
# Never commit .env — it's ignored by .gitignore.

# Required: 32-byte hex key used to encrypt persistent state.
# Generate with: openssl rand -hex 32
SYMBIONT_MASTER_KEY=

# Optional: LLM provider credentials (any one enables the coordinator)
# OPENROUTER_API_KEY=
# OPENAI_API_KEY=
# ANTHROPIC_API_KEY=

# Optional: structured logging level
RUST_LOG=info
"#;
        if std::fs::write(&example_path, example).is_ok() {
            println!("\u{2713} Created .env.example");
        }
    }

    if env_path.exists() {
        // Respect whatever the user already has. If the key is missing we still
        // tell them, rather than mutate the file and surprise them.
        if let Ok(existing) = std::fs::read_to_string(&env_path) {
            let has_key = existing.lines().any(|line| {
                let trimmed = line.trim_start();
                trimmed.starts_with("SYMBIONT_MASTER_KEY=")
                    && !matches!(
                        trimmed.trim_start_matches("SYMBIONT_MASTER_KEY=").trim(),
                        "" | "\"\"" | "''"
                    )
            });
            if !has_key {
                println!(
                    "\u{26a0} .env exists but has no SYMBIONT_MASTER_KEY — add one with: \
                     openssl rand -hex 32"
                );
            }
        }
        return;
    }

    let key = generate_master_key();
    let content = format!(
        "# Generated by `symbi init` — KEEP THIS FILE OUT OF VERSION CONTROL.\n\
         # Regenerate the master key with: openssl rand -hex 32\n\
         SYMBIONT_MASTER_KEY={}\n\
         RUST_LOG=info\n",
        key
    );

    if let Err(e) = std::fs::write(&env_path, content) {
        eprintln!("\u{26a0} Failed to write .env: {}", e);
        return;
    }
    set_env_permissions(&env_path);
    println!(
        "\u{2713} Generated SYMBIONT_MASTER_KEY in .env (keep this file out of version control)"
    );
}

#[cfg(unix)]
fn set_env_permissions(path: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let perms = std::fs::Permissions::from_mode(0o600);
    let _ = std::fs::set_permissions(path, perms);
}

#[cfg(not(unix))]
fn set_env_permissions(_path: &Path) {}

/// Write a ready-to-run `docker-compose.yml` matching the profile. Skips if a
/// compose file already exists (any of the canonical names).
fn write_docker_compose(dir: &Path, profile: &str) {
    for candidate in &[
        "docker-compose.yml",
        "docker-compose.yaml",
        "compose.yml",
        "compose.yaml",
    ] {
        if dir.join(candidate).exists() {
            println!(
                "  \u{26a0} Skipping {} (compose file already exists)",
                candidate
            );
            return;
        }
    }

    let compose = generate_docker_compose(profile);
    let compose_path = dir.join("docker-compose.yml");
    match std::fs::write(&compose_path, compose) {
        Ok(()) => {
            println!("\u{2713} Created docker-compose.yml");
            println!(
                "  \u{2192} docker compose up    # start the runtime in Docker (reads .env automatically)"
            );
        }
        Err(e) => eprintln!("\u{26a0} Failed to write docker-compose.yml: {}", e),
    }
}

fn generate_docker_compose(profile: &str) -> String {
    // HTTP input binds to 0.0.0.0 inside the container so the host port
    // mapping actually works (the default is 127.0.0.1 which is unreachable
    // from outside the container). The API port is bound the same way.
    format!(
        r#"# Generated by `symbi init` — profile: {profile}
# Docs: https://docs.symbiont.dev/docker
#
# Quick start:
#   1. Review .env (SYMBIONT_MASTER_KEY was generated for you).
#   2. `docker compose up` — Runtime API on :8080, HTTP Input on :8081.
#
# Volumes mount the host project into the container so edits to agents/,
# policies/, symbiont.toml, and tools/ are picked up on restart.

services:
  symbi:
    image: ghcr.io/thirdkeyai/symbi:latest
    command: ["up", "--http-bind", "0.0.0.0"]
    ports:
      - "8080:8080"
      - "8081:8081"
    volumes:
      - ./symbiont.toml:/var/lib/symbi/symbiont.toml:ro
      - ./agents:/var/lib/symbi/agents:ro
      - ./policies:/var/lib/symbi/policies:ro
      - ./tools:/var/lib/symbi/tools:ro
      - symbi-data:/var/lib/symbi/.symbi
      - symbi-audit:/var/lib/symbi/.symbiont
    environment:
      SYMBIONT_MASTER_KEY: ${{SYMBIONT_MASTER_KEY:?set SYMBIONT_MASTER_KEY in .env}}
      RUST_LOG: ${{RUST_LOG:-info}}
      # Uncomment any one of these to enable the Coordinator / LLM features:
      # OPENROUTER_API_KEY: ${{OPENROUTER_API_KEY}}
      # OPENAI_API_KEY:     ${{OPENAI_API_KEY}}
      # ANTHROPIC_API_KEY:  ${{ANTHROPIC_API_KEY}}
    restart: unless-stopped

volumes:
  symbi-data:
  symbi-audit:
"#
    )
}

pub async fn run(matches: &ArgMatches) {
    let force = matches.get_flag("force");
    let no_interact = matches.get_flag("no-interact");
    let no_docker_compose = matches.get_flag("no-docker-compose");

    // --dir PATH overrides CWD — essential for `docker run -v $(pwd):/workspace ... init --dir /workspace`.
    let target_dir = resolve_target_dir(matches);

    if !no_interact {
        let hints = detect_project_hints(&target_dir);
        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 let Err(e) = std::fs::create_dir_all(&target_dir) {
        eprintln!(
            "\u{2717} Failed to create target directory {}: {}",
            target_dir.display(),
            e
        );
        std::process::exit(1);
    }

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

    init_project(&target_dir, &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(&target_dir, &names);
        generate_agents_md(&target_dir);
    }

    // Master key: generate a .env with SYMBIONT_MASTER_KEY unless one is already present.
    write_env_files(&target_dir);

    // Docker compose: emit a ready-to-run compose file unless opted out.
    if !no_docker_compose {
        write_docker_compose(&target_dir, &profile);
    }
}

fn resolve_target_dir(matches: &ArgMatches) -> PathBuf {
    if let Some(dir) = matches.get_one::<String>("dir") {
        PathBuf::from(dir)
    } else {
        std::env::current_dir().expect("Failed to get current directory")
    }
}

#[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")));
    }

    #[test]
    fn test_generate_master_key_is_hex_and_64_chars() {
        let key = generate_master_key();
        assert_eq!(key.len(), 64);
        assert!(key.chars().all(|c| c.is_ascii_hexdigit()));
        // Two successive calls should not collide.
        assert_ne!(generate_master_key(), key);
    }

    #[test]
    fn test_write_env_files_creates_env_and_example() {
        let dir = tempfile::tempdir().unwrap();
        write_env_files(dir.path());
        let env = std::fs::read_to_string(dir.path().join(".env")).unwrap();
        assert!(env.contains("SYMBIONT_MASTER_KEY="));
        let key_line = env
            .lines()
            .find(|l| l.starts_with("SYMBIONT_MASTER_KEY="))
            .unwrap();
        let value = key_line.trim_start_matches("SYMBIONT_MASTER_KEY=");
        assert_eq!(value.len(), 64);
        assert!(value.chars().all(|c| c.is_ascii_hexdigit()));
        let example = std::fs::read_to_string(dir.path().join(".env.example")).unwrap();
        assert!(example.contains("SYMBIONT_MASTER_KEY="));
    }

    #[test]
    fn test_write_env_files_respects_existing_env() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(".env"), "SYMBIONT_MASTER_KEY=preserved\n").unwrap();
        write_env_files(dir.path());
        let env = std::fs::read_to_string(dir.path().join(".env")).unwrap();
        assert_eq!(env, "SYMBIONT_MASTER_KEY=preserved\n");
    }

    #[test]
    fn test_generate_docker_compose_has_expected_sections() {
        let compose = generate_docker_compose("assistant");
        assert!(compose.contains("profile: assistant"));
        assert!(compose.contains("image: ghcr.io/thirdkeyai/symbi:latest"));
        assert!(compose.contains("8080:8080"));
        assert!(compose.contains("8081:8081"));
        assert!(compose.contains("./agents:/var/lib/symbi/agents:ro"));
        assert!(compose.contains("./policies:/var/lib/symbi/policies:ro"));
        assert!(compose.contains("./symbiont.toml:/var/lib/symbi/symbiont.toml:ro"));
        assert!(compose.contains("SYMBIONT_MASTER_KEY"));
        // No unescaped Rust format braces leaked into the output.
        assert!(!compose.contains("{{"));
        assert!(!compose.contains("}}"));
    }

    #[test]
    fn test_write_docker_compose_skips_when_present() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("compose.yaml"), "pre-existing").unwrap();
        write_docker_compose(dir.path(), "assistant");
        // compose.yaml was the canonical file; we must not clobber it by
        // writing docker-compose.yml alongside it.
        assert!(!dir.path().join("docker-compose.yml").exists());
        assert_eq!(
            std::fs::read_to_string(dir.path().join("compose.yaml")).unwrap(),
            "pre-existing"
        );
    }

    #[test]
    fn test_write_docker_compose_writes_when_absent() {
        let dir = tempfile::tempdir().unwrap();
        write_docker_compose(dir.path(), "assistant");
        let path = dir.path().join("docker-compose.yml");
        assert!(path.exists());
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("symbi"));
    }

    #[test]
    fn test_gitignore_includes_env() {
        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(".env"));
    }
}