lanekeep-config 0.6.0

Configuration loading and canonicalized hashing for lanekeep.
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
//! Configuration loading and canonicalized hashing for lanekeep.
//!
//! Loads `lanekeep.config.ts`, resolves the rule graph, and derives the hashes feeding the
//! cache key.
//!
//! # How the config is read
//!
//! The config is a TypeScript module, so reading it means running it. A synthetic entry
//! module imports the config's default export into a global, and a second evaluation hands
//! back `JSON.stringify` of the parts that are data.
//!
//! Going through JSON rather than reaching into engine values is deliberate. It keeps
//! every value crossing the boundary plainly serializable, it makes the whole extraction
//! one testable string, and it sidesteps threading engine lifetimes through this crate.
//!
//! The one thing it cannot carry is a function, and `check` is a function. So the
//! extraction separately records whether each rule has a callable `check` and `reduce`.
//! Without that, a rule whose handler was misspelled would load cleanly and silently never
//! fire — the worst failure this tool can have, because it looks exactly like passing.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::time::Duration;

use lanekeep_core::{Examples, Gates, Namespace, RuleCard, RuleId, Severity};
use lanekeep_js::{Limits, RuleRoot, RunClock, Sandbox};
use serde::Deserialize;
use thiserror::Error;

/// A 32-byte content hash.
pub type Hash = [u8; 32];

mod json;

/// Render a hash the way it appears in diagnostics and cache paths.
#[must_use]
pub fn hex(hash: &Hash) -> String {
    use std::fmt::Write as _;
    hash.iter()
        .fold(String::with_capacity(64), |mut out, byte| {
            let _ = write!(out, "{byte:02x}");
            out
        })
}

/// A rule as the config declares it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleSpec {
    /// Zero-based position in the config's `rules` array.
    ///
    /// This is how the engine reaches the handler: the rule object lives in the loaded
    /// config, and indexing into it is what lets a function cross the boundary without
    /// ever being extracted as a value.
    pub index: usize,
    /// Namespaced identifier.
    pub id: RuleId,
    /// Which languages' grammars the query compiles against, and which files the rule runs on.
    ///
    /// A rule runs on a file only when the file's own language is one of these, and it is
    /// then parsed with *that* grammar. Running every rule against every file with a single
    /// declared grammar is what used to turn a `.tsx` file into a tree of `ERROR` nodes —
    /// silently, since a query simply matches nothing inside one.
    pub languages: Vec<String>,
    /// Severity as the rule declares it, before config overrides.
    pub severity: Severity,
    /// The rule card.
    pub card: RuleCard,
    /// The tree-sitter query gating the handler.
    pub query: String,
    /// Pre-parse gates.
    pub gates: Gates,
    /// A per-invocation budget overriding the default.
    pub timeout: Option<Duration>,
    /// Whether the rule has a `reduce` phase.
    pub has_reduce: bool,
}

/// A loaded, validated configuration.
#[expect(
    clippy::struct_field_names,
    reason = "`ruleset_hash` and `config_hash` are the names docs/architecture.md §8.1 \
              gives these two cache-key inputs. Renaming them to satisfy the lint would \
              make the code and the specification disagree about the same thing, which \
              costs more than the repetition saves."
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    /// Globs selecting files to check.
    pub include: Vec<String>,
    /// Globs excluding files from the selection.
    pub exclude: Vec<String>,
    /// Rules, in the order the config listed them.
    pub rules: Vec<RuleSpec>,
    /// Budgets, with defaults filled in.
    pub limits: Limits,
    /// Hash of every module in the rule import graph.
    pub ruleset_hash: Hash,
    /// Hash of the configuration values.
    pub config_hash: Hash,
}

/// Why a configuration could not be loaded.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ConfigError {
    /// The config file does not exist or sits outside the project.
    #[error("cannot load config `{path}`: {detail}")]
    Unreadable {
        /// The path as given.
        path: String,
        /// What went wrong.
        detail: String,
    },

    /// The config module threw, failed to parse, or breached a limit.
    #[error("config `{path}` failed to evaluate\n{detail}")]
    Evaluation {
        /// The path as given.
        path: String,
        /// The sandbox's account of it.
        detail: String,
    },

    /// The config evaluated but is not shaped like a config.
    #[error("config `{path}` is not valid: {detail}")]
    Shape {
        /// The path as given.
        path: String,
        /// What is wrong.
        detail: String,
    },

    /// A rule in the config is not usable.
    #[error("rule {position} in `{path}` is not valid: {detail}")]
    Rule {
        /// One-based position in the `rules` array, so an unnamed rule can still be found.
        position: usize,
        /// The path as given.
        path: String,
        /// What is wrong.
        detail: String,
    },
}

