sokf-core 0.8.0

sokf-core holds the logic of the sokf command-line tool: it loads and validates Superdev Open Knowledge Format (SOKF) knowledge stores, and runs each sokf command.
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
//! This module reads the configuration file, `/.sokf/config.toml`, that
//! contract-config defines.

use std::collections::BTreeMap;

use serde::Deserialize;

use super::excludes_d::AddedExclude;
use crate::{Error, RepoPath, RepoRoot, Result, Severity, source::read_optional};

// sokf-implements: CONF-1_AC-2
// sokf-implements: CONF-1_AC-4
// sokf-implements: CONF-1_AC-5
// sokf:begin config-file
/// `ConfigFile` is the configuration file as CONF-1 defines it, with one
/// field for each table.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct ConfigFile {
    knowledge: KnowledgeSection,
    repository: RepositorySection,
    markers: MarkersSection,
    harness: BTreeMap<String, HarnessSection>,
    format: FormatSection,
}
// sokf:end config-file

/// `PACKS_GONE` says why the tool refuses a `[[pack]]` entry
/// (CONF-1_AC-6).
const PACKS_GONE: &str = "`[[pack]]` declares a pack, and packs are no longer part of sokf: \
                          remove each `[[pack]]` entry";

// sokf:begin config-format
/// `FormatSection` holds the `[format]` table (CONF-10): the formatter's
/// command, with `{files}` for the files to format and `{settings}` for the
/// path of the settings, the settings that sokf passes in place of its
/// own, and the seconds that one run of the formatter lasts at most. Without
/// `command`, sokf detects the formatter.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FormatSection {
    command: Option<Vec<String>>,
    settings: Option<toml::Table>,
    timeout: Option<i64>,
}
// sokf:end config-format

/// `FORMAT_TIMEOUT` is the longest that one run of the formatter lasts
/// when `format.timeout` is absent (CONF-10_AC-20).
pub const FORMAT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// `FormatConfig` is the resolved `[format]` table: the command and the
/// settings, as JSON text, that the configuration names, and the limit of
/// one run of the formatter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormatConfig {
    /// The formatter's program and arguments, or `None` to detect it.
    pub command: Option<Vec<String>>,
    /// The settings as JSON, or `None` for sokf's own.
    pub settings: Option<String>,
    /// The longest that one run of the formatter lasts.
    pub timeout: std::time::Duration,
}

impl Default for FormatConfig {
    // sokf-implements: CONF-10_AC-20
    fn default() -> FormatConfig {
        FormatConfig {
            command: None,
            settings: None,
            timeout: FORMAT_TIMEOUT,
        }
    }
}

impl FormatSection {
    /// `resolve` checks the table and returns it as a `FormatConfig`. It
    /// refuses a command that is empty or has no element `{files}`, and a
    /// timeout that isn't a whole number of seconds above 0.
    // sokf-implements: CONF-10_AC-4
    // sokf-implements: CONF-10_AC-21
    fn resolve(self) -> std::result::Result<FormatConfig, String> {
        if let Some(command) = &self.command
            && (command.is_empty() || !command.iter().any(|a| a == "{files}"))
        {
            return Err("format.command must name a program and have an element `{files}`".into());
        }
        let settings = self
            .settings
            .map(|t| serde_json::to_string(&t).map_err(|e| format!("format.settings: {e}")))
            .transpose()?;
        let timeout = match self.timeout {
            None => FORMAT_TIMEOUT,
            Some(secs) => u64::try_from(secs)
                .ok()
                .filter(|s| *s > 0)
                .map(std::time::Duration::from_secs)
                .ok_or("format.timeout must be a whole number of seconds above 0")?,
        };
        Ok(FormatConfig {
            command: self.command,
            settings,
            timeout,
        })
    }
}

