surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
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
//! `store/servers/<id>.toml` (SPEC 5.2).

use std::collections::BTreeMap;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::env::Os;
use crate::error::ErrorCode;
use crate::model::clients::{ClientSelection, NATIVE_NAME_KEY, known_client};
use crate::model::ids::IdKind;
use crate::model::validate::{Diagnostics, at, join};
use crate::model::{SCHEMA_VERSION, StoreModel};

/// OS names accepted in `[os.<name>]` and machine overlays.
pub const OS_NAMES: [&str; 3] = [Os::Windows.as_str(), Os::Linux.as_str(), Os::MacOs.as_str()];

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Transport {
    Stdio,
    Http,
    Sse,
}

impl Transport {
    pub const fn as_str(self) -> &'static str {
        match self {
            Transport::Stdio => "stdio",
            Transport::Http => "http",
            Transport::Sse => "sse",
        }
    }
}

/// How secret references reach the server (SPEC 11.4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum DeliveryMode {
    Auto,
    Env,
    Launch,
    Command,
    Inline,
}

/// `store/servers/<id>.toml`: one MCP server.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(title = "Surjection MCP server (store/servers/<id>.toml)")]
pub struct Server {
    /// Schema version; always 1.
    #[schemars(extend("const" = 1))]
    pub schema: i64,
    /// Server id; equals the file name.
    #[schemars(extend("pattern" = crate::model::ids::SLUG_PATTERN))]
    pub id: String,
    #[serde(flatten)]
    pub body: ServerBody,
    /// System scope (user-wide) enablement.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enable: Option<Enable>,
    #[serde(flatten)]
    #[schemars(skip)]
    pub extra: toml::Table,
}

impl StoreModel for Server {
    const SCHEMA_NAME: &'static str = "server";
}

/// A server definition without identity: shared by store servers and
/// project-only servers.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ServerBody {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
    /// `stdio`, `http` or `sse`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transport: Option<Transport>,
    /// Executable (stdio).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    /// Arguments (stdio).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<String>>,
    /// Working directory (stdio); may use `${home}`, `${project}`, `${surjection_home}`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    /// Endpoint (http, sse).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// HTTP headers (http, sse); values may hold references.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headers: Option<BTreeMap<String, String>>,
    /// Environment (stdio); values are references or literal non-secrets.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub env: Option<BTreeMap<String, String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delivery: Option<Delivery>,
    /// Tool filters, written only through native fields.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tools: Option<ToolFilter>,
    /// Per-OS overrides, deep-merged over the definition.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub os: Option<BTreeMap<String, ServerOverride>>,
    /// Native passthrough fields per client id, checked against that
    /// client's allowlist; `native_name` is accepted for every client.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "Option<BTreeMap<String, BTreeMap<String, serde_json::Value>>>")]
    pub client: Option<BTreeMap<String, toml::Table>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<Meta>,
}

/// Launch and connection fields. Used for `[os.<name>]` overrides and
/// machine overlay server overrides.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ServerFields {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transport: Option<Transport>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headers: Option<BTreeMap<String, String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub env: Option<BTreeMap<String, String>>,
}

/// Field overrides deep-merged over a server (`[os.<name>]`, machine overlay).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ServerOverride {
    #[serde(flatten)]
    pub fields: ServerFields,
    #[serde(flatten)]
    #[schemars(skip)]
    pub extra: toml::Table,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Enable {
    /// Client ids, or "all-detected". Unknown ids are a warning and are kept.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub clients: Option<ClientSelection>,
    #[serde(flatten)]
    #[schemars(skip)]
    pub extra: toml::Table,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Delivery {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode: Option<DeliveryMode>,
    #[serde(flatten)]
    #[schemars(skip)]
    pub extra: toml::Table,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ToolFilter {
    /// Only these tools.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allow: Option<Vec<String>>,
    /// Never these tools.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deny: Option<Vec<String>>,
    #[serde(flatten)]
    #[schemars(skip)]
    pub extra: toml::Table,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Meta {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub homepage: Option<String>,
    /// `manual`, `imported:<client>`, `migrated:skilldock`, `catalog:<source>`,
    /// `source:git` or `source:local`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,
    /// Where a server drafted from a Git repository or folder came from
    /// (#5): provenance only; the clone it may run from is machine-local.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<ServerSource>,
    #[serde(flatten)]
    #[schemars(skip)]
    pub extra: toml::Table,
}

/// What a source server came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ServerSourceKind {
    Git,
    Local,
    /// An entry of an MCP registry catalog (#26): its `server.json`.
    Registry,
}

impl ServerSourceKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            ServerSourceKind::Git => "git",
            ServerSourceKind::Local => "local",
            ServerSourceKind::Registry => "registry",
        }
    }
}

