talahon 3.0.0

Talahon — automated AI SOC analyst (host orchestrator)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
//! `talahon doctor`: one command that explains why Talahon can or cannot run.
//!
//! Prints machine-readable blocks (same format as `talahon setup`):
//! `CHECK_ENVIRONMENT` and `CHECK_VLLM` from `talon-setup`, then
//! `CHECK_GATEWAY` (bind address the LLM gateway would use and whether
//! containers can reach it), `CHECK_EXPOSURE` (vLLM API key requirement,
//! HTTP API bind address — MYTH-05), `CHECK_NETWORK` (the dedicated agent
//! network exists — MYTH-05), `CHECK_INSTRUCTIONS` (which file holds each
//! group folder's instructions: `AGENT.md`, or the legacy `CLAUDE.md` —
//! MYTH-09), `CHECK_RENAME` (what this installation still uses under the
//! pre-rename name `talon`: `TALON_*` keys, `~/.config/talon`), `AUDIT_VERIFY`,
//! and a final `DOCTOR` summary with one hint per problem. Exit code 0 when
//! no problem was found.

use std::net::{IpAddr, Ipv4Addr};
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;

use talon_container::runtime::network_inspect_args;
use talon_container::{ContainerRuntime, HostPlatform, RunnerConfig};
use talon_core::config::TalonConfig;
use talon_core::provider::effective_vllm;
use talon_db::{Db, DbOptions, default_db_path};
use talon_http::HttpConfig;
use talon_security::instructions::InstructionFiles;
use talon_setup::checks::check_port;
use talon_setup::{SetupContext, StatusBlock, Step, StepArgs, run_step};

use crate::app::{ApiKeyPolicy, DEFAULT_CONTAINER_HOST, api_key_policy, gateway_bind_ip};

/// Operator hint for an issue code.
pub fn hint(issue: &str) -> &'static str {
    match issue {
        "container_runtime_missing" => "install docker or podman (CONTAINER_RUNTIME selects one)",
        "container_runtime_not_running" => {
            "start the container daemon (`docker info` must succeed)"
        }
        "configured_runtime_unavailable" => {
            "CONTAINER_RUNTIME is not installed; another runtime was found and will be used"
        }
        "image_missing" => {
            "build the agent image: ./container/build.sh (or `talahon setup container`)"
        }
        "image_has_old_name" => {
            "an image with the pre-rename name exists (CHECK_ENVIRONMENT LEGACY_IMAGE) but is \
             not used: the agent image is now called talahon-agent. Rebuild it with \
             ./container/build.sh; to keep running the old image on purpose set \
             CONTAINER_IMAGE to its name"
        }
        "vllm_not_configured" => {
            "set TALAHON_VLLM_BASE_URL and TALAHON_VLLM_MODEL in .env (see .env.example); without them \
             the LLM gateway does not start and every agent run fails"
        }
        "vllm_invalid_url" => "TALAHON_VLLM_BASE_URL must be an http(s) URL, e.g. http://vllm:8000",
        "vllm_unreachable" => {
            "vLLM is not reachable from this host (network, firewall, server down)"
        }
        "vllm_auth_failed" => {
            "vLLM rejected the key: set TALAHON_VLLM_API_KEY in .env to vLLM's --api-key"
        }
        "vllm_api_key_unset" => {
            "TALAHON_VLLM_API_KEY is not set, so the LLM gateway refuses to start (without a key \
             containers could call vLLM directly and bypass the gateway): start vLLM with \
             --api-key and put the same value in .env; only if containers provably cannot reach \
             vLLM, set TALAHON_VLLM_ALLOW_NO_API_KEY=true"
        }
        "vllm_model_missing" => {
            "TALAHON_VLLM_MODEL is not served by vLLM (compare with --served-model-name / MODELS)"
        }
        "vllm_http_error" | "vllm_invalid_response" => {
            "vLLM answered /v1/models unexpectedly; check TALAHON_VLLM_BASE_URL points at vLLM"
        }
        "gateway_port_in_use" => {
            "TALAHON_LLM_GATEWAY_PORT is in use (expected while talahon is running; otherwise pick another port)"
        }
        "gateway_port_unavailable" | "gateway_bind_unavailable" => {
            "the LLM gateway cannot bind its address: set TALAHON_LLM_GATEWAY_BIND to a local address"
        }
        "gateway_bind_loopback" => {
            "on Linux, containers cannot reach a gateway bound to 127.0.0.1: set \
             TALAHON_LLM_GATEWAY_BIND to the docker bridge address (e.g. 172.17.0.1)"
        }
        "agent_network_missing" => {
            "the agent container network (talon-agents) does not exist: run `talahon setup egress` \
             (creates it with inter-container traffic disabled plus the egress firewall rules); \
             `talahon run` also creates the network at startup, but not the firewall rules"
        }
        "agent_network_unchecked" => {
            "the agent container network could not be inspected (is the container runtime running?)"
        }
        "dirs_not_writable" => {
            "store/, data/, groups/ and logs/ must be writable by the service user"
        }
        "low_disk_space" => "free some disk space (images, logs, data/)",
        "http_api_public_bind" => {
            "the CoPilot HTTP API listens on every interface (COPILOT_HTTP_BIND=0.0.0.0 / ::): \
             bind it to 127.0.0.1 or the private address CoPilot uses, and firewall the port"
        }
        "http_config_invalid" => {
            "a COPILOT_HTTP_* setting is invalid (see CHECK_EXPOSURE ERROR); `talahon run` refuses to start"
        }
        "http_api_key_unset" => {
            "HTTP_API_KEY is not set: the CoPilot HTTP API rejects every request (openssl rand -hex 32)"
        }
        "audit_chain_tampered" => {
            "the audit log does not verify (see AUDIT_VERIFY ERROR): investigate with `talahon audit \
             tail` before trusting it"
        }
        "audit_key_missing" => {
            "the audit log has keyed rows but TALAHON_AUDIT_KEY is not set in .env: restore the key \
             (`talahon run` refuses to start without it)"
        }
        "audit_key_invalid" => {
            "TALAHON_AUDIT_KEY is too short or not random (openssl rand -hex 32); `talahon run` \
             refuses to start"
        }
        "instructions_conflict" => {
            "a group folder has both AGENT.md and CLAUDE.md with content (see CHECK_INSTRUCTIONS \
             CONFLICT): every run in that folder is refused, because the file is the trusted \
             system prompt and older versions did not protect the name AGENT.md. Inspect both \
             files, keep the one you wrote and delete the other (keep exactly one; rename a kept \
             CLAUDE.md to AGENT.md)"
        }
        "instructions_unsafe" => {
            "AGENT.md or CLAUDE.md of a group folder is a symlink, directory or other non-regular \
             file (see CHECK_INSTRUCTIONS UNSAFE): every run in that folder is refused. Replace \
             it with a regular file, or remove it"
        }
        _ => "see the blocks above",
    }
}

