instruction-md 0.6.1

Read, check, resolve and verify instruction.md files (Markdown rules for AI agents, specification instruction/1): the reader and its diagnostics, the exact text an agent receives, composition of bases and includes, and Ed25519 signature verification. No I/O, no unsafe.
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
//! The integrations policy in the front matter (proposal S34): which of a document's MCP servers, skills and agents
//! may be used, and which of a server's tools. Two layers, one shape: `host-integrations`, which only the host that
//! serves the document writes (a workspace's policy, put in at serve time), and `integrations`, which the author may
//! write to narrow it. The effective policy ([`Policy`], [`crate::Reading::policy`]) is both at once: a target is
//! allowed only where every layer that lists targets lists it, and a tool is blocked where any layer blocks it, so an
//! author can narrow the host's policy and never widen it. A port of the reference's `policy.ts` (packages/spec).
//!
//! The host's block sits outside the signed bytes: a host writes it as its own lines right after the front matter's
//! opening `---` (or as a front matter of its own, when the source has none, [`with_host_block`]), and
//! [`authored_candidates`] takes them out again, so an author signature still verifies over the served text.
//!
//! ```
//! use instruction_md::{read, ReadOptions, check_reading};
//!
//! let served = "---\nhost-integrations:\n  servers:\n    \"https://cal.example.org/mcp\": {\"blocked\": [\"events.delete\"]}\n---\n\n\
//!               ::mcp{id=cal src=\"https://cal.example.org/mcp\" tools=\"events.list,events.delete\"}\n";
//! let r = read(served, &ReadOptions::default());
//! let policy = r.policy.as_ref().unwrap();
//! assert!(policy.tool_blocked(&["https://cal.example.org/mcp/"], "events.delete"));
//! assert!(!policy.tool_blocked(&["https://cal.example.org/mcp"], "events.list"));
//! let d = &check_reading(&r)[0];
//! assert_eq!((d.code, d.message.as_str()), ("tool-blocked", "events.delete: this tool is blocked in your workspace"));
//! ```

use std::collections::{BTreeMap, HashMap};

use serde_json::{Map, Value};

use crate::js::{js_space, js_trim, js_value, utf16_cmp};
use crate::types::{Attrs, Node, Object};

/// The front matter key only the host that serves a document writes.
pub const HOST_POLICY_KEY: &str = "host-integrations";
/// The front matter key an author may write to narrow the host's policy.
pub const AUTHOR_POLICY_KEY: &str = "integrations";

/// What a server's tools not named in a layer are: `allowed` (the default) or `blocked` (new tools blocked until
/// reviewed).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ToolDefault {
    #[default]
    Allowed,
    Blocked,
}

impl ToolDefault {
    pub fn as_str(self) -> &'static str {
        match self {
            ToolDefault::Allowed => "allowed",
            ToolDefault::Blocked => "blocked",
        }
    }
}

/// One server's tools in a layer, as written (lists trimmed, deduplicated and sorted): those blocked, those allowed,
/// and what any other tool is (`None`: allowed).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ServerTools {
    pub allowed: Option<Vec<String>>,
    pub blocked: Option<Vec<String>>,
    pub default: Option<ToolDefault>,
}

/// One layer (a `host-integrations` or `integrations` value, [`layer_of`]): `allowed`, when present, is every target
/// its connected objects may use (an empty list allows none); `servers`, by a server's normalized target, its tools.
/// Also what a host passes as [`crate::ReadOptions::host`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PolicyLayer {
    pub allowed: Option<Vec<String>>,
    pub servers: Option<BTreeMap<String, ServerTools>>,
}

/// A server's tools in the effective policy: `blocked`, the `default` for any other tool and, when the default is
/// `blocked`, the tools `allowed`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerPolicy {
    pub blocked: Vec<String>,
    pub default: ToolDefault,
    pub allowed: Option<Vec<String>>,
}

/// Which layers an effective policy was made from.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PolicyFrom {
    pub host: bool,
    pub author: bool,
}

/// The effective policy ([`merge_policy`]): the layers merged, targets normalized ([`normalize_target`]), lists
/// sorted. `allowed` is `None` when no layer restricts the targets.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Policy {
    pub allowed: Option<Vec<String>>,
    pub servers: BTreeMap<String, ServerPolicy>,
    pub from: PolicyFrom,
}

impl Policy {
    /// Whether a tool is blocked on a server known by these targets: blocked on any of them.
    pub fn tool_blocked<S: AsRef<str>>(&self, targets: &[S], tool: &str) -> bool {
        targets.iter().any(|t| {
            self.servers.get(&normalize_target(t.as_ref())).is_some_and(|s| {
                s.blocked.iter().any(|x| x == tool)
                    || (s.default == ToolDefault::Blocked && !s.allowed.as_deref().unwrap_or_default().iter().any(|x| x == tool))
            })
        })
    }

