slabs-core 0.5.0

Core error, ID, config, and manifest primitives for Slabs
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
//! Core types for the Slabs web framework.
//!
//! This crate owns prefixed ULID generation, the unified HTTP error type,
//! environment configuration, and JSON route/job manifests.
//!
//! # Owned types
//!
//! - [`id::new`]: generates lowercase, time-sortable prefixed ULIDs such as `msg_01j...`.
//! - [`SlabError`] and [`SlabResult`]: explicit error enum returned by every transaction script and background job.
//! - [`Validate`]: multi-field procedural validation builder returning [`SlabError::ValidationErrors`].
//! - [`AppEnv`] and [`AppConfig`]: deployment environment and runtime configuration loaded from `DATABASE_URL` and `SLABS_*` environment variables, plus [`AppConfig::for_test`] for isolated tests and [`AppConfig::validate`] for fail-closed staging/production startup checks.
//! - [`AppManifest`], [`RouteMeta`], and [`JobMeta`]: JSON metadata returned by `/_slabs/manifest` and `slabs manifest`, plus `OpenAPI` 3.1.0 export via [`AppManifest::to_openapi_3_1`].
//!
//! # HTTP status mapping
//!
//! [`SlabError`] implements [`axum::response::IntoResponse`] and returns a JSON body with `error` and `message` fields:
//!
//! | Variant | HTTP status | JSON `error` field | Notes |
//! | --- | --- | --- | --- |
//! | [`SlabError::BadRequest`] | `400` | `"bad_request"` | Includes the error message. |
//! | [`SlabError::Unauthorized`] | `401` | `"unauthorized"` | Missing or invalid credentials. |
//! | [`SlabError::Forbidden`] | `403` | `"forbidden"` | Authenticated caller lacks permission. |
//! | [`SlabError::NotFound`] | `404` | `"not_found"` | Resource does not exist. |
//! | [`SlabError::Database`] (`RowNotFound`) | `404` | `"not_found"` | Message is fixed to `"record not found"`. |
//! | [`SlabError::Conflict`] | `409` | `"conflict"` | Unique key or state conflict. |
//! | [`SlabError::Validation`] | `422` | `"validation_error"` | Also includes a `field` string. |
//! | [`SlabError::ValidationErrors`] | `422` | `"validation_error"` | Includes a `fields` map of field names to error message lists. |
//! | [`SlabError::TooManyRequests`] | `429` | `"too_many_requests"` | Sets `Retry-After` header and `retry_after_secs`. |
//! | [`SlabError::Database`] (other) | `500` | `"database_error"` | Logs via `tracing::error!` and hides raw SQL details. |
//! | [`SlabError::Internal`] | `500` | `"internal_error"` | Logs via `tracing::error!` and returns `"internal server error"`. |
//!
//! # Environment variables
//!
//! [`AppConfig::from_env`] reads these variables and falls back to local development defaults derived from `app_name`:
//!
//! - `SLABS_ENV`: deployment environment (`development`, `test`, `staging`, `production`). Defaults to `development`.
//! - `SLABS_BIND`: bind address. Defaults to `"127.0.0.1:3000"`.
//! - `DATABASE_URL`: database connection string. Defaults to `"sqlite://{app_name}.db?mode=rwc"`.
//! - `SLABS_SECRET_KEY`: signing key for cookies, tokens, and HMAC digests. Generates an ephemeral 32-byte key in dev/test; required (>= 32 bytes) in staging/production.
//! - `SLABS_STORAGE_DIR`: local blob directory. Defaults to `"./storage/{app_name}"`.
//! - `SLABS_ASSETS_DIR`: static assets directory. Defaults to `"./assets"` when present, otherwise `"./examples/{app_name}/assets"`.
//! - `SLABS_JOB_POLL_MS`: background worker poll interval in milliseconds. Defaults to `500`.
//! - `SLABS_JOB_CONCURRENCY`: maximum concurrent background jobs. Defaults to `4`.
//! - `SLABS_COOKIE_SECURE`: enables the `Secure` cookie attribute when `"1"` or `"true"`. Defaults to `true` in staging/production and `false` in dev/test.
//! - `SLABS_WEBHOOKS_LIVE`: enables live outbound webhook HTTP requests when `"1"` or `"true"`. Defaults to `false`.
//! - `SLABS_WEBHOOKS_ALLOW_LOCAL`: permits webhooks to target loopback addresses when `"1"` or `"true"`. Defaults to `false`.
//! - `SLABS_CORS_ORIGINS`: comma-separated list of allowed CORS origins. Defaults to empty.
//! - `SLABS_TRUST_PROXY`: trusts reverse-proxy forwarding headers when `"1"` or `"true"`. Defaults to `false`.
//! - `SLABS_METRICS_TOKEN`: optional bearer token guarding `/_slabs/metrics`.
//! - `SLABS_MAX_BODY_BYTES`: maximum HTTP request body size in bytes. Defaults to `4 MiB`.
//! - `SLABS_MAX_BLOB_BYTES`: maximum blob upload size in bytes. Defaults to `10 MiB`.
//! - `SLABS_CSRF_ENFORCE`: enforces CSRF origin checks on cookie-authenticated mutations. Defaults to `true`.
//! - `SLABS_SLOW_REQUEST_MS`: HTTP latency threshold in milliseconds for recording `slow_request` incidents. Defaults to `500`.
//! - `SLABS_SLOW_JOB_MS`: background job latency threshold in milliseconds for recording `slow_job` incidents. Defaults to `5000`.
//! - `SLABS_GIT_SHA`: optional deployment commit SHA attached to recorded runtime incidents.
//! - `SLABS_INCIDENT_WEBHOOK_URL`: optional outbound webhook URL notified when a new or re-opened runtime incident is recorded or resolved.
//! - `SLABS_INCIDENT_WEBHOOK_SECRET`: optional HMAC-SHA256 signing secret for Incident Protocol v1 webhooks (`X-Slabs-Signature: sha256=<hex>`).
//! - `SLABS_INCIDENT_STALE_DAYS`: number of days after which inactive `"open"` or `"reopened"` runtime incidents are auto-resolved (`0` disables auto-closing). Defaults to `30`.
//!
//! # Invariants
//!
//! - [`id::new`] produces lowercase ULIDs prefixed with `<prefix>_` so `SQLite` B-tree primary keys stay append-friendly.
//! - Returning `?` on a [`sqlx::Error::RowNotFound`] produces HTTP 404 without manual mapping.
//! - Unexpected database and internal errors never leak internal messages or SQL strings in the HTTP response body.
//! - [`AppConfig::for_test`] pins `database_url` to `"sqlite::memory:"`, `bind_addr` to `"127.0.0.1:0"`, and disables live webhooks.
//!
//! # Usage
//!
//! ```rust
//! use slabs_core::{id, AppConfig, SlabError, SlabResult};
//!
//! fn validate_title(title: &str) -> SlabResult<String> {
//!     if title.trim().is_empty() {
//!         return Err(SlabError::validation("title", "cannot be blank"));
//!     }
//!     Ok(id::new("room"))
//! }
//!
//! let config = AppConfig::from_env("campfire");
//! assert_eq!(config.app_name, "campfire");
//! assert!(validate_title("Lobby").unwrap().starts_with("room_"));
//! assert_eq!(validate_title("  ").unwrap_err().status_code().as_u16(), 422);
//! ```

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;
use thiserror::Error;

