trustee-api 0.14.2

REST + WebSocket API server for Trustee agent
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
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
//! THQ (Torpi) auto-registration.
//!
//! Two registration modes (16E):
//!
//! 1. **Per-agent-user** (the agents-as-users model): every directory under
//!    `~/.trustee/users/{hash}/` whose overlay config
//!    (`users/{hash}/config/trustee.toml`) carries a `[thq]` section is
//!    registered as its OWN agent in THQ — one process, N agents. Each entry
//!    gets a stable per-user id (`users/{hash}/agent_id`), an identity
//!    Bearer from that user's `.env` (attribution; the THQ registration
//!    route is open), and a heartbeat whose `status` reflects live session
//!    state (`idle` / `running`).
//!
//! 2. **Legacy single** (pre-0.12 behavior): when NO per-user `[thq]`
//!    entries exist but the process config has one, the whole process
//!    registers once under `[thq].agent_name` with id `~/.trustee/agent_id`.
//!
//! The per-user `[thq]` sections are read from the overlay FILES at boot.
//! Changing them requires a restart — MCP tool sets stay hot-reloadable,
//! THQ identity does not.
//!
//! Registration payloads match Torpi's `AgentEntry` and re-POST with the
//! same `id` is an upsert, which is exactly what the heartbeat does.

use std::time::Duration;

use serde::{Deserialize, Serialize};

/// Configuration for THQ registration, parsed from a `[thq]` TOML section.
#[derive(Debug, Clone)]
pub struct ThqConfig {
    /// Base URL of the Torpi instance (e.g. <https://torpi.tanbal.ir>).
    pub torpi_url: String,
    /// This agent's externally-reachable URL (e.g. <https://192.168.1.10:3000>).
    pub advertise_url: String,
    /// Human-friendly agent name (e.g. "trustee-podtan").
    pub agent_name: String,
    /// Agent role (default: "general").
    pub agent_role: String,
    /// Hardcoded capabilities list.
    pub capabilities: Vec<String>,
    /// Hardcoded tags list.
    pub tags: Vec<String>,
    /// Re-registration interval in seconds (default: 30).
    pub heartbeat_interval: u64,
    /// Optional Bearer token for authenticating with the THQ API.
    /// Sent as `Authorization: Bearer <token>` on every registration request.
    /// When None, registration is unauthenticated (legacy Torpi instances).
    pub registration_token: Option<String>,
    /// Owning user's subject identifier (typically their JWT `sub` UUID).
    /// When set, Torpi associates this agent with the user so they can
    /// manage it through the THQ UI without admin privileges.
    /// Set from the `[thq] owner_id` config field.
    /// 16E: for agent-users this MUST be the agent's Kanidm `sub` — it is
    /// the key used to read live session state for the busy/idle heartbeat,
    /// matching the agent `user_key` pin (agents are keyed by `sub`).
    pub owner_id: Option<String>,
    /// Issue 8e0a1215: the agent DECLARES which env var holds her Kanidm
    /// service credential — e.g. `service_token = "${PAYDAR_SERVICE_ACCOUNT}"`.
    /// Resolved from the agent's per-user `.env` at boot; a bare key name
    /// (without the `${…}` wrapper) is accepted too. This is the ONLY
    /// credential source — the legacy hardcoded key scan
    /// (THQ/FAME/FARZAN/KANIDM_SERVICE_TOKEN) was REMOVED in api 0.13.0,
    /// so an agent without this field is NOT dispatchable (loud boot error
    /// when `owner_id` is set). Declared but unresolved → loud boot ERROR
    /// as well. Never a silent skip.
    pub service_token: Option<String>,
}

impl ThqConfig {
    /// Parse from a trustee config TOML (shared config or a per-user overlay).
    ///
    /// Reads the `[thq]` section. Returns `None` if the section is absent
    /// (registration disabled).  `torpi_url` and `advertise_url` are required;
    /// all other fields have defaults.
    pub fn from_toml(config_toml: &str) -> Option<Self> {
        let table: toml::Table = toml::from_str(config_toml).ok()?;
        let thq = table.get("thq")?.as_table()?;

        let torpi_url = thq
            .get("torpi_url")
            .and_then(|v| v.as_str())
            .map(|s| s.trim_end_matches('/').to_string())?;
        let advertise_url = thq
            .get("advertise_url")
            .and_then(|v| v.as_str())
            .map(|s| s.trim_end_matches('/').to_string())?;
        let agent_name = thq
            .get("agent_name")
            .and_then(|v| v.as_str())
            .map(String::from)
            .unwrap_or_else(|| {
                std::env::var("HOSTNAME")
                    .or_else(|_| std::env::var("COMPUTERNAME"))
                    .unwrap_or_else(|_| "trustee".to_string())
            });
        let agent_role = thq
            .get("agent_role")
            .and_then(|v| v.as_str())
            .unwrap_or("general")
            .to_string();
        let capabilities = thq
            .get("capabilities")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();
        let tags = thq
            .get("tags")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();
        let heartbeat_interval = thq
            .get("heartbeat_interval")
            .and_then(|v| v.as_integer())
            .map(|v| v as u64)
            .unwrap_or(30);
        let registration_token = thq
            .get("registration_token")
            .and_then(|v| v.as_str())
            .map(String::from);
        let owner_id = thq
            .get("owner_id")
            .and_then(|v| v.as_str())
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());
        let service_token = thq
            .get("service_token")
            .and_then(|v| v.as_str())
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());

        Some(Self {
            torpi_url,
            advertise_url,
            agent_name,
            agent_role,
            capabilities,
            tags,
            heartbeat_interval,
            registration_token,
            owner_id,
            service_token,
        })
    }
}