// sokf:begin config-harness
/// `HarnessSection` holds one `[harness.NAME]` table (CONF-4). `without`
/// lists the parts of the harness that `install` skips, and `with` the parts
/// that are off by default and that `install` writes. `command` sets the
/// program that the harness's hook lines run.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct HarnessSection {
    without: Vec<String>,
    with: Vec<String>,
    command: Option<String>,
}
// sokf:end config-harness

/// `parse` reads the text of `/.sokf/config.toml` as a `ConfigFile`. It
/// refuses a file that holds a `[[pack]]` entry, or a key `pack` of any other
/// form, with `PACKS_GONE`, before it reads the tables, so that the key is
/// neither read nor named among the keys that the file can hold.
// sokf-implements: CONF-1_AC-6
fn parse(text: &str) -> std::result::Result<ConfigFile, String> {
    let table: toml::Table = toml::from_str(text).map_err(|e| e.message().to_string())?;
    if table.contains_key("pack") {
        return Err(PACKS_GONE.to_string());
    }
    toml::from_str(text).map_err(|e| e.message().to_string())
}

impl ConfigFile {
    fn declined(&self) -> BTreeMap<String, Vec<String>> {
        self.harness
            .iter()
            .map(|(name, section)| (name.clone(), section.without.clone()))
            .collect()
    }

    /// `bad_with` returns the message for the first part that a `with` list
    /// names and that isn't off by default.
    fn bad_with(&self) -> Option<String> {
        self.harness
            .iter()
            .find_map(|(name, section)| crate::harness::bad_with(name, &section.with))
    }

    /// `hook_commands` returns the program that each harness's hook line
    /// runs, for each harness whose table sets a `command`.
    fn hook_commands(&self) -> BTreeMap<String, String> {
        self.harness
            .iter()
            .filter_map(|(name, section)| section.command.clone().map(|c| (name.clone(), c)))
            .collect()
    }
}

// sokf-implements: CONF-2_AC-1
// sokf:begin config-knowledge
/// `KnowledgeSection` holds the `[knowledge]` table (CONF-2): the knowledge
/// roots, each of which the tool checks as a separate knowledge store.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct KnowledgeSection {
    roots: Vec<String>,
}

impl Default for KnowledgeSection {
    fn default() -> Self {
        KnowledgeSection {
            roots: vec!["/knowledge".into()],
        }
    }
}
// sokf:end config-knowledge

// sokf:begin config-repository
/// `RepositorySection` holds the `[repository]` table (CONF-3): the
/// `/`-rooted globs that the tool skips in its walk of the repository
/// outside the knowledge roots. That walk finds the files that
/// `additional-files` globs match.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct RepositorySection {
    exclude: Vec<String>,
}
// sokf:end config-repository

// sokf:begin config-markers
/// `MarkersSection` holds the `[markers]` table (CONF-7), which sets how a
/// run reports the markers of the files outside the knowledge roots.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct MarkersSection {
    check: MarkerCheck,
}

/// `MarkerCheck` selects what a run does with markers: the run reports a broken
/// marker as an error or as a warning, or it does not check markers at all.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MarkerCheck {
    /// A broken marker is an error.
    #[default]
    Error,
    /// A broken marker is a warning.
    Warn,
    /// The run does not check markers.
    Off,
}
// sokf:end config-markers

impl MarkerCheck {
    /// `severity` returns the severity of a broken marker: a warning under
    /// `warn`, and an error otherwise.
    pub fn severity(self) -> Severity {
        match self {
            MarkerCheck::Warn => Severity::Warning,
            _ => Severity::Error,
        }
    }
}