/// Prefix-tagged, time-sortable ULID generator (for example `msg_01j...` or `usr_01j...`).
///
/// Time-sorted IDs keep `SQLite` B-tree indexes compact and append-friendly.
pub mod id {
    use ulid::Ulid;

    /// Generates a lowercase prefixed ULID string in the form `<prefix>_<ulid>`.
    ///
    /// The ULID suffix is 26 Crockford Base32 characters encoded in lowercase.
    #[must_use]
    pub fn new(prefix: &str) -> String {
        format!("{prefix}_{}", Ulid::new().to_string().to_lowercase())
    }
}

/// Unified HTTP error type returned by every transaction script and background job.
///
/// Implements [`IntoResponse`] with JSON error bodies and explicit HTTP status codes.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SlabError {
    /// Input validation failure targeting a specific field (HTTP 422, `error: "validation_error"`).
    #[error("validation failed on `{field}`: {message}")]
    Validation {
        /// Name of the field that failed validation.
        field: String,
        /// Human-readable description of the validation failure.
        message: String,
    },

    /// Multi-field input validation failure (HTTP 422, `error: "validation_error"`).
    #[error("validation failed on {} field(s)", .0.len())]
    ValidationErrors(BTreeMap<String, Vec<String>>),

    /// Malformed or invalid client request (HTTP 400, `error: "bad_request"`).
    #[error("bad request: {0}")]
    BadRequest(String),

    /// Missing or invalid authentication credentials (HTTP 401, `error: "unauthorized"`).
    #[error("unauthorized: {0}")]
    Unauthorized(String),

    /// Authenticated caller lacks permission for the requested action (HTTP 403, `error: "forbidden"`).
    #[error("forbidden: {0}")]
    Forbidden(String),

    /// Requested resource does not exist (HTTP 404, `error: "not_found"`).
    #[error("not found: {0}")]
    NotFound(String),

    /// Resource state conflict, such as a duplicate unique key (HTTP 409, `error: "conflict"`).
    #[error("conflict: {0}")]
    Conflict(String),

    /// Rate limit exceeded (HTTP 429, `error: "too_many_requests"`).
    ///
    /// Sets the `Retry-After` response header to `retry_after_secs`.
    #[error("too many requests: {message} (retry after {retry_after_secs}s)")]
    TooManyRequests {
        /// Seconds the client should wait before retrying.
        retry_after_secs: u64,
        /// Human-readable rate-limit explanation.
        message: String,
    },

    /// Underlying `sqlx` database error.
    ///
    /// Maps [`sqlx::Error::RowNotFound`] to HTTP 404 (`"record not found"`).
    /// Maps all other database errors to HTTP 500 and logs the raw error with `tracing::error!`.
    #[error("database error: {0}")]
    Database(#[from] sqlx::Error),

    /// Unexpected server-side failure (HTTP 500, `error: "internal_error"`).
    ///
    /// Logs the message with `tracing::error!` and returns `"internal server error"` to clients.
    #[error("internal error: {0}")]
    Internal(String),
}

impl SlabError {
    /// Creates a [`SlabError::Validation`] error (HTTP 422) for `field` with `message`.
    #[must_use]
    pub fn validation(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self::Validation {
            field: field.into(),
            message: message.into(),
        }
    }

    /// Creates a [`SlabError::BadRequest`] error (HTTP 400).
    #[must_use]
    pub fn bad_request(msg: impl Into<String>) -> Self {
        Self::BadRequest(msg.into())
    }

    /// Creates a [`SlabError::Unauthorized`] error (HTTP 401).
    #[must_use]
    pub fn unauthorized(msg: impl Into<String>) -> Self {
        Self::Unauthorized(msg.into())
    }

    /// Creates a [`SlabError::Forbidden`] error (HTTP 403).
    #[must_use]
    pub fn forbidden(msg: impl Into<String>) -> Self {
        Self::Forbidden(msg.into())
    }

    /// Creates a [`SlabError::NotFound`] error (HTTP 404).
    #[must_use]
    pub fn not_found(msg: impl Into<String>) -> Self {
        Self::NotFound(msg.into())
    }

    /// Creates a [`SlabError::Conflict`] error (HTTP 409).
    #[must_use]
    pub fn conflict(msg: impl Into<String>) -> Self {
        Self::Conflict(msg.into())
    }

    /// Creates a [`SlabError::TooManyRequests`] error (HTTP 429) with a `Retry-After` value in seconds.
    #[must_use]
    pub fn too_many_requests(retry_after_secs: u64, msg: impl Into<String>) -> Self {
        Self::TooManyRequests {
            retry_after_secs,
            message: msg.into(),
        }
    }

    /// Creates a [`SlabError::Internal`] error (HTTP 500).
    #[must_use]
    pub fn internal(msg: impl Into<String>) -> Self {
        Self::Internal(msg.into())
    }

