kova-docs-lint 0.8.0

Frontmatter linter, link checker, and write-boundary validator for docs/agent
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
//! kova-docs-lint — lints the machine-readable contract docs under
//! `docs/agent/` and enforces the write boundary those docs declare.
//!
//! Subcommands:
//! - `lint`: frontmatter schema, relative-link resolution, and Tier 1 →
//!   Tier 2 cross-reference checks (CI gate for `docs/agent/`).
//! - `check-writes`: Codebase Write Limits validator — checks write entries
//!   (file paths or `state:` surfaces) against the declared boundary.
//! - `check-plan`: Plan Modification Gateway — extracts a plan's `writes`
//!   fence and rejects the plan if any declared write is out of bounds.

mod boundary;
mod frontmatter;

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, Subcommand};
use frontmatter::MetaValue;

#[derive(Parser)]
#[command(
    name = "kova-docs-lint",
    version,
    about = "Lints docs/agent contracts and enforces the declared write boundary"
)]
struct Cli {
    /// Repository root (where crates/ lives)
    #[arg(long, default_value = ".")]
    repo_root: PathBuf,

    /// Docs directory (contains agent/)
    #[arg(long, default_value = "docs")]
    docs_dir: PathBuf,

    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Frontmatter + link lint over docs/agent (excluding templates/)
    Lint,
    /// Validate write entries against the declared boundary
    CheckWrites {
        /// Entries: file paths, `file:`-prefixed paths, or `state:` names
        #[arg(value_name = "WRITE")]
        entries: Vec<String>,

        /// Read entries from stdin, one per line
        #[arg(long)]
        stdin: bool,
    },
    /// Validate a plan's declared writes fence (Plan Modification Gateway)
    CheckPlan {
        /// Plan markdown file
        plan: PathBuf,
    },
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    match run(cli) {
        Ok(code) => code,
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::from(2)
        }
    }
}

fn run(cli: Cli) -> Result<ExitCode, String> {
    match cli.cmd {
        Cmd::Lint => lint(&cli.repo_root, &cli.docs_dir),
        Cmd::CheckWrites { entries, stdin } => check_writes(&cli.docs_dir, entries, stdin),
        Cmd::CheckPlan { plan } => check_plan(&cli.docs_dir, &plan),
    }
}

// ---------------------------------------------------------------------------
// lint
// ---------------------------------------------------------------------------

fn lint(repo_root: &Path, docs_dir: &Path) -> Result<ExitCode, String> {
    let agent = docs_dir.join("agent");
    if !agent.is_dir() {
        return Err(format!("no agent docs at {:?}", agent.display()));
    }
    let mut issues: Vec<String> = Vec::new();
    let mut checked = 0usize;

    for path in walk_md(&agent) {
        checked += 1;
        let rel = path.strip_prefix(repo_root).unwrap_or(&path);
        let text = std::fs::read_to_string(&path)
            .map_err(|e| format!("cannot read {:?}: {e}", rel.display()))?;
        let (meta, body) = match frontmatter::split_frontmatter(&text) {
            Ok(v) => v,
            Err(e) => {
                issues.push(format!("{:?}: frontmatter: {e}", rel.display()));
                continue;
            }
        };

        // Doc kind + per-kind schema checks.
        let tier = meta
            .get("doc_tier")
            .and_then(|v| v.as_scalar())
            .map(str::to_string);
        let is_code_flow = meta.get("doc_kind").and_then(|v| v.as_scalar()) == Some("code_flow");

        if let Some(t) = &tier {
            if t == "1" {
                lint_tier1(repo_root, rel, &meta, &body, &mut issues);
            } else if t == "2" {
                lint_tier2(repo_root, rel, &meta, &mut issues);
            } else {
                issues.push(format!(
                    "{:?}: doc_tier must be 1 or 2, got {t:?}",
                    rel.display()
                ));
            }
        } else if !is_code_flow {
            issues.push(format!(
                "{:?}: unknown doc kind: expected doc_tier 1|2 or doc_kind code_flow",
                rel.display()
            ));
        } else {
            lint_code_flow(repo_root, rel, &meta, &mut issues);
        }

        // Relative .md links must resolve.
        for (line_no, target) in md_links(&body) {
            let t = target.split('#').next().unwrap_or("").trim();
            if t.is_empty()
                || t.starts_with("http://")
                || t.starts_with("https://")
                || t.starts_with("mailto:")
                || t.starts_with('/')
                || !t.ends_with(".md")
            {
                continue;
            }
            let resolved = match path.parent() {
                Some(parent) => parent.join(t),
                None => PathBuf::from(t),
            };
            if !resolved.is_file() {
                issues.push(format!(
                    "{:?}:{}: link to {} does not resolve (resolved: {:?})",
                    rel.display(),
                    line_no,
                    t,
                    resolved.display()
                ));
            }
        }
    }

    if issues.is_empty() {
        println!("kova-docs-lint: {checked} docs checked, no issues");
        Ok(ExitCode::SUCCESS)
    } else {
        for issue in &issues {
            eprintln!("{issue}");
        }
        eprintln!(
            "kova-docs-lint: {checked} docs checked, {} issue(s)",
            issues.len()
        );
        Ok(ExitCode::from(1))
    }
}