/// `Config` is the resolved configuration, with every root checked.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    /// The knowledge roots, each an existing directory: the own roots of
    /// `knowledge.roots`, then the roots of `/.sokf/roots.d/`.
    pub roots: Vec<RepoPath>,
    /// The number of registered roots, those of `/.sokf/roots.d/`, at the
    /// end of `roots`. The roots before them are the own roots of
    /// `knowledge.roots` (CLI-6_AC-116).
    pub registered_count: usize,
    /// The `/`-rooted globs of `repository.exclude`, pruned from the
    /// repository walk.
    pub exclude: Vec<String>,
    /// The `/`-rooted globs of the files of `/.sokf/excludes.d/`, each with
    /// its file, pruned from the repository walk too.
    pub added_exclude: Vec<AddedExclude>,
    /// The declined parts of each harness, by harness name.
    pub declined: BTreeMap<String, Vec<String>>,
    /// How a run reports markers.
    pub markers: MarkerCheck,
    /// The formatter that a run compares generated blocks with.
    pub format: FormatConfig,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            roots: vec![RepoPath::parse("/knowledge").expect("literal")],
            registered_count: 0,
            exclude: Vec::new(),
            added_exclude: Vec::new(),
            declined: BTreeMap::new(),
            markers: MarkerCheck::default(),
            format: FormatConfig::default(),
        }
    }
}

impl Config {
    /// `excludes` returns every glob that the walk prunes: those of
    /// `repository.exclude`, then those of `/.sokf/excludes.d/`.
    pub fn excludes(&self) -> impl Iterator<Item = &str> {
        self.exclude
            .iter()
            .map(String::as_str)
            .chain(self.added_exclude.iter().map(|e| e.glob.as_str()))
    }
}

/// `glob_fault` returns the message for a glob of the list `key`, such as
/// `repository.exclude`, that isn't `/`-rooted or doesn't parse, and `None`
/// for a glob that the walk can prune by.
// sokf-implements: CONF-3_AC-5
// sokf-implements: CONF-3_AC-6
pub(super) fn glob_fault(key: &str, g: &str) -> Option<String> {
    if !g.starts_with('/') {
        return Some(format!("{key} glob `{g}` is not /-rooted"));
    }
    crate::walk::repo_glob(g)
        .err()
        .map(|e| format!("{key} glob `{g}` does not parse: {e}"))
}

/// `config_path` returns the path of the configuration file.
pub fn config_path() -> RepoPath {
    RepoPath::parse("/.sokf/config.toml").expect("literal")
}

/// `load_config` reads `/.sokf/config.toml`, or returns the defaults when the
/// file is absent. It refuses a file that does not parse, that holds a
/// `[[pack]]` entry (CONF-1_AC-6), or that has an unknown key, a glob that is
/// not `/`-rooted or does not parse, or a root that is not a directory. It also
/// refuses a file of `/.sokf/excludes.d/` that does not parse, that has a key
/// other than `exclude`, or that lists such a glob (CONF-3_AC-10,
/// CONF-3_AC-11).
pub fn load_config(root: &RepoRoot) -> Result<Config> {
    let path = config_path();
    let fs_path = path.to_fs(root);
    // The tool reads an absent file as a file with no tables, so it
    // checks the default root as it checks a root written in the file.
    // sokf-implements: CONF-1_AC-1
    let text = read_optional(&fs_path)?.unwrap_or_default();
    // sokf-implements: CONF-1_AC-3
    // sokf-implements: CONF-6_AC-1
    let file = parse(&text).map_err(|m| Error::config(path.clone(), m))?;
    if let Some(m) = file.bad_with() {
        return Err(Error::config(path, m));
    }
    let mut roots = Vec::new();
    for r in &file.knowledge.roots {
        // sokf-implements: CONF-2_AC-7
        let Some(rp) = RepoPath::parse(r) else {
            return Err(Error::config(
                path,
                format!("knowledge.roots entry `{r}` is not a /-rooted path"),
            ));
        };
        // sokf-implements: CONF-2_AC-6
        if !rp.to_fs(root).is_dir() {
            return Err(Error::config(
                path,
                format!("knowledge root `{r}` is not a directory"),
            ));
        }
        roots.push(rp);
    }
    // sokf-implements: CONF-2_AC-48
    let registered = super::roots_d::read_registered(root, &|p, m| Error::config(p, m))?;
    for r in &registered {
        // sokf-implements: CONF-2_AC-52
        if !r.root.to_fs(root).is_dir() {
            return Err(Error::config(
                r.file.clone(),
                format!("knowledge root `{}` is not a directory", r.root),
            ));
        }
    }
    super::roots_d::check_apart(&roots, &registered)?;
    let registered_count = registered.len();
    roots.extend(registered.into_iter().map(|r| r.root));
    for g in &file.repository.exclude {
        if let Some(m) = glob_fault("repository.exclude", g) {
            return Err(Error::config(path, m));
        }
    }
    let added_exclude = super::excludes_d::read_added(root)?;
    let declined = file.declined();
    let format = file
        .format
        .resolve()
        .map_err(|m| Error::config(path.clone(), m))?;
    Ok(Config {
        roots,
        registered_count,
        declined,
        exclude: file.repository.exclude,
        added_exclude,
        markers: file.markers.check,
        format,
    })
}

