impyard 0.1.1

Rent the intelligence, own the governance — a control plane for imps: software colleagues whose every action passes through a gateway you control (default-deny egress, injected credentials, budgets, approval gates, audit).
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
//! Live config. `org.toml` + `imps/*/imp.toml` parse straight into the
//! gateway's OWN types (schema::Policy, budget::BudgetPolicy, …), scope-tagged
//! in memory — there is no compile step and no intermediate artifact. This is
//! still the payoff of one language, one schema (D20): what validates is
//! literally what runs.
//!
//! Consumers call `snapshot()` (mtime-fingerprint cache, so admin edits are
//! live). Invalid config fails closed: the gateway denies, dispatch pauses,
//! `server start` refuses to boot — and `impyard server validate` prints every
//! error. `load()` is side-effect free.

use crate::action::ActionPolicy;
use crate::gateway::budget::BudgetPolicy;
use crate::gateway::schema::Policy;
use crate::imp::context::{CompiledContextPolicy, ContextPolicy};
use crate::imp::memory::{CompiledMemoryPolicy, MemoryPolicy};
use crate::imp::storage::{CompiledStoragePolicy, StoragePolicy};
use crate::paths;
use serde_json::{json, Value};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock};

/// A service connection (`connections/<name>.toml`): one intent — "this
/// imp may act on that service" — compiled into a grant with injection,
/// an env exposure, and a provider template, all keyed by one name that is
/// also the vault credential. Missing secret ⇒ disabled with a warning, not
/// a config failure (nothing forwards a sentinel either way).
#[derive(Clone, Debug)]
pub struct Connection {
    pub name: String,
    pub provider: String,
    /// None = org-wide; Some = these imps only.
    pub imps: Option<Vec<String>>,
    pub hosts: Vec<String>,
    pub methods: Vec<String>,
    pub env: String,
    /// Secret present in the vault?
    pub enabled: bool,
}

#[derive(Clone, Debug)]
pub struct Expose {
    /// "org" or "org/<imp>" — which imps see this env var.
    pub scope: String,
    /// Vault credential name (must exist — fail closed, like listeners).
    pub credential: String,
    /// The env var set in the box (to the sentinel, never the real value).
    pub env: String,
}

pub struct Loaded {
    pub policy: Policy,
    pub budget: BudgetPolicy,
    pub actions: ActionPolicy,
    pub triggers: Vec<Value>,
    pub memory: CompiledMemoryPolicy,
    pub context: CompiledContextPolicy,
    pub storage: CompiledStoragePolicy,
    /// (imp, platform, vault credential) — `server start` starts one
    /// listener each. Platforms: "discord", "slack".
    pub listeners: Vec<(String, String, String)>,
    /// `[[expose]]` — env vars set in the box to the sentinel; the gateway's
    /// per-grant injection swaps in the real credential in transit, only on
    /// requests the grant's scope allows. Leaking the box env leaks nothing.
    /// Includes the exposures compiled from enabled connections.
    pub exposes: Vec<Expose>,
    /// Service connections, for `server connections` and the wizard.
    pub connections: Vec<Connection>,
    /// Non-fatal conditions (e.g. a disabled connection) — printed by
    /// `validate` and `server start`, never fail-closed.
    pub warnings: Vec<String>,
    pub imps: Vec<String>,
    /// `[engine] dir` in org.toml — a dev checkout mounted read-only over the
    /// engine baked into the impyard-box image. Unset (the default) runs the
    /// baked engine.
    pub engine_dir: Option<PathBuf>,
}

