autumn-web 0.9.0

An opinionated, convention-over-configuration web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
//! Agent readiness (AEO) by default.
//!
//! AEO means "Agent Engine Optimization". An Autumn app tells AI
//! agents what it is, how to read it, and what they can do, with no code.
//! The checks follow <https://isitagentready.com>.
//!
//! | Part | Default |
//! |---|---|
//! | `robots.txt` content signals and AI crawler groups | On |
//! | `Accept: text/markdown` negotiation | On |
//! | Homepage `Link` headers | On |
//!
//! Turn each part off in `[aeo]`:
//!
//! ```toml
//! [aeo]
//! enabled = true
//! markdown = true
//!
//! [aeo.content_signals]
//! search = true
//! ai_input = true
//! ai_train = false
//!
//! [aeo.ai_crawlers]
//! training = "disallow"
//! ```
//!
//! See `docs/guide/aeo.md`.

pub mod commerce;
pub mod dns_aid;
pub(crate) mod documents;
mod entities;
pub mod markdown;
pub(crate) mod negotiate;
pub mod robots;
pub mod web_bot_auth;
pub mod webmcp;

use std::sync::Arc;

use axum::body::Body;
use axum::http::{HeaderValue, Method, Request};
use axum::response::{IntoResponse as _, Response};
use serde::Deserialize;

pub use documents::{AgentSkill, AgentSkillError};
pub use robots::{AI_SEARCH_CRAWLERS, AI_TRAINING_CRAWLERS, AI_USER_FETCHERS, BotPolicy};

/// `[aeo]` settings.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
#[allow(clippy::struct_excessive_bools)] // independent on/off switches
pub struct AeoConfig {
    /// Master switch. `false` turns every AEO part off.
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Content signals in `robots.txt`.
    #[serde(default)]
    pub content_signals: ContentSignalsConfig,

    /// AI crawler groups in `robots.txt`.
    #[serde(default)]
    pub ai_crawlers: AiCrawlersConfig,

    /// Site name for `llms.txt`, the server card, and the ARD manifest.
    /// Default: the `OpenAPI` title, else the host name.
    #[serde(default)]
    pub site_name: Option<String>,

    /// One-line site summary. Default: the `OpenAPI` description.
    #[serde(default)]
    pub site_description: Option<String>,

    /// Answer `Accept: text/markdown` with a Markdown copy of HTML pages.
    #[serde(default = "default_true")]
    pub markdown: bool,

    /// Largest HTML body (bytes) to convert. A larger page stays HTML.
    #[serde(default = "default_markdown_max_bytes")]
    pub markdown_max_bytes: usize,

    /// Send agent `Link` headers on the homepage.
    #[serde(default = "default_true")]
    pub link_headers: bool,

    /// Serve `/llms.txt`.
    #[serde(default = "default_true")]
    pub llms_txt: bool,

    /// Publish the generated `site-guide` agent skill.
    #[serde(default = "default_true")]
    pub site_guide_skill: bool,

    /// Publish the MCP tool list (server card, `WebMCP`, `site-guide`). Set
    /// `false` when a proxy or an app-wide layer guards `/mcp`. A
    /// `secure_mcp` endpoint never publishes its tools.
    #[serde(default = "default_true")]
    pub publish_tools: bool,

    /// `/auth.md` settings.
    #[serde(default)]
    pub auth_md: AuthMdConfig,

    /// OAuth discovery settings.
    #[serde(default)]
    pub oauth: OAuthConfig,

    /// Web Bot Auth key settings.
    #[serde(default)]
    pub web_bot_auth: web_bot_auth::WebBotAuthConfig,

    /// x402 payment settings for [`AeoConfig::paid_routes`].
    #[serde(default)]
    pub x402: commerce::X402Config,

    /// Priced routes (x402 challenge, MPP discovery).
    #[serde(default)]
    pub paid_routes: Vec<commerce::PaidRoute>,
}

impl AeoConfig {
    /// Refuse an x402 route that can never match a request: its handler
    /// would run free.
    ///
    /// # Errors
    /// Names the first such route.
    pub fn validate(&self) -> Result<(), String> {
        if !self.enabled {
            return Ok(());
        }
        for route in self.paid_routes.iter().filter(|r| r.is_x402()) {
            if let Some(problem) = commerce::unmatchable_route(route) {
                return Err(format!("[[aeo.paid_routes]] {problem}"));
            }
        }
        if let Some(problem) = commerce::mixed_protocol_route(&self.paid_routes) {
            return Err(format!("[[aeo.paid_routes]] {problem}"));
        }
        Ok(())
    }
}

impl Default for AeoConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            content_signals: ContentSignalsConfig::default(),
            ai_crawlers: AiCrawlersConfig::default(),
            site_name: None,
            site_description: None,
            markdown: true,
            markdown_max_bytes: default_markdown_max_bytes(),
            link_headers: true,
            llms_txt: true,
            site_guide_skill: true,
            publish_tools: true,
            auth_md: AuthMdConfig::default(),
            oauth: OAuthConfig::default(),
            web_bot_auth: web_bot_auth::WebBotAuthConfig::default(),
            x402: commerce::X402Config::default(),
            paid_routes: Vec::new(),
        }
    }
}

/// `[aeo.auth_md]`: the `/auth.md` page for agents.
///
/// Autumn serves it when the app has an MCP server, an `OpenAPI` document, or
/// OAuth settings.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AuthMdConfig {
    /// Serve `/auth.md`.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Page where an agent or its user gets a credential.
    #[serde(default)]
    pub registration_url: Option<String>,
    /// Extra Markdown added under "Register".
    #[serde(default)]
    pub instructions: Option<String>,
}

impl Default for AuthMdConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            registration_url: None,
            instructions: None,
        }
    }
}

/// `[aeo.oauth]`: OAuth discovery documents.
///
/// Autumn publishes only the values set here. It does not run an
/// authorization server.
#[derive(Debug, Clone, Default, Deserialize)]
#[non_exhaustive]
pub struct OAuthConfig {
    /// Issuer URLs of the authorization servers for this API. When set,
    /// Autumn serves `/.well-known/oauth-protected-resource` (RFC 9728).
    #[serde(default)]
    pub authorization_servers: Vec<String>,
    /// Scopes the API accepts.
    #[serde(default)]
    pub scopes_supported: Vec<String>,
    /// Metadata for an authorization server at this origin. When `issuer`
    /// is set, Autumn serves `/.well-known/oauth-authorization-server`
    /// (RFC 8414).
    #[serde(default)]
    pub authorization_server: AuthorizationServerConfig,
}