/// The shape `JSON.stringify` hands back. Deliberately permissive — every field is checked
/// afterwards, so a malformed config produces a diagnostic naming the field rather than a
/// deserialization error naming a line of JSON the user never wrote.
#[derive(Debug, Deserialize)]
struct RawConfig {
    #[serde(default)]
    include: Vec<String>,
    #[serde(default)]
    exclude: Vec<String>,
    #[serde(default)]
    namespaces: Vec<String>,
    #[serde(default)]
    severity: BTreeMap<String, String>,
    #[serde(default)]
    timeouts: RawTimeouts,
    #[serde(default)]
    rules: Vec<RawRule>,
}

#[derive(Debug, Default, Deserialize)]
struct RawTimeouts {
    rule: Option<u64>,
    global: Option<u64>,
}

#[derive(Debug, Deserialize)]
struct RawRule {
    id: Option<String>,
    language: Option<RawLanguages>,
    severity: Option<String>,
    card: Option<RawCard>,
    query: Option<String>,
    #[serde(default)]
    gates: Gates,
    timeout: Option<u64>,
    has_check: bool,
    has_reduce: bool,
}

/// `language: 'tsx'` and `language: ['typescript', 'tsx']` are both ordinary things to write.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RawLanguages {
    One(String),
    Many(Vec<String>),
}

impl RawLanguages {
    fn into_vec(self) -> Vec<String> {
        match self {
            Self::One(language) => vec![language],
            Self::Many(languages) => languages,
        }
    }
}

#[derive(Debug, Deserialize)]
struct RawCard {
    message: Option<String>,
    remediation: Option<String>,
    examples: Option<RawExamples>,
}

#[derive(Debug, Deserialize)]
struct RawExamples {
    bad: Option<String>,
    good: Option<String>,
}

/// The name of the synthetic entry module.
///
/// It has to sit inside the rules root, because the resolver treats a module's name as its
/// path when resolving that module's imports.
const ENTRY: &str = "__lanekeep_entry__.js";

/// The script that reduces the config to JSON.
///
/// `has_check` and `has_reduce` are recorded here rather than inferred later, because
/// `JSON.stringify` drops functions and there is no way to tell afterwards whether a rule
/// had a handler or a typo.
const EXTRACT: &str = r"
    (() => {
        const c = globalThis.__lanekeepConfig;
        if (c === null || typeof c !== 'object') return JSON.stringify(null);
        const rules = Array.isArray(c.rules) ? c.rules : [];
        return JSON.stringify({
            include: c.include ?? [],
            namespaces: c.namespaces ?? [],
            exclude: c.exclude ?? [],
            severity: c.severity ?? {},
            timeouts: c.timeouts ?? {},
            rules: rules.map((r) => ({
                id: r?.id ?? null,
                language: r?.language ?? null,
                severity: r?.severity ?? null,
                card: r?.card ?? null,
                query: r?.query ?? null,
                gates: r?.gates ?? {},
                timeout: r?.timeout ?? null,
                has_check: typeof r?.check === 'function',
                has_reduce: typeof r?.reduce === 'function',
            })),
        });
    })()
";

/// The entry module the loader evaluates, whichever format the config is written in.
///
/// Both formats converge here, and that is the point: a JSON config is compiled into the
/// same module a TypeScript one is imported by, so extraction, validation, hashing and the
/// cache key never learn which format they came from. Two loaders would be two behaviors
/// eventually, and the divergence would show up as a rule that runs under one form and not
/// the other.
fn entry_source(root: &RuleRoot, config_path: &Path, display: &str) -> Result<String, ConfigError> {
    if json::is_json(config_path) {
        return json::entry_source(config_path);
    }

    let specifier =
        relative_specifier(root.path(), config_path).ok_or_else(|| ConfigError::Unreadable {
            path: display.to_owned(),
            detail: "the config file must sit inside the rules root".to_owned(),
        })?;
    Ok(format!(
        "import config from '{specifier}';\nglobalThis.__lanekeepConfig = config;\n"
    ))
}