/// Parse and validate everything, collecting every error (not just the first).
/// Side-effect free — this is also `impyard server validate`.
pub fn load() -> Result<Loaded, Vec<String>> {
    let mut errors: Vec<String> = Vec::new();
    let org_path = paths::org_file();
    let org = match read_toml(&org_path) {
        Ok(v) => v,
        Err(e) => {
            errors.push(format!("{}: {e}", org_path.display()));
            toml::Value::Table(Default::default())
        }
    };

    let mut rules: Vec<Value> = Vec::new();
    let mut limits: Vec<Value> = Vec::new();
    let mut actions: Vec<Value> = Vec::new();
    let mut trust: Vec<Value> = Vec::new();
    let mut triggers: Vec<Value> = Vec::new();
    let mut listeners: Vec<(String, String, String)> = Vec::new();
    let mut exposes: Vec<Expose> = Vec::new();
    let mut imps: Vec<String> = Vec::new();

    let default_memory = memory_policy(org.get("memory"), None).unwrap_or_else(|e| {
        errors.push(format!("org.toml [memory]: {e}"));
        MemoryPolicy::default()
    });
    let default_context = context_policy(org.get("context"), None).unwrap_or_else(|e| {
        errors.push(format!("org.toml [context]: {e}"));
        ContextPolicy::default()
    });
    let default_storage = storage_policy(&org, None).unwrap_or_else(|e| {
        errors.push(format!("org.toml [knowledge]: {e}"));
        StoragePolicy::default()
    });
    let mut imp_memory = std::collections::HashMap::new();
    let mut imp_context = std::collections::HashMap::new();
    let mut imp_storage = std::collections::HashMap::new();

    for g in array(&org, "grant") {
        rules.push(with_scope(g, "org"));
    }
    for a in array(&org, "action") {
        actions.push(with_scope(a, "org"));
    }
    for t in array(&org, "trust") {
        trust.push(with_scope(t, "org"));
    }
    let org_budget = org.get("budget");
    for l in org_budget.map(|b| array(b, "limit")).unwrap_or_default() {
        limits.push(with_scope(l, "org"));
    }
    for e in array(&org, "expose") {
        parse_expose(e, "org", "org.toml", &mut exposes, &mut errors);
    }

    let engine_dir = org
        .get("engine")
        .and_then(|e| e.get("dir"))
        .and_then(|v| v.as_str())
        .map(PathBuf::from);

    let imps_dir = paths::imps_dir();
    if imps_dir.is_dir() {
        let mut names: Vec<String> = std::fs::read_dir(&imps_dir)
            .into_iter()
            .flatten()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .collect();
        names.sort();
        for name in names {
            let spec = imps_dir.join(&name).join("imp.toml");
            if !spec.exists() {
                continue;
            }
            let w = match read_toml(&spec) {
                Ok(v) => v,
                Err(e) => {
                    errors.push(format!("{}: {e}", spec.display()));
                    continue;
                }
            };
            let declared = w.get("name").and_then(|v| v.as_str());
            if declared != Some(name.as_str()) {
                errors.push(format!(
                    "{}: name {declared:?} != folder \"{name}\"",
                    spec.display()
                ));
                continue;
            }
            let scope = format!("org/{name}");
            imps.push(name.clone());
            match memory_policy(w.get("memory"), Some(&default_memory)) {
                Ok(p) => {
                    imp_memory.insert(name.clone(), p);
                }
                Err(e) => errors.push(format!("{name} [memory]: {e}")),
            }
            match context_policy(w.get("context"), Some(&default_context)) {
                Ok(p) => {
                    imp_context.insert(name.clone(), p);
                }
                Err(e) => errors.push(format!("{name} [context]: {e}")),
            }
            match storage_policy(&w, Some(&default_storage)) {
                Ok(storage) => {
                    match crate::imp::storage::validate_imp_overlay(&default_storage, &storage) {
                        Ok(()) => {
                            imp_storage.insert(name.clone(), storage);
                        }
                        Err(e) => errors.push(format!("{name} [knowledge]: {e}")),
                    }
                }
                Err(e) => errors.push(format!("{name} [knowledge]: {e}")),
            }
            for g in array(&w, "grant") {
                rules.push(with_scope(g, &scope));
            }
            for a in array(&w, "action") {
                actions.push(with_scope(a, &scope));
            }
            for t in array(&w, "trust") {
                trust.push(with_scope(t, &scope));
            }
            for tr in array(&w, "trigger") {
                // Triggers name their imp so dispatch knows whose task to file.
                let mut j = to_json(tr);
                if let Some(obj) = j.as_object_mut() {
                    obj.insert("imp".to_string(), json!(name));
                }
                triggers.push(j);
            }
            if let Some(b) = w.get("budget") {
                for l in array(b, "limit") {
                    limits.push(with_scope(l, &scope));
                }
            }
            for e in array(&w, "expose") {
                parse_expose(e, &scope, &name, &mut exposes, &mut errors);
            }
            // [channels] — which vault credential each of this imp's
            // inbound edges uses. Two listeners on one credential would
            // double-file every message, so that is a validation error, not a
            // runtime surprise.
            for platform in ["discord", "slack"] {
                if let Some(credential) = w
                    .get("channels")
                    .and_then(|c| c.get(platform))
                    .and_then(|v| v.as_str())
                {
                    if let Some((taken, _, _)) = listeners.iter().find(|(_, _, c)| c == credential)
                    {
                        errors.push(format!(
                            "imps {taken} and {name} both listen with credential \"{credential}\" — one bot cannot serve two listeners"
                        ));
                    } else {
                        listeners.push((
                            name.clone(),
                            platform.to_string(),
                            credential.to_string(),
                        ));
                    }
                }
            }
        }
    }

    // Service connections (connections/<name>.toml). Their grants are spliced
    // BEFORE all hand-written grants: first-match-wins, and a connection is
    // host-specific by construction, so it must not be shadowed by a broad
    // hand-written rule like `web-fetch` (GET on *).
    let mut warnings: Vec<String> = Vec::new();
    let mut connections: Vec<Connection> = Vec::new();
    let mut connection_rules: Vec<Value> = Vec::new();
    let registry = crate::credential::registry::registry_json();
    let mut connection_files: Vec<PathBuf> = std::fs::read_dir(paths::connections_dir())
        .into_iter()
        .flatten()
        .flatten()
        .map(|e| e.path())
        .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("toml"))
        .collect();
    connection_files.sort();
    for path in connection_files {
        let name = path
            .file_stem()
            .unwrap_or_default()
            .to_string_lossy()
            .into_owned();
        let v = match read_toml(&path) {
            Ok(v) => v,
            Err(e) => {
                errors.push(format!("{}: {e}", path.display()));
                continue;
            }
        };
        match compile_connection(
            &name,
            &v,
            &imps,
            |p| registry.contains_key(p),
            |c| crate::credential::vault::get_credential(c).is_some(),
        ) {
            Ok((connection, rules, connection_exposes, warning)) => {
                connection_rules.extend(rules);
                exposes.extend(connection_exposes);
                warnings.extend(warning);
                connections.push(connection);
            }
            Err(mut e) => errors.append(&mut e),
        }
    }
    connection_rules.extend(rules);
    let rules = connection_rules;

    // Validate by deserializing into the runtime's own types.
    let policy = parse::<Policy>(&mut errors, "policy (grants)", json!({ "rules": rules }));
    let budget = parse::<BudgetPolicy>(
        &mut errors,
        "budget",
        json!({
            "scope": "org",
            "currencies": org_budget.and_then(|b| b.get("currencies")).map(to_json).unwrap_or(json!([])),
            "vars": org_budget.and_then(|b| b.get("vars")).map(to_json).unwrap_or(json!({})),
            "meters": org_budget.map(|b| array(b, "meter")).unwrap_or_default().iter().map(|m| to_json(m)).collect::<Vec<_>>(),
            "limits": limits,
        }),
    );
    let actions = parse::<ActionPolicy>(
        &mut errors,
        "actions/trust",
        json!({ "actions": actions, "trust": trust }),
    );

    validate_exposes(
        &exposes,
        |name| crate::credential::vault::get_credential(name).is_some(),
        &mut errors,
    );

    if !errors.is_empty() {
        return Err(errors);
    }
    Ok(Loaded {
        policy,
        budget,
        actions,
        triggers,
        memory: CompiledMemoryPolicy {
            default: default_memory,
            imps: imp_memory,
        },
        context: CompiledContextPolicy {
            default: default_context,
            imps: imp_context,
        },
        storage: CompiledStoragePolicy {
            default: default_storage,
            imps: imp_storage,
        },
        listeners,
        exposes,
        connections,
        warnings,
        imps,
        engine_dir,
    })
}

