silcrow 0.1.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
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
use std::path::Path;

use crate::scheme;
use crate::walk::Patterns;

/// The `code` list `install` writes, and an old block that omits it reads: every file.
pub const DEFAULT_CODE: &str = "**/*";

/// The words a decision note holds at most as `install` writes `note-words`: about a quarter
/// of an hour of reading.
pub const DEFAULT_NOTE_WORDS: usize = 3000;

/// The words a decision note holds at most, and whether `check` fails or warns past them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NoteWords {
    pub limit: usize,
    pub warn: bool,
}

/// What `check` does with a marker in test code: fails it, warns on it, or admits it. Under
/// `Warn` and `Allow` it pays the code duty.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TestMarkers {
    Error,
    Warn,
    Allow,
}

impl TestMarkers {
    pub fn attr(self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Warn => "warn",
            Self::Allow => "allow",
        }
    }
}

/// The test code of a project by its path: the files its `tests` list matches, or each
/// language's own convention when the block omits it.
#[derive(Clone, Debug)]
pub struct TestPaths {
    list: Option<Patterns>,
}

impl TestPaths {
    /// Each language's own convention, as a block that omits `tests` reads.
    pub fn conventions() -> Self {
        Self { list: None }
    }

    /// The test paths of the project at `root`, as its block declares them.
    pub fn at(root: &Path) -> anyhow::Result<Self> {
        ProjectPolicy::from_root(root)
            .map(|policy| policy.tests)
            .map_err(anyhow::Error::msg)
    }

    /// Whether the file at `rel` is test code by its path.
    pub fn holds(&self, rel: &Path) -> bool {
        // § kwxna1ebv@35575
        match &self.list {
            Some(list) => list.matches(rel),
            None => by_convention(rel),
        }
    }
}

/// Whether the file at `rel` is test code by the convention of its language: under a `tests/`
/// directory in any language, Go `*_test.go`, Python `test_*.py` and `*_test.py`, JavaScript
/// and TypeScript `*.test.*`, `*.spec.*` and under `__tests__/`, Java and Kotlin under
/// `src/test/`.
fn by_convention(rel: &Path) -> bool {
    // § kwxna1ebv.a@jz6xr
    let dirs: Vec<&str> = rel
        .parent()
        .into_iter()
        .flat_map(Path::components)
        .filter_map(|c| c.as_os_str().to_str())
        .collect();
    let name = rel.file_name().and_then(|n| n.to_str()).unwrap_or_default();
    let ext = rel.extension().and_then(|e| e.to_str()).unwrap_or_default();
    let script = matches!(
        ext,
        "js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts"
    );
    dirs.contains(&"tests")
        || (ext == "go" && name.ends_with("_test.go"))
        || (ext == "py" && (name.starts_with("test_") || name.ends_with("_test.py")))
        || (script
            && (dirs.contains(&"__tests__")
                || name
                    .split('.')
                    .skip(1)
                    .any(|part| part == "test" || part == "spec")))
        || (matches!(ext, "java" | "kt" | "kts") && dirs.windows(2).any(|w| w == ["src", "test"]))
}

/// What an active law owes: a marker in a file `code` matches, and one in a file `docs`
/// matches for a public promise. Which code is test code is `tests`.
#[derive(Clone, Debug)]
pub struct ProjectPolicy {
    pub code: Patterns,
    pub docs: Patterns,
    pub tests: TestPaths,
    /// What `check` does with a marker in test code.
    pub test_markers: TestMarkers,
    /// The words a decision note of the project holds at most.
    pub note_words: NoteWords,
    note_words_attr: String,
    code_list: String,
    docs_list: String,
    tests_list: String,
}

impl ProjectPolicy {
    pub fn defaults() -> Self {
        Self::of(DEFAULT_CODE, "").expect("the default lists are valid")
    }

    pub fn from_root(root: &Path) -> Result<Self, String> {
        let text = std::fs::read_to_string(root.join("AGENTS.md")).ok();
        Self::from_agents(text.as_deref())
    }

    /// The policy of the worktree block at `root`, which writes every attribute: one it omits
    /// fails, naming `install`, which writes each at its default.
    pub fn explicit_at(root: &Path) -> Result<Self, String> {
        // § yymjgaqr0.h@47khq
        let text = std::fs::read_to_string(root.join("AGENTS.md")).ok();
        let policy = Self::from_agents(text.as_deref())?;
        if let Some(text) = &text {
            let written = scheme::attr_names(text);
            let omitted: Vec<String> = crate::published::BLOCK_ATTRS
                .iter()
                .filter(|attr| !written.iter().any(|w| w == *attr))
                .map(|attr| format!("`{attr}`"))
                .collect();
            if !omitted.is_empty() {
                return Err(format!(
                    "AGENTS.md: the Silcrow block omits {}, and a project writes each attribute of its block. Run `silcrow install`, which writes each one at its default and keeps the values you set.",
                    omitted.join(", ")
                ));
            }
        }
        Ok(policy)
    }