fn issues_of(block: Option<&StatusBlock>) -> Vec<String> {
    block
        .and_then(|b| b.get("ISSUES"))
        .filter(|v| *v != "none" && !v.is_empty())
        .map(|v| v.split(',').map(|s| s.trim().to_string()).collect())
        .unwrap_or_default()
}

/// `CHECK_GATEWAY` block plus issue codes.
async fn gateway_block(config: &TalonConfig) -> (StatusBlock, Vec<String>) {
    let mut issues = Vec::new();
    let mut block = StatusBlock::new("CHECK_GATEWAY");
    let explicit = config.env.get("TALAHON_LLM_GATEWAY_BIND").is_some();
    block.set(
        "BIND_SOURCE",
        if explicit { "explicit" } else { "detected" },
    );
    let runtime = ContainerRuntime::detect(&config.container_runtime).ok();
    let ip: Option<IpAddr> = match &runtime {
        Some(rt) => match gateway_bind_ip(config, rt).await {
            Ok(ip) => Some(ip),
            Err(e) => {
                block.set("ERROR", format!("{e:#}"));
                issues.push("gateway_bind_unavailable".to_string());
                None
            }
        },
        None => config
            .env
            .get("TALAHON_LLM_GATEWAY_BIND")
            .and_then(|v| v.trim().parse().ok())
            .or(Some(IpAddr::V4(Ipv4Addr::LOCALHOST))),
    };
    if let Some(ip) = ip {
        block.set("BIND", ip);
        block.set("PORT", config.llm_gateway_port);
        let port = check_port(&ip.to_string(), config.llm_gateway_port).await;
        block.set("PORT_STATUS", port.as_str());
        match port.as_str() {
            "free" => {}
            "in_use" => issues.push("gateway_port_in_use".to_string()),
            _ => issues.push("gateway_bind_unavailable".to_string()),
        }
        let linux = runtime
            .as_ref()
            .is_some_and(|rt| rt.platform() == HostPlatform::Linux);
        if linux && ip.is_loopback() {
            issues.push("gateway_bind_loopback".to_string());
        }
    }
    let host = config
        .env
        .get("TALAHON_LLM_GATEWAY_HOST")
        .unwrap_or_else(|| DEFAULT_CONTAINER_HOST.to_string());
    block.set(
        "CONTAINER_URL",
        format!("http://{host}:{}/v1", config.llm_gateway_port),
    );
    block.set(
        "STATUS",
        if issues.is_empty() {
            "success"
        } else {
            "failed"
        },
    );
    (block, issues)
}