/// Evaluate the config module into a sandbox, leaving the rule objects reachable.
///
/// Separate from [`load`] because every worker needs the ruleset present in its own engine
/// — a rule's `check` is a function, and a function cannot be moved between runtimes. Each
/// worker therefore evaluates the same modules rather than receiving extracted values.
///
/// # Errors
///
/// Returns [`ConfigError`] when the config sits outside the rules root or fails to
/// evaluate.
pub fn evaluate_into(
    sandbox: &Sandbox,
    root: &RuleRoot,
    config_path: &Path,
) -> Result<(), ConfigError> {
    let display = config_path.display().to_string();
    let entry = root.path().join(ENTRY);
    let source = entry_source(root, config_path, &display)?;

    sandbox
        .eval_module(&entry.display().to_string(), &source)
        .map_err(|e| ConfigError::Evaluation {
            path: display,
            detail: e.to_string(),
        })
}

/// Load and validate a configuration.
///
/// # Errors
///
/// Returns [`ConfigError`] when the file cannot be read, the module fails to evaluate, or
/// the result is not shaped like a config.
pub fn load(sandbox: &Sandbox, root: &RuleRoot, config_path: &Path) -> Result<Config, ConfigError> {
    let display = config_path.display().to_string();

    let entry = root.path().join(ENTRY);
    let source = entry_source(root, config_path, &display)?;
    sandbox
        .eval_module(&entry.display().to_string(), &source)
        .map_err(|e| ConfigError::Evaluation {
            path: display.clone(),
            detail: e.to_string(),
        })?;

    let json: String = sandbox.eval(EXTRACT).map_err(|e| ConfigError::Evaluation {
        path: display.clone(),
        detail: e.to_string(),
    })?;

    let raw: Option<RawConfig> = serde_json::from_str(&json).map_err(|e| ConfigError::Shape {
        path: display.clone(),
        detail: e.to_string(),
    })?;
    let raw = raw.ok_or_else(|| ConfigError::Shape {
        path: display.clone(),
        detail: "the default export is not an object — did you forget `export default`?".to_owned(),
    })?;

    build(sandbox, raw, &display)
}

fn build(sandbox: &Sandbox, raw: RawConfig, display: &str) -> Result<Config, ConfigError> {
    let overrides = parse_severity_overrides(&raw.severity, display)?;

    // Namespaces this project claims, beyond the two lanekeep defines. Validated for shape
    // here so a malformed one is reported against `namespaces` rather than against whichever
    // rule happened to use it first.
    let mut declared = BTreeSet::new();
    for namespace in &raw.namespaces {
        RuleId::namespace_from_str(namespace).map_err(|e| ConfigError::Shape {
            path: display.to_owned(),
            detail: format!("`namespaces` contains an invalid entry: {e}"),
        })?;
        if namespace == Namespace::LANEKEEP {
            return Err(ConfigError::Shape {
                path: display.to_owned(),
                detail: "`lanekeep` is reserved for rules shipped with lanekeep — a rule's \
                         origin should be readable from its ID"
                    .to_owned(),
            });
        }
        declared.insert(namespace.clone());
    }

    let mut rules = Vec::with_capacity(raw.rules.len());
    for (index, rule) in raw.rules.into_iter().enumerate() {
        rules.push(build_rule(rule, index + 1, display, &overrides, &declared)?);
    }

    let mut limits = Limits::default();
    if let Some(ms) = raw.timeouts.rule {
        limits = limits.with_rule_timeout(Duration::from_millis(ms));
    }
    if let Some(ms) = raw.timeouts.global {
        limits = limits.with_global_timeout(Duration::from_millis(ms));
    }

    let ruleset_hash = hash_ruleset(sandbox);
    let config_hash = hash_config(&raw.include, &raw.exclude, &overrides, &limits);

    Ok(Config {
        include: raw.include,
        exclude: raw.exclude,
        rules,
        limits,
        ruleset_hash,
        config_hash,
    })
}

fn parse_severity_overrides(
    raw: &BTreeMap<String, String>,
    display: &str,
) -> Result<BTreeMap<RuleId, Severity>, ConfigError> {
    raw.iter()
        .map(|(id, severity)| {
            let id = id.parse::<RuleId>().map_err(|e| ConfigError::Shape {
                path: display.to_owned(),
                detail: format!("in `severity`: {e}"),
            })?;
            let severity = severity
                .parse::<Severity>()
                .map_err(|e| ConfigError::Shape {
                    path: display.to_owned(),
                    detail: format!("in `severity` for `{id}`: {e}"),
                })?;
            Ok((id, severity))
        })
        .collect()
}