/// `[aeo.oauth.authorization_server]`: RFC 8414 metadata fields.
#[derive(Debug, Clone, Default, Deserialize)]
#[non_exhaustive]
pub struct AuthorizationServerConfig {
    /// `issuer`. Required to publish the document.
    #[serde(default)]
    pub issuer: Option<String>,
    /// `authorization_endpoint`.
    #[serde(default)]
    pub authorization_endpoint: Option<String>,
    /// `token_endpoint`.
    #[serde(default)]
    pub token_endpoint: Option<String>,
    /// `jwks_uri`.
    #[serde(default)]
    pub jwks_uri: Option<String>,
    /// `registration_endpoint`.
    #[serde(default)]
    pub registration_endpoint: Option<String>,
    /// `scopes_supported`.
    #[serde(default)]
    pub scopes_supported: Vec<String>,
    /// `response_types_supported`. Default: `["code"]`.
    #[serde(default)]
    pub response_types_supported: Vec<String>,
    /// `grant_types_supported`.
    #[serde(default)]
    pub grant_types_supported: Vec<String>,
    /// `code_challenge_methods_supported`.
    #[serde(default)]
    pub code_challenge_methods_supported: Vec<String>,
    /// Auth.md agent registration endpoint (`agent_auth`).
    #[serde(default)]
    pub agent_identity_endpoint: Option<String>,
    /// Auth.md claim endpoint (`agent_auth`).
    #[serde(default)]
    pub agent_claim_endpoint: Option<String>,
    /// Auth.md identity types (`anonymous`, `identity_assertion`, ...).
    #[serde(default)]
    pub agent_identity_types: Vec<String>,
    /// Auth.md credential types an agent gets (`api_key`, `access_token`).
    #[serde(default)]
    pub agent_credential_types: Vec<String>,
    /// Auth.md assertion types (`urn:ietf:params:oauth:token-type:id-jag`,
    /// `verified_email`).
    #[serde(default)]
    pub agent_assertion_types: Vec<String>,
    /// Auth.md revocation endpoint.
    #[serde(default)]
    pub agent_revocation_endpoint: Option<String>,
    /// Auth.md events endpoint.
    #[serde(default)]
    pub agent_events_endpoint: Option<String>,
}

/// `[aeo.content_signals]`: the `Content-Signal` line in `robots.txt`.
///
/// See <https://contentsignals.org/>.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
#[allow(clippy::struct_excessive_bools)] // one bool per signal
pub struct ContentSignalsConfig {
    /// Write the `Content-Signal` line.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// `search`: use the content for a search index.
    #[serde(default = "default_true")]
    pub search: bool,
    /// `ai-input`: use the content as input to AI answers.
    #[serde(default = "default_true")]
    pub ai_input: bool,
    /// `ai-train`: use the content to train AI models.
    #[serde(default)]
    pub ai_train: bool,
}

impl Default for ContentSignalsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            search: true,
            ai_input: true,
            ai_train: false,
        }
    }
}

/// `[aeo.ai_crawlers]`: access for each class of AI crawler.
///
/// `allow` puts the class in the `User-agent: *` group, so it gets the same
/// rules as every crawler. `disallow` gives the class its own group with
/// `Disallow: /`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[non_exhaustive]
pub struct AiCrawlersConfig {
    /// AI search crawlers ([`AI_SEARCH_CRAWLERS`]).
    #[serde(default)]
    pub search: CrawlerAccess,
    /// Fetchers that run when a user asks an AI ([`AI_USER_FETCHERS`]).
    #[serde(default)]
    pub user_fetch: CrawlerAccess,
    /// AI training crawlers ([`AI_TRAINING_CRAWLERS`]).
    #[serde(default)]
    pub training: CrawlerAccess,
}

/// Access for one class of AI crawler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum CrawlerAccess {
    /// Same rules as `User-agent: *`.
    #[default]
    Allow,
    /// `Disallow: /`.
    Disallow,
}

/// Skills registered with `AppBuilder::agent_skill` (an `AppState`
/// extension).
#[derive(Debug, Clone, Default)]
pub(crate) struct RegisteredAgentSkills(pub Vec<AgentSkill>);

/// UCP and ACP documents registered on the app builder (an `AppState`
/// extension).
#[derive(Debug, Clone, Default)]
pub(crate) struct RegisteredCommerceDocs {
    /// `/.well-known/ucp`.
    pub(crate) ucp: Option<commerce::UcpProfile>,
    /// `/.well-known/acp.json`.
    pub(crate) acp: Option<commerce::AcpDiscovery>,
}

/// What AEO serves for one router: the site facts and the layer settings.
/// Stored as an `AppState` extension at router build time.
#[derive(Debug, Clone, Default)]
pub(crate) struct AeoSite {
    /// `[aeo] enabled`.
    pub(crate) enabled: bool,
    /// `[seo] base_url`.
    pub(crate) base_url: Option<String>,
    /// The facts the documents render from.
    pub(crate) facts: documents::SiteFacts,
    /// Settings for [`negotiate::NegotiateLayer`].
    pub(crate) negotiate: negotiate::NegotiateConfig,
}