/// `CHECK_EXPOSURE` block plus issue codes: the vLLM API key requirement
/// (only when vLLM is configured — otherwise `vllm_not_configured` already
/// says what is missing) and the HTTP API bind address (MYTH-05).
pub fn exposure_block(config: &TalonConfig) -> (StatusBlock, Vec<String>) {
    let mut issues = Vec::new();
    let mut block = StatusBlock::new("CHECK_EXPOSURE");
    let key = match api_key_policy(config) {
        ApiKeyPolicy::Present => "set",
        ApiKeyPolicy::MissingAllowed => "unset_allowed",
        ApiKeyPolicy::Missing => {
            if effective_vllm(&config.provider_defaults).is_some() {
                issues.push("vllm_api_key_unset".to_string());
            }
            "unset"
        }
    };
    block.set("VLLM_API_KEY", key);
    match HttpConfig::from_talon_config(config) {
        Ok(http) => {
            block.set("HTTP_BIND", http.bind);
            block.set("HTTP_PORT", http.port);
            block.set("HTTP_TLS_TERMINATED", http.tls_terminated);
            if http.bind.is_unspecified() {
                issues.push("http_api_public_bind".to_string());
            }
        }
        Err(e) => {
            block.set("ERROR", e);
            issues.push("http_config_invalid".to_string());
        }
    }
    block.set(
        "STATUS",
        if issues.is_empty() {
            "success"
        } else {
            "failed"
        },
    );
    (block, issues)
}

/// How long `<runtime> network inspect` may take.
const NETWORK_INSPECT_TIMEOUT: Duration = Duration::from_secs(20);

/// Result of `<runtime> network inspect <name>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkState {
    /// The network exists.
    Exists,
    /// The runtime says there is no such network.
    Missing,
    /// The inspection failed for another reason.
    Unknown,
}

/// Classify a `network inspect` outcome.
pub fn classify_network_inspect(success: bool, stderr: &str) -> NetworkState {
    if success {
        return NetworkState::Exists;
    }
    let err = stderr.to_ascii_lowercase();
    if err.contains("no such network")
        || err.contains("not found")
        || err.contains("unable to find network")
    {
        NetworkState::Missing
    } else {
        NetworkState::Unknown
    }
}

async fn inspect_network(bin: &str, name: &str) -> Result<NetworkState, String> {
    let child = tokio::process::Command::new(bin)
        .args(network_inspect_args(name))
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .kill_on_drop(true)
        .output();
    match tokio::time::timeout(NETWORK_INSPECT_TIMEOUT, child).await {
        Ok(Ok(out)) => Ok(classify_network_inspect(
            out.status.success(),
            &String::from_utf8_lossy(&out.stderr),
        )),
        Ok(Err(e)) => Err(format!("cannot run {bin}: {e}")),
        Err(_) => Err(format!("{bin} network inspect timed out")),
    }
}

/// `CHECK_NETWORK` block plus issue codes: the network agent containers
/// run on (`TALAHON_CONTAINER_NETWORK`, default `talon-agents`) must exist.
/// Skipped without a container runtime (reported by the environment step).
async fn network_block(config: &TalonConfig) -> Option<(StatusBlock, Vec<String>)> {
    let runtime = ContainerRuntime::detect(&config.container_runtime).ok()?;
    let mut block = StatusBlock::new("CHECK_NETWORK");
    let mut issues = Vec::new();
    match RunnerConfig::from_talon_config(config).default_network {
        None => {
            block.set("NETWORK", "runtime-default");
            block.set(
                "NOTE",
                "TALAHON_CONTAINER_NETWORK selects the runtime default bridge: containers can reach \
                 each other and `talahon setup egress` rules do not apply",
            );
        }
        Some(network) => {
            block.set("NETWORK", &network);
            match inspect_network(runtime.bin(), &network).await {
                Ok(NetworkState::Exists) => block.set("EXISTS", "yes"),
                Ok(NetworkState::Missing) => {
                    block.set("EXISTS", "no");
                    issues.push("agent_network_missing".to_string());
                }
                Ok(NetworkState::Unknown) => {
                    block.set("EXISTS", "unknown");
                    issues.push("agent_network_unchecked".to_string());
                }
                Err(e) => {
                    block.set("EXISTS", "unknown");
                    block.set("ERROR", e);
                    issues.push("agent_network_unchecked".to_string());
                }
            }
        }
    }
    block.set(
        "STATUS",
        if issues.is_empty() {
            "success"
        } else {
            "failed"
        },
    );
    Some((block, issues))
}

/// Most folder names listed per field of `CHECK_INSTRUCTIONS`.
const MAX_LISTED_FOLDERS: usize = 50;

fn listed(names: &[String]) -> String {
    if names.is_empty() {
        return "none".to_string();
    }
    let mut out = names
        .iter()
        .take(MAX_LISTED_FOLDERS)
        .map(String::as_str)
        .collect::<Vec<_>>()
        .join(",");
    if names.len() > MAX_LISTED_FOLDERS {
        out.push_str(&format!(",... ({} more)", names.len() - MAX_LISTED_FOLDERS));
    }
    out
}