/// Registration payload matching Torpi's `AgentEntry` struct.
#[derive(Debug, Serialize, Deserialize)]
struct AgentEntry {
    id: String,
    name: String,
    endpoint: String,
    role: String,
    capabilities: Vec<String>,
    status: String,
    tags: Vec<String>,
    last_seen: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    owner_id: Option<String>,
}

/// One discovered agent-user (16E): a `users/{hash}/` home whose overlay
/// config carries a `[thq]` section.
#[derive(Debug, Clone)]
pub struct DiscoveredAgent {
    /// Hash directory name under `~/.trustee/users/`.
    pub user_hash: String,
    /// The user's home directory (`~/.trustee/users/{hash}/`).
    pub user_home: std::path::PathBuf,
    /// Parsed `[thq]` section from the user's overlay config.
    pub config: ThqConfig,
}

/// Scan `~/.trustee/users/*/config/trustee.toml` for per-user `[thq]`
/// sections. Deterministic order (sorted by hash) so startup logs and
/// heartbeat staggering are reproducible.
pub fn discover_user_agents() -> Vec<DiscoveredAgent> {
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .unwrap_or_else(|_| ".".to_string());
    discover_user_agents_in(
        &std::path::PathBuf::from(home)
            .join(".trustee")
            .join("users"),
    )
}

/// Testable core of [`discover_user_agents`].
pub fn discover_user_agents_in(users_dir: &std::path::Path) -> Vec<DiscoveredAgent> {
    let mut found = Vec::new();
    let Ok(entries) = std::fs::read_dir(users_dir) else {
        return found;
    };
    for entry in entries.flatten() {
        let user_home = entry.path();
        if !user_home.is_dir() {
            continue;
        }
        let overlay = user_home.join("config").join("trustee.toml");
        let Ok(content) = std::fs::read_to_string(&overlay) else {
            continue;
        };
        if let Some(config) = ThqConfig::from_toml(&content) {
            found.push(DiscoveredAgent {
                user_hash: user_home
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_default(),
                user_home,
                config,
            });
        }
    }
    found.sort_by(|a, b| a.user_hash.cmp(&b.user_hash));
    found
}

/// Resolve or create a persistent agent ID at an explicit file path (16E).
///
/// Reads from the file if present; otherwise generates a UUID v4, persists
/// it, and returns it. Per-agent identities live at
/// `users/{hash}/agent_id`; the legacy single identity at
/// `~/.trustee/agent_id`.
fn resolve_agent_id_at(id_file: &std::path::Path) -> Result<String, std::io::Error> {
    // Try existing
    if id_file.exists() {
        let id = std::fs::read_to_string(id_file)?;
        let id = id.trim().to_string();
        if !id.is_empty() {
            return Ok(id);
        }
    }

    // Generate new
    let id = uuid::Uuid::new_v4().to_string();
    if let Some(parent) = id_file.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(id_file, &id)?;
    tracing::info!("Generated new agent ID: {} -> {}", id, id_file.display());
    Ok(id)
}

/// Legacy single-process id (`~/.trustee/agent_id`).
fn resolve_agent_id() -> Result<String, std::io::Error> {
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .unwrap_or_else(|_| ".".to_string());
    resolve_agent_id_at(
        &std::path::PathBuf::from(home)
            .join(".trustee")
            .join("agent_id"),
    )
}

/// The issuer declared by the overlay's first `service-account` credential —
/// the origin the agent's service token was minted for (16F: exchange is
/// origin-bound, so it must travel with the entry).
fn read_overlay_service_issuer(user_home: &std::path::Path) -> Option<String> {
    let overlay = std::fs::read_to_string(user_home.join("config").join("trustee.toml")).ok()?;
    let v: toml::Value = overlay.parse().ok()?;
    let creds = v.get("mcp")?.get("credentials")?.as_table()?;
    for (_name, cred) in creds {
        if cred.get("type").and_then(|t| t.as_str()) == Some("service-account") {
            if let Some(issuer) = cred.get("issuer_url").and_then(|i| i.as_str()) {
                return Some(issuer.to_string());
            }
        }
    }
    None
}