impl AeoSite {
    /// Build the site from config and the facts the router collected.
    #[must_use]
    pub(crate) fn new(
        config: &crate::config::AutumnConfig,
        mut facts: documents::SiteFacts,
    ) -> Self {
        let aeo = &config.aeo;
        if aeo.site_name.is_some() {
            facts.name.clone_from(&aeo.site_name);
        }
        if aeo.site_description.is_some() {
            facts.description.clone_from(&aeo.site_description);
        }
        facts.site_guide_skill = aeo.site_guide_skill;
        facts.llms_txt = aeo.llms_txt;
        facts.markdown = aeo.markdown;
        facts.auth_md = aeo.auth_md.clone();
        facts.oauth = aeo.oauth.clone();
        // OAuth discovery (RFC 8414, RFC 9728) asks the host root, which an
        // app served below a path prefix does not answer.
        facts.prefixed = !base_path(config).is_empty();
        facts
            .csrf_header
            .clone_from(&config.security.csrf.token_header);
        facts.csrf_required = facts
            .mcp
            .as_ref()
            .is_some_and(|mcp| csrf_checks_post(config, &mcp.path));
        if !aeo.publish_tools
            && let Some(mcp) = facts.mcp.as_mut()
        {
            mcp.public_tools = false;
            mcp.tools.clear();
        }
        facts.robots_txt = aeo.enabled.then(|| default_robots_txt(config));
        facts.sitemap = aeo.enabled;
        warn_on_config(config);
        // The master switch covers signing too: with AEO off the key
        // directory is not served, so a signature could not be verified.
        let wba_key = aeo
            .enabled
            .then(|| {
                web_bot_auth::WebBotAuthKey::from_config(&aeo.web_bot_auth, &crate::config::OsEnv)
            })
            .flatten();
        facts.web_bot_auth = match wba_key {
            Some(Ok(key)) => Some(key),
            Some(Err(err)) => {
                tracing::warn!(error = %err, "aeo: Web Bot Auth key not loaded");
                None
            }
            None => None,
        };
        // One `Link` value per home page: each names its own Markdown copy.
        // Its targets sit below the path of `[seo] base_url`, if any.
        let base_path = base_path(config);
        let home_links: Vec<(String, HeaderValue)> = if aeo.link_headers && !facts.no_home {
            let homes = if facts.home_paths.is_empty() {
                vec!["/".to_owned()]
            } else {
                facts.home_paths.clone()
            };
            homes
                .into_iter()
                .filter_map(|home| {
                    let link = documents::homepage_link_header(&facts, &home, &base_path);
                    HeaderValue::from_str(&link).ok().map(|v| (home, v))
                })
                .collect()
        } else {
            Vec::new()
        };
        // The `*` signal `robots.txt` states: the operator's own, when
        // `additional_rules` sets one, else the configured one.
        let content_signal = robots::wildcard_signal(&config.seo.robots.additional_rules)
            .map(ToOwned::to_owned)
            .or_else(|| {
                aeo.content_signals
                    .enabled
                    .then(|| robots::content_signal_value(aeo.content_signals))
            })
            .and_then(|value| HeaderValue::from_str(&value).ok());
        // RFC 9728 §5.1: a `401` points at the protected resource metadata.
        let configured = documents::Origin::resolve(config.seo.base_url.as_deref(), None);
        let prefixed = facts.prefixed;
        let resource_metadata =
            (!aeo.oauth.authorization_servers.is_empty() && configured.configured && !prefixed)
                .then(|| {
                    HeaderValue::from_str(&format!(
                        "Bearer resource_metadata=\"{}\"",
                        configured.url(documents::OAUTH_RESOURCE_PATH)
                    ))
                    .ok()
                })
                .flatten();
        Self {
            enabled: aeo.enabled,
            base_url: config.seo.base_url.clone(),
            facts,
            negotiate: negotiate::NegotiateConfig {
                markdown: aeo.markdown,
                max_bytes: aeo.markdown_max_bytes,
                home_links,
                content_signal,
                resource_metadata_from_host: !aeo.oauth.authorization_servers.is_empty()
                    && !prefixed
                    && resource_metadata.is_none(),
                resource_metadata,
            },
        }
    }

    /// A signer for outbound requests, when AEO is on and a Web Bot Auth
    /// key is set.
    ///
    /// `Signature-Agent` is `[aeo.web_bot_auth] signature_agent`, else
    /// `[seo] base_url`.
    #[must_use]
    pub(crate) fn web_bot_auth_signer(
        &self,
        config: &crate::config::AutumnConfig,
    ) -> Option<web_bot_auth::WebBotAuthSigner> {
        if !self.enabled {
            return None;
        }
        let key = self.facts.web_bot_auth.clone()?;
        let wba = &config.aeo.web_bot_auth;
        let fallback = wba.signature_agent.is_none();
        let agent = wba
            .signature_agent
            .clone()
            .or_else(|| self.base_url.clone())?;
        // Verifiers look the key directory up at the agent's origin root. An
        // app below a `base_url` path serves it under that path instead, so
        // the base URL only names the agent when it has no path.
        if fallback && url::Url::parse(agent.trim()).is_ok_and(|u| !matches!(u.path(), "" | "/")) {
            tracing::warn!(
                base_url = %agent,
                "aeo: [seo] base_url has a path, so verifiers cannot find the key \
                 directory at its origin; set [aeo.web_bot_auth] signature_agent. \
                 Requests are not signed"
            );
            return None;
        }
        // Verifiers fetch the key directory from this origin, and accept
        // only an `https` one: a signature naming an `http` agent fails.
        if !url::Url::parse(agent.trim()).is_ok_and(|u| u.scheme() == "https" && u.has_host()) {
            tracing::warn!(
                signature_agent = %agent,
                "aeo: Signature-Agent is not an https URL; requests are not signed"
            );
            return None;
        }
        let signer = web_bot_auth::WebBotAuthSigner::new(key, agent.trim());
        Some(match wba.expires_secs {
            Some(secs) => signer.expires_secs(secs),
            None => signer,
        })
    }

    /// The response layer, or `None` when AEO is off.
    #[must_use]
    pub(crate) fn layer(&self) -> Option<negotiate::NegotiateLayer> {
        self.enabled
            .then(|| negotiate::NegotiateLayer::new(self.negotiate.clone()))
    }
}

/// Router fallback: serve an AEO document for an unmatched `GET`/`HEAD`,
/// else the framework 404.
///
/// Serving from the fallback means an application route at the same path
/// always wins, and a generated path can never collide with one.
#[cfg(test)]
pub(crate) async fn fallback(site: Option<Arc<AeoSite>>, req: Request<Body>) -> Response {
    match serve_document(site, &req) {
        Some(res) => res,
        None => {
            crate::middleware::error_page_filter::fallback_404_handler(
                req.method().clone(),
                req.uri().clone(),
            )
            .await
        }
    }
}