    pub fn from_agents(text: Option<&str>) -> Result<Self, String> {
        // § xs2e8kj86.e@z87p0
        let Some(text) = text else {
            return Ok(Self::defaults());
        };
        // § xs2e8kj86.d@85870
        let unknown: Vec<String> = scheme::attr_names(text)
            .into_iter()
            .filter(|attr| !crate::published::BLOCK_ATTRS.contains(&attr.as_str()))
            .collect();
        if !unknown.is_empty() {
            return Err(unknown_attrs(&unknown));
        }
        // § end xs2e8kj86.d
        crate::walk::Notes::from_agents(Some(text)).map_err(|e| format!("AGENTS.md: {e}"))?;
        let code = scheme::attr_from_agents(text, "code");
        let docs = scheme::attr_from_agents(text, "docs");
        let code = code.unwrap_or_else(|| DEFAULT_CODE.to_string());
        if code.split_whitespace().next().is_none() {
            return Err(format!(
                "AGENTS.md: the `code` list is empty, so no marker could pay a law's code duty. Name the code, or write `code=\"{DEFAULT_CODE}\"` for every file."
            ));
        }
        let note_words_attr = scheme::attr_from_agents(text, "note-words");
        let note_words = note_words(note_words_attr.as_deref())?;
        let tests = tests(scheme::attr_from_agents(text, "tests").as_deref())?;
        let test_markers = test_markers(scheme::attr_from_agents(text, "test-markers").as_deref())?;
        let policy = Self::of(&code, docs.as_deref().unwrap_or(""))
            .map_err(|e| format!("AGENTS.md: {e}"))?;
        let tests_list = scheme::attr_from_agents(text, "tests")
            .map(|v| v.split_whitespace().collect::<Vec<_>>().join(" "))
            .unwrap_or_default();
        Ok(Self {
            note_words,
            note_words_attr: note_words_attr
                .map(|v| v.trim().to_string())
                .unwrap_or_default(),
            tests,
            test_markers,
            tests_list,
            ..policy
        })
    }

    fn of(code: &str, docs: &str) -> anyhow::Result<Self> {
        let words = |list: &str| list.split_whitespace().collect::<Vec<_>>().join(" ");
        Ok(Self {
            code: Patterns::parse("code", code)?,
            docs: Patterns::parse("docs", docs)?,
            note_words: NoteWords {
                limit: DEFAULT_NOTE_WORDS,
                warn: false,
            },
            note_words_attr: String::new(),
            tests: TestPaths::conventions(),
            test_markers: TestMarkers::Error,
            code_list: words(code),
            docs_list: words(docs),
            tests_list: String::new(),
        })
    }

    pub fn code_attr(&self) -> &str {
        &self.code_list
    }

    pub fn docs_attr(&self) -> &str {
        &self.docs_list
    }

    /// The `note-words` value as `install` writes it: as the block writes it, or the default.
    pub fn note_words_attr(&self) -> String {
        match self.note_words_attr.is_empty() {
            true => format!("error:{DEFAULT_NOTE_WORDS}"),
            false => self.note_words_attr.clone(),
        }
    }

    /// The `tests` value as `install` writes it: the list, or `conventions`.
    pub fn tests_attr(&self) -> String {
        match self.tests.list {
            Some(_) => self.tests_list.clone(),
            None => TESTS_CONVENTIONS.to_string(),
        }
    }
}

/// The `tests` value that names each language's convention, as an omitted list does.
const TESTS_CONVENTIONS: &str = "conventions";

/// The test paths a block's `tests` list declares, each language's convention when it omits it.
fn tests(value: Option<&str>) -> Result<TestPaths, String> {
    // § kwxna1ebv.b@n2dzy
    let Some(value) = value.filter(|v| v.trim() != TESTS_CONVENTIONS) else {
        return Ok(TestPaths::conventions());
    };
    let list = Patterns::parse("tests", value).map_err(|e| format!("AGENTS.md: {e}"))?;
    if list.is_empty() {
        return Err("AGENTS.md: the `tests` list is empty. Name the test code, such as `tests=\"spec/**\"`, or write `tests=\"conventions\"` for the convention of each language.".to_string());
    }
    Ok(TestPaths { list: Some(list) })
}