fn lint_tier1(
    repo_root: &Path,
    rel: &Path,
    meta: &std::collections::BTreeMap<String, MetaValue>,
    body: &str,
    issues: &mut Vec<String>,
) {
    // module: crates/<module> must exist.
    let module = match meta.get("module").and_then(|v| v.as_scalar()) {
        Some(m) if !m.is_empty() => Some(m),
        _ => {
            issues.push(format!(
                "{:?}: tier1 requires a non-empty `module`",
                rel.display()
            ));
            None
        }
    };

    // structs: non-empty list; every entry must resolve to a type item.
    let structs = match meta.get("structs") {
        Some(MetaValue::List(items)) => items.clone(),
        Some(_) => {
            issues.push(format!("{:?}: `structs` must be a list", rel.display()));
            Vec::new()
        }
        None => {
            issues.push(format!(
                "{:?}: tier1 requires a `structs` list",
                rel.display()
            ));
            Vec::new()
        }
    };
    if structs.is_empty() {
        issues.push(format!("{:?}: `structs` must be non-empty", rel.display()));
    }
    if let Some(m) = module {
        if !repo_root.join("crates").join(m).is_dir() {
            issues.push(format!(
                "{:?}: module `{m}` does not resolve (no crates/{m}/)",
                rel.display()
            ));
        } else {
            for s in &structs {
                if !type_declared(repo_root, m, s) {
                    issues.push(format!(
                        "{:?}: struct `{s}` not found in crates/{m}/src",
                        rel.display()
                    ));
                }
            }
        }
    }

    // reads / writes: must be present lists.
    for key in ["reads", "writes"] {
        match meta.get(key) {
            Some(MetaValue::List(_)) => {}
            Some(_) => issues.push(format!("{:?}: `{key}` must be a list", rel.display())),
            None => issues.push(format!(
                "{:?}: tier1 requires a `{key}` list",
                rel.display()
            )),
        }
    }

    // Tier 1 with non-empty writes must cross-link at least one Tier 2 doc.
    let writes_nonempty = meta
        .get("writes")
        .and_then(|v| v.as_list())
        .is_some_and(|w| !w.is_empty());
    if writes_nonempty {
        let links_tier2 = md_links(body).iter().any(|(_, target)| {
            let t = target.split('#').next().unwrap_or("").trim();
            let resolved = match rel.parent() {
                Some(parent) => parent.join(t),
                None => PathBuf::from(t),
            };
            let canon = std::fs::canonicalize(&resolved).ok();
            canon.is_some_and(|c| {
                c.to_string_lossy().contains("agent")
                    && c.to_string_lossy()
                        .contains(&format!("{sep}tier2", sep = std::path::MAIN_SEPARATOR))
            })
        });
        if !links_tier2 {
            issues.push(format!(
                "{:?}: non-empty `writes` requires a cross-link to a docs/agent/tier2/ doc",
                rel.display()
            ));
        }
    }
}

fn lint_tier2(
    repo_root: &Path,
    rel: &Path,
    meta: &std::collections::BTreeMap<String, MetaValue>,
    issues: &mut Vec<String>,
) {
    let target = match meta.get("target_file").and_then(|v| v.as_scalar()) {
        Some(f) if !f.is_empty() => f,
        _ => {
            issues.push(format!(
                "{:?}: tier2 requires a non-empty `target_file`",
                rel.display()
            ));
            return;
        }
    };
    if !repo_root.join(target).is_file() {
        issues.push(format!(
            "{:?}: target_file `{target}` does not exist",
            rel.display()
        ));
    }
    for key in ["procs", "drivers", "env"] {
        match meta.get(key) {
            Some(MetaValue::List(_)) => {}
            Some(_) => issues.push(format!("{:?}: `{key}` must be a list", rel.display())),
            None => issues.push(format!(
                "{:?}: tier2 requires a `{key}` list",
                rel.display()
            )),
        }
    }
}

