koala-core 1.0.4

Shared types, invariant evaluator, and primitives for the koala framework.
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
//! User-defined invariants from `.koala/invariants/*.toml`.
//!
//! Each TOML file may declare any number of `[[rule]]` blocks. A rule
//! has an `id`, `category`, `intent`, optional `adr`, and a `match`
//! table that drives the (small set of) supported predicates:
//!
//! ```toml
//! [[rule]]
//! id       = "biz.no-todo-in-public-api"
//! category = "docs"
//! intent   = "Public API doc-comments must not contain TODO/FIXME."
//! adr      = "ADR-0019"
//! match    = { kind = "forbid-substring", glob = "crates/**/*.rs", needle = "/// TODO" }
//! ```
//!
//! Two `kind`s are supported in v1.0:
//!   - `forbid-substring` — fail if any file matching `glob` contains
//!     `needle`.
//!   - `require-substring` — fail if no file matching `glob` contains
//!     `needle`.
//!
//! Anything richer (property-based, perf bench, regex) lives in
//! native invariants — TOML stays declarative on purpose.

use crate::invariant::{Category, Context, Invariant, Outcome};
use serde::Deserialize;
use std::fs;
use std::path::{Path, PathBuf};

const USER_DIR: &str = ".koala/invariants";

#[derive(Debug, Deserialize)]
struct File {
    #[serde(default)]
    rule: Vec<UserRule>,
}

#[derive(Debug, Deserialize, Clone)]
struct UserRule {
    id: String,
    category: String,
    intent: String,
    #[serde(default)]
    adr: Option<String>,
    #[serde(rename = "match")]
    match_: MatchSpec,
}

#[derive(Debug, Deserialize, Clone)]
#[serde(tag = "kind")]
enum MatchSpec {
    #[serde(rename = "forbid-substring")]
    ForbidSubstring { glob: String, needle: String },
    #[serde(rename = "require-substring")]
    RequireSubstring { glob: String, needle: String },
}

#[derive(Debug)]
pub enum LoadError {
    Io { path: PathBuf, err: std::io::Error },
    Parse { path: PathBuf, err: toml::de::Error },
    BadCategory { id: String, value: String },
}

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io { path, err } => write!(f, "io ({}): {err}", path.display()),
            Self::Parse { path, err } => write!(f, "parse ({}): {err}", path.display()),
            Self::BadCategory { id, value } => write!(
                f,
                "rule `{id}`: unknown category `{value}` (expected arch / deps / docs / \
                 governance / health / security)"
            ),
        }
    }
}

impl std::error::Error for LoadError {}

#[derive(Debug)]
pub struct UserDefinedInvariant {
    id: String,
    category: Category,
    intent: String,
    adr: Option<String>,
    spec: MatchSpec,
}

impl UserDefinedInvariant {
    pub fn category_label(&self) -> &str {
        self.category.as_str()
    }
}

impl Invariant for UserDefinedInvariant {
    fn id(&self) -> &'static str {
        // Trait wants &'static str; leak the id once. Fine for
        // long-running CLI runs.
        Box::leak(self.id.clone().into_boxed_str())
    }

    fn category(&self) -> Category {
        self.category
    }

    fn intent(&self) -> &'static str {
        Box::leak(self.intent.clone().into_boxed_str())
    }

    fn adr(&self) -> Option<&'static str> {
        self.adr.clone().map(|s| &*Box::leak(s.into_boxed_str()))
    }

    fn evaluate(&self, ctx: &Context) -> Outcome {
        match &self.spec {
            MatchSpec::ForbidSubstring { glob, needle } => evaluate_forbid(ctx, glob, needle),
            MatchSpec::RequireSubstring { glob, needle } => evaluate_require(ctx, glob, needle),
        }
    }
}

fn evaluate_forbid(ctx: &Context, glob: &str, needle: &str) -> Outcome {
    let mut hits = Vec::new();
    for path in walk_glob(ctx.root(), glob) {
        let Ok(text) = fs::read_to_string(&path) else {
            continue;
        };
        if text.contains(needle) {
            hits.push(rel_display(&path, ctx.root()));
        }
    }
    if hits.is_empty() {
        Outcome::pass()
    } else {
        Outcome::fail_repro(
            format!(
                "{n} file(s) contain forbidden substring `{needle}`:\n  {body}",
                n = hits.len(),
                body = hits.join("\n  ")
            ),
            format!("rg -F '{needle}' {glob}"),
        )
    }
}