    /// Returns the HTTP [`StatusCode`] mapped to this error variant.
    #[must_use]
    pub fn status_code(&self) -> StatusCode {
        match self {
            Self::Validation { .. } | Self::ValidationErrors(_) => StatusCode::UNPROCESSABLE_ENTITY,
            Self::BadRequest(_) => StatusCode::BAD_REQUEST,
            Self::Unauthorized(_) => StatusCode::UNAUTHORIZED,
            Self::Forbidden(_) => StatusCode::FORBIDDEN,
            Self::NotFound(_) | Self::Database(sqlx::Error::RowNotFound) => StatusCode::NOT_FOUND,
            Self::Conflict(_) => StatusCode::CONFLICT,
            Self::TooManyRequests { .. } => StatusCode::TOO_MANY_REQUESTS,
            Self::Database(_) | Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl IntoResponse for SlabError {
    fn into_response(self) -> Response {
        let status = self.status_code();
        if let Self::TooManyRequests {
            retry_after_secs,
            message,
        } = self
        {
            let mut resp = (
                status,
                Json(json!({
                    "error": "too_many_requests",
                    "retry_after_secs": retry_after_secs,
                    "message": message,
                })),
            )
                .into_response();
            if let Ok(val) = http::HeaderValue::from_str(&retry_after_secs.to_string()) {
                resp.headers_mut().insert(http::header::RETRY_AFTER, val);
            }
            return resp;
        }
        let body = match &self {
            Self::Validation { field, message } => json!({
                "error": "validation_error",
                "field": field,
                "message": message,
            }),
            Self::ValidationErrors(fields) => json!({
                "error": "validation_error",
                "fields": fields,
            }),
            Self::Database(sqlx::Error::RowNotFound) => json!({
                "error": "not_found",
                "message": "record not found",
            }),
            Self::Database(err) => {
                tracing::error!(error = %err, "database error in slab");
                json!({
                    "error": "database_error",
                    "message": "internal database error",
                })
            }
            Self::Internal(msg) => {
                tracing::error!(error = %msg, "internal error in slab");
                json!({
                    "error": "internal_error",
                    "message": "internal server error",
                })
            }
            other => json!({
                "error": status.canonical_reason().unwrap_or("error").to_lowercase().replace(' ', "_"),
                "message": other.to_string(),
            }),
        };

        (status, Json(body)).into_response()
    }
}

/// Result alias using [`SlabError`] as the error type.
pub type SlabResult<T> = Result<T, SlabError>;

/// Multi-field procedural validation builder for transaction scripts.
///
/// Accumulates field errors in deterministic key order and returns
/// [`SlabError::ValidationErrors`] (HTTP 422) from [`Validate::finish`].
#[derive(Debug, Clone, Default)]
pub struct Validate {
    errors: BTreeMap<String, Vec<String>>,
}

impl Validate {
    /// Creates an empty [`Validate`] builder with no recorded errors.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Requires `value` to be non-empty after trimming whitespace.
    ///
    /// Records `"is required"` under `field` when empty.
    pub fn required(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
        if value.trim().is_empty() {
            self.push(field, "is required");
        }
        self
    }

    /// Requires the trimmed `value` to have at least `min` Unicode scalar characters.
    pub fn min_len(&mut self, field: impl Into<String>, value: &str, min: usize) -> &mut Self {
        if value.trim().chars().count() < min {
            self.push(field, format!("must be at least {min} characters"));
        }
        self
    }

    /// Requires the trimmed `value` to have at most `max` Unicode scalar characters.
    pub fn max_len(&mut self, field: impl Into<String>, value: &str, max: usize) -> &mut Self {
        if value.trim().chars().count() > max {
            self.push(field, format!("must be at most {max} characters"));
        }
        self
    }

    /// Requires the trimmed `value` to look like an email address.
    ///
    /// Rejects ASCII control characters, whitespace, values longer than 254 bytes, and
    /// requires a non-empty local part before `@` and a domain containing `.` after `@`.
    pub fn email(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
        let trimmed = value.trim();
        let valid = !trimmed.is_empty()
            && trimmed.len() <= 254
            && !has_ascii_control(value)
            && !trimmed.chars().any(char::is_whitespace)
            && trimmed.split_once('@').is_some_and(|(local, domain)| {
                !local.is_empty()
                    && !domain.is_empty()
                    && !domain.contains('@')
                    && domain.contains('.')
                    && !domain.starts_with('.')
                    && !domain.ends_with('.')
            });
        if !valid {
            self.push(field, "must be a valid email address");
        }
        self
    }

    /// Requires the trimmed `value` to parse as an `http://` or `https://` URL with a host.
    ///
    /// Rejects ASCII control characters, whitespace, and values longer than 2048 bytes.
    pub fn url(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
        let trimmed = value.trim();
        let valid = !trimmed.is_empty()
            && trimmed.len() <= 2048
            && !has_ascii_control(value)
            && !trimmed.chars().any(char::is_whitespace)
            && url::Url::parse(trimmed).is_ok_and(|parsed| {
                matches!(parsed.scheme(), "http" | "https") && parsed.host().is_some()
            });
        if !valid {
            self.push(field, "must start with http:// or https://");
        }
        self
    }

    /// Requires `value` to match one of the entries in `allowed`.
    pub fn one_of(&mut self, field: impl Into<String>, value: &str, allowed: &[&str]) -> &mut Self {
        if !allowed.contains(&value) {
            self.push(field, format!("must be one of: {}", allowed.join(", ")));
        }
        self
    }

    /// Records `message` under `field` when `condition` is `false`.
    pub fn check(
        &mut self,
        field: impl Into<String>,
        condition: bool,
        message: impl Into<String>,
    ) -> &mut Self {
        if !condition {
            self.push(field, message);
        }
        self
    }

    /// Unconditionally appends `message` to the error list for `field`.
    pub fn push(&mut self, field: impl Into<String>, message: impl Into<String>) -> &mut Self {
        self.errors
            .entry(field.into())
            .or_default()
            .push(message.into());
        self
    }

    /// Returns `true` when no validation errors have been recorded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Returns the map of field names to accumulated validation messages.
    #[must_use]
    pub fn errors(&self) -> &BTreeMap<String, Vec<String>> {
        &self.errors
    }

    /// Finalizes validation, returning `Ok(())` when empty or [`SlabError::ValidationErrors`].
    pub fn finish(self) -> SlabResult<()> {
        if self.errors.is_empty() {
            Ok(())
        } else {
            Err(SlabError::ValidationErrors(self.errors))
        }
    }
}

fn has_ascii_control(s: &str) -> bool {
    s.bytes().any(|b| b < 0x20 || b == 0x7f)
}

fn parse_bool_env(key: &str) -> Option<bool> {
    let raw = std::env::var(key).ok()?;
    let trimmed = raw.trim();
    if trimmed == "1" || trimmed.eq_ignore_ascii_case("true") {
        Some(true)
    } else if trimmed == "0" || trimmed.eq_ignore_ascii_case("false") {
        Some(false)
    } else {
        None
    }
}

fn redact_database_url(raw: &str) -> String {
    if let Ok(mut parsed) = url::Url::parse(raw) {
        if parsed.password().is_some() {
            const SENTINEL: &str = "__SLABS_REDACTED_PW__";
            if parsed.set_password(Some(SENTINEL)).is_ok() {
                return parsed.as_str().replace(SENTINEL, "[REDACTED]");
            }
        }
        return raw.to_owned();
    }
    if let Some(scheme_end) = raw.find("://") {
        let rest = &raw[scheme_end + 3..];
        let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
        let authority = &rest[..authority_end];
        if let Some(at_pos) = authority.rfind('@') {
            let userinfo = &authority[..at_pos];
            if let Some(colon_pos) = userinfo.find(':') {
                let prefix_end = scheme_end + 3 + colon_pos + 1;
                let suffix_start = scheme_end + 3 + at_pos;
                return format!("{}[REDACTED]{}", &raw[..prefix_end], &raw[suffix_start..]);
            }
        }
    }
    raw.to_owned()
}

/// Deployment environment controlling security defaults and fail-closed startup checks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AppEnv {
    /// Local development environment (`"dev"` / `"development"`).
    Development,
    /// Automated test environment (`"test"`).
    Test,
    /// Staging or review environment (`"staging"` / `"review"`).
    Staging,
    /// Production environment (`"prod"` / `"production"`).
    Production,
}

impl AppEnv {
    /// Parses a deployment environment string (case-insensitive, trimmed).
    ///
    /// Maps `"dev"` / `"development"` to [`AppEnv::Development`], `"test"` to [`AppEnv::Test`],
    /// `"staging"` / `"review"` to [`AppEnv::Staging`], and `"prod"` / `"production"` to
    /// [`AppEnv::Production`]. Unrecognized values default to [`AppEnv::Development`].
    #[must_use]
    pub fn parse_env(value: &str) -> Self {
        match value.trim().to_ascii_lowercase().as_str() {
            "test" => Self::Test,
            "staging" | "review" => Self::Staging,
            "prod" | "production" => Self::Production,
            _ => Self::Development,
        }
    }

    /// Reads the deployment environment from `SLABS_ENV`, defaulting to [`AppEnv::Development`].
    #[must_use]
    pub fn from_env() -> Self {
        std::env::var("SLABS_ENV").map_or(Self::Development, |v| Self::parse_env(&v))
    }

    /// Returns `true` for [`AppEnv::Staging`] and [`AppEnv::Production`].
    #[must_use]
    pub fn is_prod_like(self) -> bool {
        matches!(self, Self::Staging | Self::Production)
    }

    /// Returns `true` for [`AppEnv::Development`] and [`AppEnv::Test`].
    #[must_use]
    pub fn is_dev_or_test(self) -> bool {
        matches!(self, Self::Development | Self::Test)
    }

    /// Returns the canonical lowercase string name of this environment.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Development => "development",
            Self::Test => "test",
            Self::Staging => "staging",
            Self::Production => "production",
        }
    }
}