    /// Whether a connected object reaching these targets ([`remote_targets`]) is allowed: every one of them listed,
    /// when the policy lists any. An object with no remote target is its document's own, and always allowed.
    pub fn targets_allowed<S: AsRef<str>>(&self, targets: &[S]) -> bool {
        let Some(allowed) = &self.allowed else { return true };
        targets.iter().all(|t| allowed.contains(&normalize_target(t.as_ref())))
    }

    /// The policy as JSON, as the reference's `ReadResult.policy` is (the vectors' `policy`).
    pub fn to_json(&self) -> Value {
        let list = |xs: &[String]| Value::Array(xs.iter().cloned().map(Value::String).collect());
        let mut m = Map::new();
        if let Some(a) = &self.allowed {
            m.insert("allowed".into(), list(a));
        }
        let mut servers = Map::new();
        for (t, s) in &self.servers {
            let mut e = Map::new();
            e.insert("blocked".into(), list(&s.blocked));
            e.insert("default".into(), s.default.as_str().into());
            if let Some(a) = &s.allowed {
                e.insert("allowed".into(), list(a));
            }
            servers.insert(t.clone(), Value::Object(e));
        }
        m.insert("servers".into(), Value::Object(servers));
        let mut from = Map::new();
        from.insert("host".into(), self.from.host.into());
        from.insert("author".into(), self.from.author.into());
        m.insert("from".into(), Value::Object(from));
        Value::Object(m)
    }
}

/// What is wrong with a layer as written: its key, and the message of the `invalid-metadata` error the reader gives.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LayerProblem {
    pub key: String,
    pub message: String,
}

/// Strings deduplicated and sorted as ECMAScript sorts them (by UTF-16 code units).
fn sorted(xs: impl IntoIterator<Item = String>) -> Vec<String> {
    let mut v: Vec<String> = xs.into_iter().collect();
    v.sort_by(|a, b| utf16_cmp(a, b));
    v.dedup();
    v
}

/// A list of non-blank strings, trimmed; `None` for anything else.
fn names(v: Option<&Value>) -> Option<Vec<String>> {
    let Some(Value::Array(a)) = v else { return None };
    a.iter().map(|x| x.as_str().map(js_trim).filter(|s| !s.is_empty()).map(str::to_string)).collect()
}

/// Is a key an array index (a canonical integer below 2^32 - 1), which ECMAScript lists first, in numeric order?
fn array_index(k: &str) -> Option<u32> {
    let n: u32 = k.parse().ok()?;
    (n != u32::MAX && n.to_string() == k).then_some(n)
}

/// A mapping's keys in ECMAScript's order (`Object.keys`): array indexes ascending, then the rest as written.
fn js_keys(written: Vec<String>) -> Vec<String> {
    let (mut idx, rest): (Vec<String>, Vec<String>) = written.into_iter().partition(|k| array_index(k).is_some());
    idx.sort_by_key(|k| array_index(k));
    idx.extend(rest);
    idx
}

/// How a mapping at a path (its keys from the layer's own value) lists its keys as written.
type Order<'a> = &'a dyn Fn(&[&str], &Object) -> Vec<String>;

/// A layer from its front matter value, normalized, with what is wrong with it (each problem an `invalid-metadata`
/// error). Keys are taken in the order a `serde_json` mapping keeps them; the reader takes them in the order written.
pub fn layer_of(value: &Value, key: &str) -> (Option<PolicyLayer>, Vec<LayerProblem>) {
    layer_in_order(value, key, &|_, m| m.keys().cloned().collect())
}