/// The generated document at `req`'s path, if there is one (else the caller
/// answers: a mounted plugin, or the framework 404).
pub(crate) fn serve_document(site: Option<Arc<AeoSite>>, req: &Request<Body>) -> Option<Response> {
    let method = req.method().clone();
    let uri = req.uri().clone();
    let readable = method == Method::GET || method == Method::HEAD;
    if let Some(site) = site.filter(|s| s.enabled)
        && (readable || method == Method::OPTIONS)
        && documents::is_document_path(uri.path())
    {
        let (origin, host) = documents::Origin::for_request(site.base_url.as_deref(), req);
        let host = host.as_deref();
        if let Some(mut doc) = documents::render(&site.facts, &origin, uri.path()) {
            // The directory signature covers `@authority`: through another
            // trusted host a verifier would rebuild a different one.
            if uri.path() == web_bot_auth::DIRECTORY_PATH && !origin.is_request_authority(host) {
                doc.headers
                    .retain(|(name, _)| !matches!(*name, "signature" | "signature-input"));
            }
            return Some(document_response(doc, &method, req.headers()));
        }
    }
    None
}

/// Marks a generated document, so the response layer removes any
/// `Set-Cookie` that an inner layer (CSRF, session) added: a public
/// document must not carry one visitor's cookie to the next.
#[derive(Debug, Clone, Copy)]
pub(crate) struct AeoDocument;

/// With locale-prefixed routing, each page that is not excluded from it is
/// served at `/{locale}{path}` (the bare path only redirects), so it is
/// listed once per locale, as the `[seo]` sitemap lists it.
#[cfg_attr(not(feature = "i18n"), allow(dead_code))]
pub(crate) fn localize_pages(
    pages: Vec<documents::PageFacts>,
    locales: &[String],
    exclude_prefixes: &[String],
    exclude_exact: &[String],
) -> Vec<documents::PageFacts> {
    if locales.is_empty() {
        return pages;
    }
    let mut out = Vec::with_capacity(pages.len() * locales.len());
    for page in pages {
        if exclude_exact.contains(&page.path)
            || crate::seo::matches_locale_exclude_prefix(&page.path, exclude_prefixes)
        {
            out.push(page);
            continue;
        }
        for locale in locales {
            let path = if page.path == "/" {
                format!("/{locale}")
            } else {
                format!("/{locale}{}", page.path)
            };
            out.push(documents::PageFacts {
                path,
                ..page.clone()
            });
        }
    }
    out
}

/// Turn a rendered document into a response: `OPTIONS` preflight for CORS
/// documents, a strong `ETag`, and `304` for a matching `If-None-Match`.
fn document_response(
    doc: documents::Document,
    method: &Method,
    request_headers: &axum::http::HeaderMap,
) -> Response {
    use axum::http::{StatusCode, header};

    let etag = format!(
        "\"{}\"",
        &documents::sha256_digest(doc.body.as_bytes())["sha256:".len()..][..32]
    );
    // Weak comparison (RFC 9110 §13.1.2): a proxy may send `W/` back.
    let not_modified = request_headers
        .get_all(header::IF_NONE_MATCH)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .flat_map(|v| v.split(','))
        .map(|t| t.trim().trim_start_matches("W/"))
        .any(|t| t == etag || t == "*");
    let mut res = if *method == Method::OPTIONS {
        if !doc
            .headers
            .iter()
            .any(|(k, _)| *k == "access-control-allow-origin")
        {
            return StatusCode::NOT_FOUND.into_response();
        }
        StatusCode::NO_CONTENT.into_response()
    } else if not_modified {
        StatusCode::NOT_MODIFIED.into_response()
    } else {
        let len = doc.body.len();
        // HEAD gets the headers GET gets, with no body.
        let mut res = if *method == Method::HEAD {
            axum::body::Body::empty().into_response()
        } else {
            doc.body.into_response()
        };
        res.headers_mut().insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static(doc.content_type),
        );
        res.headers_mut()
            .insert(header::CONTENT_LENGTH, HeaderValue::from(len));
        res
    };
    let headers = res.headers_mut();
    if let Ok(v) = HeaderValue::from_str(&etag) {
        headers.insert(header::ETAG, v);
    }
    for (name, value) in doc.headers {
        if let Ok(value) = HeaderValue::from_str(&value) {
            headers.append(name, value);
        }
    }
    res.extensions_mut().insert(AeoDocument);
    res
}

/// The `robots.txt` AEO serves when no `[seo]` route does. Only the `dev`
/// and `test` profiles close the site: a custom profile name (`staging`,
/// `live`) must not hide a public site from search engines by accident.
fn default_robots_txt(config: &crate::config::AutumnConfig) -> String {
    robots::robots_txt_with_policy(robots_profile(config), None, &[], &robots_policy(config))
}

/// The profile AEO's own `robots.txt` uses: every profile but `dev` and
/// `test` (a custom `live` or `staging` one too) is a public site.
#[must_use]
pub(crate) fn robots_profile(config: &crate::config::AutumnConfig) -> &'static str {
    match config.profile.as_deref() {
        Some("dev" | "test") | None => "dev",
        Some(_) => "prod",
    }
}

/// Log the `[aeo]` settings that cannot work as written.
fn warn_on_config(config: &crate::config::AutumnConfig) {
    let aeo = &config.aeo;
    if !aeo.enabled {
        return;
    }
    let prod = matches!(config.profile.as_deref(), Some("prod" | "production"));
    if let Some(base) = config.seo.base_url.as_deref()
        && !documents::Origin::resolve(Some(base), None).configured
    {
        tracing::warn!(
            base_url = base,
            "aeo: [seo] base_url is not an http(s) URL without credentials, a query or a fragment; the \
             agent documents use the request Host instead, and a static build writes none"
        );
    }
    if prod && config.seo.base_url.is_none() {
        tracing::warn!(
            "aeo: set [seo] base_url in production; without it the agent documents use \
             the request Host and are not cached"
        );
    }
    for problem in commerce::paid_route_problems(&aeo.paid_routes) {
        tracing::warn!(
            "aeo: [[aeo.paid_routes]] {problem}; an x402 route answers 503, and the route \
             is not in the OpenAPI payment info"
        );
    }
    if !aeo.oauth.authorization_servers.is_empty() && !base_path(config).is_empty() {
        tracing::warn!(
            "aeo: [aeo.oauth] authorization_servers needs an app served at the host root: \
             [seo] base_url has a path, and RFC 9728 discovery asks the root; Autumn does \
             not publish the protected resource metadata"
        );
    }
    if let Some(issuer) = aeo.oauth.authorization_server.issuer.as_deref() {
        // With no `base_url` the origin comes from each request; check only
        // the issuer path here.
        let origin =
            documents::Origin::resolve(config.seo.base_url.as_deref().or(Some(issuer)), None);
        let facts = documents::SiteFacts {
            oauth: aeo.oauth.clone(),
            ..documents::SiteFacts::default()
        };
        if !base_path(config).is_empty() {
            tracing::warn!(
                issuer,
                "aeo: [aeo.oauth.authorization_server] needs an app served at the host \
                 root: [seo] base_url has a path, and RFC 8414 discovery asks the root; \
                 Autumn does not publish its metadata"
            );
        } else if documents::render(&facts, &origin, documents::OAUTH_SERVER_PATH).is_none() {
            tracing::warn!(
                issuer,
                "aeo: [aeo.oauth.authorization_server] issuer must be this site's origin \
                 with no path; Autumn does not publish its metadata"
            );
        }
    }
}