fn build_rule(
    raw: RawRule,
    position: usize,
    display: &str,
    overrides: &BTreeMap<RuleId, Severity>,
    declared: &BTreeSet<String>,
) -> Result<RuleSpec, ConfigError> {
    let fail = |detail: String| ConfigError::Rule {
        position,
        path: display.to_owned(),
        detail,
    };

    let id = raw
        .id
        .ok_or_else(|| fail("missing `id`".to_owned()))?
        .parse::<RuleId>()
        .map_err(|e| fail(e.to_string()))?;

    // A namespace nobody declared is a typo, and this is the only layer that can tell.
    // Parsing accepts any well-formed namespace so a team can use its own; declaring it is
    // what keeps `lanekep/foo` from becoming a valid ID that quietly matches nothing.
    if !id.namespace().is_built_in() && !declared.contains(id.namespace().as_str()) {
        let mut known: Vec<String> = Namespace::built_ins()
            .iter()
            .map(|n| format!("`{n}`"))
            .collect();
        known.extend(declared.iter().map(|n| format!("`{n}`")));
        return Err(fail(format!(
            "rule namespace `{}` is not declared — add it to `namespaces` in the config, \
             or use one of {}",
            id.namespace(),
            known.join(", ")
        )));
    }

    // The check that JSON extraction exists to make possible. A rule whose handler is
    // missing or misspelled would otherwise load cleanly and never report, which is
    // indistinguishable from the code being fine.
    if !raw.has_check {
        return Err(fail(format!(
            "`{id}` has no `check` function — a rule without one can never report anything"
        )));
    }

    let query = raw
        .query
        .ok_or_else(|| fail(format!("`{id}` has no `query`")))?;
    if query.trim().is_empty() {
        return Err(fail(format!("`{id}` has an empty `query`")));
    }

    let card = raw
        .card
        .ok_or_else(|| fail(format!("`{id}` has no `card`")))?;
    let examples = card.examples.unwrap_or(RawExamples {
        bad: None,
        good: None,
    });
    let card = RuleCard {
        message: card.message.unwrap_or_default(),
        remediation: card.remediation.unwrap_or_default(),
        examples: Examples {
            bad: examples.bad.unwrap_or_default(),
            good: examples.good.unwrap_or_default(),
        },
    };
    card.validate()
        .map_err(|problems| fail(format!("`{id}` has an unusable card: {problems:?}")))?;

    let declared = raw
        .severity
        .map(|s| s.parse::<Severity>())
        .transpose()
        .map_err(|e| fail(format!("`{id}`: {e}")))?
        .unwrap_or(Severity::Error);

    Ok(RuleSpec {
        index: position - 1,
        // Config severity wins over what the rule declares, per §9.
        severity: overrides.get(&id).copied().unwrap_or(declared),
        id,
        // Both TypeScript dialects by default, because a rule written for TypeScript is
        // meant for the TypeScript in the project — and in any React codebase most of that
        // lives in `.tsx`, which the TypeScript grammar cannot parse.
        languages: raw.language.map_or_else(
            || vec!["typescript".to_owned(), "tsx".to_owned()],
            RawLanguages::into_vec,
        ),
        card,
        query,
        gates: raw.gates,
        timeout: raw.timeout.map(Duration::from_millis),
        has_reduce: raw.has_reduce,
    })
}

/// Hash every module the loader read.
///
/// # A correction to the architecture
///
/// §8 says `ruleset_hash` must be over *canonicalized* rule definitions, so that
/// reformatting does not invalidate while editing a regex does. That was written when rules
/// were declarative data, where canonicalizing means normalizing a parsed value.
///
/// Rules are now TypeScript, and canonicalizing arbitrary TypeScript would mean shipping a
/// formatter and agreeing on its output forever. So this hashes module source bytes:
/// reformatting a rule *does* invalidate its cached results.
///
/// That is over-invalidation, which costs a recompute. The alternative error —
/// under-invalidating and serving results computed by code that no longer exists — is the
/// one §8 exists to prevent, and it is not symmetric with this one.
fn hash_ruleset(sandbox: &Sandbox) -> Hash {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"lanekeep-ruleset-v1");

    if let Some(loaded) = sandbox.loaded_modules() {
        // The map is ordered, so the hash does not depend on load order — which varies with
        // import structure and is not something the user changed.
        for (path, source) in loaded.borrow().iter() {
            hasher.update(path.to_string_lossy().as_bytes());
            hasher.update(&[0]);
            hasher.update(source.as_bytes());
            hasher.update(&[0]);
        }
    }

    *hasher.finalize().as_bytes()
}