pub(crate) fn layer_in_order(value: &Value, key: &str, order: Order<'_>) -> (Option<PolicyLayer>, Vec<LayerProblem>) {
    let mut problems = Vec::new();
    let mut bad =
        |message: String| problems.push(LayerProblem { key: key.into(), message: format!("the front matter's {key}: {message}") });
    let Value::Object(value) = value else {
        bad("is a mapping of allowed and servers".into());
        return (None, problems);
    };
    let mut layer = PolicyLayer::default();
    for k in js_keys(order(&[], value)) {
        if k != "allowed" && k != "servers" {
            bad(format!("\"{k}\" is not one of its keys (allowed, servers)"));
        }
    }
    if value.contains_key("allowed") {
        match names(value.get("allowed")) {
            None => bad("allowed is a list of targets (addresses or registry names)".into()),
            Some(xs) => layer.allowed = Some(sorted(xs.iter().map(|x| normalize_target(x)))),
        }
    }
    if let Some(servers) = value.get("servers") {
        match servers {
            Value::Object(servers) => {
                let mut out: BTreeMap<String, ServerTools> = BTreeMap::new();
                for target in js_keys(order(&["servers"], servers)) {
                    let Some(Value::Object(entry)) = servers.get(&target) else {
                        bad(format!("servers.\"{target}\" is a mapping of allowed, blocked and default"));
                        continue;
                    };
                    let mut t = ServerTools::default();
                    for k in js_keys(order(&["servers", &target], entry)) {
                        if !["allowed", "blocked", "default"].contains(&k.as_str()) {
                            bad(format!("servers.\"{target}\": \"{k}\" is not one of its keys (allowed, blocked, default)"));
                        }
                    }
                    for k in ["allowed", "blocked"] {
                        if entry.contains_key(k) {
                            match names(entry.get(k)) {
                                None => bad(format!("servers.\"{target}\".{k} is a list of tool names")),
                                Some(xs) => {
                                    let xs = Some(sorted(xs));
                                    if k == "allowed" { t.allowed = xs } else { t.blocked = xs }
                                }
                            }
                        }
                    }
                    if let Some(d) = entry.get("default") {
                        match d.as_str() {
                            Some("allowed") => t.default = Some(ToolDefault::Allowed),
                            Some("blocked") => t.default = Some(ToolDefault::Blocked),
                            _ => bad(format!("servers.\"{target}\".default is allowed or blocked")),
                        }
                    }
                    // (two spellings of one target are one server: what either blocks is blocked)
                    let n = normalize_target(&target);
                    let merged = match out.remove(&n) {
                        Some(was) => merge_tools(&[&was, &t]),
                        None => t,
                    };
                    out.insert(n, merged);
                }
                layer.servers = Some(out);
            }
            _ => bad("servers is a mapping of a server's target to its tools".into()),
        }
    }
    (Some(layer), problems)
}

/// A server's tools in several layers at once: blocked where any blocks; blocked by default where any is; then
/// allowed only where every layer that blocks by default allows.
fn merge_tools(ts: &[&ServerTools]) -> ServerTools {
    let blocked = sorted(ts.iter().flat_map(|t| t.blocked.iter().flatten().cloned()));
    let closed: Vec<&&ServerTools> = ts.iter().filter(|t| t.default == Some(ToolDefault::Blocked)).collect();
    let Some(first) = closed.first() else {
        return ServerTools { allowed: None, blocked: Some(blocked), default: Some(ToolDefault::Allowed) };
    };
    let mut allowed: Vec<String> = first.allowed.clone().unwrap_or_default();
    for t in &closed[1..] {
        let theirs = t.allowed.as_deref().unwrap_or_default();
        allowed.retain(|x| theirs.contains(x));
    }
    let allowed = sorted(allowed.into_iter().filter(|x| !blocked.contains(x)));
    ServerTools { allowed: Some(allowed), blocked: Some(blocked), default: Some(ToolDefault::Blocked) }
}

/// The layers merged (the host's, then the author's): `None` when neither is given.
pub fn merge_policy(host: Option<&PolicyLayer>, author: Option<&PolicyLayer>) -> Option<Policy> {
    let layers: Vec<&PolicyLayer> = [host, author].into_iter().flatten().collect();
    if layers.is_empty() {
        return None;
    }
    let mut allowed: Option<Vec<String>> = None;
    for l in &layers {
        let Some(theirs) = &l.allowed else { continue };
        allowed = Some(match allowed {
            None => theirs.clone(),
            Some(mut a) => {
                a.retain(|t| theirs.contains(t));
                a
            }
        });
    }
    let targets = sorted(layers.iter().flat_map(|l| l.servers.iter().flat_map(|s| s.keys().cloned())));
    let mut servers = BTreeMap::new();
    for target in targets {
        let ts: Vec<&ServerTools> = layers.iter().filter_map(|l| l.servers.as_ref()?.get(&target)).collect();
        let m = merge_tools(&ts);
        let default = m.default.unwrap_or_default();
        let allowed = (default == ToolDefault::Blocked).then(|| m.allowed.unwrap_or_default());
        servers.insert(target, ServerPolicy { blocked: m.blocked.unwrap_or_default(), default, allowed });
    }
    Some(Policy { allowed: allowed.map(sorted), servers, from: PolicyFrom { host: host.is_some(), author: author.is_some() } })
}

// ---- targets ----

/// The kinds an integration stands for: MCP servers, skills, A2A agents, and APIs (a `service`, proposal S32).
pub const INTEGRATED_KINDS: &[&str] = &["mcp", "skill", "agent", "service"];