/// Path of the ARD manifest.
pub const AI_CATALOG_PATH: &str = "/.well-known/ai-catalog.json";

/// The agent documents a static build writes. The key directory is not
/// here: its signature expires.
const STATIC_DOCUMENT_PATHS: &[&str] = &[
    documents::LLMS_TXT_PATH,
    documents::SKILLS_INDEX_PATH,
    AI_CATALOG_PATH,
    documents::ARD_PATH,
    documents::API_CATALOG_PATH,
    documents::SERVER_CARD_PATH,
    documents::OAUTH_RESOURCE_PATH,
    documents::OAUTH_SERVER_PATH,
    documents::AUTH_MD_PATH,
    commerce::UCP_PATH,
    commerce::ACP_PATH,
];

/// Write the agent documents of `router` into the static build `dist`.
///
/// The documents hold absolute URLs, so without `[seo] base_url`
/// (`base_url` is `None`) only the `WebMCP` script is written: it holds none,
/// and a page's `head_tags` load it. A file that is already in `dist`
/// stays. `home_links` are the home pages' agent `Link` values: a home page
/// the build wrote gets its own in `_headers`. Returns the paths it wrote.
///
/// # Errors
///
/// Returns an I/O error when a file cannot be written.
pub(crate) async fn write_static_documents(
    router: axum::Router,
    base_url: Option<&str>,
    home_links: &[(String, HeaderValue)],
    dist: &std::path::Path,
) -> std::io::Result<Vec<String>> {
    use tower::ServiceExt as _;

    // The build has no request `Host`: without a usable base URL every
    // absolute link would point at localhost.
    let configured = documents::Origin::resolve(base_url, None).configured;
    let mut queue: Vec<String> = if configured {
        STATIC_DOCUMENT_PATHS
            .iter()
            .map(|p| (*p).to_owned())
            .collect()
    } else {
        Vec::new()
    };
    queue.push(webmcp::WEBMCP_JS_PATH.to_owned());
    let mut written = Vec::new();
    // The index names each skill by absolute URL: its local path follows
    // the site's base.
    let base = documents::Origin::resolve(base_url, None).base;
    // The skills index waits for its skills: a `SKILL.md` already in `dist`
    // is kept, and the index must name the digest of the bytes served.
    let mut index = None;
    // The response headers of each file written, for a static host.
    let mut host_headers: Vec<(String, Vec<(String, String)>)> = Vec::new();
    while let Some(path) = queue.pop() {
        // A build render: x402 charges the live request for these bytes.
        let Ok(req) = Request::get(path.as_str())
            .extension(crate::static_gen::RenderDeadlineExempt)
            .body(Body::empty())
        else {
            continue;
        };
        let Ok(res) = router.clone().oneshot(req).await;
        if res.status() != axum::http::StatusCode::OK
            || res.extensions().get::<AeoDocument>().is_none()
        {
            continue;
        }
        let headers = static_host_headers(res.headers());
        let Ok(body) = axum::body::to_bytes(res.into_body(), usize::MAX).await else {
            continue;
        };
        if path == documents::SKILLS_INDEX_PATH {
            queue.extend(skill_paths(&body, &base));
            index = Some((body, headers));
            continue;
        }
        let file = dist.join(path.trim_start_matches('/'));
        if tokio::fs::try_exists(&file).await.unwrap_or(false) {
            continue;
        }
        if let Some(parent) = file.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        tokio::fs::write(&file, &body).await?;
        // A host serves the script by its `.js` name; it needs no entry.
        if path != webmcp::WEBMCP_JS_PATH {
            host_headers.push((path.clone(), headers));
        }
        written.push(path);
    }
    if let Some((body, headers)) = index {
        let file = dist.join(documents::SKILLS_INDEX_PATH.trim_start_matches('/'));
        if !tokio::fs::try_exists(&file).await.unwrap_or(false) {
            let body = index_with_disk_digests(&body, &base, dist).await;
            if let Some(parent) = file.parent() {
                tokio::fs::create_dir_all(parent).await?;
            }
            tokio::fs::write(&file, &body).await?;
            host_headers.push((documents::SKILLS_INDEX_PATH.to_owned(), headers));
            written.push(documents::SKILLS_INDEX_PATH.to_owned());
        }
    }
    // A home page the build wrote keeps its agent `Link`, once the
    // documents it names are written too.
    if configured {
        for (home, link) in home_links {
            let Some(link) = link.to_str().ok().and_then(static_home_link) else {
                continue;
            };
            if static_page_exists(dist, home).await {
                host_headers.push((home.clone(), vec![("link".to_owned(), link)]));
            }
        }
    }
    // A static host serves a file by its extension and with no CORS: the
    // `_headers` file (Netlify, Cloudflare Pages) gives each document the
    // headers the server sends. One the app ships stays.
    if !host_headers.is_empty() {
        let file = dist.join(STATIC_HEADERS_FILE);
        if tokio::fs::try_exists(&file).await.unwrap_or(false) {
            tracing::warn!(
                "aeo: dist/{STATIC_HEADERS_FILE} exists; the agent documents' headers are not added to it"
            );
        } else {
            // Paths as the host sees `dist`. An app below a path prefix
            // deploys `dist` at that prefix, as it does its static pages,
            // which the build writes at their route paths too.
            tokio::fs::write(&file, headers_file(&host_headers)).await?;
            written.push(format!("/{STATIC_HEADERS_FILE}"));
        }
    }
    written.sort();
    Ok(written)
}