/// `ConfigText` is the configuration as written, for `init` and the harness
/// commands: the roots as listed, whether or not each one is a directory,
/// and the file's text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigText {
    /// `knowledge.roots` as written, or the default when the file is absent.
    pub roots: Vec<RepoPath>,
    /// The roots of `/.sokf/roots.d/` as written, whether or not each one is
    /// a directory.
    pub registered: Vec<RepoPath>,
    /// The declined parts of each harness, as written.
    pub declined: BTreeMap<String, Vec<String>>,
    /// The program each harness's hook line runs, where one is set.
    pub hook_commands: BTreeMap<String, String>,
    /// The file's text, or `None` when the file is absent.
    pub text: Option<String>,
}

/// `read_lenient` reads `/.sokf/config.toml` without requiring its roots to
/// exist. It refuses a file that does not parse, a file that holds a
/// `[[pack]]` entry, or a root that is not `/`-rooted, with an `init` error
/// (CONF-1_AC-3, CONF-1_AC-6). `init` and the harness
/// commands call `read_lenient`, not `load_config`, because `load_config`
/// refuses a root that is not a directory. That refusal is right for every
/// other command, but wrong for `init`, the command that creates the roots.
// sokf-implements: CONF-1_AC-1
// sokf-implements: CONF-1_AC-3
// sokf-implements: CONF-2_AC-7
// sokf-implements: CONF-2_AC-8
pub fn read_lenient(root: &RepoRoot) -> Result<ConfigText> {
    let path = config_path();
    let fs_path = path.to_fs(root);
    // A file of `/.sokf/roots.d/` that doesn't parse registers nothing here,
    // so that the tool that owns the file can write it again.
    let registered = super::roots_d::registered_lenient(root);
    let Some(text) = read_optional(&fs_path)? else {
        return Ok(ConfigText {
            roots: Config::default().roots,
            registered,
            declined: BTreeMap::new(),
            hook_commands: BTreeMap::new(),
            text: None,
        });
    };
    let file = parse(&text).map_err(|m| Error::Init(format!("{path}: {m}")))?;
    if let Some(m) = file.bad_with() {
        return Err(Error::Init(format!("{path}: {m}")));
    }
    let mut roots = Vec::new();
    for r in &file.knowledge.roots {
        let rp = RepoPath::parse(r).ok_or_else(|| {
            Error::Init(format!(
                "{path}: knowledge.roots entry `{r}` is not a /-rooted path"
            ))
        })?;
        roots.push(rp);
    }
    Ok(ConfigText {
        roots,
        registered,
        declined: file.declined(),
        hook_commands: file.hook_commands(),
        text: Some(text),
    })
}

#[cfg(test)]
mod tests {
    use std::{
        fs,
        path::{Path, PathBuf},
    };

    use super::*;