/// A target as a policy compares it (RFC-0038 §3): an http(s) URL with its scheme and host lower-cased and its
/// default port, credentials, fragment and trailing slash dropped (its path keeps its case), parsed as the WHATWG URL
/// standard parses it; any other target, a registry's server name, trimmed and lower-cased.
///
/// One difference from the reference's `new URL`: a host with non-ASCII characters is lower-cased, not converted to
/// its IDNA (punycode) form.
///
/// ```
/// use instruction_md::normalize_target;
///
/// assert_eq!(normalize_target(" HTTPS://Cal.Example.org:443/MCP/#x"), "https://cal.example.org/MCP");
/// assert_eq!(normalize_target("IO.Example/Weather"), "io.example/weather");
/// ```
pub fn normalize_target(target: &str) -> String {
    let t = js_trim(target);
    if is_http(t)
        && let Some(u) = url::normalize(t)
    {
        return u;
    }
    t.to_lowercase()
}

/// Does it start with `http://` or `https://`, in any case?
fn is_http(s: &str) -> bool {
    let b = s.as_bytes();
    let starts = |p: &[u8]| b.len() >= p.len() && b[..p.len()].eq_ignore_ascii_case(p);
    starts(b"http://") || starts(b"https://")
}

/// The targets by which a connected object reaches outside its document: an http(s) `src` or `endpoint`, a
/// `registry` or `server` name, normalized. Never a relative path (a resource of the document's own bundle) or a
/// `#id`; nothing for a kind that is not an integration's ([`INTEGRATED_KINDS`]).
pub fn remote_targets(kind: &str, attrs: &Attrs) -> Vec<String> {
    if !INTEGRATED_KINDS.contains(&kind) {
        return Vec::new();
    }
    let mut out = Vec::new();
    for key in ["src", "endpoint", "registry", "server"] {
        let Some(Value::String(v)) = attrs.get(key) else { continue };
        let t = js_trim(v);
        if t.is_empty() || t.starts_with('#') {
            continue;
        }
        let relative = t.starts_with('/') || t.starts_with("./") || t.starts_with("../");
        if is_http(t) || ((key == "registry" || key == "server") && !relative) {
            out.push(normalize_target(v));
        }
    }
    out
}

/// A list attribute's names: a list, or a string of names apart by commas or whitespace.
fn names_of(v: Option<&Value>) -> Vec<String> {
    let raw: Vec<String> = match v {
        Some(Value::Array(a)) => a.iter().map(|x| js_value(Some(x))).collect(),
        Some(Value::String(s)) => s.split(|c: char| c == ',' || js_space(c)).map(str::to_string).collect(),
        _ => Vec::new(),
    };
    raw.iter().map(|x| js_trim(x)).filter(|x| !x.is_empty()).map(str::to_string).collect()
}

/// The tools a connected object names for use, and the targets of the server they are on.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NamedTools {
    pub targets: Vec<String>,
    pub tools: Vec<String>,
}

/// The tools a connected object names for use, and its server's targets: an `mcp`'s `tools` and `allow` (its `deny`
/// names what not to use), a `tool`'s `name` on its `server` — the document's MCP server (or service) it references
/// (`#id`, looked up in `body`), or a server named outright. `None` for any other object.
pub fn named_tools(n: &Node, body: &[Node]) -> Option<NamedTools> {
    let by_id = objects_by_id(body);
    named_in(n, &by_id)
}

fn named_in(n: &Node, by_id: &HashMap<&str, &Node>) -> Option<NamedTools> {
    if n.kind == "mcp" {
        let mut tools: Vec<String> = Vec::new();
        for t in names_of(n.attrs.get("tools")).into_iter().chain(names_of(n.attrs.get("allow"))) {
            if !tools.contains(&t) {
                tools.push(t);
            }
        }
        return Some(NamedTools { targets: remote_targets("mcp", &n.attrs), tools });
    }
    let name = match n.attrs.get("name") {
        Some(Value::String(s)) if n.kind == "tool" && !js_trim(s).is_empty() => js_trim(s).to_string(),
        _ => return None,
    };
    let server = n.attrs.get("server").and_then(Value::as_str).map(js_trim).unwrap_or("");
    // (the server a tool is on: an MCP server, or a service — an API's operation, S32)
    let targets = if let Some(id) = server.strip_prefix('#') {
        match by_id.get(id) {
            Some(on) if on.kind == "mcp" || on.kind == "service" => remote_targets(&on.kind, &on.attrs),
            Some(_) => Vec::new(),
            None => remote_targets("mcp", &server_attrs(server)),
        }
    } else if !server.is_empty() {
        remote_targets("mcp", &server_attrs(server))
    } else {
        Vec::new()
    };
    Some(NamedTools { targets, tools: vec![name] })
}

fn server_attrs(server: &str) -> Attrs {
    let mut a = Attrs::new();
    a.insert("server".into(), server.into());
    a
}