/// 16F: every service-account issuer declared by the discovered agent-user
/// overlays — the vhosts the deployed agents' tokens are actually minted on.
pub fn discover_service_issuers() -> Vec<String> {
    let mut out = Vec::new();
    for agent in discover_user_agents() {
        if let Some(issuer) = read_overlay_service_issuer(&agent.user_home) {
            if !out.contains(&issuer) {
                out.push(issuer);
            }
        }
    }
    out
}

/// Issue 8e0a1215: outcome of resolving an agent-user's dispatch credential.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServiceTokenResolution {
    /// `[thq].service_token` declared and resolved from the agent's `.env`.
    /// The ONLY way an agent becomes dispatchable — the hardcoded key scan
    /// (THQ/FAME/FARZAN/KANIDM_SERVICE_TOKEN) was removed in api 0.13.0.
    Resolved(String),
    /// No `[thq].service_token` declared at all. The agent is NOT
    /// dispatchable; with an `owner_id` present (dispatch intent) boot
    /// FAILS LOUD — an undeclared credential is the same silent-skip shape
    /// this issue was filed to kill.
    Undeclared,
    /// `[thq].service_token` DECLARED but its variable did not resolve from
    /// the agent's `.env` (missing file, missing key, or an unresolved
    /// `${…}` placeholder value). Boot FAILS LOUD naming agent + variable;
    /// the agent is NOT dispatchable. Never a silent skip.
    DeclaredUnresolved { var: String },
}

/// Extract the env-var name from a `[thq].service_token` declaration.
/// Accepts the canonical `"${KEY}"` wrapper and a bare `"KEY"`. Malformed
/// input returns the raw trimmed string — the lookup then fails and the
/// boot error names exactly what the config said.
fn declared_service_var(decl: &str) -> String {
    let s = decl.trim();
    match s.strip_prefix("${").and_then(|r| r.strip_suffix('}')) {
        Some(inner) => inner.trim().to_string(),
        None => s.to_string(),
    }
}

/// Look up `key` in a `.env` file (`KEY=value`, quotes unwrapped, `#`
/// comments skipped). A missing key, an empty value, or an unresolved
/// `${…}` placeholder value (the house "never provisioned" convention)
/// all yield None. The user's `.env` is the
/// ONLY source — no process-env fallback, so a declared credential must be
/// provisioned where the agent's identity lives.
fn lookup_env_value(env_path: &std::path::Path, key: &str) -> Option<String> {
    if key.is_empty() {
        return None;
    }
    let env = std::fs::read_to_string(env_path).ok()?;
    let prefix = format!("{key}=");
    for line in env.lines() {
        let line = line.trim();
        if line.starts_with('#') {
            continue;
        }
        if let Some(value) = line.strip_prefix(&prefix) {
            let value = value.trim().trim_matches('"').trim_matches('\'');
            if !value.is_empty() && !value.starts_with("${") {
                return Some(value.to_string());
            }
        }
    }
    None
}

/// Issue 8e0a1215: resolve an agent-user's dispatch credential.
///
/// The `[thq].service_token` declaration is the ONLY source — the config
/// declares, the code never guesses. Declared-but-unresolved and
/// undeclared are both distinct loud outcomes
/// ([`ServiceTokenResolution`]); neither silently degrades.
pub fn resolve_user_service_token(
    user_home: &std::path::Path,
    config: &ThqConfig,
) -> ServiceTokenResolution {
    match config.service_token.as_deref() {
        Some(decl) => {
            let var = declared_service_var(decl);
            match lookup_env_value(&user_home.join(".env"), &var) {
                Some(value) => ServiceTokenResolution::Resolved(value),
                None => ServiceTokenResolution::DeclaredUnresolved { var },
            }
        }
        None => ServiceTokenResolution::Undeclared,
    }
}

/// Busy = any of the user's sessions currently running.
///
/// `user_key` is the THQ `owner_id` (the agent's Kanidm `sub`) — the same
/// key the agent authenticates with, per the 16D agent user_key pin.
/// Session mutexes are tokio (async): Arc clones are collected and the
/// DashMap guard is dropped BEFORE any await.
async fn is_busy(state: &crate::state::ServerState, user_key: Option<&str>) -> bool {
    let Some(key) = user_key else {
        return false;
    };
    let Some(user) = state.sessions.get(key) else {
        return false;
    };
    let session_locks: Vec<_> = user
        .sessions
        .iter()
        .map(|e| e.value().session.clone())
        .collect();
    drop(user);
    for session in session_locks {
        if session.lock().await.workflow_state == trustee_core::types::WorkflowState::Running {
            return true;
        }
    }
    false
}