/// `CHECK_INSTRUCTIONS` block plus issue codes: which file holds the
/// instructions of each folder under `groups/` (`groups/global` included).
///
/// - `LEGACY`: folders that still read `CLAUDE.md` (the fallback). Not a
///   problem: a `HINT` says how to rename the file.
/// - `CONFLICT`: folders in which both names have content; runs there are
///   refused until the operator keeps exactly one (`instructions_conflict`).
/// - `UNSAFE`: folders in which either name is a symlink or another
///   non-regular file; runs there are refused (`instructions_unsafe`).
///
/// Symlinked folders are skipped (lanes refuse them anyway).
pub fn instructions_block(config: &TalonConfig) -> (StatusBlock, Vec<String>) {
    let mut block = StatusBlock::new("CHECK_INSTRUCTIONS");
    let mut issues = Vec::new();
    let mut folders: Vec<String> = std::fs::read_dir(&config.groups_dir)
        .map(|entries| {
            entries
                .filter_map(Result::ok)
                .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
                .filter_map(|e| e.file_name().into_string().ok())
                .collect()
        })
        .unwrap_or_default();
    folders.sort();
    let (mut legacy, mut conflicts, mut unsafe_entries) = (Vec::new(), Vec::new(), Vec::new());
    for folder in &folders {
        let files = match InstructionFiles::inspect(&config.groups_dir.join(folder)) {
            Ok(files) => files,
            Err(e) => {
                unsafe_entries.push(format!("{folder} (cannot be inspected: {e})"));
                continue;
            }
        };
        if let Some(found) = files.unsafe_entry() {
            unsafe_entries.push(format!("{folder} ({found})"));
        } else if files.is_conflict() {
            conflicts.push(folder.clone());
        } else if files.uses_legacy() {
            legacy.push(folder.clone());
        }
    }
    block.set("FOLDERS", folders.len());
    block.set("LEGACY", listed(&legacy));
    block.set("CONFLICT", listed(&conflicts));
    block.set("UNSAFE", listed(&unsafe_entries));
    if !legacy.is_empty() {
        block.set(
            "HINT",
            "the LEGACY folders still keep their instructions in CLAUDE.md, which is read as \
             before. Rename it when convenient: `mv groups/<folder>/CLAUDE.md \
             groups/<folder>/AGENT.md` (this replaces the AGENT.md mount-point stub Talahon put \
             there; use `git mv -f` for tracked files)",
        );
    }
    if !conflicts.is_empty() {
        issues.push("instructions_conflict".to_string());
    }
    if !unsafe_entries.is_empty() {
        issues.push("instructions_unsafe".to_string());
    }
    block.set(
        "STATUS",
        if issues.is_empty() {
            "success"
        } else {
            "failed"
        },
    );
    (block, issues)
}

/// `CHECK_RENAME` block: what this installation still uses under the name
/// the project had up to 2.x. Nothing in it is a problem (everything listed
/// keeps working until the next major version), so it never adds an issue.
///
/// - `DEPRECATED_KEYS`: `TALON_*` keys found in `.env` or the process
///   environment, each with the spelling to rename it to.
/// - `CONFLICTING_KEYS`: old keys whose `TALAHON_*` counterpart is set to a
///   different value. The new one wins; the old value is ignored.
/// - `CONFIG_DIR` / `CONFIG_DIR_NAME`: the one configuration directory in
///   effect (`current` = `~/.config/talahon`, `legacy` = `~/.config/talon`).
/// - `IGNORED_CONFIG_DIR`: `~/.config/talon` when both exist (never merged).
pub fn rename_block(
    keys: &[talon_core::env::LegacyKey],
    config_dir: &talon_core::paths::ConfigDir,
) -> StatusBlock {
    use talon_core::env::EnvSource;
    let mut block = StatusBlock::new("CHECK_RENAME");
    let describe = |k: &talon_core::env::LegacyKey| {
        let source = match k.source {
            EnvSource::File => ".env",
            EnvSource::Process => "environment",
        };
        format!("{} -> {} ({source})", k.legacy, k.current)
    };
    let deprecated: Vec<String> = keys.iter().map(describe).collect();
    let conflicts: Vec<String> = keys.iter().filter(|k| k.conflict).map(describe).collect();
    block.set("DEPRECATED_KEYS", listed(&deprecated));
    block.set("CONFLICTING_KEYS", listed(&conflicts));
    block.set("CONFIG_DIR", config_dir.path.display());
    block.set(
        "CONFIG_DIR_NAME",
        if config_dir.legacy {
            "legacy"
        } else {
            "current"
        },
    );
    if let Some(ignored) = &config_dir.ignored_legacy {
        block.set("IGNORED_CONFIG_DIR", ignored.display());
    }
    let mut hints: Vec<String> = Vec::new();
    if !deprecated.is_empty() {
        hints.push(
            "rename the DEPRECATED_KEYS (TALON_* -> TALAHON_*); the old spellings are read \
             until the next major version"
                .into(),
        );
    }
    if !conflicts.is_empty() {
        hints.push(
            "CONFLICTING_KEYS are set under both names with different values: the TALAHON_* \
             value is used, the TALON_* value is ignored; delete the old key"
                .into(),
        );
    }
    if config_dir.legacy {
        hints.push(format!(
            "the mount and sender allowlists are read from {} (pre-rename name); rename the \
             directory to ~/.config/{} when convenient",
            config_dir.path.display(),
            talon_core::paths::CONFIG_DIR_NAME
        ));
    }
    if let Some(ignored) = &config_dir.ignored_legacy {
        hints.push(format!(
            "{} is NOT read (only CONFIG_DIR is; the two are never merged): move anything \
             still needed from it, then delete it",
            ignored.display()
        ));
    }
    if !hints.is_empty() {
        block.set("HINT", hints.join("; "));
    }
    block.set("STATUS", "success");
    block
}