/// Compile one connection file into (record, judge rules, exposures, warning).
/// What one connection file compiles into: the record, the judge rules it
/// contributes, its env exposures, and a warning when it is disabled.
type CompiledConnection = (Connection, Vec<Value>, Vec<Expose>, Option<String>);

/// Pure over the injected lookups, so it is unit-testable.
fn compile_connection(
    name: &str,
    v: &toml::Value,
    known_imps: &[String],
    provider_exists: impl Fn(&str) -> bool,
    secret_exists: impl Fn(&str) -> bool,
) -> Result<CompiledConnection, Vec<String>> {
    let mut errors = Vec::new();
    let ctx = format!("connection \"{name}\"");

    let provider = v
        .get("provider")
        .and_then(|x| x.as_str())
        .unwrap_or_default()
        .to_string();
    if provider.is_empty() {
        errors.push(format!("{ctx}: needs provider = \"<registry name>\""));
    } else if !provider_exists(&provider) {
        errors.push(format!(
            "{ctx}: unknown provider \"{provider}\" (declare it in providers.toml)"
        ));
    }

    let strings = |key: &str| -> Option<Vec<String>> {
        v.get(key).and_then(|x| x.as_array()).map(|a| {
            a.iter()
                .filter_map(|s| s.as_str())
                .map(str::to_string)
                .collect()
        })
    };
    let org_scoped = v.get("scope").and_then(|x| x.as_str()) == Some("org");
    let imps = strings("imps");
    match (&imps, org_scoped) {
        (Some(_), true) => errors.push(format!(
            "{ctx}: choose imps = [..] OR scope = \"org\", not both"
        )),
        (None, false) => errors.push(format!(
            "{ctx}: needs imps = [\"<name>\", ..] or scope = \"org\""
        )),
        (Some(list), false) => {
            for w in list {
                if !known_imps.contains(w) {
                    errors.push(format!("{ctx}: no such imp \"{w}\""));
                }
            }
            if list.is_empty() {
                errors.push(format!(
                    "{ctx}: imps = [] grants nothing — use scope = \"org\" or name imps"
                ));
            }
        }
        (None, true) => {}
    }

    let hosts = strings("hosts").unwrap_or_default();
    if hosts.is_empty() {
        errors.push(format!("{ctx}: needs hosts = [\"api.example.com\", ..]"));
    }
    let methods = strings("methods").unwrap_or_else(|| vec!["GET".into()]);
    let env = v
        .get("env")
        .and_then(|x| x.as_str())
        .unwrap_or_default()
        .to_string();
    if env.is_empty() {
        errors.push(format!("{ctx}: needs env = \"<VAR the box sees>\""));
    }
    if !errors.is_empty() {
        return Err(errors);
    }

    let enabled = secret_exists(name);
    let connection = Connection {
        name: name.to_string(),
        provider,
        imps: imps.clone(),
        hosts: hosts.clone(),
        methods: methods.clone(),
        env: env.clone(),
        enabled,
    };
    if !enabled {
        // Disabled, not broken: no grant, no exposure, nothing to inject —
        // and the rest of the config keeps working.
        let fix = if name == connection.provider {
            format!("impyard server connect {name}")
        } else {
            format!("impyard server connect {} --as {name}", connection.provider)
        };
        let warning =
            format!("{ctx} is disabled — no \"{name}\" credential in the vault (run: {fix})");
        return Ok((connection, Vec::new(), Vec::new(), Some(warning)));
    }

    let scopes: Vec<String> = match &imps {
        Some(list) => list.iter().map(|w| format!("org/{w}")).collect(),
        None => vec!["org".to_string()],
    };
    let rules = scopes
        .iter()
        .map(|scope| {
            json!({
                "scope": scope,
                "name": format!("connection:{name}"),
                "match": { "host": hosts, "port": 443, "method": methods },
                "verdict": "allow",
                "inject": { "credential": name },
            })
        })
        .collect();
    let exposes = scopes
        .into_iter()
        .map(|scope| Expose {
            scope,
            credential: name.to_string(),
            env: env.clone(),
        })
        .collect();
    Ok((connection, rules, exposes, None))
}

