spec-driven-docs 0.6.5

Spec-driven documentation: current specs, immutable decision records, and executable gates kept coherent for people and coding agents.
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
//! The delivered gates: every check an instance wires as a pre-commit hook.
//!
//! This module owns the registry — identity, display name, hook wiring,
//! citable rules, and implementation for each gate — so a gate cannot exist
//! unwired: the exhaustive match over [`GateId`] is the declaration. Gate
//! implementations live one per file below; rendering the registry into
//! pre-commit YAML and running one gate from the command line live in
//! `services` and `commands`.

pub mod paths;

pub mod adr_cites_a_live_rule;
pub mod adr_filename_shape;
pub mod adr_word_cap;
pub mod agents_digest_size;
pub mod chapter_size_cap;
pub mod comparison_dated_tables;
pub mod comparison_escaped_pipes;
pub mod comparison_legend;
pub mod comparison_one_reference_per_cell;
pub mod comparison_verdict_word;
pub mod gate_message_cites_a_rule;
pub mod instance_manifest;
pub mod ki_bugzilla_report_width;
pub mod ki_checked_date;
pub mod ki_filename_shape;
pub mod ki_filing;
pub mod ki_mechanism_walkthrough;
pub mod ki_record;
pub mod ki_report_body;
pub mod ki_retire_when;
pub mod ki_state;
pub mod markdown_prose;
pub mod no_personal_path;
pub mod no_self_narration;
pub mod prose_stays_unwrapped;
pub mod spec_change_is_typed;
pub mod spec_requirement_parts;
pub mod spec_rule_id_unique;
pub mod spec_size_cap;
pub mod spec_verify_hooks_exist;
pub mod suppression_names_its_case;
pub mod tracking_registry;

use std::fmt;

use camino::{Utf8Path, Utf8PathBuf};
use thiserror::Error;

use crate::domain::finding::Finding;
use crate::domain::gate_id::GateId;
use crate::domain::rule_id::RuleId;

/// Where a gate runs: the repository root pre-commit invoked it from.
#[derive(Debug, Clone)]
pub struct GateCtx {
    /// The repository root; every path a gate reads or reports is relative to it.
    pub repo_root: Utf8PathBuf,
}

impl GateCtx {
    /// A context rooted at the given repository.
    #[must_use]
    pub fn new(repo_root: impl Into<Utf8PathBuf>) -> Self {
        Self {
            repo_root: repo_root.into(),
        }
    }

    /// Resolve a repository-relative path for reading.
    #[must_use]
    pub fn path(&self, relative: impl AsRef<Utf8Path>) -> Utf8PathBuf {
        self.repo_root.join(relative)
    }
}

/// One line a failing gate prints.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Violation {
    /// A rule violation, rendered as its `FAIL <domain>:<rule> ...` line.
    Finding(Finding),
    /// The repository does not have the shape the gate needs; rendered as
    /// `FAIL <reason>` with no rule to cite.
    Layout(String),
    /// A continuation line under a preceding violation, rendered verbatim.
    Note(String),
}

impl fmt::Display for Violation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Finding(finding) => finding.fmt(f),
            Self::Layout(reason) => write!(f, "FAIL {reason}"),
            Self::Note(text) => f.write_str(text),
        }
    }
}

/// A gate that could not run at all — distinct from one that found violations.
#[derive(Debug, Error)]
pub enum GateError {
    /// A file the gate needed could not be read.
    #[error("{path}: {source}")]
    Io {
        /// The path that failed.
        path: Utf8PathBuf,
        /// The underlying failure.
        source: std::io::Error,
    },
}

impl GateError {
    pub(crate) fn io(path: impl Into<Utf8PathBuf>, source: std::io::Error) -> Self {
        Self::Io {
            path: path.into(),
            source,
        }
    }
}

impl From<GateError> for crate::error::AppError {
    fn from(error: GateError) -> Self {
        match error {
            GateError::Io { path, source } => {
                let kind = source.kind();
                Self::Io(std::io::Error::new(kind, format!("{path}: {source}")))
            }
        }
    }
}

/// What every gate returns: the violations it found, or why it could not run.
pub type GateResult = Result<Vec<Violation>, GateError>;

/// The implementation shape shared by every gate.
pub type GateFn = fn(&GateCtx, &[String]) -> GateResult;