    // sokf-tests: CONF-1_AC-1
    // sokf-tests: CONF-1_AC-3
    // sokf-tests: CONF-1_AC-4
    // sokf-tests: CONF-2_AC-7
    // sokf-tests: CONF-2_AC-8
    #[test]
    fn reads_leniently_for_init() {
        let dir = temp("lenient");
        let root = RepoRoot::new(dir.clone());
        assert_eq!(
            read_lenient(&root).unwrap(),
            ConfigText {
                roots: Config::default().roots,
                registered: vec![],
                declined: BTreeMap::new(),
                hook_commands: BTreeMap::new(),
                text: None
            }
        );
        // `read_lenient` keeps a root that is not a directory, and it keeps
        // the harness table unchanged.
        let text = "# c\n[knowledge]\nroots = [\"/missing\", \"/docs\"]\n[harness.claude]\nwithout = [\"hooks\"]\n";
        fs::write(dir.join(".sokf/config.toml"), text).unwrap();
        assert_eq!(
            read_lenient(&root).unwrap(),
            ConfigText {
                roots: vec![
                    RepoPath::parse("/missing").unwrap(),
                    RepoPath::parse("/docs").unwrap()
                ],
                registered: vec![],
                declined: BTreeMap::from([("claude".to_string(), vec!["hooks".to_string()])]),
                hook_commands: BTreeMap::new(),
                text: Some(text.into())
            }
        );
        for bad in [
            "not toml [",
            "[knowledge]\nroots = [\"docs\"]\n",
            "[nope]\n",
        ] {
            fs::write(dir.join(".sokf/config.toml"), bad).unwrap();
            let e = read_lenient(&root).unwrap_err();
            assert!(matches!(e, Error::Init(_)), "{bad:?} -> {e}");
            assert!(
                e.to_string().starts_with("init: /.sokf/config.toml: "),
                "{e}"
            );
        }
        fs::remove_dir_all(&dir).unwrap();
    }

    fn temp(name: &str) -> PathBuf {
        let dir = crate::test_support::fresh_dir(&format!("config-{name}"));
        fs::create_dir_all(dir.join(".sokf")).unwrap();
        fs::create_dir_all(dir.join("knowledge")).unwrap();
        fs::create_dir_all(dir.join("docs")).unwrap();
        dir
    }

    fn with(dir: &Path, text: &str) -> Result<Config> {
        fs::write(dir.join(".sokf/config.toml"), text).unwrap();
        load_config(&RepoRoot::new(dir.to_path_buf()))
    }

    #[test]
    fn absent_file_gives_defaults() {
        let dir = temp("absent");
        assert_eq!(
            load_config(&RepoRoot::new(dir.clone())).unwrap(),
            Config::default()
        );
        fs::remove_dir_all(&dir).unwrap();
    }

    // sokf-tests: CONF-1_AC-1
    // sokf-tests: CONF-2_AC-1
    #[test]
    fn an_absent_file_reads_as_a_file_with_no_tables() {
        let dir = temp("no-tables");
        fs::remove_file(dir.join(".sokf/config.toml")).ok();
        let absent = load_config(&RepoRoot::new(dir.clone())).unwrap();
        assert_eq!(absent.roots, vec![RepoPath::parse("/knowledge").unwrap()]);
        for text in ["", "# A comment only.\n"] {
            assert_eq!(with(&dir, text).unwrap(), absent, "{text:?}");
        }
        // Without a `/knowledge` directory, the absent file and the empty
        // file give the same refusal.
        fs::remove_dir_all(dir.join("knowledge")).unwrap();
        let empty = with(&dir, "").unwrap_err().to_string();
        fs::remove_file(dir.join(".sokf/config.toml")).unwrap();
        let absent = load_config(&RepoRoot::new(dir.clone()))
            .unwrap_err()
            .to_string();
        assert_eq!(absent, empty);
        assert!(absent.contains("is not a directory"), "{absent}");
        fs::remove_dir_all(&dir).unwrap();
    }

