shallguard 0.1.2

ShallGuard requirement traceability, executable coverage, and review tooling
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
//! Structural linting and deterministic formatting for requirement documents.

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

use anyhow::{Context, Result, bail};
use regex::Regex;

use crate::DocSpec;
use crate::docs::parse_text;
use crate::evidence_mark::EvidenceMark;

const REQUIREMENT_LINE_WIDTH: usize = 88;

/// One requirement-document lint failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormatDiagnostic {
    /// Workspace-relative document containing the failure.
    pub document: String,
    /// One-based source line where the requirement starts.
    pub line: usize,
    /// Human-readable explanation of the malformed structure.
    pub message: String,
}

/// Result of checking or formatting one or more requirement documents.
#[derive(Debug)]
pub struct FormatReport {
    /// Number of documents inspected.
    pub documents: usize,
    /// Number of requirement blocks inspected.
    pub requirements: usize,
    /// Documents whose canonical representation differs from disk.
    pub changed_documents: Vec<PathBuf>,
    /// Structural lint failures. Formatting refuses to write when non-empty.
    pub diagnostics: Vec<FormatDiagnostic>,
}

impl FormatReport {
    /// Returns whether every document is structurally valid and canonically formatted.
    pub fn is_clean(&self) -> bool {
        self.diagnostics.is_empty() && self.changed_documents.is_empty()
    }
}

struct PreparedDocument {
    path: PathBuf,
    formatted: String,
    changed: bool,
    requirements: usize,
    diagnostics: Vec<FormatDiagnostic>,
}

struct FormattedText {
    text: String,
    requirements: usize,
    diagnostics: Vec<FormatDiagnostic>,
}

/// Checks requirement structure and canonical formatting without changing files.
///
/// # Errors
///
/// Returns an error when a document cannot be read or when semantic-equivalence
/// verification of the formatted representation fails.
#[shallguard::enforces("REQ-SPEC-006")]
pub fn check(root: &Path, specs: &[DocSpec]) -> Result<FormatReport> {
    run(root, specs, false)
}

/// Lints and canonically formats requirement blocks in place.
///
/// No document is changed when any selected document has a structural lint
/// failure. Surrounding Markdown outside requirement blocks is retained.
///
/// # Errors
///
/// Returns an error when a document cannot be read or written, or when formatting
/// would change the parsed requirement meaning.
#[shallguard::enforces("REQ-SPEC-005")]
pub fn format(root: &Path, specs: &[DocSpec]) -> Result<FormatReport> {
    run(root, specs, true)
}

fn run(root: &Path, specs: &[DocSpec], write: bool) -> Result<FormatReport> {
    let mut prepared = Vec::with_capacity(specs.len());
    for spec in specs {
        prepared.push(prepare_document(root, spec, write)?);
    }

    let diagnostics = prepared
        .iter()
        .flat_map(|document| document.diagnostics.iter().cloned())
        .collect::<Vec<_>>();
    if write && diagnostics.is_empty() {
        for document in prepared.iter().filter(|document| document.changed) {
            write_atomic(&document.path, document.formatted.as_bytes())?;
        }
    }

    Ok(FormatReport {
        documents: specs.len(),
        requirements: prepared.iter().map(|document| document.requirements).sum(),
        changed_documents: prepared
            .iter()
            .filter(|document| document.changed)
            .map(|document| workspace_relative(root, &document.path))
            .collect(),
        diagnostics,
    })
}

/// Reads and formats one document. The write mode adds the canonical keyword
/// next to an emoji evidence alias. The check mode keeps the marks as they
/// are, so an emoji-only document passes `fmt --check`.
fn prepare_document(root: &Path, spec: &DocSpec, add_keywords: bool) -> Result<PreparedDocument> {
    let path = root.join(&spec.path);
    let original = std::fs::read_to_string(&path)
        .with_context(|| format!("reading requirement document {}", path.display()))?;
    let formatted = format_text(&original, spec, add_keywords);
    if formatted.diagnostics.is_empty() {
        verify_semantic_equivalence(&original, &formatted.text, spec)?;
    }
    Ok(PreparedDocument {
        changed: original != formatted.text,
        path,
        formatted: formatted.text,
        requirements: formatted.requirements,
        diagnostics: formatted.diagnostics,
    })
}