/// The skills index with each local skill's digest taken from the file in
/// `dist`: the one written, or one the build kept. Unchanged when every
/// digest already matches.
async fn index_with_disk_digests(index: &[u8], base: &str, dist: &std::path::Path) -> Vec<u8> {
    let Ok(mut value) = serde_json::from_slice::<serde_json::Value>(index) else {
        return index.to_vec();
    };
    let mut changed = false;
    if let Some(skills) = value.get_mut("skills").and_then(|s| s.as_array_mut()) {
        for skill in skills {
            let Some(path) = skill
                .get("url")
                .and_then(|u| u.as_str())
                .and_then(|u| skill_path(u, base))
            else {
                continue;
            };
            let Ok(bytes) = tokio::fs::read(dist.join(path.trim_start_matches('/'))).await else {
                continue;
            };
            let digest = serde_json::Value::String(documents::sha256_digest(&bytes));
            if skill.get("digest") != Some(&digest) {
                skill["digest"] = digest;
                changed = true;
            }
        }
    }
    if changed {
        serde_json::to_vec_pretty(&value).unwrap_or_else(|_| index.to_vec())
    } else {
        index.to_vec()
    }
}

/// The path of a usable `[seo] base_url`, without a trailing slash.
///
/// `/shop` for `https://example.com/shop`, empty for none or a root URL. An
/// app served below that prefix puts its links there, as
/// [`webmcp::head_tags_at`] does.
#[must_use]
pub fn base_path(config: &crate::config::AutumnConfig) -> String {
    documents::Origin::resolve(config.seo.base_url.as_deref(), None)
        .configured
        .then_some(config.seo.base_url.as_deref())
        .flatten()
        .and_then(|base| url::Url::parse(base.trim()).ok())
        .map(|url| url.path().trim_end_matches('/').to_owned())
        .unwrap_or_default()
}

/// The static-host headers file `autumn build` writes into `dist`.
const STATIC_HEADERS_FILE: &str = "_headers";

/// The headers of a generated document that a static host must send too:
/// its type, CORS, `Link` and cache policy. Validators and lengths are the
/// host's own.
fn static_host_headers(headers: &axum::http::HeaderMap) -> Vec<(String, String)> {
    headers
        .iter()
        .filter(|(name, _)| {
            let name = name.as_str();
            name == "content-type"
                || name == "cache-control"
                || name == "link"
                || name.starts_with("access-control-")
        })
        .filter_map(|(name, value)| {
            Some((name.as_str().to_owned(), value.to_str().ok()?.to_owned()))
        })
        .collect()
}

/// A home page's `Link` for a static host: every link but the Markdown copy,
/// which only the server can negotiate.
fn static_home_link(link: &str) -> Option<String> {
    let kept: Vec<String> = link
        .split(", <")
        .enumerate()
        .map(|(i, entry)| {
            if i == 0 {
                entry.to_owned()
            } else {
                format!("<{entry}")
            }
        })
        .filter(|entry| !entry.contains("type=\"text/markdown\""))
        .collect();
    (!kept.is_empty()).then(|| kept.join(", "))
}

/// `true` when the static build wrote the page at `path`
/// (`<path>/index.html`).
async fn static_page_exists(dist: &std::path::Path, path: &str) -> bool {
    let page = dist.join(path.trim_matches('/')).join("index.html");
    tokio::fs::try_exists(page).await.unwrap_or(false)
}

/// `files` in the `_headers` format: each path, then its headers indented.
fn headers_file(files: &[(String, Vec<(String, String)>)]) -> String {
    use std::fmt::Write as _;

    let mut out =
        String::from("# Written by `autumn build`: the agent documents' response headers.\n");
    for (path, headers) in files {
        if headers.is_empty() {
            continue;
        }
        let _ = writeln!(out, "\n{path}");
        for (name, value) in headers {
            let _ = writeln!(out, "  {name}: {value}");
        }
    }
    out
}

/// The local `SKILL.md` paths that a skills index names.
fn skill_paths(index: &[u8], base: &str) -> Vec<String> {
    serde_json::from_slice::<serde_json::Value>(index)
        .ok()
        .and_then(|v| v.get("skills")?.as_array().cloned())
        .unwrap_or_default()
        .iter()
        .filter_map(|s| skill_path(s.get("url")?.as_str()?, base))
        .map(str::to_owned)
        .collect()
}

/// The path of a skill `url` under the site's `base`, when it names a file
/// in `dist`: a local path that cannot climb out of it.
fn skill_path<'a>(url: &'a str, base: &str) -> Option<&'a str> {
    let path = url.strip_prefix(base)?;
    (path.starts_with('/') && !path.starts_with("//") && !path.contains("..")).then_some(path)
}

/// The `robots.txt` [`BotPolicy`] for `config`, with `Agentmap:` when
/// `[seo] base_url` is set.
#[must_use]
pub fn robots_policy(config: &crate::config::AutumnConfig) -> BotPolicy {
    let agentmap = config
        .aeo
        .enabled
        .then_some(config.seo.base_url.as_deref())
        .flatten()
        .map(|base| documents::Origin::resolve(Some(base), None))
        .filter(|origin| origin.configured)
        .map(|origin| origin.url(AI_CATALOG_PATH));
    BotPolicy::from_config(&config.aeo).agentmap(agentmap)
}

/// `true` when the CSRF layer checks a `POST` to `path`: protection is on,
/// `POST` is not a safe method, and neither an exempt path nor a webhook
/// endpoint (which the layer also exempts) covers it.
fn csrf_checks_post(config: &crate::config::AutumnConfig, path: &str) -> bool {
    let csrf = &config.security.csrf;
    let exempt: Vec<String> = csrf
        .exempt_paths
        .iter()
        .cloned()
        .chain(
            config
                .security
                .webhooks
                .endpoints
                .iter()
                .map(|e| e.path.clone()),
        )
        .collect();
    csrf.enabled
        && !csrf
            .safe_methods
            .iter()
            .any(|m| m.eq_ignore_ascii_case("POST"))
        && !crate::security::path::is_exempt_path(path, &exempt)
}

const fn default_markdown_max_bytes() -> usize {
    2 * 1024 * 1024
}