/// The env vars provisioning owns — an `[[expose]]` may not overwrite the
/// box's wiring (proxy, trust, identity), only add credential placeholders.
const RESERVED_ENV: &[&str] = &[
    "HOME",
    "TMPDIR",
    "PI_CODING_AGENT_DIR",
    "ANTHROPIC_API_KEY",
    "HTTP_PROXY",
    "HTTPS_PROXY",
    "NO_PROXY",
    "NODE_USE_ENV_PROXY",
    "NODE_EXTRA_CA_CERTS",
    "SSL_CERT_FILE",
    "CURL_CA_BUNDLE",
    "REQUESTS_CA_BUNDLE",
    "GIT_SSL_CAINFO",
    "PIP_CERT",
];

fn parse_expose(
    v: &toml::Value,
    scope: &str,
    source: &str,
    exposes: &mut Vec<Expose>,
    errors: &mut Vec<String>,
) {
    let field = |k: &str| v.get(k).and_then(|x| x.as_str()).map(str::to_string);
    match (field("credential"), field("env")) {
        (Some(credential), Some(env)) => exposes.push(Expose {
            scope: scope.to_string(),
            credential,
            env,
        }),
        _ => errors.push(format!(
            "{source} [[expose]]: needs string fields \"credential\" and \"env\""
        )),
    }
}