/// The document's directives by their ids (the first of an id wins), for a `tool`'s `server=#id`.
fn objects_by_id(body: &[Node]) -> HashMap<&str, &Node> {
    let mut all = HashMap::new();
    crate::objects::walk(body, &mut |n, _| {
        if let Some(Value::String(id)) = n.attrs.get("id") {
            all.entry(id.as_str()).or_insert(n);
        }
        true
    });
    all
}

// ---- the reader's checks ----

/// The reader's S34 checks: each layer's shape (`invalid-metadata` errors), then each connected object against the
/// effective policy — `tool-blocked` and `integration-not-allowed` warnings. Returns the effective policy.
pub(crate) fn check(
    front: &Object,
    order: &crate::types::KeyOrder,
    at: u32,
    host_option: Option<&PolicyLayer>,
    body: &[Node],
    out: &mut Vec<crate::types::Diagnostic>,
) -> Option<Policy> {
    use crate::types::{Diagnostic, Severity};
    let mut layer = |key: &str| -> Option<PolicyLayer> {
        let v = front.get(key)?;
        let written = |path: &[&str], m: &Object| order.keys(&crate::types::KeyOrder::path(key, path), m);
        let (l, problems) = layer_in_order(v, key, &written);
        for p in problems {
            out.push(Diagnostic::new("invalid-metadata", Severity::Error, p.message, at));
        }
        l
    };
    let from_matter = layer(HOST_POLICY_KEY);
    let author = layer(AUTHOR_POLICY_KEY);
    let host = from_matter.as_ref().or(host_option);
    let policy = merge_policy(host, author.as_ref())?;
    let host_only = merge_policy(host, None);
    let by_id = objects_by_id(body);
    crate::objects::walk(body, &mut |n, _| {
        let line = n.range.map_or(0, |r| r.start);
        if let Some(named) = named_in(n, &by_id) {
            for tool in &named.tools {
                if !policy.tool_blocked(&named.targets, tool) {
                    continue;
                }
                let by_host = host_only.as_ref().is_some_and(|p| p.tool_blocked(&named.targets, tool));
                let whose = if by_host { "in your workspace" } else { "by this instruction's integrations" };
                let mut d = Diagnostic::new("tool-blocked", Severity::Warning, format!("{tool}: this tool is blocked {whose}"), line);
                d.target = tool.clone();
                d.remedy = if by_host {
                    "Use another tool, or ask an admin to allow it in Integrations"
                } else {
                    "Use another tool, or allow it in the front matter's integrations"
                }
                .into();
                out.push(d);
            }
        }
        let targets = remote_targets(&n.kind, &n.attrs);
        if !policy.targets_allowed(&targets) {
            let name = match (n.attrs.get("title"), n.attrs.get("id")) {
                (Some(Value::String(t)), _) => t.clone(),
                (_, Some(Value::String(id))) => format!("#{id}"),
                _ => n.kind.clone(),
            };
            let noun = match n.kind.as_str() {
                "mcp" => "MCP server",
                k => k,
            };
            let by_host = host_only.as_ref().is_some_and(|p| !p.targets_allowed(&targets));
            let whose = if by_host { "your workspace's" } else { "this instruction's" };
            let mut d = Diagnostic::new(
                "integration-not-allowed",
                Severity::Warning,
                format!("{name}: this {noun} is not one of {whose} integrations, so it is not used"),
                line,
            );
            d.target = targets[0].clone();
            d.remedy = if by_host {
                "Use one of your integrations, or ask an admin to add it"
            } else {
                "Use one of the integrations the front matter allows"
            }
            .into();
            out.push(d);
        }
        true
    });
    Some(policy)
}

// ---- the host's block in the served text ----

fn json_string(s: &str) -> String {
    serde_json::to_string(s).unwrap_or_default()
}

fn flow_list(xs: &[String]) -> String {
    format!("[{}]", xs.iter().map(|x| json_string(x)).collect::<Vec<_>>().join(", "))
}

/// A host's layer as the lines it serves: `host-integrations:`, then each key on a line of its own indented two
/// spaces (a server's tools as a JSON object), each line ending in LF; `None` when the layer says nothing.
pub fn host_block(layer: Option<&PolicyLayer>) -> Option<String> {
    let layer = layer?;
    if layer.allowed.is_none() && layer.servers.is_none() {
        return None;
    }
    let mut out = format!("{HOST_POLICY_KEY}:\n");
    if let Some(a) = &layer.allowed {
        out += &format!("  allowed: {}\n", flow_list(&sorted(a.iter().cloned())));
    }
    let servers = layer.servers.as_ref().map(|s| sorted(s.keys().cloned())).unwrap_or_default();
    if !servers.is_empty() {
        out += "  servers:\n";
        for s in servers {
            let t = &layer.servers.as_ref().expect("servers")[&s];
            let mut parts = Vec::new();
            if let Some(a) = &t.allowed {
                parts.push(format!("\"allowed\": {}", flow_list(&sorted(a.iter().cloned()))));
            }
            if let Some(b) = &t.blocked {
                parts.push(format!("\"blocked\": {}", flow_list(&sorted(b.iter().cloned()))));
            }
            if let Some(d) = t.default {
                parts.push(format!("\"default\": \"{}\"", d.as_str()));
            }
            out += &format!("    {}: {{{}}}\n", json_string(&s), parts.join(", "));
        }
    }
    Some(out)
}