/// `[meta.source]`: the repository or folder a server was drafted from,
/// so an update check can read it again (#5).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ServerSource {
    /// `git`, `local` or `registry`.
    pub kind: ServerSourceKind,
    /// Git URL, userinfo removed (git); the registry's base URL
    /// (registry).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// The folder, `${home}` for the home folder (local).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub folder: Option<String>,
    /// Folder inside the repository, `/`-separated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// Branch or tag followed (git); the version pinned (registry).
    #[serde(rename = "ref", default, skip_serializing_if = "Option::is_none")]
    pub git_ref: Option<String>,
    /// The resolved commit (git).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(extend("pattern" = "^[0-9a-f]{40}$"))]
    pub commit: Option<String>,
    /// The file the definition came from, relative to the folder.
    pub file: String,
    /// `registry`, `bundle`, `client:<id>`, `npm`, `python` or `docker`.
    pub converter: String,
    /// Which definition of the file (`packages[0]`, an entry name).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entry: Option<String>,
    /// The server runs from the machine-local clone
    /// `<SURJECTION_HOME>/servers/<id>`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checkout: Option<bool>,
    /// The machine a local folder belongs to (its machine id): the server
    /// runs only there (local sources).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub machine: Option<String>,
    /// The catalog entry it was installed from, `<catalog>/<entry id>`
    /// (#26).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub catalog: Option<String>,
    /// The registry entry's version (registry).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    #[serde(flatten)]
    #[schemars(skip)]
    pub extra: toml::Table,
}

impl ServerSource {
    pub fn uses_checkout(&self) -> bool {
        self.checkout == Some(true)
    }

    fn validate_into(&self, path: &str, d: &mut Diagnostics) {
        match self.kind {
            ServerSourceKind::Git if self.url.as_deref().is_none_or(str::is_empty) => d.error(
                ErrorCode::MissingField,
                join(path, "url"),
                "a git source needs its url",
            ),
            ServerSourceKind::Local if self.folder.as_deref().is_none_or(str::is_empty) => d.error(
                ErrorCode::MissingField,
                join(path, "folder"),
                "a local source needs its folder",
            ),
            ServerSourceKind::Registry if self.url.as_deref().is_none_or(str::is_empty) => d.error(
                ErrorCode::MissingField,
                join(path, "url"),
                "a registry source needs the registry's url",
            ),
            ServerSourceKind::Registry if self.catalog.as_deref().is_none_or(str::is_empty) => d
                .error(
                    ErrorCode::MissingField,
                    join(path, "catalog"),
                    "a registry source needs its catalog entry",
                ),
            ServerSourceKind::Registry if self.version.as_deref().is_none_or(str::is_empty) => d
                .error(
                    ErrorCode::MissingField,
                    join(path, "version"),
                    "a registry source needs its version",
                ),
            _ => {}
        }
        if self.kind == ServerSourceKind::Registry
            && let Some(problem) = self
                .url
                .as_deref()
                .filter(|url| !url.is_empty())
                .and_then(crate::model::catalogs::registry_url_problem)
        {
            d.error(ErrorCode::InvalidValue, join(path, "url"), problem);
        }
        if self.commit.is_some() && self.kind == ServerSourceKind::Registry {
            d.error(
                ErrorCode::InvalidValue,
                join(path, "commit"),
                "a registry source has a version, not a commit",
            );
        }
        if self.version.is_some() && self.kind != ServerSourceKind::Registry {
            d.error(
                ErrorCode::InvalidValue,
                join(path, "version"),
                "only a registry source has a version",
            );
        }
        if let Some(commit) = &self.commit
            && !crate::model::ids::is_commit_id(commit)
        {
            d.error(
                ErrorCode::InvalidValue,
                join(path, "commit"),
                format!("{commit:?} is not a commit id (40 hex characters)"),
            );
        }
        if self.machine.is_some() && self.kind != ServerSourceKind::Local {
            d.error(
                ErrorCode::InvalidValue,
                join(path, "machine"),
                "only a local folder source is bound to a machine",
            );
        }
        if self.uses_checkout() && self.kind != ServerSourceKind::Git {
            d.error(
                ErrorCode::InvalidValue,
                join(path, "checkout"),
                "only a git source runs from a checkout",
            );
        }
        if self.file.is_empty() || self.converter.is_empty() {
            d.error(
                ErrorCode::MissingField,
                path.to_owned(),
                "a source needs its file and converter",
            );
        }
    }
}