/// Every exposure must name a real credential (fail closed, like listener
/// credentials), a well-formed env name outside the reserved wiring, and no
/// two exposures that could reach the same imp may claim one env name.
fn validate_exposes(
    exposes: &[Expose],
    credential_exists: impl Fn(&str) -> bool,
    errors: &mut Vec<String>,
) {
    for (i, e) in exposes.iter().enumerate() {
        let well_formed = !e.env.is_empty()
            && !e.env.as_bytes()[0].is_ascii_digit()
            && e.env
                .bytes()
                .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_');
        if !well_formed {
            errors.push(format!(
                "[[expose]] env \"{}\": use UPPER_SNAKE_CASE",
                e.env
            ));
        }
        if RESERVED_ENV.contains(&e.env.as_str()) || e.env.starts_with("IMPYARD_") {
            errors.push(format!(
                "[[expose]] env \"{}\" is reserved box wiring",
                e.env
            ));
        }
        if !credential_exists(&e.credential) {
            errors.push(format!(
                "[[expose]] {}: no \"{}\" credential in the vault — run: impyard server vault connect",
                e.env, e.credential
            ));
        }
        for other in &exposes[i + 1..] {
            let overlap = e.scope == other.scope || e.scope == "org" || other.scope == "org";
            if e.env == other.env && overlap {
                errors.push(format!(
                    "[[expose]] env \"{}\" claimed twice for overlapping scopes {} and {}",
                    e.env, e.scope, other.scope
                ));
            }
        }
    }
}

/// The cached view. Reloads when any config file's fingerprint changes, so
/// admin edits are live without a restart. On invalid config returns Err —
/// callers fail closed.
pub fn snapshot() -> Result<Arc<Loaded>, String> {
    /// The cached config, keyed by the fingerprint it was loaded from.
    type Cached = Mutex<Option<(String, Arc<Loaded>)>>;
    static CACHE: OnceLock<Cached> = OnceLock::new();
    let cache = CACHE.get_or_init(|| Mutex::new(None));
    let fp = fingerprint();
    {
        let cached = cache.lock().unwrap();
        if let Some((cached_fp, loaded)) = cached.as_ref() {
            if *cached_fp == fp {
                return Ok(loaded.clone());
            }
        }
    }
    match load() {
        Ok(loaded) => {
            let loaded = Arc::new(loaded);
            *cache.lock().unwrap() = Some((fp, loaded.clone()));
            Ok(loaded)
        }
        Err(errors) => Err(errors.join("\n")),
    }
}

/// mtime+len of every config file, so an edit anywhere invalidates the cache.
fn fingerprint() -> String {
    fn stamp(path: &std::path::Path) -> String {
        std::fs::metadata(path)
            .map(|m| {
                let mtime = m
                    .modified()
                    .ok()
                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                    .map(|d| d.as_nanos())
                    .unwrap_or(0);
                format!("{}:{mtime}:{}", path.display(), m.len())
            })
            .unwrap_or_else(|_| format!("{}:absent", path.display()))
    }
    let mut parts = vec![stamp(&paths::org_file())];
    let mut names: Vec<PathBuf> = std::fs::read_dir(paths::imps_dir())
        .into_iter()
        .flatten()
        .flatten()
        .map(|e| e.path().join("imp.toml"))
        .collect();
    names.sort();
    for spec in names {
        parts.push(stamp(&spec));
    }
    let mut connections: Vec<PathBuf> = std::fs::read_dir(paths::connections_dir())
        .into_iter()
        .flatten()
        .flatten()
        .map(|e| e.path())
        .collect();
    connections.sort();
    for c in connections {
        parts.push(stamp(&c));
    }
    // A connection's enabled-ness lives in the vault: the DIR mtime moves on
    // credential create/delete (not on token refresh rewrites, which must not
    // thrash this cache).
    parts.push(stamp(&crate::paths::vault_dir()));
    parts.join("|")
}