/// Build a reqwest client that accepts self-signed certs (Torpi may use them).
fn build_http_client() -> reqwest::Client {
    reqwest::Client::builder()
        .danger_accept_invalid_certs(true)
        .timeout(Duration::from_secs(10))
        .build()
        .expect("Failed to build HTTP client for THQ registration")
}

/// The registration/heartbeat loop: POST the entry immediately, then re-POST
/// every heartbeat interval. `status` is recomputed every tick from live
/// session state when `state` is provided. Failures are logged, never fatal.
async fn registration_loop(
    client: reqwest::Client,
    url: String,
    mut entry: AgentEntry,
    interval_secs: u64,
    bearer: Option<String>,
    status_key: Option<String>,
    state: Option<crate::state::ServerState>,
    label: String,
) {
    let mut first = true;
    loop {
        entry.status = match state.as_ref() {
            Some(state) => {
                if is_busy(state, status_key.as_deref()).await {
                    "running".to_string()
                } else {
                    "idle".to_string()
                }
            }
            None => "idle".to_string(),
        };
        entry.last_seen = chrono::Utc::now().to_rfc3339();

        let body = serde_json::to_value(&entry).unwrap_or_default();

        let mut request = client.post(&url).json(&body);
        if let Some(ref token) = bearer {
            request = request.header("Authorization", format!("Bearer {}", token));
        }

        match request.send().await {
            Ok(resp) => {
                let status = resp.status();
                if status.is_success() {
                    if first {
                        tracing::info!(
                            "THQ registration successful: {} at {}",
                            entry.name,
                            entry.endpoint
                        );
                        first = false;
                    } else {
                        tracing::debug!("THQ heartbeat successful: {}", label);
                    }
                } else {
                    let text = resp.text().await.unwrap_or_default();
                    tracing::warn!(
                        "THQ registration returned {}: {} ({})",
                        status,
                        text.chars().take(200).collect::<String>(),
                        label
                    );
                }
            }
            Err(e) => {
                if first {
                    tracing::warn!("THQ registration failed (will retry): {} ({})", e, label);
                } else {
                    tracing::debug!("THQ heartbeat failed: {} ({})", e, label);
                }
            }
        }

        tokio::time::sleep(Duration::from_secs(interval_secs)).await;
    }
}

/// Legacy single-process registration (pre-0.12 behavior). Used only when
/// NO per-user `[thq]` entries exist.
pub fn spawn(config: ThqConfig) {
    let agent_id = match resolve_agent_id() {
        Ok(id) => id,
        Err(e) => {
            tracing::error!(
                "Failed to resolve agent ID: {} — THQ registration disabled",
                e
            );
            return;
        }
    };

    tracing::info!(
        "THQ registration enabled: agent={} (id={}) -> {}",
        config.agent_name,
        agent_id,
        config.torpi_url
    );

    let entry = AgentEntry {
        id: agent_id,
        name: config.agent_name.clone(),
        endpoint: config.advertise_url.clone(),
        role: config.agent_role.clone(),
        capabilities: config.capabilities.clone(),
        status: "idle".to_string(),
        tags: config.tags.clone(),
        last_seen: chrono::Utc::now().to_rfc3339(),
        owner_id: config.owner_id.clone(),
    };

    let url = format!("{}/thq/api/agents", config.torpi_url);
    let bearer = config.registration_token.clone();

    tokio::spawn(registration_loop(
        build_http_client(),
        url,
        entry,
        config.heartbeat_interval,
        bearer,
        None,
        None,
        config.agent_name,
    ));
}