/// One registry row: everything the deliveries need to know about a gate.
#[derive(Debug)]
pub struct GateSpec {
    /// The gate's identity.
    pub id: GateId,
    /// The display name pre-commit shows.
    pub name: &'static str,
    /// The default `files:` pattern, with `{docs_root}` left templated.
    ///
    /// A row that does not set `always_run` carries one, under
    /// `release:a-delivered-gate-reads-what-the-convention-owns`: a `types:`
    /// scope alone reaches every matching file in the project, including the
    /// ones another tool wrote.
    pub files: Option<&'static str>,
    /// The `types:` scope, when the gate takes one.
    pub types: Option<&'static str>,
    /// The default `exclude:` pattern, with `{docs_root}` left templated.
    pub exclude: Option<&'static str>,
    /// Whether the gate runs regardless of which files changed.
    pub always_run: bool,
    /// Every rule the gate can cite in a finding.
    pub cites: &'static [RuleId],
    /// The implementation.
    pub run: GateFn,
}

/// Look up one gate's registry row.
#[must_use]
pub fn spec(id: GateId) -> &'static GateSpec {
    let index = GateId::ALL.iter().position(|g| *g == id).unwrap_or(0);
    &GATES[index]
}

/// The delivered gate set, in [`GateId::ALL`] order.
pub static GATES: &[GateSpec] = &[
    GateSpec {
        id: GateId::AdrCitesALiveRule,
        name: "decision record citations resolve",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: adr_cites_a_live_rule::CITES,
        run: adr_cites_a_live_rule::run,
    },
    GateSpec {
        id: GateId::AdrFilenameShape,
        name: "decision record filename shape",
        files: Some(r"^{docs_root}/decisions/.*\.md$"),
        types: None,
        exclude: None,
        always_run: false,
        cites: adr_filename_shape::CITES,
        run: adr_filename_shape::run,
    },
    GateSpec {
        id: GateId::AdrWordCap,
        name: "decision record word cap",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: adr_word_cap::CITES,
        run: adr_word_cap::run,
    },
    GateSpec {
        id: GateId::AgentsDigestSize,
        name: "agent digest size",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: agents_digest_size::CITES,
        run: agents_digest_size::run,
    },
    GateSpec {
        id: GateId::ChapterSizeCap,
        name: "chapter and catalog size",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: chapter_size_cap::CITES,
        run: chapter_size_cap::run,
    },
    GateSpec {
        id: GateId::ComparisonDatedTables,
        name: "comparison tables are dated",
        files: Some(r"(^|/)COMPARISON-[a-z0-9-]+\.md$"),
        types: None,
        exclude: None,
        always_run: false,
        cites: comparison_dated_tables::CITES,
        run: comparison_dated_tables::run,
    },
    GateSpec {
        id: GateId::ComparisonEscapedPipes,
        name: "comparison table pipes are escaped",
        files: Some(r"(^|/)COMPARISON-[a-z0-9-]+\.md$"),
        types: None,
        exclude: None,
        always_run: false,
        cites: comparison_escaped_pipes::CITES,
        run: comparison_escaped_pipes::run,
    },
    GateSpec {
        id: GateId::ComparisonLegend,
        name: "comparison legend",
        files: Some(r"(^|/)COMPARISON-[a-z0-9-]+\.md$"),
        types: None,
        exclude: None,
        always_run: false,
        cites: comparison_legend::CITES,
        run: comparison_legend::run,
    },
    GateSpec {
        id: GateId::ComparisonOneReferencePerCell,
        name: "one reference per comparison cell",
        files: Some(r"(^|/)COMPARISON-[a-z0-9-]+\.md$"),
        types: None,
        exclude: None,
        always_run: false,
        cites: comparison_one_reference_per_cell::CITES,
        run: comparison_one_reference_per_cell::run,
    },
    GateSpec {
        id: GateId::ComparisonVerdictWord,
        name: "comparison verdict word",
        files: Some(r"(^|/)COMPARISON-[a-z0-9-]+\.md$"),
        types: None,
        exclude: None,
        always_run: false,
        cites: comparison_verdict_word::CITES,
        run: comparison_verdict_word::run,
    },
    GateSpec {
        id: GateId::GateMessageCitesARule,
        name: "gate messages cite a rule",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: gate_message_cites_a_rule::CITES,
        run: gate_message_cites_a_rule::run,
    },
    GateSpec {
        id: GateId::InstanceManifest,
        name: "instance manifest",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: instance_manifest::CITES,
        run: instance_manifest::run,
    },
    GateSpec {
        id: GateId::KiBugzillaReportWidth,
        name: "Bugzilla report width",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: ki_bugzilla_report_width::CITES,
        run: ki_bugzilla_report_width::run,
    },
    GateSpec {
        id: GateId::KiCheckedDate,
        name: "known issue last-check date",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: ki_checked_date::CITES,
        run: ki_checked_date::run,
    },
    GateSpec {
        id: GateId::KiFilenameShape,
        name: "known issue filename shape",
        files: Some(r"^{docs_root}/reference/known-issues/.*\.md$"),
        types: None,
        exclude: None,
        always_run: false,
        cites: ki_filename_shape::CITES,
        run: ki_filename_shape::run,
    },
    GateSpec {
        id: GateId::KiFiling,
        name: "known issue filing state",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: ki_filing::CITES,
        run: ki_filing::run,
    },
    GateSpec {
        id: GateId::KiMechanismWalkthrough,
        name: "known issue mechanism walkthrough",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: ki_mechanism_walkthrough::CITES,
        run: ki_mechanism_walkthrough::run,
    },
    GateSpec {
        id: GateId::KiReportBody,
        name: "known issue report body",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: ki_report_body::CITES,
        run: ki_report_body::run,
    },
    GateSpec {
        id: GateId::KiRetireWhen,
        name: "known issue retirement condition",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: ki_retire_when::CITES,
        run: ki_retire_when::run,
    },
    GateSpec {
        id: GateId::KiState,
        name: "known issue state",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: ki_state::CITES,
        run: ki_state::run,
    },
    GateSpec {
        id: GateId::NoPersonalPath,
        name: "no personal path",
        files: Some(r"^{docs_root}/.*\.md$"),
        types: Some("text"),
        exclude: None,
        always_run: false,
        cites: no_personal_path::CITES,
        run: no_personal_path::run,
    },
    GateSpec {
        id: GateId::NoSelfNarration,
        name: "documents state the present",
        files: Some(r"^{docs_root}/.*\.md$"),
        types: Some("markdown"),
        exclude: Some("^{docs_root}/decisions/"),
        always_run: false,
        cites: no_self_narration::CITES,
        run: no_self_narration::run,
    },
    GateSpec {
        id: GateId::ProseStaysUnwrapped,
        name: "prose lines stay unwrapped",
        files: Some(r"^{docs_root}/.*\.md$"),
        types: Some("markdown"),
        exclude: Some(r"(?:^|/)CHANGELOG\.md$"),
        always_run: false,
        cites: prose_stays_unwrapped::CITES,
        run: prose_stays_unwrapped::run,
    },
    GateSpec {
        id: GateId::SpecChangeIsTyped,
        name: "spec changes are typed",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: spec_change_is_typed::CITES,
        run: spec_change_is_typed::run,
    },
    GateSpec {
        id: GateId::SpecRequirementParts,
        name: "spec requirement parts",
        files: Some(r"^{docs_root}/specs/SPEC-.*\.md$"),
        types: None,
        exclude: None,
        always_run: false,
        cites: spec_requirement_parts::CITES,
        run: spec_requirement_parts::run,
    },
    GateSpec {
        id: GateId::SpecRuleIdUnique,
        name: "spec rule IDs are unique",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: spec_rule_id_unique::CITES,
        run: spec_rule_id_unique::run,
    },
    GateSpec {
        id: GateId::SpecSizeCap,
        name: "spec size cap",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: spec_size_cap::CITES,
        run: spec_size_cap::run,
    },
    GateSpec {
        id: GateId::SpecVerifyHooksExist,
        name: "spec hook references exist",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: spec_verify_hooks_exist::CITES,
        run: spec_verify_hooks_exist::run,
    },
    GateSpec {
        id: GateId::SuppressionNamesItsCase,
        name: "suppressions name a known issue",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: suppression_names_its_case::CITES,
        run: suppression_names_its_case::run,
    },
    GateSpec {
        id: GateId::TrackingRegistry,
        name: "tracking registry is valid and current",
        files: None,
        types: None,
        exclude: None,
        always_run: true,
        cites: tracking_registry::CITES,
        run: tracking_registry::run,
    },
];