/// Hash the configuration values.
///
/// Canonicalized properly, because these *are* structured data: the severity map is ordered
/// so writing the same entries in a different order hashes the same, and the budgets are
/// hashed as numbers rather than as whatever the user typed.
fn hash_config(
    include: &[String],
    exclude: &[String],
    severity: &BTreeMap<RuleId, Severity>,
    limits: &Limits,
) -> Hash {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"lanekeep-config-v1");

    for (label, globs) in [
        (b"include".as_slice(), include),
        (b"exclude".as_slice(), exclude),
    ] {
        hasher.update(label);
        // Include and exclude are order-insensitive in effect, so hashing them in the
        // order written would invalidate on a reordering that changes nothing.
        let mut sorted: Vec<&String> = globs.iter().collect();
        sorted.sort();
        for glob in sorted {
            hasher.update(glob.as_bytes());
            hasher.update(&[0]);
        }
    }

    hasher.update(b"severity");
    for (id, level) in severity {
        hasher.update(id.to_string().as_bytes());
        hasher.update(&[0]);
        hasher.update(level.as_str().as_bytes());
        hasher.update(&[0]);
    }

    hasher.update(b"limits");
    for value in [
        limits.rule_timeout.as_millis(),
        limits.global_timeout.as_millis(),
        limits.memory_bytes as u128,
    ] {
        hasher.update(&value.to_le_bytes());
    }

    *hasher.finalize().as_bytes()
}

/// A `./`-relative specifier from the root to a file inside it.
fn relative_specifier(root: &Path, file: &Path) -> Option<String> {
    let file = file.canonicalize().ok()?;
    let relative = file.strip_prefix(root).ok()?;
    let joined = relative
        .components()
        .map(|c| c.as_os_str().to_string_lossy())
        .collect::<Vec<_>>()
        .join("/");
    Some(format!("./{joined}"))
}

/// Build a sandbox able to load configuration from a rules root.
///
/// # Errors
///
/// Returns [`ConfigError::Unreadable`] if the sandbox cannot be constructed.
pub fn sandbox_for(
    root: &RuleRoot,
    typescript: std::sync::Arc<dyn lanekeep_js::Language>,
    javascript: std::sync::Arc<dyn lanekeep_js::Language>,
) -> Result<Sandbox, ConfigError> {
    let limits = Limits::default();
    Sandbox::with_modules(
        limits,
        RunClock::start(limits.global_timeout),
        root.clone(),
        typescript,
        javascript,
    )
    .map_err(|e| ConfigError::Unreadable {
        path: root.path().display().to_string(),
        detail: e.to_string(),
    })
}