/// The text as a host serves it with its block: right after the front matter's opening line, or, with no front
/// matter, in one of its own before the text (after a byte-order mark, which stays first).
pub fn with_host_block(text: &str, block: Option<&str>) -> String {
    let Some(block) = block else { return text.to_string() };
    let bom = if text.starts_with('\u{feff}') { "\u{feff}" } else { "" };
    let rest = &text[bom.len()..];
    match fence(rest.as_bytes()) {
        Some(n) => format!("{bom}{}{block}{}", &rest[..n], &rest[n..]),
        None => format!("{bom}---\n{block}---\n{rest}"),
    }
}

const BOM: &[u8] = "\u{feff}".as_bytes();

/// The length of a `---` line with its line ending at the start of `b`, if it is one.
fn fence(b: &[u8]) -> Option<usize> {
    let rest = b.strip_prefix(b"---")?;
    match rest {
        [b'\r', b'\n', ..] => Some(5),
        [b'\r', ..] | [b'\n', ..] => Some(4),
        _ => None,
    }
}

/// The length of a line ending in LF with no CR in it, at the start of `b`.
fn lf_line(b: &[u8]) -> Option<usize> {
    let end = b.iter().position(|&c| c == b'\n' || c == b'\r')?;
    (b[end] == b'\n').then_some(end + 1)
}

/// What an author may have signed, given a served text: the text itself and, when its front matter opens with the
/// host's block, the text without it — and without the front matter left empty, for a host that made one.
pub fn authored_candidates(text: &[u8]) -> Vec<Vec<u8>> {
    let bom = if text.starts_with(BOM) { BOM.len() } else { 0 };
    let rest = &text[bom..];
    let Some(open) = fence(rest) else { return vec![text.to_vec()] };
    let after = &rest[open..];
    let key = format!("{HOST_POLICY_KEY}:");
    if !after.starts_with(key.as_bytes()) {
        return vec![text.to_vec()];
    }
    let Some(mut n) = lf_line(after) else { return vec![text.to_vec()] };
    while matches!(after.get(n), Some(b' ' | b'\t')) {
        match lf_line(&after[n..]) {
            Some(k) => n += k,
            None => break,
        }
    }
    let mut stripped = text[..bom + open].to_vec();
    stripped.extend_from_slice(&after[n..]);
    let mut out = vec![text.to_vec(), stripped.clone()];
    if let Some(a) = fence(&stripped[bom..])
        && let Some(b) = fence(&stripped[bom + a..])
    {
        let mut empty = text[..bom].to_vec();
        empty.extend_from_slice(&stripped[bom + a + b..]);
        out.push(empty);
    }
    out
}

/// The WHATWG URL parser's answer for an http(s) URL, as `normalize_target` serializes it: what ECMAScript's
/// `new URL` gives (`protocol//host` + the path without trailing slashes + `search`), or `None` where it throws.
mod url {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";

    fn encode(out: &mut String, s: &str, set: impl Fn(u8) -> bool) {
        for &b in s.as_bytes() {
            if !(0x20..=0x7e).contains(&b) || set(b) {
                out.push('%');
                out.push(HEX[(b >> 4) as usize] as char);
                out.push(HEX[(b & 15) as usize] as char);
            } else {
                out.push(b as char);
            }
        }
    }

    fn path_set(b: u8) -> bool {
        matches!(b, b' ' | b'"' | b'#' | b'<' | b'>' | b'?' | b'`' | b'{' | b'}')
    }

    fn query_set(b: u8) -> bool {
        matches!(b, b' ' | b'"' | b'#' | b'<' | b'>' | b'\'')
    }

    fn percent_decode(s: &str) -> Vec<u8> {
        let b = s.as_bytes();
        let mut out = Vec::with_capacity(b.len());
        let mut i = 0;
        while i < b.len() {
            if b[i] == b'%'
                && i + 2 < b.len()
                && let (Some(h), Some(l)) = ((b[i + 1] as char).to_digit(16), (b[i + 2] as char).to_digit(16))
            {
                out.push((h * 16 + l) as u8);
                i += 3;
                continue;
            }
            out.push(b[i]);
            i += 1;
        }
        out
    }