const fn default_true() -> bool {
    true
}

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

    fn site_router(config: &crate::config::AutumnConfig) -> axum::Router {
        let site = Arc::new(AeoSite::new(config, documents::SiteFacts::default()));
        axum::Router::new().fallback(move |req| fallback(Some(Arc::clone(&site)), req))
    }

    #[test]
    fn a_prefixed_app_publishes_no_oauth_metadata() {
        // Codex review: RFC 8414 discovery for `https://example.com` asks
        // `/.well-known/oauth-authorization-server` at the host root, which
        // an app below `/shop` does not answer.
        let mut config = crate::config::AutumnConfig::default();
        config.aeo.oauth.authorization_server.issuer = Some("https://example.com".to_owned());
        config.aeo.oauth.authorization_server.token_endpoint =
            Some("https://example.com/token".to_owned());
        let published = |config: &crate::config::AutumnConfig| {
            let site = AeoSite::new(config, documents::SiteFacts::default());
            let origin = documents::Origin::resolve(config.seo.base_url.as_deref(), None);
            documents::render(&site.facts, &origin, documents::OAUTH_SERVER_PATH).is_some()
        };
        config.seo.base_url = Some("https://example.com".to_owned());
        assert!(published(&config));
        config.seo.base_url = Some("https://example.com/shop".to_owned());
        assert!(!published(&config));

        // RFC 9728 §3 puts the protected resource metadata for
        // `https://example.com/shop` at the host root too.
        config.aeo.oauth.authorization_servers = vec!["https://auth.example".to_owned()];
        let site = AeoSite::new(&config, documents::SiteFacts::default());
        let origin = documents::Origin::resolve(config.seo.base_url.as_deref(), None);
        assert!(documents::render(&site.facts, &origin, documents::OAUTH_RESOURCE_PATH).is_none());
        assert!(site.negotiate.resource_metadata.is_none());
        assert!(!site.negotiate.resource_metadata_from_host);
        config.seo.base_url = Some("https://example.com".to_owned());
        let site = AeoSite::new(&config, documents::SiteFacts::default());
        let origin = documents::Origin::resolve(config.seo.base_url.as_deref(), None);
        assert!(documents::render(&site.facts, &origin, documents::OAUTH_RESOURCE_PATH).is_some());
        assert!(site.negotiate.resource_metadata.is_some());
    }

    #[tokio::test]
    async fn a_static_build_writes_the_agent_documents() {
        let mut config = crate::config::AutumnConfig::default();
        config.seo.base_url = Some("https://example.com".to_owned());
        let dist = tempfile::tempdir().unwrap();
        std::fs::write(dist.path().join("llms.txt"), "mine").unwrap();

        let written = write_static_documents(
            site_router(&config),
            config.seo.base_url.as_deref(),
            &[],
            dist.path(),
        )
        .await
        .unwrap();

        let read = |p: &str| std::fs::read_to_string(dist.path().join(p)).unwrap();
        assert_eq!(read("llms.txt"), "mine", "a file in dist stays");
        assert!(!written.iter().any(|p| p == "/llms.txt"), "{written:?}");
        assert!(read(".well-known/ai-catalog.json").contains("https://example.com"));
        let index: serde_json::Value =
            serde_json::from_str(&read(".well-known/agent-skills/index.json")).unwrap();
        let skill = index["skills"][0]["url"].as_str().unwrap();
        let skill = skill
            .strip_prefix("https://example.com/")
            .expect("absolute");
        assert!(read(skill).starts_with("---\n"));
        assert!(!dist.path().join(".well-known/api-catalog").exists());

        // Codex review (P2): a static host gets each document's headers.
        assert!(written.iter().any(|p| p == "/_headers"), "{written:?}");
        let headers = read("_headers");
        let index_entry = headers
            .split("\n\n")
            .find(|e| e.starts_with("/.well-known/agent-skills/index.json\n"))
            .unwrap_or_else(|| panic!("{headers}"));
        for want in [
            "  content-type: application/json",
            "  access-control-allow-origin: *",
            "  access-control-expose-headers: ETag",
        ] {
            assert!(index_entry.contains(want), "{want}:\n{headers}");
        }
        assert!(!headers.contains("/_autumn/webmcp.js"), "{headers}");
    }

    /// Codex review (P2): a static home page keeps its agent `Link` on a
    /// static host, less the Markdown copy the host cannot negotiate.
    #[tokio::test]
    async fn a_static_home_page_keeps_its_link_header() {
        let mut config = crate::config::AutumnConfig::default();
        config.seo.base_url = Some("https://example.com".to_owned());
        let dist = tempfile::tempdir().unwrap();
        std::fs::write(dist.path().join("index.html"), "<h1>Home</h1>").unwrap();
        let link = HeaderValue::from_static(
            "</llms.txt>; rel=\"describedby\"; type=\"text/plain\", \
             </>; rel=\"alternate\"; type=\"text/markdown\"",
        );
        let homes = [
            ("/".to_owned(), link.clone()),
            // No page in `dist`, so no entry.
            ("/fr".to_owned(), link),
        ];
        write_static_documents(
            site_router(&config),
            config.seo.base_url.as_deref(),
            &homes,
            dist.path(),
        )
        .await
        .unwrap();
        let headers = std::fs::read_to_string(dist.path().join("_headers")).unwrap();
        assert!(
            headers
                .contains("\n/\n  link: </llms.txt>; rel=\"describedby\"; type=\"text/plain\"\n"),
            "{headers}"
        );
        assert!(!headers.contains("rel=\"alternate\""), "{headers}");
        assert!(!headers.contains("\n/fr\n"), "{headers}");
    }

    /// Codex review (P2): an operator `*` signal in `additional_rules`
    /// replaces the configured one in the Markdown header too, as it does
    /// in `robots.txt`.
    #[test]
    fn the_markdown_signal_follows_the_robots_wildcard_signal() {
        let mut config = crate::config::AutumnConfig::default();
        let site = AeoSite::new(&config, documents::SiteFacts::default());
        assert_eq!(
            site.negotiate.content_signal.as_ref().unwrap(),
            robots::content_signal_value(config.aeo.content_signals).as_str()
        );
        config.seo.robots.additional_rules =
            vec!["Content-Signal: search=yes, ai-input=no, ai-train=yes".to_owned()];
        let site = AeoSite::new(&config, documents::SiteFacts::default());
        assert_eq!(
            site.negotiate.content_signal.as_ref().unwrap(),
            "search=yes, ai-input=no, ai-train=yes"
        );
    }

    /// Codex review (P2): `dist` is deployed at the base URL's path, pages
    /// and documents alike, so each `_headers` path is the file's path in
    /// `dist`.
    #[tokio::test]
    async fn a_static_headers_file_matches_the_files_in_dist() {
        let mut config = crate::config::AutumnConfig::default();
        config.seo.base_url = Some("https://example.com/shop".to_owned());
        let dist = tempfile::tempdir().unwrap();
        write_static_documents(
            site_router(&config),
            config.seo.base_url.as_deref(),
            &[],
            dist.path(),
        )
        .await
        .unwrap();
        let headers = std::fs::read_to_string(dist.path().join("_headers")).unwrap();
        let entry = "/.well-known/agent-skills/index.json";
        assert!(headers.contains(&format!("\n{entry}\n")), "{headers}");
        assert!(
            dist.path().join(entry.trim_start_matches('/')).exists(),
            "{headers}"
        );
        assert!(!headers.contains("/shop/"), "{headers}");
    }

    #[tokio::test]
    async fn a_static_build_keeps_the_apps_own_headers_file() {
        let mut config = crate::config::AutumnConfig::default();
        config.seo.base_url = Some("https://example.com".to_owned());
        let dist = tempfile::tempdir().unwrap();
        std::fs::write(dist.path().join("_headers"), "/*\n  X-Mine: 1\n").unwrap();
        let written = write_static_documents(
            site_router(&config),
            config.seo.base_url.as_deref(),
            &[],
            dist.path(),
        )
        .await
        .unwrap();
        assert!(!written.iter().any(|p| p == "/_headers"), "{written:?}");
        assert_eq!(
            std::fs::read_to_string(dist.path().join("_headers")).unwrap(),
            "/*\n  X-Mine: 1\n"
        );
    }

    #[tokio::test]
    async fn a_kept_skill_file_sets_its_index_digest() {
        let mut config = crate::config::AutumnConfig::default();
        config.seo.base_url = Some("https://example.com".to_owned());
        let dist = tempfile::tempdir().unwrap();
        let kept = dist
            .path()
            .join(".well-known/agent-skills/site-guide/SKILL.md");
        std::fs::create_dir_all(kept.parent().unwrap()).unwrap();
        std::fs::write(&kept, "---\nname: site-guide\ndescription: mine\n---\n").unwrap();

        write_static_documents(
            site_router(&config),
            config.seo.base_url.as_deref(),
            &[],
            dist.path(),
        )
        .await
        .unwrap();

        let index: serde_json::Value = serde_json::from_slice(
            &std::fs::read(dist.path().join(".well-known/agent-skills/index.json")).unwrap(),
        )
        .unwrap();
        let entry = index["skills"]
            .as_array()
            .unwrap()
            .iter()
            .find(|s| s["name"] == "site-guide")
            .unwrap();
        assert_eq!(
            entry["digest"],
            documents::sha256_digest(&std::fs::read(&kept).unwrap()),
            "the index names the bytes served"
        );
    }

    #[tokio::test]
    async fn a_static_build_without_a_usable_base_url_writes_only_the_script() {
        let config = crate::config::AutumnConfig::default();
        let dist = tempfile::tempdir().unwrap();
        for base in [
            None,
            Some("https://example.com?tenant=a"),
            Some("ftp://example.com"),
        ] {
            let written = write_static_documents(site_router(&config), base, &[], dist.path())
                .await
                .unwrap();
            assert!(
                written.iter().all(|p| p == webmcp::WEBMCP_JS_PATH),
                "{base:?}: {written:?}"
            );
        }
        assert!(!dist.path().join("llms.txt").exists());
        // The page `head_tags` load it, so a static site serves it too.
        assert!(dist.path().join("_autumn/webmcp.js").exists());
    }

    #[test]
    fn every_profile_but_dev_and_test_is_public() {
        let mut config = crate::config::AutumnConfig::default();
        for (profile, want) in [
            (None, "dev"),
            (Some("dev"), "dev"),
            (Some("test"), "dev"),
            (Some("prod"), "prod"),
            (Some("live"), "prod"),
        ] {
            config.profile = profile.map(str::to_owned);
            assert_eq!(robots_profile(&config), want, "{profile:?}");
        }
    }

    #[test]
    fn csrf_checks_a_post_to_mcp_unless_it_is_exempt() {
        let mut config = crate::config::AutumnConfig::default();
        config.security.csrf.enabled = false;
        assert!(!csrf_checks_post(&config, "/mcp"));
        config.security.csrf.enabled = true;
        assert!(csrf_checks_post(&config, "/mcp"));
        config.security.csrf.exempt_paths = vec!["/mcp".to_owned()];
        assert!(!csrf_checks_post(&config, "/mcp"));
        config.security.csrf.exempt_paths.clear();
        config.security.csrf.safe_methods.push("post".to_owned());
        assert!(!csrf_checks_post(&config, "/mcp"));
    }

    #[test]
    fn localized_pages_get_one_entry_per_locale() {
        let page = |path: &str| documents::PageFacts {
            path: path.to_owned(),
            title: "T".to_owned(),
            description: None,
        };
        let locales = ["en".to_owned(), "fr".to_owned()];
        let out = localize_pages(
            vec![page("/"), page("/about"), page("/api/docs"), page("/legal")],
            &locales,
            &["/api".to_owned()],
            &["/legal".to_owned()],
        );
        let paths: Vec<&str> = out.iter().map(|p| p.path.as_str()).collect();
        assert_eq!(
            paths,
            [
                "/en",
                "/fr",
                "/en/about",
                "/fr/about",
                "/api/docs",
                "/legal"
            ]
        );
        assert_eq!(localize_pages(vec![page("/x")], &[], &[], &[]).len(), 1);
    }

    #[tokio::test]
    async fn a_static_build_needs_a_base_url() {
        let config = crate::config::AutumnConfig::default();
        let dist = tempfile::tempdir().unwrap();
        let written = write_static_documents(site_router(&config), None, &[], dist.path())
            .await
            .unwrap();
        // Only the script, which holds no absolute URL.
        assert_eq!(written, [webmcp::WEBMCP_JS_PATH], "{written:?}");
    }
}