/// 16E: register EVERY agent-user found under `~/.trustee/users/` (per-user
/// `[thq]` overlays); fall back to the legacy single-process registration
/// only when none exist — so a legacy install keeps its exact behavior and
/// an agents-as-users install never double-registers a machine entry.
pub fn spawn_all(legacy: Option<ThqConfig>, state: crate::state::ServerState) {
    let agents = discover_user_agents();
    if agents.is_empty() {
        match legacy {
            Some(config) => {
                tracing::info!(
                    "THQ: no per-user [thq] entries under users/ — legacy single registration ({})",
                    config.agent_name
                );
                spawn(config);
            }
            None => tracing::debug!("THQ registration not configured (no [thq] section)"),
        }
        return;
    }

    tracing::info!(
        "THQ: registering {} agent-users from users/ (legacy_single=false)",
        agents.len()
    );
    let client = build_http_client();

    for agent in agents.iter() {
        let label = format!("{} ({})", agent.config.agent_name, agent.user_hash);
        let agent_id = match resolve_agent_id_at(&agent.user_home.join("agent_id")) {
            Ok(id) => id,
            Err(e) => {
                tracing::warn!(
                    "THQ: cannot resolve agent id for {} — skipping: {}",
                    label,
                    e
                );
                continue;
            }
        };
        // Issue 8e0a1215: credential resolution is config-DECLARED, not
        // code-guessed. An explicit [thq].service_token wins; absent →
        // legacy scan; declared-but-unresolved → LOUD error, non-dispatchable.
        let resolution = resolve_user_service_token(&agent.user_home, &agent.config);
        let bearer = match &resolution {
            ServiceTokenResolution::Resolved(token) => Some(token.clone()),
            ServiceTokenResolution::Undeclared => {
                tracing::error!(
                    "THQ: agent {} has NO [thq].service_token declaration — dispatch credentials are \
                     config-declared since api 0.13.0 (the hardcoded THQ/FAME/FARZAN/KANIDM key scan \
                     was removed). Add service_token = \"${{YOUR_KEY}}\" to the [thq] section of {} — \
                     agent NOT dispatchable until then.",
                    label,
                    agent.user_home.join("config").join("trustee.toml").display()
                );
                None
            }
            ServiceTokenResolution::DeclaredUnresolved { var } => {
                tracing::error!(
                    "THQ: agent {} declared [thq].service_token = \"${{{var}}}\" but {var} is NOT set in {} — \
                     agent NOT dispatchable. Set the variable in the agent's .env (a placeholder value \
                     like ${{...}} does not count) or fix the declaration.",
                    label,
                    agent.user_home.join(".env").display()
                );
                None
            }
        };
        let url = format!("{}/thq/api/agents", agent.config.torpi_url);

        // 16F: register the dispatch target so THQ-proxied sessions can be
        // impersonated AS this agent-user (see crate::xagent).
        if agent.config.owner_id.as_deref().map(str::len).unwrap_or(0) > 0 {
            if !matches!(resolution, ServiceTokenResolution::Resolved(_)) {
                // Already SCREAMED above — the agent stays out of the
                // dispatch table (non-dispatchable), registration continues
                // so the THQ UI still shows her. Never a silent skip.
            } else {
                state.thq_dispatch.insert(
                    agent.config.agent_name.clone(),
                    crate::state::ThqDispatchEntry {
                        user_key: agent.config.owner_id.clone().unwrap_or_default(),
                        service_token: bearer.clone(),
                        issuer_url: read_overlay_service_issuer(&agent.user_home),
                    },
                );
            }
        } else {
            tracing::warn!(
                "THQ: agent-user {} has no [thq].owner_id — NOT dispatchable (16F)",
                label
            );
        }

        let entry = AgentEntry {
            id: agent_id.clone(),
            name: agent.config.agent_name.clone(),
            endpoint: agent.config.advertise_url.clone(),
            role: agent.config.agent_role.clone(),
            capabilities: agent.config.capabilities.clone(),
            status: "idle".to_string(),
            tags: agent.config.tags.clone(),
            last_seen: chrono::Utc::now().to_rfc3339(),
            owner_id: agent.config.owner_id.clone(),
        };

        tracing::info!(
            "THQ: agent-user {} -> {} as id {} (owner={})",
            label,
            agent.config.torpi_url,
            agent_id,
            agent.config.owner_id.as_deref().unwrap_or("<none>")
        );

        tokio::spawn(registration_loop(
            client.clone(),
            url,
            entry,
            agent.config.heartbeat_interval,
            bearer,
            agent.config.owner_id.clone(),
            Some(state.clone()),
            label,
        ));
    }
}