fn format_text(text: &str, spec: &DocSpec, add_keywords: bool) -> FormattedText {
    let candidate_re =
        Regex::new(r"^\s*-\s+\*\*REQ-").expect("BUG: invalid requirement candidate regex");
    let lines = text.lines().collect::<Vec<_>>();
    let mut output = Vec::with_capacity(lines.len());
    let mut diagnostics = Vec::new();
    let mut requirements = 0;
    let mut index = 0;

    while index < lines.len() {
        if !candidate_re.is_match(lines[index]) {
            output.push(lines[index].to_string());
            index += 1;
            continue;
        }

        let start = index;
        index += 1;
        while index < lines.len()
            && !lines[index].is_empty()
            && lines[index].chars().next().is_some_and(char::is_whitespace)
        {
            index += 1;
        }
        let block = &lines[start..index];
        requirements += 1;
        let block_diagnostics = lint_block(block, spec, start + 1);
        if block_diagnostics.is_empty() {
            output.extend(format_block(block, add_keywords));
        } else {
            output.extend(block.iter().map(|line| (*line).to_string()));
            diagnostics.extend(block_diagnostics);
        }
    }

    let mut text = output.join("\n");
    text.push('\n');
    FormattedText {
        text,
        requirements,
        diagnostics,
    }
}

#[shallguard::enforces("REQ-SPEC-001", "REQ-SPEC-002", "REQ-SPEC-004", "REQ-SPEC-007")]
fn lint_block(block: &[&str], spec: &DocSpec, line: usize) -> Vec<FormatDiagnostic> {
    let header_re = Regex::new(r"^- \*\*(REQ-([A-Z]{2,})-\d{3})\*\* — \S")
        .expect("BUG: invalid requirement header regex");
    let normative_re =
        Regex::new(r"\b(?:SHALL(?: NOT)?|MAY)\b").expect("BUG: invalid normative regex");
    let combined = normalized_block(block);
    let mut messages = Vec::new();

    if !header_re.is_match(&combined) {
        messages.push(
            "expected `- **REQ-<AREA>-<NNN>** — <normative statement>` with an uppercase area and three-digit number"
                .to_string(),
        );
    }

    let enforced_count = combined.matches("*Enforced:*").count();
    let verified_count = combined.matches("*Verified:*").count();
    let retired = combined.to_ascii_lowercase().contains("(retired");
    if retired && enforced_count == 0 && verified_count == 0 {
        return diagnostics(spec, line, messages);
    }
    if enforced_count != 1 {
        messages.push(format!(
            "active requirement must contain exactly one `*Enforced:*` segment; found {enforced_count}"
        ));
    }
    if verified_count != 1 {
        messages.push(format!(
            "active requirement must contain exactly one `*Verified:*` segment; found {verified_count}"
        ));
    }
    let Some((statement, after_enforced)) = combined.split_once("*Enforced:*") else {
        return diagnostics(spec, line, messages);
    };
    let Some((enforced, verified)) = after_enforced.split_once("*Verified:*") else {
        return diagnostics(spec, line, messages);
    };
    if !normative_re.is_match(statement) && !enforced.contains("not implemented") {
        messages.push("active requirement statement must use SHALL, SHALL NOT, or MAY".to_string());
    }
    if enforced.trim().trim_end_matches('·').trim().is_empty() {
        messages.push("`*Enforced:*` segment must name enforcement evidence".to_string());
    }
    if !enforced.trim_end().ends_with('·') {
        messages.push("separate `*Enforced:*` and `*Verified:*` with `·`".to_string());
    }
    if verified.trim().is_empty() {
        messages.push("`*Verified:*` segment must name verification evidence".to_string());
    }
    if !EvidenceMark::any_claimed_in(verified) {
        messages.push(format!(
            "`*Verified:*` must contain an evidence mark: {} (the emoji aliases are accepted)",
            EvidenceMark::keyword_list()
        ));
    }
    diagnostics(spec, line, messages)
}