    // sokf-tests: CONF-1_AC-2
    // sokf-tests: CONF-6_AC-1
    #[test]
    fn reads_roots_and_excludes() {
        let dir = temp("ok");
        let c = with(
            &dir,
            "[knowledge]\nroots = [\"/knowledge\", \"/docs\"]\n[repository]\nexclude = [\"/vendor/**\"]\n",
        )
        .unwrap();
        assert_eq!(c.roots.len(), 2);
        assert_eq!(c.exclude, vec!["/vendor/**"]);
        let c = with(&dir, "[repository]\nexclude = []\n").unwrap();
        assert_eq!(c.roots, Config::default().roots);
        // TOML 1.1 accepts a `\xHH` escape, which TOML 1.0 refuses.
        let c = with(&dir, "[knowledge]\nroots = [\"\\x2Fdocs\"]\n").unwrap();
        assert_eq!(c.roots, vec![RepoPath::parse("/docs").unwrap()]);
        fs::remove_dir_all(&dir).unwrap();
    }

    // sokf-tests: CONF-7_AC-1
    // sokf-tests: CONF-7_AC-2
    #[test]
    fn reads_the_markers_table() {
        let dir = temp("markers");
        assert_eq!(with(&dir, "").unwrap().markers, MarkerCheck::Error);
        for (text, check) in [
            ("[markers]\ncheck = \"error\"\n", MarkerCheck::Error),
            ("[markers]\ncheck = \"warn\"\n", MarkerCheck::Warn),
            ("[markers]\ncheck = \"off\"\n", MarkerCheck::Off),
            ("[markers]\n", MarkerCheck::Error),
        ] {
            assert_eq!(with(&dir, text).unwrap().markers, check, "{text:?}");
        }
        for bad in [
            "[markers]\ncheck = \"loud\"\n",
            "[markers]\nchecks = \"off\"\n",
        ] {
            let e = with(&dir, bad).unwrap_err();
            assert!(matches!(e, Error::Config { .. }), "{bad:?} -> {e}");
        }
        fs::remove_dir_all(&dir).unwrap();
    }

    // sokf-tests: CONF-4_AC-1
    #[test]
    fn reads_the_harness_table() {
        let dir = temp("harness");
        let c = with(
            &dir,
            "[harness.claude]\nwithout = [\"hooks\", \"skills\"]\n",
        )
        .unwrap();
        assert_eq!(
            c.declined,
            BTreeMap::from([(
                "claude".to_string(),
                vec!["hooks".to_string(), "skills".to_string()]
            )])
        );
        // A table with no `without` key declines nothing, and the tool reads
        // a table for another harness as written.
        let c = with(&dir, "[harness.claude]\n[harness.other]\nwithout = []\n").unwrap();
        assert_eq!(c.declined["claude"], Vec::<String>::new());
        assert_eq!(c.declined["other"], Vec::<String>::new());
        // A `with` list may list the hooks, which are off by default, or nothing.
        for text in [
            "[harness.claude]\nwith = []\n",
            "[harness.claude]\nwith = [\"hooks\"]\n",
        ] {
            assert!(with(&dir, text).is_ok(), "{text:?}");
        }
        // A `with` list that lists a part that is on by default opts in to nothing, so the
        // tool refuses it and names the list.
        let e = with(&dir, "[harness.claude]\nwith = [\"skills\"]\n").unwrap_err();
        assert!(matches!(e, Error::Config { .. }), "{e}");
        assert!(e.to_string().contains("harness.claude.with"), "{e}");
        // The tool refuses an unknown key in the table, as it refuses every
        // unknown key.
        let e = with(&dir, "[harness.claude]\nwithin = []\n").unwrap_err();
        assert!(matches!(e, Error::Config { .. }), "{e}");
        fs::remove_dir_all(&dir).unwrap();
    }