/// Shared test fixture: a fresh temp dir standing in for a user home.
#[cfg(test)]
fn temp_users_dir(tag: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("trustee-thq-test-{}-{}", tag, std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

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

    #[test]
    fn parse_full_config() {
        let toml = r#"
[thq]
torpi_url = "https://torpi.example.com"
advertise_url = "https://10.0.0.5:3000"
agent_name = "edge-paris"
agent_role = "code-review"
capabilities = ["rust", "docker"]
tags = ["edge", "arm64"]
heartbeat_interval = 60
"#;
        let cfg = ThqConfig::from_toml(toml).expect("should parse");
        assert_eq!(cfg.torpi_url, "https://torpi.example.com");
        assert_eq!(cfg.advertise_url, "https://10.0.0.5:3000");
        assert_eq!(cfg.agent_name, "edge-paris");
        assert_eq!(cfg.agent_role, "code-review");
        assert_eq!(cfg.capabilities, vec!["rust", "docker"]);
        assert_eq!(cfg.tags, vec!["edge", "arm64"]);
        assert_eq!(cfg.heartbeat_interval, 60);
        assert!(cfg.registration_token.is_none());
        assert!(cfg.owner_id.is_none());
    }

    #[test]
    fn parse_minimal_config() {
        let toml = r#"
[thq]
torpi_url = "https://torpi.example.com/"
advertise_url = "https://10.0.0.5:3000/"
"#;
        let cfg = ThqConfig::from_toml(toml).expect("should parse");
        assert_eq!(cfg.torpi_url, "https://torpi.example.com"); // trailing slash trimmed
        assert_eq!(cfg.advertise_url, "https://10.0.0.5:3000");
        assert_eq!(cfg.agent_role, "general");
        assert!(cfg.capabilities.is_empty());
        assert!(cfg.tags.is_empty());
        assert_eq!(cfg.heartbeat_interval, 30);
        assert!(cfg.registration_token.is_none());
        assert!(cfg.owner_id.is_none());
    }

    #[test]
    fn parse_registration_token() {
        let toml = r#"
[thq]
torpi_url = "https://torpi.example.com"
advertise_url = "https://10.0.0.5:3000"
registration_token = "secret-agent-token"
"#;
        let cfg = ThqConfig::from_toml(toml).expect("should parse");
        assert_eq!(
            cfg.registration_token.as_deref(),
            Some("secret-agent-token")
        );
    }

    #[test]
    fn parse_owner_id() {
        let toml = r#"
[thq]
torpi_url = "https://torpi.example.com"
advertise_url = "https://10.0.0.5:3000"
owner_id = "d0f5c4ba-9c10-4ff7-85a4-f2c0e588a55a"
"#;
        let cfg = ThqConfig::from_toml(toml).expect("should parse");
        assert_eq!(
            cfg.owner_id.as_deref(),
            Some("d0f5c4ba-9c10-4ff7-85a4-f2c0e588a55a")
        );
    }

    #[test]
    fn parse_empty_owner_id_is_none() {
        let toml = r#"
[thq]
torpi_url = "https://torpi.example.com"
advertise_url = "https://10.0.0.5:3000"
owner_id = ""
"#;
        let cfg = ThqConfig::from_toml(toml).expect("should parse");
        assert!(cfg.owner_id.is_none());
    }

    #[test]
    fn parse_no_section_returns_none() {
        let toml = r#"
[oidc]
issuer_url = "https://example.com"
"#;
        assert!(ThqConfig::from_toml(toml).is_none());
    }

    #[test]
    fn parse_missing_required_returns_none() {
        let toml = r#"
[thq]
torpi_url = "https://torpi.example.com"
"#;
        assert!(ThqConfig::from_toml(toml).is_none()); // missing advertise_url
    }

    #[test]
    fn parse_overlay_with_mcp_and_thq() {
        // 16E: the per-user overlay carries [mcp] AND [thq]; the parser must
        // find [thq] and ignore the rest.
        let toml = r#"
[mcp]
enabled = true

[mcp.credentials.x]
type = "service-account"
service_token = "${FAME_SERVICE_TOKEN}"

[[mcp.servers]]
name = "fame"
url = "https://fame.example/abc"
credentials = "x"

[thq]
torpi_url = "https://torpi.example.com"
advertise_url = "https://10.0.0.5:3000"
agent_name = "ravand"
owner_id = "1a71c077-b3b3-4581-b605-925c3f276f30"
"#;
        let cfg = ThqConfig::from_toml(toml).expect("should parse overlay");
        assert_eq!(cfg.agent_name, "ravand");
        assert_eq!(
            cfg.owner_id.as_deref(),
            Some("1a71c077-b3b3-4581-b605-925c3f276f30")
        );
    }

    #[test]
    fn agent_entry_serializes_correctly() {
        let entry = AgentEntry {
            id: "test-id".to_string(),
            name: "test".to_string(),
            endpoint: "https://localhost:3000".to_string(),
            role: "general".to_string(),
            capabilities: vec!["rust".to_string()],
            status: "idle".to_string(),
            tags: vec![],
            last_seen: "2025-01-01T00:00:00Z".to_string(),
            owner_id: None,
        };
        let json = serde_json::to_string(&entry).unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(v["id"], "test-id");
        assert_eq!(v["status"], "idle");
        assert!(v["capabilities"].is_array());
        // owner_id should be absent when None (skip_serializing_if)
        assert!(v.get("owner_id").is_none());
    }

    #[test]
    fn agent_entry_serializes_owner_id() {
        let entry = AgentEntry {
            id: "test-id".to_string(),
            name: "test".to_string(),
            endpoint: "https://localhost:3000".to_string(),
            role: "general".to_string(),
            capabilities: vec!["rust".to_string()],
            status: "idle".to_string(),
            tags: vec![],
            last_seen: "2025-01-01T00:00:00Z".to_string(),
            owner_id: Some("user-uuid-123".to_string()),
        };
        let json = serde_json::to_string(&entry).unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(v["owner_id"], "user-uuid-123");
    }

    // ── 16E tests ───────────────────────────────────────────────────────

    /// Unique temp dir without the tempfile dev-dependency.
    #[test]
    fn discover_finds_only_users_with_thq() {
        let base = temp_users_dir("discover");
        let thq_overlay = format!(
            "[mcp]\nenabled = true\n\n[thq]\ntorpi_url = \"https://torpi.example.com\"\nadvertise_url = \"https://10.0.0.5:3000\"\nagent_name = \"ravand\"\n"
        );
        for (hash, content) in [
            ("aaaa1111", thq_overlay.as_str()),
            ("bbbb2222", "[mcp]\nenabled = true\n"), // no thq
            ("cccc3333", "not toml at all {{{"),     // unparsable
        ] {
            let dir = base.join(hash).join("config");
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(dir.join("trustee.toml"), content).unwrap();
        }

        let found = discover_user_agents_in(&base);
        assert_eq!(found.len(), 1, "only the [thq]-bearing user is discovered");
        assert_eq!(found[0].user_hash, "aaaa1111");
        assert_eq!(found[0].config.agent_name, "ravand");
        assert_eq!(
            found[0].user_home,
            base.join("aaaa1111"),
            "user_home points at the hash dir"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn discover_is_deterministic_and_sorted() {
        let base = temp_users_dir("sorted");
        for hash in ["dddd4444", "bbbb2222", "cccc3333"] {
            let dir = base.join(hash).join("config");
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                dir.join("trustee.toml"),
                "[thq]\ntorpi_url = \"https://t.example\"\nadvertise_url = \"https://10.0.0.5:3000\"\n",
            )
            .unwrap();
        }
        let found = discover_user_agents_in(&base);
        let hashes: Vec<&str> = found.iter().map(|a| a.user_hash.as_str()).collect();
        assert_eq!(hashes, vec!["bbbb2222", "cccc3333", "dddd4444"]);
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn discover_missing_dir_is_empty() {
        let base = temp_users_dir("missing");
        let found = discover_user_agents_in(&base.join("does-not-exist"));
        assert!(found.is_empty());
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn resolve_agent_id_at_is_stable_and_persists() {
        let base = temp_users_dir("agentid");
        let id_file = base.join("agent_id");

        let first = resolve_agent_id_at(&id_file).unwrap();
        assert!(!first.is_empty());
        assert!(id_file.exists(), "id persisted");

        let second = resolve_agent_id_at(&id_file).unwrap();
        assert_eq!(first, second, "id is stable across calls");

        // Whitespace-padded existing id is trimmed, not regenerated.
        std::fs::write(&id_file, format!("  {first}\n")).unwrap();
        let third = resolve_agent_id_at(&id_file).unwrap();
        assert_eq!(first, third);
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn read_overlay_service_issuer_picks_service_account_credential() {
        let base = std::env::temp_dir().join(format!("trustee-thq-issuer-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let dir = base.join("config");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("trustee.toml"),
            "[mcp.credentials.fame_service]\ntype = \"service-account\"\nservice_token = \"${FAME_SERVICE_TOKEN}\"\nissuer_url = \"https://idp.tanbal.ir/oauth2/openid/pdt-api\"\n\n[mcp.credentials.interactive]\ntype = \"interactive\"\nissuer_url = \"https://ignored.example/\"\n",
        )
        .unwrap();
        let issuer = read_overlay_service_issuer(&base);
        assert_eq!(
            issuer.as_deref(),
            Some("https://idp.tanbal.ir/oauth2/openid/pdt-api"),
            "issuer must come from the service-account credential, not another type"
        );
        // No overlay file -> None.
        assert!(read_overlay_service_issuer(&base.join("nope")).is_none());
        let _ = std::fs::remove_dir_all(&base);
    }
}

// ---------------------------------------------------------------------------
// Issue 8e0a1215: [thq].service_token declared credential key
// ---------------------------------------------------------------------------

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

    /// Minimal overlay TOML with an optional service_token declaration.
    fn thq_toml(service_token: Option<&str>) -> String {
        let mut s = String::from(
            "[thq]\ntorpi_url = \"https://torpi.example.com\"\nadvertise_url = \"https://10.0.0.5:3000\"\n",
        );
        if let Some(st) = service_token {
            s.push_str(&format!("service_token = \"{st}\"\n"));
        }
        s
    }

    #[test]
    fn parse_declared_service_token_field() {
        let cfg = ThqConfig::from_toml(&thq_toml(Some("${PAYDAR_SERVICE_ACCOUNT}")))
            .expect("should parse");
        assert_eq!(
            cfg.service_token.as_deref(),
            Some("${PAYDAR_SERVICE_ACCOUNT}"),
            "declaration is stored verbatim; resolution happens at boot"
        );
        assert!(
            ThqConfig::from_toml(&thq_toml(None))
                .unwrap()
                .service_token
                .is_none(),
            "absent field = None (legacy path)"
        );
    }

    #[test]
    fn declared_var_accepts_wrapped_and_bare_forms() {
        assert_eq!(
            declared_service_var("${PAYDAR_SERVICE_ACCOUNT}"),
            "PAYDAR_SERVICE_ACCOUNT"
        );
        assert_eq!(
            declared_service_var("  ${ PAYDAR_SERVICE_ACCOUNT }  "),
            "PAYDAR_SERVICE_ACCOUNT"
        );
        assert_eq!(
            declared_service_var("PAYDAR_SERVICE_ACCOUNT"),
            "PAYDAR_SERVICE_ACCOUNT"
        );
        // Malformed input surfaces verbatim in the loud error, never swallowed.
        assert_eq!(declared_service_var(""), "");
        assert_eq!(declared_service_var("${"), "${");
    }

    /// THE PAYDAR CASE (live incident, issue 8e0a1215): an agent whose
    /// credential lives under a key OUTSIDE the legacy four dispatches with
    /// zero source changes — config-declared, not code-guessed.
    #[test]
    fn declared_field_wins_over_legacy_scan_with_custom_key_name() {
        let base = temp_users_dir("declared-wins");
        std::fs::write(
            base.join(".env"),
            "THQ_SERVICE_TOKEN=legacy-token\nPAYDAR_SERVICE_ACCOUNT=paydar-token\n",
        )
        .unwrap();
        let cfg = ThqConfig::from_toml(&thq_toml(Some("${PAYDAR_SERVICE_ACCOUNT}"))).unwrap();
        assert_eq!(
            resolve_user_service_token(&base, &cfg),
            ServiceTokenResolution::Resolved("paydar-token".to_string()),
            "explicit declaration must win over the legacy priority list"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn declared_but_env_file_missing_is_loud_unresolved() {
        let base = temp_users_dir("declared-no-env");
        let cfg = ThqConfig::from_toml(&thq_toml(Some("${PAYDAR_SERVICE_ACCOUNT}"))).unwrap();
        assert_eq!(
            resolve_user_service_token(&base, &cfg),
            ServiceTokenResolution::DeclaredUnresolved {
                var: "PAYDAR_SERVICE_ACCOUNT".to_string()
            },
            ".env missing entirely → same loud path, never a silent skip"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn declared_but_key_missing_from_env_is_loud_unresolved() {
        let base = temp_users_dir("declared-no-key");
        std::fs::write(base.join(".env"), "THQ_SERVICE_TOKEN=legacy-token\n").unwrap();
        let cfg = ThqConfig::from_toml(&thq_toml(Some("${PAYDAR_SERVICE_ACCOUNT}"))).unwrap();
        assert_eq!(
            resolve_user_service_token(&base, &cfg),
            ServiceTokenResolution::DeclaredUnresolved {
                var: "PAYDAR_SERVICE_ACCOUNT".to_string()
            },
            "legacy key presence must NOT satisfy a different declared key"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn declared_but_placeholder_value_is_unresolved() {
        let base = temp_users_dir("declared-placeholder");
        // House convention: a ${...} VALUE means the secret was never
        // provisioned (house convention: a ${...} value is never provisioned).
        std::fs::write(
            base.join(".env"),
            "PAYDAR_SERVICE_ACCOUNT=${PAYDAR_SERVICE_ACCOUNT}\n",
        )
        .unwrap();
        let cfg = ThqConfig::from_toml(&thq_toml(Some("${PAYDAR_SERVICE_ACCOUNT}"))).unwrap();
        assert_eq!(
            resolve_user_service_token(&base, &cfg),
            ServiceTokenResolution::DeclaredUnresolved {
                var: "PAYDAR_SERVICE_ACCOUNT".to_string()
            }
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    /// The hardcoded key scan is REMOVED (api 0.13.0): an agent declaring
    /// nothing is `Undeclared` — non-dispatchable, loud at boot when
    /// `owner_id` (dispatch intent) is set. Legacy keys in .env are INERT.
    #[test]
    fn undeclared_declaration_is_undeclared_even_with_legacy_keys_present() {
        let base = temp_users_dir("undeclared");
        // The blessed-four keys sit right there in .env — they no longer
        // conjure a credential. Config declares or the agent is out.
        std::fs::write(base.join(".env"), "THQ_SERVICE_TOKEN=thq-token\n").unwrap();
        let cfg = ThqConfig::from_toml(&thq_toml(None)).unwrap();
        assert_eq!(
            resolve_user_service_token(&base, &cfg),
            ServiceTokenResolution::Undeclared,
            "no declaration → Undeclared; the legacy scan must NOT rescue it"
        );
        // Same answer with no .env at all — the outcome is config-shaped,
        // not env-shaped.
        assert_eq!(
            resolve_user_service_token(&base.join("no-env"), &cfg),
            ServiceTokenResolution::Undeclared
        );
        let _ = std::fs::remove_dir_all(&base);
    }
}