// ── helpers (moved from the retired deploy step) ─────────────────────────────

fn parse<T: serde::de::DeserializeOwned + Default>(
    errors: &mut Vec<String>,
    what: &str,
    v: Value,
) -> T {
    match serde_json::from_value::<T>(v) {
        Ok(t) => t,
        Err(e) => {
            errors.push(format!("{what}: {e}"));
            T::default()
        }
    }
}

type BErr = Box<dyn std::error::Error>;

fn context_policy(
    value: Option<&toml::Value>,
    base: Option<&ContextPolicy>,
) -> Result<ContextPolicy, BErr> {
    let mut merged = serde_json::to_value(base.cloned().unwrap_or_default())?;
    if let Some(value) = value {
        merge_json(&mut merged, to_json(value));
    }
    serde_json::from_value(merged).map_err(|e| format!("context policy is invalid: {e}").into())
}

fn memory_policy(
    value: Option<&toml::Value>,
    base: Option<&MemoryPolicy>,
) -> Result<MemoryPolicy, BErr> {
    let mut merged = serde_json::to_value(base.cloned().unwrap_or_default())?;
    if let Some(value) = value {
        merge_json(&mut merged, to_json(value));
    }
    let policy: MemoryPolicy =
        serde_json::from_value(merged).map_err(|e| format!("memory policy is invalid: {e}"))?;
    if let Some(kind) = policy
        .allowed_kinds
        .iter()
        .find(|kind| !crate::imp::memory::SUPPORTED_MEMORY_KINDS.contains(&kind.as_str()))
    {
        return Err(format!(
            "memory policy kind \"{kind}\" is not interaction memory; supported kinds are {}",
            crate::imp::memory::SUPPORTED_MEMORY_KINDS.join(", ")
        )
        .into());
    }
    Ok(policy)
}

fn storage_policy(
    value: &toml::Value,
    base: Option<&StoragePolicy>,
) -> Result<StoragePolicy, BErr> {
    let mut merged = serde_json::to_value(base.cloned().unwrap_or_default())?;
    let overlay = json!({
        "knowledge": value.get("knowledge").map(to_json).unwrap_or(json!({})),
    });
    merge_json(&mut merged, overlay);
    let policy: StoragePolicy = serde_json::from_value(merged)
        .map_err(|error| format!("storage policy is invalid: {error}"))?;
    crate::imp::storage::validate(&policy)
        .map_err(|error| format!("storage policy is invalid: {error}"))?;
    Ok(policy)
}

fn merge_json(base: &mut Value, overlay: Value) {
    match (base, overlay) {
        (Value::Object(base), Value::Object(overlay)) => {
            for (key, value) in overlay {
                match base.get_mut(&key) {
                    Some(existing) => merge_json(existing, value),
                    None => {
                        base.insert(key, value);
                    }
                }
            }
        }
        (base, overlay) => *base = overlay,
    }
}

fn read_toml(path: &std::path::Path) -> Result<toml::Value, BErr> {
    if !path.exists() {
        return Ok(toml::Value::Table(Default::default()));
    }
    Ok(toml::from_str(&std::fs::read_to_string(path)?)?)
}

/// The array of tables under `key` in a TOML table (`[[key]]`), or empty.
fn array<'a>(v: &'a toml::Value, key: &str) -> Vec<&'a toml::Value> {
    v.get(key)
        .and_then(|x| x.as_array())
        .map(|a| a.iter().collect())
        .unwrap_or_default()
}

fn to_json(v: &toml::Value) -> Value {
    serde_json::to_value(v).unwrap_or(Value::Null)
}