/// What a block's `test-markers` does with a marker in test code, `error` when it omits it.
fn test_markers(value: Option<&str>) -> Result<TestMarkers, String> {
    // § xs2e8kj86.k@0t3sg
    match value {
        None | Some("error") => Ok(TestMarkers::Error),
        Some("warn") => Ok(TestMarkers::Warn),
        Some("allow") => Ok(TestMarkers::Allow),
        Some(other) => Err(format!(
            "AGENTS.md: `test-markers=\"{other}\"` is neither `error`, `warn` nor `allow`. Write `test-markers=\"allow\"` where a test carries a law the tree decides nowhere else, `test-markers=\"warn\"` to warn on a marker in test code, or `test-markers=\"error\"` to fail it."
        )),
    }
}

/// The `note-words` limit a block writes, or the default when it omits it.
fn note_words(value: Option<&str>) -> Result<NoteWords, String> {
    // § ht00zbbhg.c@ecc33
    let Some(value) = value else {
        return Ok(NoteWords {
            limit: DEFAULT_NOTE_WORDS,
            warn: false,
        });
    };
    // § end ht00zbbhg.c
    // § ht00zbbhg.b@4bhpf
    let written = value.trim();
    let (warn, count) = match written.split_once(':') {
        Some(("error", count)) => (false, Some(count)),
        Some(("warn", count)) => (true, Some(count)),
        _ => (false, None),
    };
    let limit = count
        .filter(|count| count.bytes().all(|b| b.is_ascii_digit()))
        .and_then(|count| count.parse::<usize>().ok());
    match limit {
        Some(limit) if limit > 0 => Ok(NoteWords { limit, warn }),
        _ => Err(format!(
            "AGENTS.md: `note-words=\"{value}\"` is not a positive integer after `error:` or `warn:`. Write `note-words=\"error:{DEFAULT_NOTE_WORDS}\"` to fail a note past {DEFAULT_NOTE_WORDS} words, or `note-words=\"warn:{DEFAULT_NOTE_WORDS}\"` to warn on it."
        )),
    }
}