/// `AUDIT_VERIFY` block plus issue codes (skipped without a database).
fn audit_block(config: &TalonConfig) -> Option<(StatusBlock, Vec<String>)> {
    let path = default_db_path(&config.store_dir);
    if !path.exists() {
        return None;
    }
    let db = match Db::open_with_options(
        &path,
        &DbOptions {
            assistant_name: config.assistant_name.clone(),
        },
    ) {
        Ok(db) => db,
        Err(e) => {
            return Some((
                StatusBlock::new("AUDIT_VERIFY")
                    .field("STATUS", "failed")
                    .field("ERROR", e),
                vec!["audit_chain_tampered".to_string()],
            ));
        }
    };
    if let Err(e) = crate::audit_cmd::enable_audit_key(&db, config) {
        return Some((
            StatusBlock::new("AUDIT_VERIFY")
                .field("STATUS", "failed")
                .field("ERROR", format!("{e:#}")),
            vec!["audit_key_invalid".to_string()],
        ));
    }
    match crate::audit_cmd::verify_block(&db) {
        // An unkeyed chain is reported as a HINT in the block, not as an
        // issue: it is the default.
        Ok((block, true)) => Some((block, Vec::new())),
        Ok((block, false)) => {
            let issue = if block.get("CHAIN") == Some("unverifiable") {
                "audit_key_missing"
            } else {
                "audit_chain_tampered"
            };
            Some((block, vec![issue.to_string()]))
        }
        Err(e) => Some((
            StatusBlock::new("AUDIT_VERIFY")
                .field("STATUS", "failed")
                .field("ERROR", format!("{e:#}")),
            Vec::new(),
        )),
    }
}

/// The final `DOCTOR` block.
pub fn summary_block(issues: &[String]) -> StatusBlock {
    let mut block = StatusBlock::new("DOCTOR").field("VERSION", crate::VERSION);
    if issues.is_empty() {
        block.set("ISSUES", "none");
        block.set("STATUS", "success");
        return block;
    }
    block.set("ISSUES", issues.join(","));
    for (i, issue) in issues.iter().enumerate() {
        block.set(
            &format!("HINT_{}", i + 1),
            format!("{issue}: {}", hint(issue)),
        );
    }
    block.set("STATUS", "failed");
    block
}