    pub(super) fn normalize(input: &str) -> Option<String> {
        // leading and trailing C0 controls and spaces go, and every tab and newline
        let s: String = input.trim_matches(|c: char| c <= ' ').chars().filter(|c| !matches!(c, '\t' | '\n' | '\r')).collect();
        let colon = s.find(':')?;
        let scheme = s[..colon].to_ascii_lowercase();
        let default_port = match scheme.as_str() {
            "http" => "80",
            "https" => "443",
            _ => return None,
        };
        let rest = s[colon + 1..].trim_start_matches(['/', '\\']);
        let end = rest.find(['/', '\\', '?', '#']).unwrap_or(rest.len());
        let (authority, rest) = rest.split_at(end);
        let host_port = match authority.rfind('@') {
            Some(at) => &authority[at + 1..],
            None => authority,
        };
        let (host, port) = split_port(host_port)?;
        let host = parse_host(host)?;
        let port = match port {
            None | Some("") => String::new(),
            Some(p) => {
                if !p.bytes().all(|b| b.is_ascii_digit()) {
                    return None;
                }
                let digits = p.trim_start_matches('0');
                if digits.len() > 5 {
                    return None;
                }
                let n: u32 = if digits.is_empty() { 0 } else { digits.parse().ok()? };
                if n > 65535 {
                    return None;
                }
                let n = n.to_string();
                if n == default_port { String::new() } else { format!(":{n}") }
            }
        };
        let rest = rest.split('#').next().unwrap_or("");
        let (path, query) = match rest.find('?') {
            Some(q) => (&rest[..q], Some(&rest[q + 1..])),
            None => (rest, None),
        };
        let pathname = pathname(path);
        let mut out = format!("{scheme}://{host}{port}");
        if pathname.len() > 1 {
            out.push_str(pathname.trim_end_matches('/'));
        }
        if let Some(q) = query
            && !q.is_empty()
        {
            out.push('?');
            encode(&mut out, q, query_set);
        }
        Some(out)
    }

    /// The host and the port, split at the first colon outside brackets.
    fn split_port(s: &str) -> Option<(&str, Option<&str>)> {
        let mut inside = false;
        for (i, c) in s.char_indices() {
            match c {
                '[' => inside = true,
                ']' => inside = false,
                ':' if !inside => return Some((&s[..i], Some(&s[i + 1..]))),
                _ => {}
            }
        }
        Some((s, None))
    }

    fn pathname(path: &str) -> String {
        let mut segments: Vec<String> = Vec::new();
        let raw: Vec<&str> = if path.is_empty() { vec![""] } else { path[1..].split(['/', '\\']).collect() };
        let last = raw.len() - 1;
        for (i, seg) in raw.iter().enumerate() {
            let mut buf = String::new();
            encode(&mut buf, seg, path_set);
            let lower = buf.to_ascii_lowercase();
            let double = matches!(lower.as_str(), ".." | ".%2e" | "%2e." | "%2e%2e");
            let single = matches!(lower.as_str(), "." | "%2e");
            if double {
                segments.pop();
                if i == last {
                    segments.push(String::new());
                }
            } else if single {
                if i == last {
                    segments.push(String::new());
                }
            } else {
                segments.push(buf);
            }
        }
        format!("/{}", segments.join("/"))
    }

    fn parse_host(s: &str) -> Option<String> {
        if let Some(inner) = s.strip_prefix('[') {
            let inner = inner.strip_suffix(']')?;
            return Some(format!("[{}]", ipv6(inner)?));
        }
        if s.is_empty() {
            return None;
        }
        let decoded = String::from_utf8(percent_decode(s)).ok()?;
        let domain = decoded.to_lowercase();
        if domain.is_empty()
            || domain.chars().any(|c| {
                c < ' ' || matches!(c, ' ' | '#' | '%' | '/' | ':' | '<' | '>' | '?' | '@' | '[' | '\\' | ']' | '^' | '|' | '\u{7f}')
            })
        {
            return None;
        }
        if ends_in_number(&domain) {
            return ipv4(&domain);
        }
        Some(domain)
    }

    fn ends_in_number(s: &str) -> bool {
        let mut parts: Vec<&str> = s.split('.').collect();
        if parts.last() == Some(&"") {
            if parts.len() == 1 {
                return false;
            }
            parts.pop();
        }
        let Some(last) = parts.last() else { return false };
        if !last.is_empty() && last.bytes().all(|b| b.is_ascii_digit()) {
            return true;
        }
        let hex = last.strip_prefix("0x").or_else(|| last.strip_prefix("0X"));
        hex.is_some_and(|h| h.bytes().all(|b| b.is_ascii_hexdigit()))
    }