impl Server {
    /// A minimal server; fill `body` before saving.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            schema: SCHEMA_VERSION,
            id: id.into(),
            body: ServerBody::default(),
            enable: None,
            extra: toml::Table::new(),
        }
    }

    /// Validates per SPEC 5.2. `file_id` is the file name without `.toml`.
    pub fn validate(&self, file_id: Option<&str>) -> Diagnostics {
        let mut d = Diagnostics::new();
        d.check_named_id(IdKind::Server, &self.id, "id", file_id);
        self.body.validate_into("", true, &mut d);
        if let Some(clients) = self.enable.as_ref().and_then(|e| e.clients.as_ref()) {
            d.check_client_selection(clients, "enable.clients");
        }
        d
    }

    /// Sets `[enable] clients` (`None` removes it), keeping the table's
    /// other keys; a table left empty is removed.
    pub fn set_clients(&mut self, clients: Option<ClientSelection>) {
        self.enable = match (self.enable.take(), clients) {
            (Some(mut enable), clients) => {
                enable.clients = clients;
                (enable.clients.is_some() || !enable.extra.is_empty()).then_some(enable)
            }
            (None, Some(clients)) => Some(Enable {
                clients: Some(clients),
                ..Enable::default()
            }),
            (None, None) => None,
        };
    }
}

impl ServerBody {
    /// The launch and connection fields of this definition.
    pub fn fields(&self) -> ServerFields {
        ServerFields {
            transport: self.transport,
            command: self.command.clone(),
            args: self.args.clone(),
            cwd: self.cwd.clone(),
            url: self.url.clone(),
            headers: self.headers.clone(),
            env: self.env.clone(),
        }
    }

    /// Checks templates, OS overrides, client passthrough and metadata;
    /// with `complete`, also the transport rules for every OS.
    pub(crate) fn validate_into(&self, prefix: &str, complete: bool, d: &mut Diagnostics) {
        let base = self.fields();
        base.check_templates(prefix, d);
        let overrides = self.os.as_ref();
        for (os, over) in overrides.into_iter().flatten() {
            let path = join(&join(prefix, "os"), os);
            if !OS_NAMES.contains(&os.as_str()) {
                d.warning(
                    ErrorCode::UnknownOs,
                    &path,
                    format!("unknown OS {os:?}; expected one of {OS_NAMES:?}; kept as written"),
                );
            }
            over.fields.check_templates(&path, d);
        }
        if complete {
            check_transport(&base, overrides, prefix, d);
        }
        for (client_id, table) in self.client.iter().flatten() {
            let path = join(&join(prefix, "client"), client_id);
            check_passthrough(client_id, table, &path, d);
        }
        let meta_path = join(prefix, "meta");
        if let Some(origin) = self.meta.as_ref().and_then(|meta| meta.origin.as_ref())
            && !is_valid_origin(origin)
        {
            d.error(
                ErrorCode::InvalidValue,
                join(&meta_path, "origin"),
                format!(
                    "invalid origin {origin:?}; expected manual, imported:<client>, \
                     migrated:skilldock, catalog:<source>, source:git or source:local"
                ),
            );
        }
        if let Some(source) = self.meta.as_ref().and_then(|meta| meta.source.as_ref()) {
            source.validate_into(&join(&meta_path, "source"), d);
        }
    }
}