fn evaluate_require(ctx: &Context, glob: &str, needle: &str) -> Outcome {
    let any_present = walk_glob(ctx.root(), glob).into_iter().any(|p| {
        fs::read_to_string(&p)
            .map(|t| t.contains(needle))
            .unwrap_or(false)
    });
    if any_present {
        Outcome::pass()
    } else {
        Outcome::fail_repro(
            format!("no file matching `{glob}` contains required substring `{needle}`"),
            format!("rg -F '{needle}' {glob}"),
        )
    }
}

fn rel_display(p: &Path, root: &Path) -> String {
    p.strip_prefix(root)
        .unwrap_or(p)
        .display()
        .to_string()
        .replace('\\', "/")
}

/// Minimal glob: only supports `**` (anywhere) and `*` (one path
/// segment, no `/`). Sufficient for the v1.0 declarative ruleset.
fn walk_glob(root: &Path, glob: &str) -> Vec<PathBuf> {
    let mut out = Vec::new();
    for entry in walkdir::WalkDir::new(root).into_iter().flatten() {
        if !entry.file_type().is_file() {
            continue;
        }
        let p = entry.path();
        let Some(rel) = p.strip_prefix(root).ok() else {
            continue;
        };
        let rel = rel.to_string_lossy().replace('\\', "/");
        if glob_match(glob, &rel) {
            out.push(p.to_path_buf());
        }
    }
    out
}

fn glob_match(pattern: &str, text: &str) -> bool {
    let segs: Vec<&str> = pattern.split('/').collect();
    let parts: Vec<&str> = text.split('/').collect();
    glob_segments(&segs, &parts)
}

fn glob_segments(pat: &[&str], text: &[&str]) -> bool {
    if pat.is_empty() {
        return text.is_empty();
    }
    let head = pat[0];
    let rest_pat = &pat[1..];
    if head == "**" {
        // Match zero or more text segments.
        if glob_segments(rest_pat, text) {
            return true;
        }
        for i in 1..=text.len() {
            if glob_segments(rest_pat, &text[i..]) {
                return true;
            }
        }
        return false;
    }
    if text.is_empty() {
        return false;
    }
    if !segment_match(head, text[0]) {
        return false;
    }
    glob_segments(rest_pat, &text[1..])
}

fn segment_match(pat: &str, text: &str) -> bool {
    // Within one path segment: `*` matches any run of non-`/` chars.
    let pb = pat.as_bytes();
    let tb = text.as_bytes();
    let mut pi = 0usize;
    let mut ti = 0usize;
    let mut star_pi: Option<usize> = None;
    let mut star_ti = 0usize;
    while ti < tb.len() {
        if pi < pb.len() && pb[pi] == b'*' {
            star_pi = Some(pi + 1);
            star_ti = ti;
            pi += 1;
            continue;
        }
        if pi < pb.len() && pb[pi] == tb[ti] {
            pi += 1;
            ti += 1;
            continue;
        }
        if let Some(spi) = star_pi {
            star_ti += 1;
            ti = star_ti;
            pi = spi;
            continue;
        }
        return false;
    }
    while pi < pb.len() && pb[pi] == b'*' {
        pi += 1;
    }
    pi == pb.len()
}

pub fn load_all(repo_root: &Path) -> Result<Vec<UserDefinedInvariant>, LoadError> {
    let dir = repo_root.join(USER_DIR);
    let Ok(read) = fs::read_dir(&dir) else {
        return Ok(Vec::new());
    };
    let mut out = Vec::new();
    for entry in read.flatten() {
        let path = entry.path();
        if path.extension().and_then(|s| s.to_str()) != Some("toml") {
            continue;
        }
        let text = fs::read_to_string(&path).map_err(|err| LoadError::Io {
            path: path.clone(),
            err,
        })?;
        let file: File = toml::from_str(&text).map_err(|err| LoadError::Parse {
            path: path.clone(),
            err,
        })?;
        for r in file.rule {
            let category = parse_category(&r.id, &r.category)?;
            out.push(UserDefinedInvariant {
                id: r.id,
                category,
                intent: r.intent,
                adr: r.adr,
                spec: r.match_,
            });
        }
    }
    out.sort_by(|a, b| a.id.cmp(&b.id));
    Ok(out)
}