fn lint_code_flow(
    repo_root: &Path,
    rel: &Path,
    meta: &std::collections::BTreeMap<String, MetaValue>,
    issues: &mut Vec<String>,
) {
    let module = match meta.get("module").and_then(|v| v.as_scalar()) {
        Some(m) if !m.is_empty() => m,
        _ => {
            issues.push(format!(
                "{:?}: code_flow requires a non-empty `module`",
                rel.display()
            ));
            return;
        }
    };
    if !repo_root.join("crates").join(module).is_dir() {
        issues.push(format!(
            "{:?}: module `{module}` does not resolve (no crates/{module}/)",
            rel.display()
        ));
    }
    match meta.get("chain") {
        Some(MetaValue::List(items)) if !items.is_empty() => {}
        Some(MetaValue::List(_)) => {
            issues.push(format!("{:?}: `chain` must be non-empty", rel.display()))
        }
        _ => issues.push(format!(
            "{:?}: code_flow requires a `chain` list",
            rel.display()
        )),
    }
}

// ---------------------------------------------------------------------------
// check-writes
// ---------------------------------------------------------------------------

fn check_writes(
    docs_dir: &Path,
    mut entries: Vec<String>,
    stdin: bool,
) -> Result<ExitCode, String> {
    if stdin {
        use std::io::Read;
        let mut buf = String::new();
        std::io::stdin()
            .read_to_string(&mut buf)
            .map_err(|e| format!("stdin: {e}"))?;
        for line in buf.lines() {
            let t = line.trim();
            if t.is_empty() || t.starts_with('#') {
                continue;
            }
            entries.push(t.to_string());
        }
    }
    if entries.is_empty() {
        return Err("no write entries given (pass entries or use --stdin)".into());
    }
    let b = boundary::build(docs_dir)?;
    let mut bad = 0usize;
    for e in &entries {
        let entry = boundary::Entry::parse(e);
        if entry.allowed(&b) {
            println!("ok        {e}");
        } else {
            bad += 1;
            println!("VIOLATION {e} — not in the declared boundary");
        }
    }
    if bad == 0 {
        println!(
            "kova-docs-lint: {} write(s) checked, all in bounds",
            entries.len()
        );
        Ok(ExitCode::SUCCESS)
    } else {
        eprintln!(
            "kova-docs-lint: {} of {} write(s) out of bounds",
            bad,
            entries.len()
        );
        Ok(ExitCode::from(1))
    }
}

// ---------------------------------------------------------------------------
// check-plan (Plan Modification Gateway)
// ---------------------------------------------------------------------------

fn check_plan(docs_dir: &Path, plan: &Path) -> Result<ExitCode, String> {
    let text = std::fs::read_to_string(plan)
        .map_err(|e| format!("cannot read {:?}: {e}", plan.display()))?;
    let writes = match frontmatter::plan_writes(&text).map_err(|e| e.to_string())? {
        None => {
            println!(
                "{:?}: no `writes` fence — nothing to check \
                 (research surface defaults to research/plans/)",
                plan.display()
            );
            return Ok(ExitCode::SUCCESS);
        }
        Some(v) => v,
    };
    let (line_no, items) = writes;
    let b = boundary::build(docs_dir)?;
    println!(
        "{:?}: {} declared write(s) from yaml fence at line {line_no}",
        plan.display(),
        items.len()
    );
    let mut bad = 0usize;
    for e in &items {
        let entry = boundary::Entry::parse(e);
        if entry.allowed(&b) {
            println!("ok        {e}");
        } else {
            bad += 1;
            println!("VIOLATION {e} — not in the declared boundary");
        }
    }
    if bad == 0 {
        Ok(ExitCode::SUCCESS)
    } else {
        eprintln!(
            "{:?}: REJECTED — {} write(s) outside the declared boundary",
            plan.display(),
            bad
        );
        Ok(ExitCode::from(1))
    }
}

// ---------------------------------------------------------------------------
// helpers
// ---------------------------------------------------------------------------