/// The directories every repository walk prunes: vendored or generated trees
/// a consumer cannot be asked to author.
pub const PRUNED_DIRS: &[&str] = &[
    ".git",
    "node_modules",
    ".venv",
    "vendor",
    "third-party",
    "target",
    "dist",
];

/// Count the newline-terminated lines of a text, as `wc -l` does.
#[must_use]
pub fn line_count(text: &str) -> usize {
    text.matches('\n').count()
}

/// Read a repository-relative text file for a gate.
///
/// # Errors
///
/// [`GateError::Io`] naming the path when the file cannot be read.
pub fn read_text(ctx: &GateCtx, relative: impl AsRef<Utf8Path>) -> Result<String, GateError> {
    let relative = relative.as_ref();
    std::fs::read_to_string(ctx.path(relative)).map_err(|source| GateError::io(relative, source))
}

/// Every value a front-matter key carries, in the order the keys appear.
///
/// The scan is the leading `---` block alone, so a `state:` line in the
/// prose below it is text about the record rather than the record's own
/// field. A key stated twice yields two entries, which is what makes
/// "exactly one" decidable.
#[must_use]
pub fn front_matter_values(text: &str, key: &str) -> Vec<String> {
    let mut lines = text.lines();
    if lines.next() != Some("---") {
        return Vec::new();
    }
    lines
        .take_while(|line| *line != "---")
        .filter_map(|line| {
            line.strip_prefix(key)
                .and_then(|rest| rest.strip_prefix(':'))
        })
        .map(|value| value.trim().to_string())
        .collect()
}