    // sokf-tests: CONF-1_AC-3
    // sokf-tests: CONF-1_AC-4
    // sokf-tests: CONF-2_AC-6
    // sokf-tests: CONF-2_AC-7
    // sokf-tests: CONF-3_AC-5
    // sokf-tests: CONF-3_AC-6
    #[test]
    fn refuses_bad_files() {
        let dir = temp("bad");
        for text in [
            "not toml [",
            "[knowledge]\nrootz = []\n",
            "[other]\nx = 1\n",
            "[knowledge]\nroots = [\"knowledge\"]\n",
            "[knowledge]\nroots = [\"/missing\"]\n",
            "[repository]\nexclude = [\"vendor/**\"]\n",
            "[repository]\nexclude = [\"/[\"]\n",
        ] {
            let e = with(&dir, text).unwrap_err();
            assert!(matches!(e, Error::Config { .. }), "{text:?} -> {e}");
            assert!(e.to_string().starts_with("/.sokf/config.toml: "), "{e}");
        }
        fs::remove_dir_all(&dir).unwrap();
    }

    // A `[[pack]]` entry, or a key `pack` of any other form, stops every
    // reader with a message that says that packs are no longer part of
    // sokf.
    // sokf-tests: CONF-1_AC-6
    #[test]
    fn refuses_the_entries_of_the_packs() {
        let dir = temp("packs");
        let root = RepoRoot::new(dir.clone());
        for text in [
            "[[pack]]\nname = \"@acme/tool\"\nsource = \"./\"\n",
            "[knowledge]\nroots = [\"/knowledge\"]\n\n[[pack]]\nname = \"rust\"\n",
            "pack = []\n",
        ] {
            let e = with(&dir, text).unwrap_err();
            assert!(matches!(e, Error::Config { .. }), "{text:?} -> {e}");
            assert!(
                e.to_string().contains("packs are no longer part of sokf"),
                "{e}"
            );
            let e = read_lenient(&root).unwrap_err();
            assert!(matches!(e, Error::Init(_)), "{text:?} -> {e}");
            assert!(
                e.to_string().contains("packs are no longer part of sokf"),
                "{e}"
            );
        }
        // The keys that the error of an unknown key lists leave out `pack`.
        let e = with(&dir, "foo = 1\n").unwrap_err().to_string();
        assert!(e.contains("unknown field `foo`"), "{e}");
        assert!(!e.contains("pack"), "{e}");
        fs::remove_dir_all(&dir).unwrap();
    }

    // `[format]` names a command with an element `{files}`, settings, which
    // the configuration holds as JSON, and a timeout of whole seconds.
    // sokf-tests: CONF-10_AC-4
    // sokf-tests: CONF-10_AC-20
    // sokf-tests: CONF-10_AC-21
    #[test]
    fn reads_the_format_table() {
        let dir = temp("format");
        for text in [
            "[format]\ncommand = []\n",
            "[format]\ncommand = [\"prettier\", \"--write\"]\n",
            "[format]\ncommand = \"prettier {files}\"\n",
            "[format]\nwidth = 3\n",
            "[format]\ntimeout = 0\n",
            "[format]\ntimeout = -1\n",
            "[format]\ntimeout = 1.5\n",
        ] {
            let e = with(&dir, text).unwrap_err();
            assert!(matches!(e, Error::Config { .. }), "{text:?} -> {e}");
        }
        let config = with(
            &dir,
            "[format]\ncommand = [\"fmt\", \"{files}\"]\nsettings = { printWidth = 80, proseWrap = \"never\" }\n",
        )
        .unwrap();
        assert_eq!(
            config.format.command,
            Some(vec!["fmt".into(), "{files}".into()])
        );
        assert_eq!(
            config.format.settings.as_deref(),
            Some(r#"{"printWidth":80,"proseWrap":"never"}"#)
        );
        assert_eq!(config.format.timeout, std::time::Duration::from_secs(10));
        let config = with(&dir, "[format]\ntimeout = 3\n").unwrap();
        assert_eq!(config.format.timeout, std::time::Duration::from_secs(3));
        assert_eq!(with(&dir, "").unwrap().format, FormatConfig::default());
        fs::remove_dir_all(&dir).unwrap();
    }
}