    fn ipv4_number(s: &str) -> Option<u64> {
        if s.is_empty() {
            return None;
        }
        let (digits, radix) = if let Some(h) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
            (h, 16)
        } else if s.len() > 1 && s.starts_with('0') {
            (&s[1..], 8)
        } else {
            (s, 10)
        };
        if digits.is_empty() {
            return Some(0);
        }
        if !digits.chars().all(|c| c.is_digit(radix)) {
            return None;
        }
        let trimmed = digits.trim_start_matches('0');
        if trimmed.len() > 12 {
            return Some(u64::MAX);
        }
        u64::from_str_radix(if trimmed.is_empty() { "0" } else { trimmed }, radix).ok()
    }

    fn ipv4(s: &str) -> Option<String> {
        let mut parts: Vec<&str> = s.split('.').collect();
        if parts.last() == Some(&"") && parts.len() > 1 {
            parts.pop();
        }
        if parts.len() > 4 {
            return None;
        }
        let nums: Vec<u64> = parts.iter().map(|p| ipv4_number(p)).collect::<Option<_>>()?;
        let (last, init) = nums.split_last()?;
        if init.iter().any(|&n| n > 255) || *last >= 256u64.pow(5 - nums.len() as u32) {
            return None;
        }
        let mut v = *last;
        for (i, &n) in init.iter().enumerate() {
            v += n * 256u64.pow(3 - i as u32);
        }
        Some(format!("{}.{}.{}.{}", v >> 24, (v >> 16) & 255, (v >> 8) & 255, v & 255))
    }

    fn ipv6(s: &str) -> Option<String> {
        let mut addr = [0u16; 8];
        let c: Vec<char> = s.chars().collect();
        let (mut piece, mut compress, mut p) = (0usize, None::<usize>, 0usize);
        if c.first() == Some(&':') {
            if c.get(1) != Some(&':') {
                return None;
            }
            p = 2;
            piece = 1;
            compress = Some(1);
        }
        while p < c.len() {
            if piece == 8 {
                return None;
            }
            if c[p] == ':' {
                if compress.is_some() {
                    return None;
                }
                p += 1;
                piece += 1;
                compress = Some(piece);
                continue;
            }
            let (mut value, mut length) = (0u32, 0);
            while length < 4 && p < c.len() && c[p].is_ascii_hexdigit() {
                value = value * 16 + c[p].to_digit(16)?;
                p += 1;
                length += 1;
            }
            if p < c.len() && c[p] == '.' {
                if length == 0 || piece > 6 {
                    return None;
                }
                p -= length;
                let mut seen = 0;
                while p < c.len() {
                    let mut v4: Option<u32> = None;
                    if seen > 0 {
                        if c[p] == '.' && seen < 4 {
                            p += 1;
                        } else {
                            return None;
                        }
                    }
                    if p >= c.len() || !c[p].is_ascii_digit() {
                        return None;
                    }
                    while p < c.len() && c[p].is_ascii_digit() {
                        let n = c[p].to_digit(10)?;
                        v4 = match v4 {
                            None => Some(n),
                            Some(0) => return None,
                            Some(x) => Some(x * 10 + n),
                        };
                        if v4? > 255 {
                            return None;
                        }
                        p += 1;
                    }
                    addr[piece] = (addr[piece] as u32 * 256 + v4?) as u16;
                    seen += 1;
                    if seen == 2 || seen == 4 {
                        piece += 1;
                    }
                }
                if seen != 4 {
                    return None;
                }
                break;
            } else if p < c.len() && c[p] == ':' {
                p += 1;
                if p >= c.len() {
                    return None;
                }
            } else if p < c.len() {
                return None;
            }
            addr[piece] = value as u16;
            piece += 1;
        }
        if let Some(cp) = compress {
            let mut swaps = piece - cp;
            piece = 7;
            while piece != 0 && swaps > 0 {
                addr.swap(piece, cp + swaps - 1);
                piece -= 1;
                swaps -= 1;
            }
        } else if piece != 8 {
            return None;
        }
        // the longest run of two or more zero pieces is compressed (the first of equal ones)
        let (mut best, mut best_len, mut i) = (None::<usize>, 1usize, 0usize);
        while i < 8 {
            if addr[i] == 0 {
                let start = i;
                while i < 8 && addr[i] == 0 {
                    i += 1;
                }
                if i - start > best_len {
                    best = Some(start);
                    best_len = i - start;
                }
            } else {
                i += 1;
            }
        }
        let mut out = String::new();
        let mut ignore0 = false;
        for (i, piece) in addr.iter().enumerate() {
            if ignore0 && *piece == 0 {
                continue;
            }
            ignore0 = false;
            if best == Some(i) {
                out.push_str(if i == 0 { "::" } else { ":" });
                ignore0 = true;
                continue;
            }
            out.push_str(&format!("{piece:x}"));
            if i != 7 {
                out.push(':');
            }
        }
        Some(out)
    }
}