fn diagnostics(spec: &DocSpec, line: usize, messages: Vec<String>) -> Vec<FormatDiagnostic> {
    messages
        .into_iter()
        .map(|message| FormatDiagnostic {
            document: spec.path.clone(),
            line,
            message,
        })
        .collect()
}

fn normalized_block(block: &[&str]) -> String {
    block
        .iter()
        .flat_map(|line| line.split_whitespace())
        .collect::<Vec<_>>()
        .join(" ")
}

fn format_block(block: &[&str], add_keywords: bool) -> Vec<String> {
    let lines = if add_keywords {
        canonicalize_evidence_marks(block)
    } else {
        block.iter().map(|line| (*line).to_string()).collect()
    };
    let mut formatted = Vec::new();
    for (index, line) in lines.iter().enumerate() {
        wrap_existing_line(line.trim(), index == 0, &mut formatted);
    }
    formatted
}

/// Adds the keyword next to every emoji evidence alias after `*Verified:*`.
///
/// Only the write mode of `fmt` calls this. The emoji stays in the document.
/// Text before the verification segment is returned unchanged, so an emoji in
/// a statement is not touched.
#[shallguard::enforces("REQ-SPEC-008")]
fn canonicalize_evidence_marks(block: &[&str]) -> Vec<String> {
    let mut in_verified = false;
    block
        .iter()
        .map(|line| {
            if in_verified {
                return EvidenceMark::canonicalize(line);
            }
            match line.split_once("*Verified:*") {
                Some((head, tail)) => {
                    in_verified = true;
                    format!("{head}*Verified:*{}", EvidenceMark::canonicalize(tail))
                }
                None => (*line).to_string(),
            }
        })
        .collect()
}

fn wrap_existing_line(line: &str, first_line: bool, output: &mut Vec<String>) {
    let indent = if first_line { "" } else { "  " };
    let mut current = indent.to_string();
    for word in line.split_whitespace() {
        let has_content = current.len() > indent.len();
        let separator = usize::from(has_content);
        if has_content
            && current.chars().count() + separator + word.chars().count() > REQUIREMENT_LINE_WIDTH
        {
            output.push(current);
            current = "  ".to_string();
        }
        let current_indent = if current.starts_with("  ") { 2 } else { 0 };
        if current.len() > current_indent {
            current.push(' ');
        }
        current.push_str(word);
    }
    if current.len() > indent.len() {
        output.push(current);
    }
}

fn verify_semantic_equivalence(original: &str, formatted: &str, spec: &DocSpec) -> Result<()> {
    let before = parse_text(original, spec);
    let after = parse_text(formatted, spec);
    if before.requirements.len() != after.requirements.len() {
        bail!(
            "formatting {} would change the parsed requirement count from {} to {}",
            spec.path,
            before.requirements.len(),
            after.requirements.len()
        );
    }
    for (before, after) in before.requirements.iter().zip(&after.requirements) {
        if before.id != after.id
            || before.statement != after.statement
            || before.enforced_text != after.enforced_text
            || before.verified_text != after.verified_text
        {
            bail!(
                "formatting {} would change the parsed meaning of {}",
                spec.path,
                before.id
            );
        }
    }
    Ok(())
}

fn write_atomic(path: &Path, content: &[u8]) -> Result<()> {
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .context("requirement document has no UTF-8 file name")?;
    let temporary = path.with_file_name(format!(".{file_name}.fmt-{}", std::process::id()));
    std::fs::write(&temporary, content)
        .with_context(|| format!("writing formatted document {}", temporary.display()))?;
    std::fs::rename(&temporary, path)
        .with_context(|| format!("publishing formatted document {}", path.display()))
}