/// Runtime configuration loaded from `SLABS_*` and `DATABASE_URL` environment variables.
#[derive(Clone, Serialize, Deserialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct AppConfig {
    /// Deployment environment (`SLABS_ENV`, default [`AppEnv::Development`]).
    pub env: AppEnv,
    /// Application name used for default database filenames, storage directories, and manifests.
    pub app_name: String,
    /// Socket address to bind the HTTP server to (`SLABS_BIND`, default `"127.0.0.1:3000"`).
    pub bind_addr: String,
    /// Connection string for the primary database (`DATABASE_URL`, default `"sqlite://{app_name}.db?mode=rwc"`).
    pub database_url: String,
    /// Secret key for signing cookies, tokens, and HMAC digests (`SLABS_SECRET_KEY`).
    #[serde(default, skip_serializing)]
    pub secret_key: String,
    /// Directory where uploaded blobs and local storage files are written (`SLABS_STORAGE_DIR`).
    pub storage_dir: PathBuf,
    /// Directory containing static assets such as CSS and JS files (`SLABS_ASSETS_DIR`).
    pub assets_dir: PathBuf,
    /// Polling interval in milliseconds for the background job worker (`SLABS_JOB_POLL_MS`, default `500`).
    pub job_poll_interval_ms: u64,
    /// Maximum number of background jobs executed concurrently (`SLABS_JOB_CONCURRENCY`, default `4`).
    pub job_concurrency: usize,
    /// Sets the `Secure` attribute on session cookies when `true` (`SLABS_COOKIE_SECURE`, default `env.is_prod_like()`).
    pub cookie_secure: bool,
    /// Enables live HTTP delivery for outbound webhooks when `true` (`SLABS_WEBHOOKS_LIVE`, default `false`).
    pub webhooks_live: bool,
    /// Allows outbound webhooks to target loopback addresses when `true` (`SLABS_WEBHOOKS_ALLOW_LOCAL`, default `false`).
    pub webhooks_allow_local: bool,
    /// Allowed CORS origins loaded from comma-separated `SLABS_CORS_ORIGINS`.
    pub cors_origins: Vec<String>,
    /// Whether to trust reverse-proxy forwarding headers (`SLABS_TRUST_PROXY`, default `false`).
    pub trust_proxy: bool,
    /// Optional bearer token protecting the metrics endpoint (`SLABS_METRICS_TOKEN`).
    #[serde(default, skip_serializing)]
    pub metrics_token: Option<String>,
    /// Maximum HTTP request body size in bytes (`SLABS_MAX_BODY_BYTES`, default `4 MiB`).
    pub max_body_bytes: usize,
    /// Maximum blob upload size in bytes (`SLABS_MAX_BLOB_BYTES`, default `10 MiB`).
    pub max_blob_bytes: usize,
    /// Enforces CSRF checks on cookie-authenticated mutations (`SLABS_CSRF_ENFORCE`, default `true`).
    pub csrf_enforce: bool,
    /// HTTP request latency threshold in milliseconds for slow-request incident capture (`SLABS_SLOW_REQUEST_MS`, default `500`).
    pub slow_request_ms: u64,
    /// Background job execution latency threshold in milliseconds for slow-job incident capture (`SLABS_SLOW_JOB_MS`, default `5_000`).
    pub slow_job_ms: u64,
    /// Optional Git commit SHA of the running build attached to runtime incidents (`SLABS_GIT_SHA`).
    pub git_sha: Option<String>,
    /// Optional webhook URL notified when a runtime incident is opened, re-opened, or resolved (`SLABS_INCIDENT_WEBHOOK_URL`).
    #[serde(default, skip_serializing)]
    pub incident_webhook_url: Option<String>,
    /// Optional HMAC-SHA256 signing secret for Incident Protocol v1 webhooks (`SLABS_INCIDENT_WEBHOOK_SECRET`).
    #[serde(default, skip_serializing)]
    pub incident_webhook_secret: Option<String>,
    /// Days of inactivity before active runtime incidents are auto-resolved (`SLABS_INCIDENT_STALE_DAYS`, default `30`; `0` disables auto-closing).
    pub incident_stale_days: u64,
}

impl fmt::Debug for AppConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let redacted_db_url = redact_database_url(&self.database_url);
        let redacted_metrics_token = self.metrics_token.as_ref().map(|_| "[REDACTED]");
        let redacted_incident_webhook_url =
            self.incident_webhook_url.as_ref().map(|_| "[CONFIGURED]");
        let redacted_incident_webhook_secret =
            self.incident_webhook_secret.as_ref().map(|_| "[REDACTED]");
        f.debug_struct("AppConfig")
            .field("env", &self.env)
            .field("app_name", &self.app_name)
            .field("bind_addr", &self.bind_addr)
            .field("database_url", &redacted_db_url)
            .field("secret_key", &"[REDACTED]")
            .field("storage_dir", &self.storage_dir)
            .field("assets_dir", &self.assets_dir)
            .field("job_poll_interval_ms", &self.job_poll_interval_ms)
            .field("job_concurrency", &self.job_concurrency)
            .field("cookie_secure", &self.cookie_secure)
            .field("webhooks_live", &self.webhooks_live)
            .field("webhooks_allow_local", &self.webhooks_allow_local)
            .field("cors_origins", &self.cors_origins)
            .field("trust_proxy", &self.trust_proxy)
            .field("metrics_token", &redacted_metrics_token)
            .field("max_body_bytes", &self.max_body_bytes)
            .field("max_blob_bytes", &self.max_blob_bytes)
            .field("csrf_enforce", &self.csrf_enforce)
            .field("slow_request_ms", &self.slow_request_ms)
            .field("slow_job_ms", &self.slow_job_ms)
            .field("git_sha", &self.git_sha)
            .field("incident_webhook_url", &redacted_incident_webhook_url)
            .field("incident_webhook_secret", &redacted_incident_webhook_secret)
            .field("incident_stale_days", &self.incident_stale_days)
            .finish()
    }
}