/// All `.md` files under `dir`, recursive, skipping the `templates/`
/// subdirectory (its placeholders are not real docs).
fn walk_md(dir: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(d) = stack.pop() {
        let read_dir = match std::fs::read_dir(&d) {
            Ok(r) => r,
            Err(_) => continue,
        };
        for de in read_dir.flatten() {
            let p = de.path();
            if p.is_dir() {
                if p.file_name().and_then(|n| n.to_str()) == Some("templates") {
                    continue;
                }
                stack.push(p);
            } else if p.extension().and_then(|e| e.to_str()) == Some("md") {
                out.push(p);
            }
        }
    }
    out.sort();
    out
}

fn walk_rs(dir: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(d) = stack.pop() {
        let read_dir = match std::fs::read_dir(&d) {
            Ok(r) => r,
            Err(_) => continue,
        };
        for de in read_dir.flatten() {
            let p = de.path();
            if p.is_dir() {
                stack.push(p);
            } else if p.extension().and_then(|e| e.to_str()) == Some("rs") {
                out.push(p);
            }
        }
    }
    out.sort();
    out
}

/// True when any `.rs` file under `crates/<module>/src` declares `name` as a
/// struct, enum, trait, or type alias (including `pub`/`pub(...)` visibility).
fn type_declared(repo_root: &Path, module: &str, name: &str) -> bool {
    let src = repo_root.join("crates").join(module).join("src");
    for file in walk_rs(&src) {
        let Ok(text) = std::fs::read_to_string(&file) else {
            continue;
        };
        for line in text.lines() {
            let t = line.trim();
            if t.starts_with("//") {
                continue;
            }
            let mut rest = t;
            // Strip visibility prefixes: `pub`, `pub(crate)`, repeated.
            loop {
                if let Some(r) = rest.strip_prefix("pub") {
                    rest = r.trim_start();
                    if let Some(r2) = rest.strip_prefix('(') {
                        if let Some(close) = r2.find(')') {
                            rest = r2[close + 1..].trim_start();
                        }
                    }
                    continue;
                }
                break;
            }
            for kw in ["struct ", "enum ", "trait ", "type "] {
                if let Some(after) = rest.strip_prefix(kw) {
                    let after = after.trim_start();
                    let id: String = after
                        .chars()
                        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
                        .collect();
                    if id == name {
                        return true;
                    }
                }
            }
        }
    }
    false
}

/// Markdown links `[text](target)` with their 1-based line numbers.
fn md_links(body: &str) -> Vec<(usize, String)> {
    let mut out = Vec::new();
    for (idx, line) in body.lines().enumerate() {
        let mut rest = line;
        while let Some(open) = rest.find('[') {
            let after = &rest[open + 1..];
            let Some(close) = after.find("](") else {
                rest = after;
                continue;
            };
            let target_part = &after[close + 2..];
            let target = target_part.split(')').next().unwrap_or(target_part).trim();
            out.push((idx + 1, target.to_string()));
            rest = target_part;
        }
    }
    out
}

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

    #[test]
    fn md_links_finds_targets_and_skips_images() {
        let body = "see [a](../tier2/engine_ops.md) and [b](https://x.dev) and [c](x.md#frag)\n";
        let links = md_links(body);
        assert_eq!(links.len(), 3);
        assert_eq!(links[0].1, "../tier2/engine_ops.md");
        assert_eq!(links[2].1, "x.md#frag");
    }

    #[test]
    fn type_declared_matches_visibility_forms() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("crates/kova-x/src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            src.join("lib.rs"),
            "pub struct Foo;\npub(crate) enum Bar;\npub trait Baz;\n// struct NotReal;\nstruct Qux;\n",
        )
        .unwrap();
        let root = tmp.path();
        assert!(type_declared(root, "kova-x", "Foo"));
        assert!(type_declared(root, "kova-x", "Bar"));
        assert!(type_declared(root, "kova-x", "Baz"));
        assert!(type_declared(root, "kova-x", "Qux"));
        assert!(!type_declared(root, "kova-x", "NotReal"));
        assert!(!type_declared(root, "kova-x", "Foo2"));
    }

    #[test]
    fn walk_md_skips_templates() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join("agent/tier1")).unwrap();
        std::fs::create_dir_all(tmp.path().join("agent/templates")).unwrap();
        std::fs::write(tmp.path().join("agent/tier1/a.md"), "x").unwrap();
        std::fs::write(tmp.path().join("agent/templates/t.md"), "x").unwrap();
        let files = walk_md(&tmp.path().join("agent"));
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("tier1/a.md"));
    }
}