fn workspace_relative(root: &Path, path: &Path) -> PathBuf {
    path.strip_prefix(root).unwrap_or(path).to_path_buf()
}

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

    fn spec() -> DocSpec {
        DocSpec::new(
            "crate/docs/USER_STORIES_AND_REQUIREMENTS.md",
            "crate",
            std::collections::BTreeMap::new(),
        )
    }

    #[shallguard::verifies("REQ-SPEC-005")]
    #[test]
    fn formats_requirement_blocks_without_touching_surrounding_markdown() {
        let input = "# Story\n\n- **REQ-AA-001** — The service SHALL retain a deliberately long value across every ordinary processing pass so the formatter has to wrap it.\n    *Enforced:* `src/lib.rs` (`apply`) · *Verified:* [test] `src/lib.rs` (`test_apply`)\n\n| prose | stays |\n";

        let formatted = format_text(input, &spec(), true);

        assert!(formatted.diagnostics.is_empty());
        assert_eq!(formatted.requirements, 1);
        assert!(
            formatted
                .text
                .lines()
                .any(|line| line.starts_with("  ") && line.contains("formatter"))
        );
        assert!(formatted.text.contains("*Enforced:*"));
        assert!(formatted.text.ends_with("\n| prose | stays |\n"));
        assert!(
            formatted
                .text
                .lines()
                .filter(|line| line.starts_with("- **REQ-") || line.starts_with("  "))
                .all(|line| line.chars().count() <= REQUIREMENT_LINE_WIDTH)
        );
    }

    #[shallguard::verifies("REQ-SPEC-005")]
    #[test]
    fn formatting_is_idempotent_and_semantically_equivalent() {
        let input = "- **REQ-AA-001** — The service SHALL retain state.\n  *Enforced:* `src/lib.rs` (`apply`) · *Verified:* [test] `src/lib.rs` (`test_apply`)\n";
        let once = format_text(input, &spec(), true);
        let twice = format_text(&once.text, &spec(), true);

        assert!(once.diagnostics.is_empty());
        assert_eq!(once.text, twice.text);
        verify_semantic_equivalence(input, &once.text, &spec())
            .expect("formatting preserves requirement meaning");
    }

    #[shallguard::verifies("REQ-SPEC-001", "REQ-SPEC-002")]
    #[test]
    fn rejects_missing_segments_and_evidence_status() {
        let missing_verified =
            "- **REQ-AA-001** — The service SHALL retain state.\n  *Enforced:* `src/lib.rs`\n";
        let no_status = "- **REQ-AA-002** — The service SHALL retain state.\n  *Enforced:* `src/lib.rs` · *Verified:* `src/lib.rs` (`test_apply`)\n";

        let first = format_text(missing_verified, &spec(), true);
        let second = format_text(no_status, &spec(), true);

        assert!(
            first
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.message.contains("exactly one `*Verified:*`"))
        );
        assert!(
            second
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.message.contains("must contain"))
        );
    }

    #[shallguard::verifies("REQ-SPEC-007", "REQ-SPEC-008")]
    #[test]
    fn adds_canonical_keywords_next_to_emoji_aliases() {
        let input = "- **REQ-AA-001** — The service SHALL retain state.\n  *Enforced:* `src/lib.rs` (`apply`) · *Verified:* ✅ `src/lib.rs` (`test_apply`) ·\n  🔬 differential run\n- **REQ-AA-002** — The service SHALL not fail.\n  *Enforced:* not implemented · *Verified:* ⏳ pending\n";

        let formatted = format_text(input, &spec(), true);

        assert!(
            formatted.diagnostics.is_empty(),
            "{:?}",
            formatted.diagnostics
        );
        let joined = formatted
            .text
            .split_whitespace()
            .collect::<Vec<_>>()
            .join(" ");
        assert!(joined.contains("*Verified:* [test] ✅ `src/lib.rs` (`test_apply`) ·"));
        assert!(joined.contains("[e2e] 🔬 differential run"));
        assert!(joined.contains("*Verified:* [pending] ⏳ pending"));
        let twice = format_text(&formatted.text, &spec(), true);
        assert_eq!(twice.text, formatted.text, "the rewrite is idempotent");
        let kept = format_text(input, &spec(), false);
        assert!(kept.diagnostics.is_empty());
        assert!(
            !kept.text.contains("[test]") && kept.text.contains('✅'),
            "the check mode keeps an emoji alias without its keyword"
        );
        verify_semantic_equivalence(input, &formatted.text, &spec())
            .expect("an alias and its keyword have the same parsed meaning");

        let before = parse_text(input, &spec());
        let after = parse_text(&formatted.text, &spec());
        assert!(before.requirements[0].automated && after.requirements[0].automated);
        assert!(before.requirements[0].e2e && after.requirements[0].e2e);
        assert!(before.requirements[1].pending && after.requirements[1].pending);
    }

    #[shallguard::verifies("REQ-SPEC-008")]
    #[test]
    fn check_accepts_emoji_aliases_and_format_adds_keywords() {
        let dir = tempfile::tempdir().expect("tempdir");
        let doc = dir
            .path()
            .join("crate/docs/USER_STORIES_AND_REQUIREMENTS.md");
        std::fs::create_dir_all(doc.parent().expect("BUG: document has a parent")).expect("mkdir");
        std::fs::write(
            &doc,
            "- **REQ-AA-001** — The service SHALL retain state.\n  *Enforced:* `src/lib.rs` (`apply`) · *Verified:* ✅ `src/lib.rs` (`test_apply`)\n",
        )
        .expect("write document");

        let report = check(dir.path(), &[spec()]).expect("check runs");

        assert!(report.diagnostics.is_empty());
        assert!(
            report.is_clean(),
            "an emoji-only document passes fmt --check"
        );
        let untouched = std::fs::read_to_string(&doc).expect("read document");
        assert!(!untouched.contains("[test]"), "check must not write");

        let written = super::format(dir.path(), &[spec()]).expect("format runs");
        assert_eq!(written.changed_documents.len(), 1);
        let migrated = std::fs::read_to_string(&doc).expect("read document");
        assert!(migrated.contains("*Verified:* [test] ✅"), "{migrated}");
        assert!(check(dir.path(), &[spec()]).expect("check runs").is_clean());
    }

    #[shallguard::verifies("REQ-SPEC-004")]
    #[test]
    fn permits_retired_requirements_without_evidence_segments() {
        let input = "- **REQ-AA-001** — *(retired into REQ-AA-002.)*\n";

        let formatted = format_text(input, &spec(), true);

        assert!(formatted.diagnostics.is_empty());
        assert_eq!(formatted.text, input);
    }

    #[test]
    fn formats_files_atomically_and_then_checks_clean() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let document = directory
            .path()
            .join("crate/docs/USER_STORIES_AND_REQUIREMENTS.md");
        std::fs::create_dir_all(document.parent().expect("document has parent"))
            .expect("document directory creates");
        std::fs::write(
            &document,
            "- **REQ-AA-001** — The service SHALL retain state.\n    *Enforced:* `src/lib.rs` (`apply`) · *Verified:* [test] `src/lib.rs` (`test_apply`)\n",
        )
        .expect("fixture writes");

        let formatted = super::format(directory.path(), &[spec()]).expect("format succeeds");
        assert_eq!(
            formatted.changed_documents,
            vec![PathBuf::from("crate/docs/USER_STORIES_AND_REQUIREMENTS.md")]
        );
        let text = std::fs::read_to_string(&document).expect("formatted document reads");
        assert!(text.contains("\n  *Enforced:*"));

        let checked = check(directory.path(), &[spec()]).expect("check succeeds");
        assert!(checked.is_clean());
    }

    #[shallguard::verifies("REQ-SPEC-005")]
    #[test]
    fn lint_failures_prevent_formatter_writes() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let document = directory
            .path()
            .join("crate/docs/USER_STORIES_AND_REQUIREMENTS.md");
        std::fs::create_dir_all(document.parent().expect("document has parent"))
            .expect("document directory creates");
        let malformed =
            "- **REQ-AA-001** — The service SHALL retain state.\n  *Enforced:* `src/lib.rs`\n";
        std::fs::write(&document, malformed).expect("fixture writes");

        let report = super::format(directory.path(), &[spec()]).expect("lint report returns");

        assert!(!report.diagnostics.is_empty());
        assert_eq!(
            std::fs::read_to_string(document).expect("unchanged document reads"),
            malformed
        );
    }
}