impl ServerFields {
    /// `over` deep-merged over `self`: `env` and `headers` merge key by key,
    /// everything else is replaced (SPEC 6.2).
    pub fn merged(&self, over: &ServerFields) -> ServerFields {
        let merge_map = |base: &Option<BTreeMap<String, String>>,
                         over: &Option<BTreeMap<String, String>>| {
            match (base, over) {
                (Some(base), Some(over)) => {
                    let mut merged = base.clone();
                    merged.extend(over.iter().map(|(k, v)| (k.clone(), v.clone())));
                    Some(merged)
                }
                (base, None) => base.clone(),
                (None, over) => over.clone(),
            }
        };
        ServerFields {
            transport: over.transport.or(self.transport),
            command: over.command.clone().or_else(|| self.command.clone()),
            args: over.args.clone().or_else(|| self.args.clone()),
            cwd: over.cwd.clone().or_else(|| self.cwd.clone()),
            url: over.url.clone().or_else(|| self.url.clone()),
            headers: merge_map(&self.headers, &over.headers),
            env: merge_map(&self.env, &over.env),
        }
    }

    fn has(&self, field: &str) -> bool {
        match field {
            "transport" => self.transport.is_some(),
            "command" => self.command.is_some(),
            "args" => self.args.is_some(),
            "cwd" => self.cwd.is_some(),
            "url" => self.url.is_some(),
            "headers" => self.headers.is_some(),
            "env" => self.env.is_some(),
            _ => false,
        }
    }

    /// Every string value goes through the template grammar (SPEC 11.2).
    pub(crate) fn check_templates(&self, prefix: &str, d: &mut Diagnostics) {
        for (field, value) in [
            ("command", &self.command),
            ("cwd", &self.cwd),
            ("url", &self.url),
        ] {
            if let Some(value) = value {
                d.check_template(value, &join(prefix, field));
            }
        }
        for (index, arg) in self.args.iter().flatten().enumerate() {
            d.check_template(arg, &at(&join(prefix, "args"), index));
        }
        for (field, map) in [("headers", &self.headers), ("env", &self.env)] {
            for (key, value) in map.iter().flatten() {
                d.check_template(value, &join(&join(prefix, field), key));
            }
        }
    }
}