/// Walk the repository, pruning [`PRUNED_DIRS`], and yield every file as a
/// `./`-prefixed repository-relative path in sorted order.
#[must_use]
pub fn walk_files(ctx: &GateCtx) -> Vec<Utf8PathBuf> {
    let root = ctx.repo_root.as_std_path();
    let mut files: Vec<Utf8PathBuf> = walkdir::WalkDir::new(root)
        .into_iter()
        .filter_entry(|entry| {
            !(entry.file_type().is_dir()
                && entry.depth() > 0
                && entry
                    .file_name()
                    .to_str()
                    .is_some_and(|name| PRUNED_DIRS.contains(&name)))
        })
        .filter_map(Result::ok)
        .filter(|entry| entry.file_type().is_file())
        .filter_map(|entry| {
            let relative = entry.path().strip_prefix(root).ok()?.to_str()?;
            Some(Utf8PathBuf::from(format!("./{relative}")))
        })
        .collect();
    files.sort();
    files
}

#[cfg(test)]
pub(crate) mod tests_support {
    /// A repository holding one known-issue record with the given `state:`
    /// value and `retire_when:` line.
    pub fn ki_fixture_state(state: &str, retire_line: &str) -> tempfile::TempDir {
        ki_record(&format!(
            "---\nupstream: https://example.invalid/issues\nstate: {state}\nfiling: gathering\n{retire_line}---\n# Vendor issue\n## How it works\nRun.\n"
        ))
    }

    /// A repository holding one known-issue record with the given `state:`
    /// value and `checked:` line.
    pub fn ki_fixture_checked(state: &str, checked_line: &str) -> tempfile::TempDir {
        ki_record(&format!(
            "---\nupstream: https://example.invalid/issues\nstate: {state}\nfiling: gathering\nretire_when: release >= 2.0\n{checked_line}---\n# Vendor issue\n## How it works\nRun.\n"
        ))
    }

    /// A repository holding one known-issue record with a conforming
    /// frontmatter and the given body.
    pub fn ki_fixture_body(body: &str) -> tempfile::TempDir {
        ki_record(&format!(
            "---\nupstream: https://example.invalid/issues\nstate: masked\nfiling: gathering\nretire_when: release >= 2.0\n---\n{body}"
        ))
    }

    /// A repository holding one filed known-issue record with the given
    /// `upstream:` value and body.
    pub fn ki_fixture_upstream(upstream: &str, body: &str) -> tempfile::TempDir {
        ki_fixture_filing("filed", upstream, body)
    }

    /// A repository holding one known-issue record with the given `filing:`
    /// value, `upstream:` value and body.
    pub fn ki_fixture_filing(filing: &str, upstream: &str, body: &str) -> tempfile::TempDir {
        ki_record(&format!(
            "---\nupstream: {upstream}\nstate: masked\nfiling: {filing}\nretire_when: release >= 2.0\n---\n{body}"
        ))
    }

    fn ki_record(text: &str) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        let records = dir.path().join("_docs/reference/known-issues");
        std::fs::create_dir_all(&records).unwrap();
        std::fs::write(records.join("KI-vendor.md"), text).unwrap();
        dir
    }
}

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

    #[test]
    fn registry_covers_every_gate_exactly_once_in_order() {
        assert_eq!(GATES.len(), GateId::ALL.len());
        for (row, id) in GATES.iter().zip(GateId::ALL) {
            assert_eq!(row.id, *id);
            assert_eq!(spec(*id).id, *id);
        }
    }

    #[test]
    fn every_gate_declares_the_rules_it_cites() {
        for row in GATES {
            assert!(!row.cites.is_empty(), "{} cites nothing", row.id);
        }
    }

    #[test]
    fn cited_rules_resolve_in_the_embedded_specs() {
        let defined = crate::embedded::spec_rule_ids();
        for row in GATES {
            for rule in row.cites {
                assert!(
                    defined.contains(rule.as_str()),
                    "{}: {rule} is undefined",
                    row.id
                );
            }
        }
    }
}