fn unknown_attrs(attrs: &[String]) -> String {
    let known =
        "The block reads `notes`, `default-branch`, `code`, `docs`, `tests`, `test-markers` and `note-words`";
    let names: Vec<String> = attrs.iter().map(|attr| format!("`{attr}`")).collect();
    match names.as_slice() {
        [one] => format!("AGENTS.md: {one} is not an attribute of the block. {known}."),
        [rest @ .., last] => format!(
            "AGENTS.md: {} and {last} are not attributes of the block. {known}.",
            rest.join(", ")
        ),
        [] => unreachable!("an unknown attribute is named"),
    }
}

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

    #[test]
    fn omitted_attrs_use_defaults() {
        let policy = ProjectPolicy::from_agents(Some("<silcrow>\n</silcrow>\n")).unwrap();
        assert!(policy.code.matches(Path::new("src/a.rs")));
        assert!(policy.code.matches(Path::new("a.py")));
        assert!(policy.docs.is_empty());
        assert_eq!((policy.code_attr(), policy.docs_attr()), ("**/*", ""));
    }

    #[test]
    fn code_and_docs_are_lists_of_patterns() {
        let policy = ProjectPolicy::from_agents(Some(
            "<silcrow code=\"src/** !src/gen/**\" docs=\"website/docs/**/*.html  README.md\">\n</silcrow>\n",
        ))
        .unwrap();
        assert!(policy.code.matches(Path::new("src/a.rs")));
        assert!(!policy.code.matches(Path::new("src/gen/a.rs")));
        assert!(!policy.code.matches(Path::new("lib/a.rs")));
        assert!(policy.docs.matches(Path::new("website/docs/a/b.html")));
        assert!(policy.docs.matches(Path::new("README.md")));
        assert!(!policy.docs.matches(Path::new("docs/arch.md")));
        assert_eq!(policy.docs_attr(), "website/docs/**/*.html README.md");
    }

    #[test]
    fn an_empty_code_list_or_an_invalid_glob_is_a_defect() {
        let err =
            ProjectPolicy::from_agents(Some("<silcrow code=\"\">\n</silcrow>\n")).unwrap_err();
        assert!(err.contains("`code` list is empty"), "{err}");
        let err =
            ProjectPolicy::from_agents(Some("<silcrow docs=\"web/[\">\n</silcrow>\n")).unwrap_err();
        assert!(err.contains("is not a glob"), "{err}");
        let err = ProjectPolicy::from_agents(Some("<silcrow code=\"!src/**\">\n</silcrow>\n"))
            .unwrap_err();
        assert!(err.contains("includes no path"), "{err}");
    }

    #[test]
    fn note_words_is_a_positive_integer_after_a_severity() {
        let policy = ProjectPolicy::from_agents(Some("<silcrow>\n</silcrow>\n")).unwrap();
        let fail = |limit| NoteWords { limit, warn: false };
        assert_eq!(policy.note_words, fail(DEFAULT_NOTE_WORDS));
        for (value, words) in [
            ("error:1", fail(1)),
            ("error:4000", fail(4000)),
            (" error:120 ", fail(120)),
            ("error:3000", fail(3000)),
            (
                "warn:3000",
                NoteWords {
                    limit: 3000,
                    warn: true,
                },
            ),
        ] {
            let policy = ProjectPolicy::from_agents(Some(&format!(
                "<silcrow note-words=\"{value}\">\n</silcrow>\n"
            )))
            .unwrap();
            assert_eq!(policy.note_words, words, "{value}");
        }
        for value in [
            "1",
            "3000",
            " 120 ",
            "0",
            "-3",
            "+3",
            "3.5",
            "abc",
            "",
            "3000 words",
            "warn:",
            "warn:0",
            "info:3000",
            "warn:+3",
            "Warn:3000",
            "warn: 3000",
            "error:warn:3000",
        ] {
            let err = ProjectPolicy::from_agents(Some(&format!(
                "<silcrow note-words=\"{value}\">\n</silcrow>\n"
            )))
            .unwrap_err();
            assert!(
                err.contains("is not a positive integer after `error:` or `warn:`")
                    && err.contains("`note-words=\"error:3000\"`")
                    && err.contains("`note-words=\"warn:3000\"`"),
                "{value}: {err}"
            );
        }
    }

    #[test]
    fn test_code_is_each_language_convention_unless_the_tests_list_names_it() {
        let conventions = TestPaths::conventions();
        for (path, test) in [
            ("tests/it.rs", true),
            ("crates/a/tests/it.rs", true),
            ("src/lib.rs", false),
            ("pkg/pay_test.go", true),
            ("pkg/pay.go", false),
            ("app/test_pay.py", true),
            ("app/pay_test.py", true),
            ("app/testing.py", false),
            ("web/pay.test.ts", true),
            ("web/pay.spec.jsx", true),
            ("web/__tests__/pay.js", true),
            ("web/test.ts", false),
            ("web/pay.ts", false),
            ("svc/src/test/java/PayTest.java", true),
            ("svc/src/test/kotlin/PayTest.kt", true),
            ("svc/src/main/java/Pay.java", false),
        ] {
            assert_eq!(conventions.holds(Path::new(path)), test, "{path}");
        }
        let policy = ProjectPolicy::from_agents(Some(
            "<silcrow tests=\"spec/** !spec/fixtures/**\">\n</silcrow>\n",
        ))
        .unwrap();
        assert!(policy.tests.holds(Path::new("spec/pay.rb")));
        assert!(!policy.tests.holds(Path::new("spec/fixtures/a.rb")));
        assert!(!policy.tests.holds(Path::new("tests/it.rs")));
        assert_eq!(policy.tests_attr(), "spec/** !spec/fixtures/**");
        assert_eq!(ProjectPolicy::defaults().tests_attr(), "conventions");
        let written =
            ProjectPolicy::from_agents(Some("<silcrow tests=\"conventions\">\n</silcrow>\n"))
                .unwrap();
        assert!(written.tests.holds(Path::new("tests/it.rs")));
        assert!(!written.tests.holds(Path::new("conventions")));
        assert_eq!(written.tests_attr(), "conventions");
        let err =
            ProjectPolicy::from_agents(Some("<silcrow tests=\"\">\n</silcrow>\n")).unwrap_err();
        assert!(err.contains("the `tests` list is empty"), "{err}");
    }

    #[test]
    fn test_markers_is_error_warn_or_allow_and_error_when_omitted() {
        let read = |attrs: &str| {
            ProjectPolicy::from_agents(Some(&format!("<silcrow{attrs}>\n</silcrow>\n")))
        };
        for (attrs, verdict) in [
            ("", TestMarkers::Error),
            (" test-markers=\"error\"", TestMarkers::Error),
            (" test-markers=\"warn\"", TestMarkers::Warn),
            (" test-markers=\"allow\"", TestMarkers::Allow),
        ] {
            assert_eq!(read(attrs).unwrap().test_markers, verdict, "{attrs}");
        }
        for value in ["", "yes", "true", "false", "Warn", " warn"] {
            let err = read(&format!(" test-markers=\"{value}\"")).unwrap_err();
            assert!(
                err.contains("is neither `error`, `warn` nor `allow`"),
                "{value}: {err}"
            );
        }
    }

    #[test]
    fn an_unknown_attribute_fails_naming_the_known_ones() {
        let err =
            ProjectPolicy::from_agents(Some("<silcrow color=\"red\">\n</silcrow>\n")).unwrap_err();
        assert!(err.contains("`color` is not an attribute"), "{err}");
    }

    #[test]
    fn an_invalid_decisions_glob_is_a_defect() {
        let err = ProjectPolicy::from_agents(Some("<silcrow notes=\"docs/[\">\n</silcrow>\n"))
            .unwrap_err();
        assert!(err.contains("is not a glob"), "{err}");
    }
}