/// Where a config file is expected, relative to a project root.
#[must_use]
pub fn default_config_paths(project_root: &Path) -> Vec<PathBuf> {
    [
        // First, so a project holding both is not silently checked against the other one.
        "lanekeep.json",
        "lanekeep.config.ts",
        "lanekeep.config.js",
        "lanekeep.config.mjs",
    ]
    .iter()
    .map(|name| project_root.join(name))
    .collect()
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::sync::Arc;

    use lanekeep_lang_js::{JavaScript, TypeScript};

    use super::*;

    struct Fixture {
        dir: PathBuf,
    }

    impl Fixture {
        fn new(name: &str, files: &[(&str, &str)]) -> Self {
            let dir = std::env::temp_dir().join(format!("lanekeep-config-{name}"));
            let _ = fs::remove_dir_all(&dir);
            fs::create_dir_all(&dir).expect("creates dir");
            let fixture = Self { dir };
            fixture.write_all(files);
            fixture
        }

        fn write_all(&self, files: &[(&str, &str)]) {
            for (path, contents) in files {
                let full = self.dir.join(path);
                if let Some(parent) = full.parent() {
                    fs::create_dir_all(parent).expect("creates parent");
                }
                fs::write(&full, contents).expect("writes");
            }
        }

        fn load_config(&self) -> Result<Config, ConfigError> {
            let root = RuleRoot::new(&self.dir).expect("canonicalizes");
            let sandbox =
                sandbox_for(&root, Arc::new(TypeScript), Arc::new(JavaScript)).expect("sandbox");
            load(&sandbox, &root, &self.dir.join("lanekeep.config.ts"))
        }
    }

    impl Drop for Fixture {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.dir);
        }
    }

    /// A minimal, valid rule module.
    fn rule(id: &str) -> String {
        format!(
            "import {{ defineRule }} from 'lanekeep';\n\
             export default defineRule({{\n\
               id: '{id}',\n\
               query: '(identifier) @id',\n\
               card: {{ message: 'no', remediation: 'do this', examples: {{ bad: 'a', good: 'b' }} }},\n\
               check(ctx, m) {{ ctx.report(m.id); }},\n\
             }});\n"
        )
    }

    fn config_with(body: &str) -> String {
        format!(
            "import {{ defineConfig }} from 'lanekeep';\n\
             import rule from './rule';\n\
             export default defineConfig({{ {body} }});\n"
        )
    }

    #[test]
    fn loads_a_valid_config() {
        let fixture = Fixture::new(
            "valid",
            &[
                ("rule.ts", &rule("local/example")),
                (
                    "lanekeep.config.ts",
                    &config_with(
                        "include: ['src/**/*.ts'], exclude: ['**/*.test.ts'], rules: [rule]",
                    ),
                ),
            ],
        );

        let config = fixture.load_config().expect("loads");
        assert_eq!(config.include, ["src/**/*.ts"]);
        assert_eq!(config.exclude, ["**/*.test.ts"]);
        assert_eq!(config.rules.len(), 1);
        assert_eq!(config.rules[0].id.to_string(), "local/example");
        assert_eq!(config.rules[0].card.message, "no");
        assert!(!config.rules[0].has_reduce);
    }

    /// A team can group its rules under its own namespace, which `local/` alone does not
    /// allow — everything project-authored ends up in one bucket regardless of who wrote it.
    #[test]
    fn a_declared_namespace_is_accepted() {
        let fixture = Fixture::new(
            "declared-namespace",
            &[
                ("rule.ts", &rule("pera/no-numeric-sizes")),
                (
                    "lanekeep.config.ts",
                    &config_with("namespaces: ['pera'], rules: [rule]"),
                ),
            ],
        );

        let config = fixture.load_config().expect("loads");
        assert_eq!(config.rules[0].id.to_string(), "pera/no-numeric-sizes");
        assert!(!config.rules[0].id.is_built_in());
    }

    /// And the property that made a closed set worth having in the first place: a namespace
    /// nobody declared is a typo, and it fails at load rather than becoming a valid ID that
    /// silently matches nothing.
    #[test]
    fn an_undeclared_namespace_is_rejected() {
        let fixture = Fixture::new(
            "undeclared-namespace",
            &[
                ("rule.ts", &rule("lanekep/no-default-export")),
                ("lanekeep.config.ts", &config_with("rules: [rule]")),
            ],
        );

        let error = fixture
            .load_config()
            .expect_err("an undeclared namespace should be refused")
            .to_string();
        assert!(error.contains("lanekep"), "{error}");
        assert!(
            error.contains("namespaces"),
            "should say how to fix it: {error}"
        );
    }

    /// `lanekeep/` stays reserved, so a rule's origin is readable from its ID alone.
    #[test]
    fn the_lanekeep_namespace_cannot_be_claimed() {
        let fixture = Fixture::new(
            "reserved-namespace",
            &[
                ("rule.ts", &rule("local/example")),
                (
                    "lanekeep.config.ts",
                    &config_with("namespaces: ['lanekeep'], rules: [rule]"),
                ),
            ],
        );

        let error = fixture
            .load_config()
            .expect_err("claiming the reserved namespace should be refused")
            .to_string();
        assert!(error.contains("reserved"), "{error}");
    }

    /// A rule with no language of its own targets both TypeScript dialects, because in a
    /// React codebase most TypeScript is `.tsx`.
    #[test]
    fn a_rule_defaults_to_both_typescript_dialects() {
        let fixture = Fixture::new(
            "default-languages",
            &[
                ("rule.ts", &rule("local/example")),
                ("lanekeep.config.ts", &config_with("rules: [rule]")),
            ],
        );

        let config = fixture.load_config().expect("loads");
        assert_eq!(config.rules[0].languages, ["typescript", "tsx"]);
    }

    /// One or several, both spelled the way a rule author would write them.
    #[test]
    fn a_rule_may_declare_one_language_or_several() {
        for (declaration, expected) in [
            ("language: 'tsx',", vec!["tsx"]),
            (
                "language: ['typescript', 'tsx'],",
                vec!["typescript", "tsx"],
            ),
        ] {
            let module = format!(
                "import {{ defineRule }} from 'lanekeep';\n\
                 export default defineRule({{\n\
                   id: 'local/example',\n\
                 {declaration}\n\
                   query: '(identifier) @id',\n\
                   card: {{ message: 'no', remediation: 'do this', examples: {{ bad: 'a', good: 'b' }} }},\n\
                   check(ctx, m) {{ ctx.report(m.id); }},\n\
                 }});\n"
            );
            let fixture = Fixture::new(
                "language-forms",
                &[
                    ("rule.ts", &module),
                    ("lanekeep.config.ts", &config_with("rules: [rule]")),
                ],
            );

            let config = fixture.load_config().expect("loads");
            assert_eq!(config.rules[0].languages, expected, "{declaration}");
        }
    }

    #[test]
    fn a_rule_without_a_check_function_is_rejected() {
        // The failure JSON extraction exists to catch. Without this the rule loads, never
        // fires, and looks exactly like the code being clean.
        //
        // The handler is named `onMatch` rather than a misspelling of `check`, because the
        // spell checker flags a real typo in source even inside a fixture — and allowing it
        // globally to keep the joke would be a poor trade. What matters is that `check` is
        // absent, not how it came to be.
        let fixture = Fixture::new(
            "no-check",
            &[
                (
                    "rule.ts",
                    "import { defineRule } from 'lanekeep';\n\
                     export default defineRule({\n\
                       id: 'local/typo',\n\
                       query: '(identifier) @id',\n\
                       card: { message: 'm', remediation: 'r', examples: { bad: 'a', good: 'b' } },\n\
                       onMatch(ctx, m) {},\n\
                     });\n",
                ),
                ("lanekeep.config.ts", &config_with("rules: [rule]")),
            ],
        );

        let err = fixture.load_config().expect_err("must be rejected");
        let rendered = err.to_string();
        assert!(rendered.contains("check"), "{rendered}");
        assert!(rendered.contains("never report"), "{rendered}");
    }

    #[test]
    fn a_rule_with_a_bare_id_is_rejected() {
        let fixture = Fixture::new(
            "bare-id",
            &[
                ("rule.ts", &rule("example")),
                ("lanekeep.config.ts", &config_with("rules: [rule]")),
            ],
        );
        let rendered = fixture
            .load_config()
            .expect_err("must be rejected")
            .to_string();
        assert!(rendered.contains("namespace"), "{rendered}");
    }

    #[test]
    fn a_rule_with_an_unusable_card_is_rejected() {
        let fixture = Fixture::new(
            "bad-card",
            &[
                (
                    "rule.ts",
                    "import { defineRule } from 'lanekeep';\n\
                     export default defineRule({\n\
                       id: 'local/empty',\n\
                       query: '(identifier) @id',\n\
                       card: { message: '', remediation: '', examples: { bad: '', good: '' } },\n\
                       check() {},\n\
                     });\n",
                ),
                ("lanekeep.config.ts", &config_with("rules: [rule]")),
            ],
        );
        assert!(fixture.load_config().is_err());
    }

    #[test]
    fn a_missing_default_export_says_so() {
        // The engine catches this at link time, before extraction runs, and its message is
        // better than a generic one would be — it names the module and the missing export.
        let fixture = Fixture::new(
            "no-default",
            &[
                ("rule.ts", &rule("local/x")),
                ("lanekeep.config.ts", "export const notDefault = 1;\n"),
            ],
        );
        let rendered = fixture
            .load_config()
            .expect_err("must be rejected")
            .to_string();
        assert!(rendered.contains("default"), "{rendered}");
    }

    #[test]
    fn a_default_export_that_is_not_an_object_says_so() {
        // This one does reach our own check: the export exists, so the engine is happy,
        // and only the shape is wrong.
        let fixture = Fixture::new(
            "default-not-object",
            &[
                ("rule.ts", &rule("local/x")),
                ("lanekeep.config.ts", "export default 42;\n"),
            ],
        );
        let rendered = fixture
            .load_config()
            .expect_err("must be rejected")
            .to_string();
        assert!(rendered.contains("export default"), "{rendered}");
    }

    #[test]
    fn config_severity_overrides_what_the_rule_declares() {
        let fixture = Fixture::new(
            "severity",
            &[
                ("rule.ts", &rule("local/example")),
                (
                    "lanekeep.config.ts",
                    &config_with("rules: [rule], severity: { 'local/example': 'warn' }"),
                ),
            ],
        );
        let config = fixture.load_config().expect("loads");
        assert_eq!(config.rules[0].severity, Severity::Warn);
    }

    #[test]
    fn timeouts_fall_back_to_the_defaults() {
        let fixture = Fixture::new(
            "timeouts-default",
            &[
                ("rule.ts", &rule("local/example")),
                ("lanekeep.config.ts", &config_with("rules: [rule]")),
            ],
        );
        let config = fixture.load_config().expect("loads");
        assert_eq!(config.limits, Limits::default());
    }

    #[test]
    fn timeouts_can_be_overridden() {
        let fixture = Fixture::new(
            "timeouts-set",
            &[
                ("rule.ts", &rule("local/example")),
                (
                    "lanekeep.config.ts",
                    &config_with("rules: [rule], timeouts: { rule: 2000, global: 30000 }"),
                ),
            ],
        );
        let config = fixture.load_config().expect("loads");
        assert_eq!(config.limits.rule_timeout, Duration::from_secs(2));
        assert_eq!(config.limits.global_timeout, Duration::from_secs(30));
    }

    // --- hashing --------------------------------------------------------------------

    #[test]
    fn the_ruleset_hash_covers_an_imported_helper() {
        // The §8 property, and the reason the loader records what it read rather than the
        // config naming its own inputs. A rule importing a helper has to invalidate when
        // that helper changes — nothing else in the system knows the helper was involved.
        let files: &[(&str, &str)] = &[
            ("helper.ts", "export const QUERY = '(identifier) @id';\n"),
            (
                "rule.ts",
                "import { defineRule } from 'lanekeep';\n\
                 import { QUERY } from './helper';\n\
                 export default defineRule({\n\
                   id: 'local/example',\n\
                   query: QUERY,\n\
                   card: { message: 'm', remediation: 'r', examples: { bad: 'a', good: 'b' } },\n\
                   check() {},\n\
                 });\n",
            ),
            ("lanekeep.config.ts", ""),
        ];
        let fixture = Fixture::new("helper-hash", files);
        fixture.write_all(&[("lanekeep.config.ts", &config_with("rules: [rule]"))]);

        let before = fixture.load_config().expect("loads").ruleset_hash;

        fixture.write_all(&[("helper.ts", "export const QUERY = '(string) @s';\n")]);
        let after = fixture.load_config().expect("loads").ruleset_hash;

        assert_ne!(
            hex(&before),
            hex(&after),
            "changing an imported helper must invalidate the ruleset hash"
        );
    }

    #[test]
    fn the_ruleset_hash_is_stable_when_nothing_changed() {
        let fixture = Fixture::new(
            "stable-hash",
            &[
                ("rule.ts", &rule("local/example")),
                ("lanekeep.config.ts", &config_with("rules: [rule]")),
            ],
        );
        let first = fixture.load_config().expect("loads").ruleset_hash;
        let second = fixture.load_config().expect("loads").ruleset_hash;
        assert_eq!(hex(&first), hex(&second));
    }

    #[test]
    fn the_config_hash_ignores_glob_order() {
        // Include and exclude are order-insensitive in effect, so reordering them must not
        // throw away a warm cache for a change that alters nothing.
        let make = |globs: &str| {
            Fixture::new(
                &format!("glob-order-{}", globs.len()),
                &[
                    ("rule.ts", &rule("local/example")),
                    (
                        "lanekeep.config.ts",
                        &config_with(&format!("rules: [rule], include: {globs}")),
                    ),
                ],
            )
            .load_config()
            .expect("loads")
            .config_hash
        };

        assert_eq!(
            hex(&make("['a/**', 'b/**']")),
            hex(&make("['b/**', 'a/**' ]")),
            "reordering globs must not change the config hash"
        );
    }

    #[test]
    fn the_config_hash_changes_with_severity() {
        let make = |extra: &str, tag: &str| {
            Fixture::new(
                &format!("severity-hash-{tag}"),
                &[
                    ("rule.ts", &rule("local/example")),
                    (
                        "lanekeep.config.ts",
                        &config_with(&format!("rules: [rule]{extra}")),
                    ),
                ],
            )
            .load_config()
            .expect("loads")
            .config_hash
        };

        assert_ne!(
            hex(&make("", "none")),
            hex(&make(", severity: { 'local/example': 'warn' }", "warn")),
            "changing a severity must invalidate"
        );
    }

    #[test]
    fn the_config_hash_changes_with_a_timeout() {
        let make = |extra: &str, tag: &str| {
            Fixture::new(
                &format!("timeout-hash-{tag}"),
                &[
                    ("rule.ts", &rule("local/example")),
                    (
                        "lanekeep.config.ts",
                        &config_with(&format!("rules: [rule]{extra}")),
                    ),
                ],
            )
            .load_config()
            .expect("loads")
            .config_hash
        };

        assert_ne!(
            hex(&make("", "d")),
            hex(&make(", timeouts: { rule: 5000 }", "t"))
        );
    }

    #[test]
    fn hex_renders_a_full_hash() {
        assert_eq!(hex(&[0u8; 32]).len(), 64);
        assert_eq!(hex(&[0xab; 32]), "ab".repeat(32));
    }
}