/// Run every check and print the blocks. Returns the exit code.
pub async fn run(project_root: &Path, config: &TalonConfig) -> i32 {
    let ctx = SetupContext::detect(project_root);
    let no_args = StepArgs::new(Vec::<String>::new());
    let mut issues: Vec<String> = Vec::new();

    let env = run_step(Step::Environment, &no_args, &ctx).await;
    println!("{}", env.render());
    issues.extend(issues_of(env.block.as_ref()));

    let vllm = run_step(Step::Vllm, &no_args, &ctx).await;
    println!("{}", vllm.render());

    let (gateway, gw_issues) = gateway_block(config).await;
    println!("{gateway}");
    // The environment step already probed 127.0.0.1:<port>; the gateway
    // block probes the real bind address, which supersedes it.
    issues.retain(|i| !i.starts_with("gateway_port_"));
    issues.extend(gw_issues);

    let (exposure, exposure_issues) = exposure_block(config);
    println!("{exposure}");
    issues.extend(exposure_issues);

    if let Some((network, network_issues)) = network_block(config).await {
        println!("{network}");
        issues.extend(network_issues);
    }

    if config.env.file_value("HTTP_API_KEY").is_none() {
        issues.push("http_api_key_unset".to_string());
    }

    let (instructions, instruction_issues) = instructions_block(config);
    println!("{instructions}");
    issues.extend(instruction_issues);

    println!(
        "{}",
        rename_block(
            &config.env.legacy_keys(),
            // The same home the configuration was resolved against.
            &talon_core::paths::resolve_config_dir(
                config
                    .config_dir
                    .parent()
                    .and_then(Path::parent)
                    .unwrap_or(&ctx.home_dir),
            ),
        )
    );

    if let Some((block, audit_issues)) = audit_block(config) {
        println!("{block}");
        issues.extend(audit_issues);
    }

    let mut seen = std::collections::HashSet::new();
    issues.retain(|i| seen.insert(i.clone()));
    println!("{}", summary_block(&issues));
    if issues.is_empty() { 0 } else { 1 }
}

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

    #[test]
    fn rename_block_lists_deprecated_keys_conflicts_and_the_config_dir() {
        use std::collections::HashMap;
        use talon_core::env::EnvFile;
        use talon_core::paths::resolve_config_dir;

        let home = tempfile::tempdir().unwrap();
        // Up to date: nothing to report.
        let clean = rename_block(
            &EnvFile::from_str_content("TALAHON_VLLM_MODEL=q\n").legacy_keys_in(&HashMap::new()),
            &resolve_config_dir(home.path()),
        );
        assert_eq!(clean.get("DEPRECATED_KEYS"), Some("none"));
        assert_eq!(clean.get("CONFLICTING_KEYS"), Some("none"));
        assert_eq!(clean.get("CONFIG_DIR_NAME"), Some("current"));
        assert_eq!(clean.get("HINT"), None);
        assert_eq!(clean.get("STATUS"), Some("success"));

        // Upgraded from 2.x: old keys, one of them contradicting the new
        // spelling, and only ~/.config/talon.
        let old_dir = home.path().join(".config/talon");
        std::fs::create_dir_all(&old_dir).unwrap();
        let env = EnvFile::from_str_content(
            "TALON_VLLM_BASE_URL=http://old:8000\nTALON_VLLM_MODEL=old\nTALAHON_VLLM_MODEL=new\n",
        );
        let process: HashMap<String, String> =
            [("TALON_LOG".to_string(), "debug".to_string())].into();
        let block = rename_block(
            &env.legacy_keys_in(&process),
            &resolve_config_dir(home.path()),
        );
        assert_eq!(
            block.get("DEPRECATED_KEYS"),
            Some(
                "TALON_LOG -> TALAHON_LOG (environment),\
                 TALON_VLLM_BASE_URL -> TALAHON_VLLM_BASE_URL (.env),\
                 TALON_VLLM_MODEL -> TALAHON_VLLM_MODEL (.env)"
            )
        );
        assert_eq!(
            block.get("CONFLICTING_KEYS"),
            Some("TALON_VLLM_MODEL -> TALAHON_VLLM_MODEL (.env)")
        );
        assert_eq!(block.get("CONFIG_DIR_NAME"), Some("legacy"));
        assert_eq!(
            block.get("CONFIG_DIR"),
            Some(old_dir.display().to_string().as_str())
        );
        assert_eq!(block.get("IGNORED_CONFIG_DIR"), None);
        let hint = block.get("HINT").unwrap();
        assert!(hint.contains("TALAHON_*"), "{hint}");
        assert!(hint.contains("ignored"), "{hint}");
        assert!(hint.contains("~/.config/talahon"), "{hint}");
        // Deprecated spellings are not a failure.
        assert_eq!(block.get("STATUS"), Some("success"));
        // The new value is the one in effect.
        assert_eq!(env.get("TALAHON_VLLM_MODEL").as_deref(), Some("new"));

        // Both directories: the new one is authoritative, the old one is
        // named as ignored.
        std::fs::create_dir_all(home.path().join(".config/talahon")).unwrap();
        let block = rename_block(&[], &resolve_config_dir(home.path()));
        assert_eq!(block.get("CONFIG_DIR_NAME"), Some("current"));
        assert_eq!(
            block.get("IGNORED_CONFIG_DIR"),
            Some(old_dir.display().to_string().as_str())
        );
        assert!(block.get("HINT").unwrap().contains("NOT read"));
    }

    #[test]
    fn issue_parsing_and_summary() {
        let block = StatusBlock::new("CHECK_ENVIRONMENT")
            .field("ISSUES", "image_missing,vllm_not_configured");
        let issues = issues_of(Some(&block));
        assert_eq!(issues, vec!["image_missing", "vllm_not_configured"]);
        assert!(issues_of(Some(&StatusBlock::new("X").field("ISSUES", "none"))).is_empty());
        assert!(issues_of(None).is_empty());

        let summary = summary_block(&issues);
        assert_eq!(summary.get("STATUS"), Some("failed"));
        assert!(
            summary
                .get("HINT_2")
                .unwrap()
                .contains("TALAHON_VLLM_BASE_URL")
        );
        assert_eq!(summary_block(&[]).get("STATUS"), Some("success"));
    }

    fn cfg(content: &str) -> TalonConfig {
        TalonConfig::from_env(
            Path::new("/tmp/talon-doctor-test"),
            talon_core::env::EnvFile::from_str_content(content),
        )
    }

    #[test]
    fn audit_block_reports_unkeyed_hint_and_key_problems() {
        const KEY: &str = "7a9c1e3b5d7f9a0c2e4b6d8f0a1c3e5b7d9f1a3c5e7b9d0f2a4c6e8b0d1f3a5c";
        let dir = tempfile::tempdir().unwrap();
        let config = |env: &str| {
            TalonConfig::from_env(dir.path(), talon_core::env::EnvFile::from_str_content(env))
        };
        let record = |config: &TalonConfig| {
            let db = Db::open(&default_db_path(&config.store_dir)).unwrap();
            crate::audit_cmd::enable_audit_key(&db, config).unwrap();
            db.record_audit(&talon_core::audit::event(
                "talon.start",
                "talon",
                None,
                "info",
                serde_json::json!({}),
            ))
            .unwrap();
        };
        // No database yet: nothing to report.
        assert!(audit_block(&config("")).is_none());

        // Unkeyed chain: a hint, not an issue (the exit code is unchanged).
        record(&config(""));
        let (block, issues) = audit_block(&config("")).unwrap();
        assert!(issues.is_empty(), "{issues:?}");
        assert_eq!(block.get("STATUS"), Some("success"));
        assert!(block.get("HINT").unwrap().contains("TALAHON_AUDIT_KEY"));

        // Invalid key.
        let (block, issues) = audit_block(&config("TALAHON_AUDIT_KEY=tooshort-pw\n")).unwrap();
        assert_eq!(issues, vec!["audit_key_invalid"]);
        assert!(!format!("{block}").contains("tooshort-pw"));
        assert!(hint("audit_key_invalid").contains("openssl rand -hex 32"));

        // Keyed chain: no hint; without the key afterwards: an issue.
        let keyed = config(&format!("TALAHON_AUDIT_KEY={KEY}\n"));
        record(&keyed);
        let (block, issues) = audit_block(&keyed).unwrap();
        assert!(issues.is_empty(), "{block}");
        assert_eq!(block.get("HINT"), None);
        assert_eq!(block.get("CHECKPOINT"), Some("verified"));
        assert!(!format!("{block}").contains(KEY));
        let (block, issues) = audit_block(&config("")).unwrap();
        assert_eq!(issues, vec!["audit_key_missing"]);
        assert_eq!(block.get("CHAIN"), Some("unverifiable"));
        assert!(hint("audit_key_missing").contains("TALAHON_AUDIT_KEY"));
    }

    /// The process environment overrides `.env` for non-secret keys.
    fn env_overridden(keys: &[&str]) -> bool {
        keys.iter().any(|k| talon_core::env::process_var_is_set(k))
    }

    #[test]
    fn exposure_flags_missing_vllm_key_and_public_http_bind() {
        if env_overridden(&[
            "TALAHON_VLLM_BASE_URL",
            "TALAHON_VLLM_MODEL",
            "TALAHON_VLLM_ALLOW_NO_API_KEY",
            "COPILOT_HTTP_BIND",
        ]) {
            return;
        }
        const VLLM: &str = "TALAHON_VLLM_BASE_URL=http://vllm:8000\nTALAHON_VLLM_MODEL=q\n";

        let (block, issues) = exposure_block(&cfg(&format!("{VLLM}COPILOT_HTTP_BIND=0.0.0.0\n")));
        assert_eq!(issues, vec!["vllm_api_key_unset", "http_api_public_bind"]);
        assert_eq!(block.get("VLLM_API_KEY"), Some("unset"));
        assert_eq!(block.get("STATUS"), Some("failed"));
        let summary = summary_block(&issues);
        assert!(
            summary
                .get("HINT_1")
                .unwrap()
                .contains("TALAHON_VLLM_API_KEY")
        );
        assert!(summary.get("HINT_2").unwrap().contains("127.0.0.1"));

        let (_, issues) = exposure_block(&cfg(&format!("{VLLM}COPILOT_HTTP_BIND=::\n")));
        assert!(issues.contains(&"http_api_public_bind".to_string()));

        let (block, issues) = exposure_block(&cfg(&format!(
            "{VLLM}TALAHON_VLLM_API_KEY=k\nCOPILOT_HTTP_BIND=127.0.0.1\n"
        )));
        assert!(issues.is_empty(), "{issues:?}");
        assert_eq!(block.get("VLLM_API_KEY"), Some("set"));
        assert_eq!(block.get("STATUS"), Some("success"));

        let (block, issues) = exposure_block(&cfg(&format!(
            "{VLLM}TALAHON_VLLM_ALLOW_NO_API_KEY=true\nCOPILOT_HTTP_BIND=10.0.0.5\n"
        )));
        assert!(issues.is_empty(), "{issues:?}");
        assert_eq!(block.get("VLLM_API_KEY"), Some("unset_allowed"));

        // Without vLLM, `vllm_not_configured` (environment step) covers it.
        let (_, issues) = exposure_block(&cfg("COPILOT_HTTP_BIND=127.0.0.1\n"));
        assert!(issues.is_empty(), "{issues:?}");

        let (block, issues) = exposure_block(&cfg("COPILOT_HTTP_BIND=not-an-ip\n"));
        assert_eq!(issues, vec!["http_config_invalid"]);
        assert!(block.get("ERROR").is_some());
    }

    #[test]
    fn network_inspect_classification() {
        assert_eq!(classify_network_inspect(true, ""), NetworkState::Exists);
        assert_eq!(
            classify_network_inspect(
                false,
                "Error response from daemon: network talon-agents not found"
            ),
            NetworkState::Missing
        );
        assert_eq!(
            classify_network_inspect(false, "Error: No such network: talon-agents"),
            NetworkState::Missing
        );
        assert_eq!(
            classify_network_inspect(
                false,
                "Error: unable to find network with name or ID talon-agents"
            ),
            NetworkState::Missing
        );
        assert_eq!(
            classify_network_inspect(false, "Cannot connect to the Docker daemon"),
            NetworkState::Unknown
        );
    }

    #[tokio::test]
    async fn network_inspect_runs_the_runtime_binary() {
        let tmp = tempfile::tempdir().unwrap();
        let fake = tmp.path().join("fake-docker");
        std::fs::write(
            &fake,
            "#!/bin/sh\n[ \"$1 $2 $3\" = \"network inspect talon-agents\" ] && exit 0\n\
             echo \"Error: No such network: $3\" >&2\nexit 1\n",
        )
        .unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
        let bin = fake.to_string_lossy();
        assert_eq!(
            inspect_network(&bin, "talon-agents").await,
            Ok(NetworkState::Exists)
        );
        assert_eq!(
            inspect_network(&bin, "other").await,
            Ok(NetworkState::Missing)
        );
        assert!(inspect_network("/nonexistent/docker", "x").await.is_err());
    }

    #[test]
    fn every_known_issue_has_a_specific_hint() {
        for issue in [
            "container_runtime_missing",
            "image_missing",
            "vllm_not_configured",
            "vllm_auth_failed",
            "gateway_bind_loopback",
            "vllm_api_key_unset",
            "agent_network_missing",
            "agent_network_unchecked",
            "http_api_public_bind",
            "http_config_invalid",
            "http_api_key_unset",
            "audit_chain_tampered",
            "instructions_conflict",
            "instructions_unsafe",
        ] {
            assert_ne!(hint(issue), hint("unknown_issue"), "{issue}");
        }
    }

    #[test]
    fn instructions_block_reports_legacy_conflicting_and_unsafe_files() {
        use talon_security::instructions::{
            AGENT_MOUNT_STUB, INSTRUCTIONS_PLACEHOLDER, LEGACY_MOUNT_STUB,
        };
        let dir = tempfile::tempdir().unwrap();
        let config =
            TalonConfig::from_env(dir.path(), talon_core::env::EnvFile::from_str_content(""));
        // No groups directory at all.
        let (block, issues) = instructions_block(&config);
        assert_eq!(block.get("FOLDERS"), Some("0"));
        assert_eq!(block.get("STATUS"), Some("success"));
        assert!(issues.is_empty());

        let groups = &config.groups_dir;
        let write = |rel: &str, content: &str| {
            let path = groups.join(rel);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, content).unwrap();
        };
        // Migrated folders (with the stub the host leaves at the old name).
        write("main/AGENT.md", "main rules");
        write("main/CLAUDE.md", LEGACY_MOUNT_STUB);
        write("global/AGENT.md", "global rules");
        // No instructions.
        write("empty/AGENT.md", INSTRUCTIONS_PLACEHOLDER);
        write("old-empty/CLAUDE.md", INSTRUCTIONS_PLACEHOLDER);
        std::fs::create_dir_all(groups.join("bare")).unwrap();
        // Fallback in use: before the first run, and after it (stub).
        write("copilot/CLAUDE.md", "old rules");
        write("team/CLAUDE.md", "old rules");
        write("team/AGENT.md", AGENT_MOUNT_STUB);
        let (block, issues) = instructions_block(&config);
        assert_eq!(block.get("FOLDERS"), Some("7"));
        assert_eq!(block.get("LEGACY"), Some("copilot,team"));
        assert_eq!(block.get("CONFLICT"), Some("none"));
        assert_eq!(block.get("UNSAFE"), Some("none"));
        assert!(
            block
                .get("HINT")
                .unwrap()
                .contains("mv groups/<folder>/CLAUDE.md")
        );
        // A hint, not an error.
        assert_eq!(block.get("STATUS"), Some("success"));
        assert!(issues.is_empty());

        // Both names with content: runs are refused; reported as a
        // problem with the fix.
        write("both/AGENT.md", "new rules");
        write("both/CLAUDE.md", "old rules");
        let (block, issues) = instructions_block(&config);
        assert_eq!(block.get("CONFLICT"), Some("both"));
        assert_eq!(block.get("LEGACY"), Some("copilot,team"));
        assert_eq!(block.get("STATUS"), Some("failed"));
        assert_eq!(issues, vec!["instructions_conflict"]);
        assert!(hint("instructions_conflict").contains("keep the one you wrote"));
        assert!(hint("instructions_conflict").contains("keep exactly one"));

        // A symlink under either name (and a symlinked folder is skipped).
        std::fs::remove_file(groups.join("both/CLAUDE.md")).unwrap();
        std::os::unix::fs::symlink("AGENT.md", groups.join("both/CLAUDE.md")).unwrap();
        std::os::unix::fs::symlink("planted.md", groups.join("copilot/AGENT.md")).unwrap();
        std::os::unix::fs::symlink(groups.join("main"), groups.join("alias")).unwrap();
        let (block, issues) = instructions_block(&config);
        assert_eq!(block.get("FOLDERS"), Some("8"));
        let unsafe_entries = block.get("UNSAFE").unwrap();
        assert!(
            unsafe_entries.contains("both (CLAUDE.md is a symlink"),
            "{unsafe_entries}"
        );
        assert!(
            unsafe_entries.contains("copilot (AGENT.md is a symlink"),
            "{unsafe_entries}"
        );
        assert_eq!(block.get("LEGACY"), Some("team"));
        assert_eq!(issues, vec!["instructions_unsafe"]);

        let many: Vec<String> = (0..60).map(|i| format!("g{i}")).collect();
        assert!(listed(&many).ends_with(",... (10 more)"));
    }
}