impl AppConfig {
    /// Legacy development fallback secret rejected by [`AppConfig::validate`] in staging and production.
    pub const DEV_SECRET_FALLBACK_SENTINEL: &str =
        "dev-only-change-me-in-production-slabs-secret-key";

    /// Loads configuration from `SLABS_*` and `DATABASE_URL` environment variables.
    ///
    /// Falls back to local development defaults derived from `app_name` when variables are unset.
    /// When `SLABS_SECRET_KEY` is unset in development or test, generates a random ephemeral
    /// 32-byte hex key and logs a warning; in staging or production it leaves `secret_key` empty
    /// so [`AppConfig::validate`] fails closed.
    #[must_use]
    pub fn from_env(app_name: impl Into<String>) -> Self {
        let app_name = app_name.into();
        let env = AppEnv::from_env();
        let secret_key = match std::env::var("SLABS_SECRET_KEY") {
            Ok(val) if !val.trim().is_empty() => val,
            _ if env.is_dev_or_test() => {
                use rand_core::RngCore as _;
                let mut bytes = [0u8; 32];
                rand_core::OsRng.fill_bytes(&mut bytes);
                tracing::warn!(
                    env = env.as_str(),
                    "SLABS_SECRET_KEY is not set; generated an ephemeral random secret key for this process"
                );
                hex::encode(bytes)
            }
            _ => String::new(),
        };

        let cors_origins = std::env::var("SLABS_CORS_ORIGINS").map_or_else(
            |_| Vec::new(),
            |raw| {
                raw.split(',')
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(ToOwned::to_owned)
                    .collect()
            },
        );

        let metrics_token = std::env::var("SLABS_METRICS_TOKEN")
            .ok()
            .map(|s| s.trim().to_owned())
            .filter(|s| !s.is_empty());

        let git_sha = std::env::var("SLABS_GIT_SHA")
            .ok()
            .map(|s| s.trim().to_owned())
            .filter(|s| !s.is_empty());

        let incident_webhook_url = std::env::var("SLABS_INCIDENT_WEBHOOK_URL")
            .ok()
            .map(|s| s.trim().to_owned())
            .filter(|s| !s.is_empty());

        let incident_webhook_secret = std::env::var("SLABS_INCIDENT_WEBHOOK_SECRET")
            .ok()
            .map(|s| s.trim().to_owned())
            .filter(|s| !s.is_empty());

        Self {
            env,
            app_name: app_name.clone(),
            bind_addr: std::env::var("SLABS_BIND").unwrap_or_else(|_| "127.0.0.1:3000".into()),
            database_url: std::env::var("DATABASE_URL")
                .unwrap_or_else(|_| format!("sqlite://{app_name}.db?mode=rwc")),
            secret_key,
            storage_dir: std::env::var("SLABS_STORAGE_DIR").map_or_else(
                |_| PathBuf::from(format!("./storage/{app_name}")),
                PathBuf::from,
            ),
            assets_dir: std::env::var("SLABS_ASSETS_DIR").map_or_else(
                |_| {
                    let local = PathBuf::from("./assets");
                    if local.is_dir() {
                        local
                    } else {
                        PathBuf::from(format!("./examples/{app_name}/assets"))
                    }
                },
                PathBuf::from,
            ),
            job_poll_interval_ms: std::env::var("SLABS_JOB_POLL_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(500),
            job_concurrency: std::env::var("SLABS_JOB_CONCURRENCY")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(4),
            cookie_secure: parse_bool_env("SLABS_COOKIE_SECURE")
                .unwrap_or_else(|| env.is_prod_like()),
            webhooks_live: parse_bool_env("SLABS_WEBHOOKS_LIVE").unwrap_or(false),
            webhooks_allow_local: parse_bool_env("SLABS_WEBHOOKS_ALLOW_LOCAL").unwrap_or(false),
            cors_origins,
            trust_proxy: parse_bool_env("SLABS_TRUST_PROXY").unwrap_or(false),
            metrics_token,
            max_body_bytes: std::env::var("SLABS_MAX_BODY_BYTES")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(4 * 1024 * 1024),
            max_blob_bytes: std::env::var("SLABS_MAX_BLOB_BYTES")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(10 * 1024 * 1024),
            csrf_enforce: parse_bool_env("SLABS_CSRF_ENFORCE").unwrap_or(true),
            slow_request_ms: std::env::var("SLABS_SLOW_REQUEST_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(500),
            slow_job_ms: std::env::var("SLABS_SLOW_JOB_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(5_000),
            git_sha,
            incident_webhook_url,
            incident_webhook_secret,
            incident_stale_days: std::env::var("SLABS_INCIDENT_STALE_DAYS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(30),
        }
    }

    /// Builds an isolated configuration for parallel tests.
    ///
    /// Uses `env = AppEnv::Test`, `database_url = "sqlite::memory:"`, `bind_addr = "127.0.0.1:0"`,
    /// a 50ms job poll interval, and disables `cookie_secure`, `webhooks_live`, and `webhooks_allow_local`.
    #[must_use]
    pub fn for_test(app_name: impl Into<String>, storage_dir: PathBuf) -> Self {
        let app_name = app_name.into();
        let assets_dir = if PathBuf::from("./assets").is_dir() {
            PathBuf::from("./assets")
        } else {
            PathBuf::from(format!("./examples/{app_name}/assets"))
        };
        Self {
            env: AppEnv::Test,
            app_name,
            bind_addr: "127.0.0.1:0".into(),
            database_url: "sqlite::memory:".into(),
            secret_key: "test-only-slabs-secret-key-at-least-32-bytes-long!".into(),
            storage_dir,
            assets_dir,
            job_poll_interval_ms: 50,
            job_concurrency: 2,
            cookie_secure: false,
            webhooks_live: false,
            webhooks_allow_local: false,
            cors_origins: Vec::new(),
            trust_proxy: false,
            metrics_token: None,
            max_body_bytes: 4 * 1024 * 1024,
            max_blob_bytes: 10 * 1024 * 1024,
            csrf_enforce: true,
            slow_request_ms: 500,
            slow_job_ms: 5_000,
            git_sha: None,
            incident_webhook_url: None,
            incident_webhook_secret: None,
            incident_stale_days: 30,
        }
    }

    /// Validates configuration invariants, failing closed in staging and production environments.
    ///
    /// Rejects missing, short (`< 32` bytes), or sentinel `SLABS_SECRET_KEY` values when
    /// `self.env.is_prod_like()` is `true`.
    pub fn validate(&self) -> SlabResult<()> {
        if self.env.is_prod_like() {
            let trimmed = self.secret_key.trim();
            if trimmed.len() < 32 || trimmed == Self::DEV_SECRET_FALLBACK_SENTINEL {
                return Err(SlabError::internal(format!(
                    "invalid SLABS_SECRET_KEY for {} environment: set SLABS_SECRET_KEY to a unique secret of at least 32 bytes",
                    self.env.as_str()
                )));
            }
        }
        Ok(())
    }
}

/// Machine-readable HTTP route metadata emitted by `/_slabs/manifest` and `slabs manifest`.
///
/// Agents read this list to inspect every registered endpoint in a single call.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteMeta {
    /// Unique identifier for the slab route (for example `rooms::create_room`).
    pub name: String,
    /// HTTP verb accepted by the route (for example `GET` or `POST`).
    pub method: String,
    /// URL path pattern registered with the router (for example `/api/rooms/{room_id}`).
    pub path: String,
    /// Short description of what the slab does.
    pub summary: String,
    /// Feature group owning this slab, derived from `slabs/<feature>/`.
    pub feature: String,
    /// Optional JSON Schema describing the expected request body.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input_schema: Option<serde_json::Value>,
    /// Optional JSON Schema describing the JSON response body.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_schema: Option<serde_json::Value>,
}

/// Machine-readable metadata describing a registered background job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobMeta {
    /// Unique job identifier used when enqueueing work.
    pub name: String,
    /// Queue name this job is routed to.
    pub queue: String,
    /// Maximum number of execution attempts before the worker marks the job failed.
    pub max_attempts: i64,
    /// Short description of what the job performs.
    pub summary: String,
}

/// Complete JSON manifest of an application's discovered HTTP routes and background jobs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppManifest {
    /// Name of the application producing this manifest.
    pub app_name: String,
    /// All HTTP slab routes registered in the application.
    pub routes: Vec<RouteMeta>,
    /// All background jobs registered in the application.
    pub jobs: Vec<JobMeta>,
}

impl AppManifest {
    /// Exports this application manifest as an `OpenAPI` `3.1.0` JSON document.
    ///
    /// Extracts `{param}` and `{*wildcard}` path segments into `OpenAPI` path parameters,
    /// attaches `requestBody` (`application/json`) when `input_schema` is present, and
    /// attaches `responses["200"]` (`application/json`) when `output_schema` is present.
    #[must_use]
    pub fn to_openapi_3_1(&self) -> serde_json::Value {
        let mut paths = serde_json::Map::new();

        for route in &self.routes {
            let mut parameters = Vec::new();
            let mut normalized_segments = Vec::new();

            for segment in route.path.split('/') {
                if let Some(inner) = segment.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
                    let param_name = inner.strip_prefix('*').unwrap_or(inner);
                    if !param_name.is_empty() {
                        parameters.push(json!({
                            "name": param_name,
                            "in": "path",
                            "required": true,
                            "schema": { "type": "string" },
                        }));
                        normalized_segments.push(format!("{{{param_name}}}"));
                        continue;
                    }
                }
                normalized_segments.push(segment.to_string());
            }

            let openapi_path = normalized_segments.join("/");
            let method_key = route.method.to_ascii_lowercase();

            let mut operation = serde_json::Map::new();
            operation.insert("operationId".into(), json!(route.name));
            operation.insert("summary".into(), json!(route.summary));
            if !route.feature.is_empty() {
                operation.insert("tags".into(), json!([route.feature]));
            }
            if !parameters.is_empty() {
                operation.insert("parameters".into(), serde_json::Value::Array(parameters));
            }
            if let Some(input_schema) = &route.input_schema {
                operation.insert(
                    "requestBody".into(),
                    json!({
                        "required": true,
                        "content": {
                            "application/json": {
                                "schema": input_schema,
                            }
                        }
                    }),
                );
            }

            let ok_response = if let Some(output_schema) = &route.output_schema {
                json!({
                    "description": "Success",
                    "content": {
                        "application/json": {
                            "schema": output_schema,
                        }
                    }
                })
            } else {
                json!({
                    "description": "Success",
                })
            };
            operation.insert("responses".into(), json!({ "200": ok_response }));

            let path_item = paths
                .entry(openapi_path)
                .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
            if let Some(path_obj) = path_item.as_object_mut() {
                path_obj.insert(method_key, serde_json::Value::Object(operation));
            }
        }