/// `stdio` requires `command` and forbids `url`/`headers`; `http`/`sse`
/// require `url` and forbid `command`/`args`/`env`. Checked on the definition
/// as each OS sees it, so a field supplied only through `[os.<name>]` counts
/// for that OS.
fn check_transport(
    base: &ServerFields,
    overrides: Option<&BTreeMap<String, ServerOverride>>,
    prefix: &str,
    d: &mut Diagnostics,
) {
    let has_os_override = overrides
        .is_some_and(|overrides| overrides.keys().any(|os| OS_NAMES.contains(&os.as_str())));
    let views: Vec<(Option<&str>, ServerFields)> = if has_os_override {
        OS_NAMES
            .iter()
            .map(|os| {
                let over = overrides.and_then(|overrides| overrides.get(*os));
                let view = over.map_or_else(|| base.clone(), |over| base.merged(&over.fields));
                (Some(*os), view)
            })
            .collect()
    } else {
        vec![(None, base.clone())]
    };

    // (code, path, message) -> OSes where it applies, in first-seen order.
    let mut problems: Vec<(ErrorCode, String, String, Vec<&'static str>)> = Vec::new();
    let mut report = |code: ErrorCode, field: &str, os: Option<&'static str>, message: String| {
        let path = match os {
            Some(os) if !base.has(field) && code == ErrorCode::FieldNotAllowed => {
                join(&join(&join(prefix, "os"), os), field)
            }
            _ => join(prefix, field),
        };
        match problems
            .iter_mut()
            .find(|(c, p, m, _)| *c == code && *p == path && *m == message)
        {
            Some((.., oses)) => oses.extend(os),
            None => problems.push((code, path, message, os.into_iter().collect())),
        }
    };
    for (os, view) in &views {
        let Some(transport) = view.transport else {
            report(
                ErrorCode::MissingField,
                "transport",
                *os,
                "`transport` is required: stdio, http or sse".to_owned(),
            );
            continue;
        };
        let (required, forbidden): (&str, &[&str]) = match transport {
            Transport::Stdio => ("command", &["url", "headers"]),
            Transport::Http | Transport::Sse => ("url", &["command", "args", "env"]),
        };
        let name = transport.as_str();
        if !view.has(required) {
            report(
                ErrorCode::MissingField,
                required,
                *os,
                format!("{name} servers need `{required}`"),
            );
        }
        for field in forbidden {
            if view.has(field) {
                report(
                    ErrorCode::FieldNotAllowed,
                    field,
                    *os,
                    format!("{name} servers must not set `{field}`"),
                );
            }
        }
    }
    for (code, path, message, oses) in problems {
        let message = if oses.is_empty() || oses.len() == views.len() {
            message
        } else {
            format!("{message} (on {})", oses.join(", "))
        };
        d.error(code, path, message);
    }
}

fn check_passthrough(client_id: &str, table: &toml::Table, path: &str, d: &mut Diagnostics) {
    let known = known_client(client_id);
    if known.is_none() {
        d.warning(
            ErrorCode::UnknownClient,
            path,
            format!("unknown client {client_id:?}; kept as written"),
        );
    }
    for (key, value) in table {
        let key_path = join(path, key);
        if key == NATIVE_NAME_KEY {
            if !value.as_str().is_some_and(|name| !name.trim().is_empty()) {
                d.error(
                    ErrorCode::InvalidValue,
                    key_path,
                    "`native_name` must be a non-empty string",
                );
            }
            continue;
        }
        if let Some(known) = known
            && !known.passthrough.contains(&key.as_str())
        {
            let allowed = if known.passthrough.is_empty() {
                format!("{client_id} accepts only `{NATIVE_NAME_KEY}`")
            } else {
                format!(
                    "{client_id} accepts `{NATIVE_NAME_KEY}`, `{}`",
                    known.passthrough.join("`, `")
                )
            };
            d.error(
                ErrorCode::PassthroughNotAllowed,
                &key_path,
                format!("`{key}` is not a passthrough field: {allowed}"),
            );
            continue;
        }
        check_value_templates(value, &key_path, d);
    }
}

fn check_value_templates(value: &toml::Value, path: &str, d: &mut Diagnostics) {
    match value {
        toml::Value::String(text) => d.check_template(text, path),
        toml::Value::Array(items) => {
            for (index, item) in items.iter().enumerate() {
                check_value_templates(item, &at(path, index), d);
            }
        }
        toml::Value::Table(table) => {
            for (key, item) in table {
                check_value_templates(item, &join(path, key), d);
            }
        }
        _ => {}
    }
}

fn is_valid_origin(origin: &str) -> bool {
    match origin.split_once(':') {
        None => origin == "manual",
        Some(("imported", client)) => !client.is_empty(),
        Some(("migrated", source)) => source == "skilldock",
        Some(("catalog", source)) => !source.is_empty(),
        Some(("source", kind)) => matches!(kind, "git" | "local"),
        Some(_) => false,
    }
}