fn parse_category(id: &str, value: &str) -> Result<Category, LoadError> {
    Ok(match value {
        "arch" => Category::Arch,
        "deps" => Category::Deps,
        "docs" => Category::Docs,
        "governance" => Category::Governance,
        "health" => Category::Health,
        "security" => Category::Security,
        other => {
            return Err(LoadError::BadCategory {
                id: id.to_string(),
                value: other.to_string(),
            })
        }
    })
}

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

    fn write(root: &Path, rel: &str, body: &str) {
        let p = root.join(rel);
        fs::create_dir_all(p.parent().unwrap()).unwrap();
        fs::write(p, body).unwrap();
    }

    #[test]
    fn glob_matches_simple_patterns() {
        assert!(glob_match("crates/**/*.rs", "crates/koala-core/src/lib.rs"));
        assert!(glob_match(
            "crates/*/Cargo.toml",
            "crates/koala-core/Cargo.toml"
        ));
        assert!(!glob_match("crates/*/Cargo.toml", "crates/a/b/Cargo.toml"));
        assert!(glob_match("**/README.md", "README.md"));
        assert!(glob_match("**/README.md", "wiki/README.md"));
    }

    #[test]
    fn user_defined_toml_loaded() {
        let tmp = TempDir::new().unwrap();
        write(
            tmp.path(),
            ".koala/invariants/biz.toml",
            r#"
[[rule]]
id       = "biz.no-fixme-in-src"
category = "health"
intent   = "Code under crates/ must not ship FIXME markers."
adr      = "ADR-0019"

[rule.match]
kind   = "forbid-substring"
glob   = "crates/**/*.rs"
needle = "FIXME"
"#,
        );
        let rules = load_all(tmp.path()).unwrap();
        assert_eq!(rules.len(), 1);
        let r = &rules[0];
        assert_eq!(r.id(), "biz.no-fixme-in-src");
        assert_eq!(r.category().as_str(), "health");
        assert_eq!(r.adr(), Some("ADR-0019"));

        // No matching files yet → pass.
        let ctx = Context::new(tmp.path().to_path_buf());
        assert!(matches!(r.evaluate(&ctx), Outcome::Pass { .. }));

        // Add a file with FIXME → fail.
        write(
            tmp.path(),
            "crates/x/src/lib.rs",
            "// FIXME: rewrite\npub fn k() {}\n",
        );
        let out = r.evaluate(&ctx);
        assert!(matches!(out, Outcome::Fail { .. }), "{out:?}");
    }

    #[test]
    fn require_substring_rule() {
        let tmp = TempDir::new().unwrap();
        write(
            tmp.path(),
            ".koala/invariants/docs.toml",
            r#"
[[rule]]
id       = "biz.readme-mentions-license"
category = "docs"
intent   = "README must mention the license."

[rule.match]
kind   = "require-substring"
glob   = "README.md"
needle = "Apache-2.0"
"#,
        );
        let rules = load_all(tmp.path()).unwrap();
        let r = &rules[0];

        // Missing → fail.
        let ctx = Context::new(tmp.path().to_path_buf());
        assert!(matches!(r.evaluate(&ctx), Outcome::Fail { .. }));

        // Present → pass.
        write(
            tmp.path(),
            "README.md",
            "# Project\n\nLicense: Apache-2.0\n",
        );
        assert!(matches!(r.evaluate(&ctx), Outcome::Pass { .. }));
    }

    #[test]
    fn missing_user_dir_returns_empty() {
        let tmp = TempDir::new().unwrap();
        let rules = load_all(tmp.path()).unwrap();
        assert!(rules.is_empty());
    }

    #[test]
    fn bad_category_is_rejected() {
        let tmp = TempDir::new().unwrap();
        write(
            tmp.path(),
            ".koala/invariants/bad.toml",
            r#"
[[rule]]
id       = "biz.x"
category = "nonsense"
intent   = "x"

[rule.match]
kind   = "forbid-substring"
glob   = "**/*"
needle = "x"
"#,
        );
        let err = load_all(tmp.path()).unwrap_err();
        assert!(matches!(err, LoadError::BadCategory { .. }));
    }
}