        json!({
            "openapi": "3.1.0",
            "info": {
                "title": self.app_name,
                "version": "0.1.0",
            },
            "paths": serde_json::Value::Object(paths),
        })
    }
}

/// URL slug generation helpers.
pub mod slug {
    /// Convert arbitrary text into a lowercase, hyphen-separated URL slug.
    ///
    /// Keeps ASCII alphanumeric characters, collapses separator runs into a single `-`,
    /// trims leading and trailing hyphens, and returns `"-"` if no alphanumeric characters remain.
    #[must_use]
    pub fn slugify(input: &str) -> String {
        let mut out = String::with_capacity(input.len());
        let mut prev_hyphen = true;
        for ch in input.chars() {
            if ch.is_ascii_alphanumeric() {
                out.push(ch.to_ascii_lowercase());
                prev_hyphen = false;
            } else if !prev_hyphen {
                out.push('-');
                prev_hyphen = true;
            }
        }
        while out.ends_with('-') {
            out.pop();
        }
        if out.is_empty() {
            "-".to_string()
        } else {
            out
        }
    }
}

/// Fractional list positioning helpers for O(1) single-row reordering.
pub mod position {
    /// Compute a fractional `f64` sort score between two optional neighbor positions.
    ///
    /// - `(None, None)` returns `1.0` (first item in an empty list).
    /// - `(Some(prev), None)` returns `prev + 1.0` (append after `prev`).
    /// - `(None, Some(next))` returns `next / 2.0` (prepend before `next`, or `next - 1.0` when `next <= 0.0`).
    /// - `(Some(prev), Some(next))` returns `(prev + next) / 2.0` (insert between `prev` and `next`).
    #[must_use]
    pub fn between(prev: Option<f64>, next: Option<f64>) -> f64 {
        match (prev, next) {
            (None, None) => 1.0,
            (Some(p), None) => p + 1.0,
            (None, Some(n)) => {
                if n > 0.0 {
                    n / 2.0
                } else {
                    n - 1.0
                }
            }
            (Some(p), Some(n)) => f64::midpoint(p, n),
        }
    }
}