fn with_scope(v: &toml::Value, scope: &str) -> Value {
    let mut j = to_json(v);
    if let Some(obj) = j.as_object_mut() {
        obj.insert("scope".to_string(), json!(scope));
    }
    j
}

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

    fn expose(scope: &str, credential: &str, env: &str) -> Expose {
        Expose {
            scope: scope.into(),
            credential: credential.into(),
            env: env.into(),
        }
    }

    fn toml(s: &str) -> toml::Value {
        toml::from_str(s).unwrap()
    }

    #[test]
    fn connection_compiles_per_imp_grants_and_exposes() {
        let v = toml(
            r#"
            provider = "github"
            imps = ["yuko", "kdemo"]
            hosts = ["api.github.com"]
            env = "GH_TOKEN"
        "#,
        );
        let imps = vec!["yuko".to_string(), "kdemo".to_string()];
        let (c, rules, exposes, warning) =
            compile_connection("github", &v, &imps, |_| true, |_| true).unwrap();
        assert!(c.enabled);
        assert_eq!(c.methods, vec!["GET"]); // the default
        assert_eq!(rules.len(), 2);
        assert_eq!(rules[0]["scope"], "org/yuko");
        assert_eq!(rules[0]["name"], "connection:github");
        assert_eq!(rules[0]["match"]["host"][0], "api.github.com");
        assert_eq!(rules[0]["inject"]["credential"], "github");
        assert_eq!(exposes.len(), 2);
        assert_eq!(exposes[1].scope, "org/kdemo");
        assert_eq!(exposes[1].env, "GH_TOKEN");
        assert!(warning.is_none());
    }

    #[test]
    fn connection_without_secret_is_disabled_not_broken() {
        let v = toml(
            r#"
            provider = "github"
            scope = "org"
            hosts = ["api.github.com"]
            env = "GH_TOKEN"
        "#,
        );
        let (c, rules, exposes, warning) =
            compile_connection("github", &v, &[], |_| true, |_| false).unwrap();
        assert!(!c.enabled);
        assert!(rules.is_empty() && exposes.is_empty());
        assert!(warning.unwrap().contains("disabled"));
    }

    #[test]
    fn connection_validation_catches_each_failure_mode() {
        let v = toml(
            r#"
            provider = "nope"
            imps = ["ghost"]
            env = ""
        "#,
        );
        let errors = compile_connection(
            "acme",
            &v,
            &["yuko".to_string()],
            |p| p == "github",
            |_| true,
        )
        .unwrap_err();
        assert!(errors.iter().any(|e| e.contains("unknown provider")));
        assert!(errors.iter().any(|e| e.contains("no such imp \"ghost\"")));
        assert!(errors.iter().any(|e| e.contains("needs hosts")));
        assert!(errors.iter().any(|e| e.contains("needs env")));
    }

    #[test]
    fn expose_validation_catches_each_failure_mode() {
        let vault = |name: &str| name == "github";

        // Well-formed, distinct imps sharing an env name: fine.
        let mut errors = Vec::new();
        let ok = [
            expose("org/a", "github", "GH_TOKEN"),
            expose("org/b", "github", "GH_TOKEN"),
        ];
        validate_exposes(&ok, vault, &mut errors);
        assert!(errors.is_empty(), "{errors:?}");

        // Reserved wiring, bad shape, unknown credential, org-scope duplicate.
        let mut errors = Vec::new();
        let bad = [
            expose("org", "github", "HTTP_PROXY"),
            expose("org", "github", "IMPYARD_X"),
            expose("org", "github", "lower"),
            expose("org", "nope", "A_TOKEN"),
            expose("org", "github", "B_TOKEN"),
            expose("org/a", "github", "B_TOKEN"),
        ];
        validate_exposes(&bad, vault, &mut errors);
        assert_eq!(errors.len(), 5, "{errors:?}");
        assert!(errors
            .iter()
            .any(|e| e.contains("reserved") && e.contains("HTTP_PROXY")));
        assert!(errors
            .iter()
            .any(|e| e.contains("reserved") && e.contains("IMPYARD_X")));
        assert!(errors.iter().any(|e| e.contains("UPPER_SNAKE_CASE")));
        assert!(errors.iter().any(|e| e.contains("no \"nope\" credential")));
        assert!(errors.iter().any(|e| e.contains("claimed twice")));
    }
}