/// Compute a lowercase SHA-256 hex digest over length-prefixed string parts.
///
/// Each part is hashed with its 64-bit little-endian byte length prefix followed by its UTF-8
/// bytes, preventing delimiter-collision attacks even when parts contain NUL bytes.
/// Use this for content fingerprints, optimistic concurrency checks (`If-Match`), and cache keys.
#[must_use]
pub fn fingerprint(parts: &[&str]) -> String {
    use sha2::{Digest, Sha256};

    let mut hasher = Sha256::new();
    for part in parts {
        hasher.update((part.len() as u64).to_le_bytes());
        hasher.update(part.as_bytes());
    }
    hex::encode(hasher.finalize())
}

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

    #[test]
    fn slugify_normalizes_titles_and_fallbacks() {
        assert_eq!(slug::slugify("Hello, World! 2026"), "hello-world-2026");
        assert_eq!(
            slug::slugify("  Rust & SQLite --- WAL  "),
            "rust-sqlite-wal"
        );
        assert_eq!(slug::slugify("!!!"), "-");
    }

    #[test]
    fn position_between_orders_items() {
        assert!((position::between(None, None) - 1.0).abs() < f64::EPSILON);
        assert!((position::between(Some(2.0), None) - 3.0).abs() < f64::EPSILON);
        assert!((position::between(None, Some(1.0)) - 0.5).abs() < f64::EPSILON);
        assert!((position::between(Some(1.0), Some(2.0)) - 1.5).abs() < f64::EPSILON);
    }

    #[test]
    fn fingerprint_distinguishes_part_boundaries_and_embedded_nuls() {
        assert_ne!(fingerprint(&["ab", "c"]), fingerprint(&["a", "bc"]));
        assert_ne!(fingerprint(&["a\0b", "c"]), fingerprint(&["a", "b\0c"]));
        assert_ne!(fingerprint(&["a", ""]), fingerprint(&["a"]));
        assert_eq!(fingerprint(&["a", "b"]).len(), 64);
    }

    #[test]
    fn app_env_parses_and_classifies_modes() {
        assert_eq!(AppEnv::parse_env("dev"), AppEnv::Development);
        assert_eq!(AppEnv::parse_env("Development"), AppEnv::Development);
        assert_eq!(AppEnv::parse_env("test"), AppEnv::Test);
        assert_eq!(AppEnv::parse_env("staging"), AppEnv::Staging);
        assert_eq!(AppEnv::parse_env("REVIEW"), AppEnv::Staging);
        assert_eq!(AppEnv::parse_env("prod"), AppEnv::Production);
        assert_eq!(AppEnv::parse_env("  Production "), AppEnv::Production);
        assert_eq!(AppEnv::parse_env("unknown"), AppEnv::Development);

        assert!(AppEnv::Development.is_dev_or_test());
        assert!(!AppEnv::Development.is_prod_like());
        assert_eq!(AppEnv::Development.as_str(), "development");

        assert!(AppEnv::Test.is_dev_or_test());
        assert!(!AppEnv::Test.is_prod_like());
        assert_eq!(AppEnv::Test.as_str(), "test");

        assert!(AppEnv::Staging.is_prod_like());
        assert!(!AppEnv::Staging.is_dev_or_test());
        assert_eq!(AppEnv::Staging.as_str(), "staging");

        assert!(AppEnv::Production.is_prod_like());
        assert!(!AppEnv::Production.is_dev_or_test());
        assert_eq!(AppEnv::Production.as_str(), "production");
    }

    #[test]
    fn app_config_validate_fails_closed_in_prod_like_envs() {
        let mut cfg = AppConfig::for_test("demo", PathBuf::from("./tmp"));
        assert!(cfg.validate().is_ok());

        // Short or empty secret allowed in dev/test
        cfg.env = AppEnv::Development;
        cfg.secret_key = String::new();
        assert!(cfg.validate().is_ok());

        // Staging/Production reject empty, short, and sentinel secrets
        for prod_env in [AppEnv::Staging, AppEnv::Production] {
            cfg.env = prod_env;
            cfg.secret_key = String::new();
            assert!(cfg.validate().is_err());

            cfg.secret_key = "too-short-secret-key".into();
            assert!(cfg.validate().is_err());

            cfg.secret_key = AppConfig::DEV_SECRET_FALLBACK_SENTINEL.into();
            assert!(cfg.validate().is_err());

            cfg.secret_key = "a".repeat(32);
            assert!(cfg.validate().is_ok());
        }
    }

    #[test]
    fn app_config_debug_and_serde_redact_secrets_and_db_passwords() {
        let mut config = AppConfig::for_test("demo", PathBuf::from("./tmp"));
        assert_eq!(config.slow_request_ms, 500);
        assert_eq!(config.slow_job_ms, 5_000);
        assert!(config.git_sha.is_none());
        assert!(config.incident_webhook_url.is_none());
        assert!(config.incident_webhook_secret.is_none());
        assert_eq!(config.incident_stale_days, 30);

        config.secret_key = "super-secret-signing-key-value-32-bytes!".into();
        config.metrics_token = Some("metrics-bearer-secret".into());
        config.database_url = "postgres://app_user:db_super_secret@db.internal:5432/slabs".into();
        config.incident_webhook_url =
            Some("https://hooks.example.com/incidents?token=topsecret123".into());
        config.incident_webhook_secret = Some("whsec_super_secret_hmac_key".into());

        let rendered = format!("{config:?}");
        assert!(!rendered.contains("super-secret-signing-key-value-32-bytes!"));
        assert!(!rendered.contains("metrics-bearer-secret"));
        assert!(!rendered.contains("db_super_secret"));
        assert!(!rendered.contains("topsecret123"));
        assert!(!rendered.contains("whsec_super_secret_hmac_key"));
        assert!(rendered.contains("postgres://app_user:[REDACTED]@db.internal:5432/slabs"));
        assert!(rendered.contains("metrics_token: Some(\"[REDACTED]\")"));
        assert!(rendered.contains("incident_webhook_url: Some(\"[CONFIGURED]\")"));
        assert!(rendered.contains("incident_webhook_secret: Some(\"[REDACTED]\")"));
        assert!(rendered.contains("incident_stale_days: 30"));
        assert!(rendered.contains("secret_key: \"[REDACTED]\""));

        let serialized = serde_json::to_value(&config).unwrap();
        assert!(serialized.get("secret_key").is_none());
        assert!(serialized.get("metrics_token").is_none());
        assert!(serialized.get("incident_webhook_url").is_none());
        assert!(serialized.get("incident_webhook_secret").is_none());
    }

    #[test]
    fn validate_rejects_control_chars_oversized_inputs_and_invalid_urls() {
        let mut v = Validate::new();
        let long_email = format!("{}@example.com", "a".repeat(250));
        let long_url = format!("https://example.com/{}", "a".repeat(2040));

        v.email("email_crlf", "alice@example.com\r\nBcc: evil@example.com")
            .email("email_nul", "alice\0@example.com")
            .email("email_del", "alice\x7f@example.com")
            .email("email_long", &long_email)
            .url("url_ctrl", "https://example.com/\x07path")
            .url("url_crlf", "https://example.com/\r\n")
            .url("url_no_host", "https://:8080/path")
            .url("url_query_only", "https://?query=1")
            .url("url_javascript", "javascript:alert(1)")
            .url("url_long", &long_url)
            .url("url_valid", "https://example.com:8443/path?a=1#frag");

        assert!(v.errors().contains_key("email_crlf"));
        assert!(v.errors().contains_key("email_nul"));
        assert!(v.errors().contains_key("email_del"));
        assert!(v.errors().contains_key("email_long"));
        assert!(v.errors().contains_key("url_ctrl"));
        assert!(v.errors().contains_key("url_crlf"));
        assert!(v.errors().contains_key("url_no_host"));
        assert!(v.errors().contains_key("url_query_only"));
        assert!(v.errors().contains_key("url_javascript"));
        assert!(v.errors().contains_key("url_long"));
        assert!(!v.errors().contains_key("url_valid"));
    }

    #[test]
    fn validate_builder_succeeds_for_valid_inputs() {
        let mut v = Validate::new();
        v.required("name", "  Alice  ")
            .min_len("name", "  Alice  ", 3)
            .max_len("name", "  Alice  ", 10)
            .email("email", " alice@example.com ")
            .url("website", "https://example.com/docs")
            .one_of("role", "admin", &["member", "admin"])
            .check("age", true, "must be adult");

        assert!(v.is_empty());
        assert!(v.errors().is_empty());
        assert!(v.finish().is_ok());
    }

    #[test]
    fn validate_builder_collects_all_field_errors_and_maps_to_422() {
        let mut v = Validate::new();
        v.required("title", "   ")
            .min_len("title", "hi", 3)
            .max_len("bio", "123456", 5)
            .email("email", "not-an-email")
            .url("website", "ftp://example.com")
            .one_of("role", "owner", &["member", "admin"])
            .check("terms", false, "must accept terms")
            .push("custom", "extra problem");

        assert!(!v.is_empty());
        assert_eq!(v.errors()["title"].len(), 2);
        assert_eq!(v.errors()["title"][0], "is required");
        assert!(v.errors().contains_key("bio"));
        assert!(v.errors().contains_key("email"));
        assert!(v.errors().contains_key("website"));
        assert!(v.errors().contains_key("role"));
        assert_eq!(v.errors()["terms"], vec!["must accept terms"]);
        assert_eq!(v.errors()["custom"], vec!["extra problem"]);

        let err = v.finish().unwrap_err();
        assert_eq!(err.status_code(), StatusCode::UNPROCESSABLE_ENTITY);

        let response = err.into_response();
        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[test]
    fn validate_checks_unicode_char_lengths_and_email_url_edge_cases() {
        let mut v = Validate::new();
        // 5 chars ("café!"), even though UTF-8 byte length is 6
        v.min_len("label", "café!", 5)
            .max_len("label", "café!", 5)
            .email("bad_at", "@example.com")
            .email("bad_dot", "alice@localhost")
            .email("bad_trail", "alice@example.")
            .url("bare_scheme", "https://")
            .url("http_ok", "http://localhost:3000");

        assert!(!v.errors().contains_key("label"));
        assert!(v.errors().contains_key("bad_at"));
        assert!(v.errors().contains_key("bad_dot"));
        assert!(v.errors().contains_key("bad_trail"));
        assert!(v.errors().contains_key("bare_scheme"));
        assert!(!v.errors().contains_key("http_ok"));
    }

    #[test]
    fn app_manifest_to_openapi_3_1_builds_paths_params_and_schemas() {
        let manifest = AppManifest {
            app_name: "campfire".into(),
            routes: vec![
                RouteMeta {
                    name: "rooms::list_rooms".into(),
                    method: "GET".into(),
                    path: "/api/rooms".into(),
                    summary: "List all rooms".into(),
                    feature: "rooms".into(),
                    input_schema: None,
                    output_schema: Some(json!({
                        "type": "array",
                        "items": { "type": "object" }
                    })),
                },
                RouteMeta {
                    name: "rooms::create_room".into(),
                    method: "POST".into(),
                    path: "/api/rooms".into(),
                    summary: "Create a room".into(),
                    feature: "rooms".into(),
                    input_schema: Some(json!({
                        "type": "object",
                        "required": ["name"],
                        "properties": { "name": { "type": "string" } }
                    })),
                    output_schema: Some(json!({
                        "type": "object",
                        "properties": { "id": { "type": "string" } }
                    })),
                },
                RouteMeta {
                    name: "messages::get_message".into(),
                    method: "GET".into(),
                    path: "/api/rooms/{room_id}/messages/{msg_id}".into(),
                    summary: "Get one message".into(),
                    feature: "messages".into(),
                    input_schema: None,
                    output_schema: None,
                },
                RouteMeta {
                    name: "files::serve_asset".into(),
                    method: "GET".into(),
                    path: "/assets/{*filepath}".into(),
                    summary: "Serve a static asset".into(),
                    feature: "files".into(),
                    input_schema: None,
                    output_schema: None,
                },
            ],
            jobs: vec![],
        };

        let doc = manifest.to_openapi_3_1();
        assert_eq!(doc["openapi"], "3.1.0");
        assert_eq!(doc["info"]["title"], "campfire");
        assert_eq!(doc["info"]["version"], "0.1.0");

        // Same path with GET and POST should merge into one Path Item object
        assert_eq!(
            doc["paths"]["/api/rooms"]["get"]["operationId"],
            "rooms::list_rooms"
        );
        assert!(doc["paths"]["/api/rooms"]["get"]["requestBody"].is_null());
        assert_eq!(
            doc["paths"]["/api/rooms"]["get"]["responses"]["200"]["content"]["application/json"]
                ["schema"]["type"],
            "array"
        );

        assert_eq!(
            doc["paths"]["/api/rooms"]["post"]["operationId"],
            "rooms::create_room"
        );
        assert_eq!(
            doc["paths"]["/api/rooms"]["post"]["requestBody"]["content"]["application/json"]
                ["schema"]["required"][0],
            "name"
        );
        assert_eq!(
            doc["paths"]["/api/rooms"]["post"]["responses"]["200"]["content"]["application/json"]
                ["schema"]["properties"]["id"]["type"],
            "string"
        );

        // Multi-parameter path extraction
        let params = doc["paths"]["/api/rooms/{room_id}/messages/{msg_id}"]["get"]["parameters"]
            .as_array()
            .unwrap();
        assert_eq!(params.len(), 2);
        assert_eq!(params[0]["name"], "room_id");
        assert_eq!(params[0]["in"], "path");
        assert_eq!(params[0]["required"], true);
        assert_eq!(params[0]["schema"]["type"], "string");
        assert_eq!(params[1]["name"], "msg_id");

        // Wildcard parameter extraction
        let wildcard_params = doc["paths"]["/assets/{filepath}"]["get"]["parameters"]
            .as_array()
            .unwrap();
        assert_eq!(wildcard_params.len(), 1);
        assert_eq!(wildcard_params[0]["name"], "filepath");
        assert_eq!(wildcard_params[0]["in"], "path");
        assert_eq!(wildcard_params[0]["required"], true);
    }

    #[test]
    fn route_meta_omits_none_schemas_when_serialized() {
        let meta = RouteMeta {
            name: "health::check".into(),
            method: "GET".into(),
            path: "/health".into(),
            summary: "Health check".into(),
            feature: "health".into(),
            input_schema: None,
            output_schema: None,
        };
        let value = serde_json::to_value(&meta).unwrap();
        assert!(value.get("input_schema").is_none());
        assert!(value.get("output_schema").is_none());

        let parsed: RouteMeta = serde_json::from_value(value).unwrap();
        assert!(parsed.input_schema.is_none());
        assert!(parsed.output_schema.is_none());
    }
}