Skip to main content

vitrify_cli/incremental/
rows.rs

1//! Which rows a gate, a re-check or a preflight runs.
2//!
3//! Every selection is a list of Verification rows — each distinct command
4//! once, in the order its first unit lists it — and, where the §5 Test
5//! command belongs, that command after them:
6//!
7//! * **an integration gate** runs the merged units' rows, then the rows of
8//!   the SDD's dirty Verified units — every dependent of the merged units is
9//!   among them, since their inputs changed — then the §5 Test command, the
10//!   whole-suite backstop. Rows of clean units are not run: their recorded
11//!   checks still hold. An SDD **without** a §5 Test command has no backstop
12//!   for coupling its declarations miss, so its gate runs every Verified
13//!   unit's rows, as a full re-run;
14//! * **a preflight** runs the rows of dirty units only — what replaces
15//!   re-running every Verified unit's table at the start of a run;
16//! * **a re-check batch** runs the dirty units' rows, then the §5 Test
17//!   command.
18//!
19//! The selections are pure: the caller reads the tables ([`tables`]) and
20//! the dirty set (`super::dirty`), and runs what comes back.
21
22use vitrify_core::CoreError;
23use vitrify_core::model::{self, Instance};
24
25use crate::gate;
26
27/// One unit's Verification rows, as a selection reads them.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct UnitTable {
30    pub unit: String,
31    /// The unit's status is Verified.
32    pub verified: bool,
33    /// Its Verification table's commands, in table order.
34    pub rows: Vec<String>,
35}
36
37/// Every unit's table of `inst`, in the SDD's unit order.
38pub fn tables(inst: &Instance) -> Result<Vec<UnitTable>, CoreError> {
39    inst.units
40        .iter()
41        .map(|u| {
42            Ok(UnitTable {
43                unit: u.unit.clone(),
44                verified: u.meta.get_str_or("status", "Draft") == "Verified",
45                rows: gate::verification_table(inst, u)?,
46            })
47        })
48        .collect()
49}
50
51/// The SDD's §5 Commands: the first `### Commands` subsection of the core
52/// file's `## Technology Decisions` section, up to the next heading of level
53/// 3 or less; each the command between the first pair of backticks on its
54/// `- Name:` line. A `Commands` heading anywhere else — at another level,
55/// under another section, in a unit region of a single-file SDD, inside a
56/// fenced block — is not §5, and nothing under it runs.
57#[derive(Debug, Clone, Default, PartialEq, Eq)]
58pub struct Commands {
59    pub bootstrap: Option<String>,
60    pub build: Option<String>,
61    pub test: Option<String>,
62    pub lint: Option<String>,
63}
64
65impl Commands {
66    /// Read from the core file's text.
67    pub fn parse(core_text: &str) -> Commands {
68        let mut out = Commands::default();
69        for line in commands_lines(core_text) {
70            let Some(rest) = line.trim_start().strip_prefix("- ") else {
71                continue;
72            };
73            let Some((name, value)) = rest.split_once(':') else {
74                continue;
75            };
76            let cmd = value
77                .split('`')
78                .nth(1)
79                .map(str::trim)
80                .filter(|c| !c.is_empty())
81                .map(str::to_string);
82            match name.trim().to_lowercase().as_str() {
83                "bootstrap" => out.bootstrap = cmd,
84                "build" => out.build = cmd,
85                "test" => out.test = cmd,
86                "lint" => out.lint = cmd,
87                _ => {}
88            }
89        }
90        out
91    }
92
93    /// Read from `inst`'s core file.
94    pub fn of(inst: &Instance) -> Result<Commands, CoreError> {
95        Ok(Commands::parse(&model::read_text(&inst.file)?))
96    }
97}
98
99/// A Markdown ATX heading's level and text; `None` for any other line.
100fn heading(line: &str) -> Option<(usize, &str)> {
101    let level = line.bytes().take_while(|&b| b == b'#').count();
102    if !(1..=6).contains(&level) {
103        return None;
104    }
105    let rest = &line[level..];
106    if !(rest.is_empty() || rest.starts_with(' ') || rest.starts_with('\t')) {
107        return None;
108    }
109    Some((level, rest.trim().trim_end_matches('#').trim_end()))
110}
111
112/// The lines of the §5 Commands subsection: under the first `## Technology
113/// Decisions`, the first `### Commands`, up to the next heading of level 3
114/// or less. Headings inside fenced blocks are not headings.
115fn commands_lines(core_text: &str) -> Vec<&str> {
116    let mut out = Vec::new();
117    let mut fence: Option<&str> = None;
118    // 0: before §5; 1: in §5; 2: in its Commands; 3: past them
119    let mut at = 0;
120    for line in core_text.lines() {
121        let trimmed = line.trim_start();
122        if let Some(open) = fence {
123            if trimmed.starts_with(open) {
124                fence = None;
125            }
126            if at == 2 {
127                out.push(line);
128            }
129            continue;
130        }
131        if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
132            fence = Some(&trimmed[..3]);
133            if at == 2 {
134                out.push(line);
135            }
136            continue;
137        }
138        if let Some((level, text)) = heading(line) {
139            at = match at {
140                0 if level == 2 && text == "Technology Decisions" => 1,
141                1 if level <= 2 => 3,
142                1 if level == 3 && text == "Commands" => 2,
143                2 if level <= 3 => 3,
144                other => other,
145            };
146            if at == 3 {
147                break;
148            }
149            continue;
150        }
151        if at == 2 {
152            out.push(line);
153        }
154    }
155    out
156}
157
158/// What to run.
159#[derive(Debug, Clone, Default, PartialEq, Eq)]
160pub struct Selection {
161    /// The units whose rows are selected, in the order they were taken.
162    pub units: Vec<String>,
163    /// Their rows, each distinct command once, in first-listed order.
164    pub rows: Vec<String>,
165    /// The §5 Test command, run after the rows; `None` when the selection
166    /// has none.
167    pub test: Option<String>,
168}
169
170impl Selection {
171    /// Take `unit`'s rows, unless it is already taken or has no table.
172    fn take(&mut self, tables: &[UnitTable], unit: &str) {
173        if self.units.iter().any(|u| u == unit) {
174            return;
175        }
176        let Some(t) = tables.iter().find(|t| t.unit == unit) else {
177            return;
178        };
179        self.units.push(t.unit.clone());
180        for row in &t.rows {
181            if !self.rows.contains(row) {
182                self.rows.push(row.clone());
183            }
184        }
185    }
186
187    /// Whether nothing at all is selected.
188    pub fn is_empty(&self) -> bool {
189        self.rows.is_empty() && self.test.is_none()
190    }
191}
192
193/// Whether `unit` is Verified in `tables`.
194fn is_verified(tables: &[UnitTable], unit: &str) -> bool {
195    tables.iter().any(|t| t.unit == unit && t.verified)
196}
197
198/// An integration gate: the `merged` units' rows; then, with a §5 Test
199/// command, the rows of the `dirty` units still Verified, and the command;
200/// without one, the rows of every Verified unit (in the SDD's order).
201pub fn for_gate(
202    tables: &[UnitTable],
203    merged: &[String],
204    dirty: &[String],
205    test: Option<&str>,
206) -> Selection {
207    let mut sel = Selection::default();
208    for unit in merged {
209        sel.take(tables, unit);
210    }
211    match test {
212        Some(test) => {
213            for unit in dirty {
214                if is_verified(tables, unit) {
215                    sel.take(tables, unit);
216                }
217            }
218            sel.test = Some(test.to_string());
219        }
220        None => {
221            for t in tables.iter().filter(|t| t.verified) {
222                sel.take(tables, &t.unit);
223            }
224        }
225    }
226    sel
227}
228
229/// A preflight: the rows of the `dirty` units still Verified; no Test
230/// command.
231pub fn for_preflight(tables: &[UnitTable], dirty: &[String]) -> Selection {
232    let mut sel = Selection::default();
233    for unit in dirty {
234        if is_verified(tables, unit) {
235            sel.take(tables, unit);
236        }
237    }
238    sel
239}
240
241/// A re-check batch: the rows of the `dirty` units still Verified, then
242/// the §5 Test command when the SDD has one.
243pub fn for_recheck(tables: &[UnitTable], dirty: &[String], test: Option<&str>) -> Selection {
244    let mut sel = for_preflight(tables, dirty);
245    sel.test = test.map(str::to_string);
246    sel
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    fn t(unit: &str, verified: bool, rows: &[&str]) -> UnitTable {
254        UnitTable {
255            unit: unit.into(),
256            verified,
257            rows: rows.iter().map(|r| r.to_string()).collect(),
258        }
259    }
260
261    fn ids(v: &[&str]) -> Vec<String> {
262        v.iter().map(|s| s.to_string()).collect()
263    }
264
265    /// U-001 a foundation, U-002 and U-003 Verified, U-004 Ready; U-003
266    /// shares a row with U-001.
267    fn sdd() -> Vec<UnitTable> {
268        vec![
269            t("U-001", false, &["test -f a", "check shared"]),
270            t("U-002", true, &["test -f b"]),
271            t("U-003", true, &["check shared", "test -f c"]),
272            t("U-004", false, &["test -f d"]),
273        ]
274    }
275
276    #[test]
277    fn a_gate_runs_the_merged_and_the_dirty_rows_then_the_suite() {
278        let sel = for_gate(
279            &sdd(),
280            &ids(&["U-001"]),
281            &ids(&["U-003", "U-004"]),
282            Some("make test"),
283        );
284        assert_eq!(sel.units, ids(&["U-001", "U-003"]));
285        // each distinct command once, in first-listed order
286        assert_eq!(sel.rows, ids(&["test -f a", "check shared", "test -f c"]));
287        assert_eq!(sel.test.as_deref(), Some("make test"));
288    }
289
290    #[test]
291    fn a_gate_with_nothing_dirty_runs_the_merged_rows_and_the_suite() {
292        let sel = for_gate(&sdd(), &ids(&["U-004"]), &[], Some("make test"));
293        assert_eq!(sel.units, ids(&["U-004"]));
294        assert_eq!(sel.rows, ids(&["test -f d"]));
295        assert_eq!(sel.test.as_deref(), Some("make test"));
296    }
297
298    #[test]
299    fn without_a_test_command_a_gate_runs_every_verified_unit() {
300        // nothing dirty, and still the full re-run: no backstop
301        let sel = for_gate(&sdd(), &ids(&["U-001"]), &[], None);
302        assert_eq!(sel.units, ids(&["U-001", "U-002", "U-003"]));
303        assert_eq!(
304            sel.rows,
305            ids(&["test -f a", "check shared", "test -f b", "test -f c"])
306        );
307        assert_eq!(sel.test, None);
308    }
309
310    #[test]
311    fn a_merged_unit_listed_dirty_too_is_taken_once() {
312        let sel = for_gate(
313            &sdd(),
314            &ids(&["U-002"]),
315            &ids(&["U-002", "U-003"]),
316            Some("t"),
317        );
318        assert_eq!(sel.units, ids(&["U-002", "U-003"]));
319        assert_eq!(sel.rows, ids(&["test -f b", "check shared", "test -f c"]));
320    }
321
322    #[test]
323    fn a_preflight_runs_dirty_verified_rows_only() {
324        let sel = for_preflight(&sdd(), &ids(&["U-003", "U-004", "U-009"]));
325        assert_eq!(sel.units, ids(&["U-003"]));
326        assert_eq!(sel.rows, ids(&["check shared", "test -f c"]));
327        assert_eq!(sel.test, None);
328        assert!(for_preflight(&sdd(), &[]).is_empty());
329    }
330
331    #[test]
332    fn a_recheck_runs_dirty_rows_then_the_suite() {
333        let sel = for_recheck(&sdd(), &ids(&["U-003", "U-002"]), Some("t"));
334        // in the order the units were given
335        assert_eq!(sel.units, ids(&["U-003", "U-002"]));
336        assert_eq!(sel.rows, ids(&["check shared", "test -f c", "test -f b"]));
337        assert_eq!(sel.test.as_deref(), Some("t"));
338        let none = for_recheck(&sdd(), &[], Some("t"));
339        assert!(none.rows.is_empty());
340        assert!(!none.is_empty());
341        assert!(for_recheck(&sdd(), &[], None).is_empty());
342    }
343
344    #[test]
345    fn commands_parse_the_commands_section() {
346        let text = "# x\n\n## Technology Decisions\n\nT.\n\n### Commands\n\n- Bootstrap: `npm ci`\n- Build:     ``\n- Test: `npm test` (whole suite)\n\n## Next\n\n- Lint: `nope`\n";
347        let c = Commands::parse(text);
348        assert_eq!(c.bootstrap.as_deref(), Some("npm ci"));
349        assert_eq!(c.build, None);
350        assert_eq!(c.test.as_deref(), Some("npm test"));
351        assert_eq!(c.lint, None);
352    }
353
354    /// A single-file SDD whose unit region has a `#### Commands` heading of
355    /// its own, after the real §5 Commands.
356    const SINGLE: &str = "# s\n\n## Ground Rules\n\n### Commands\n\n- Lint: `ground`\n\n## Technology Decisions\n\nT.\n\n### Tools\n\n- Build: `tools`\n\n### Commands\n\n- Bootstrap: `true`\n- Build:     `make`\n- Test:      `make test`\n\n```sh\n# Commands\n- Lint: `fenced`\n```\n\n#### Notes\n\n- Lint: `cargo clippy`\n\n### Commands\n\n- Build: `second`\n\n## Work Units\n\n### U-001 — a\n\n#### Commands\n\n- Build: `rm -rf /tmp/x`\n\n# Commands\n\n- Test: `evil`\n";
357
358    #[test]
359    fn a_commands_heading_outside_section_5_is_not_read() {
360        let c = Commands::parse(SINGLE);
361        // the unit region's heading, the top-level one, the one under
362        // Ground Rules, and the fenced one run nothing
363        assert_eq!(c.build.as_deref(), Some("make"));
364        assert_eq!(c.test.as_deref(), Some("make test"));
365        assert_eq!(c.bootstrap.as_deref(), Some("true"));
366        // a level-4 heading inside the subsection does not end it
367        assert_eq!(c.lint.as_deref(), Some("cargo clippy"));
368    }
369
370    #[test]
371    fn the_first_commands_under_technology_decisions_wins() {
372        // the second `### Commands` under §5 is ignored
373        assert_eq!(Commands::parse(SINGLE).build.as_deref(), Some("make"));
374        // no Technology Decisions section: no commands
375        assert_eq!(
376            Commands::parse("# x\n\n### Commands\n\n- Build: `make`\n"),
377            Commands::default()
378        );
379        // a Commands heading at level 2 under nothing is not §5 either
380        assert_eq!(
381            Commands::parse("## Technology Decisions\n\n## Commands\n\n- Build: `make`\n"),
382            Commands::default()
383        );
384    }
385
386    #[test]
387    fn every_fixture_and_the_example_parse_their_commands() {
388        // every core file of the repository's fixtures with a `### Commands`
389        // heading is a well-formed SDD: its §5 Commands are all read
390        fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
391            let mut entries: Vec<_> = std::fs::read_dir(dir)
392                .unwrap()
393                .map(|e| e.unwrap().path())
394                .collect();
395            entries.sort();
396            for p in entries {
397                if p.is_dir() {
398                    walk(&p, out);
399                } else if p.extension().is_some_and(|e| e == "md") {
400                    out.push(p);
401                }
402            }
403        }
404        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
405        let mut files = Vec::new();
406        walk(&root, &mut files);
407        let mut seen = 0;
408        for f in files {
409            let text = model::read_text(&f).unwrap();
410            if !text.lines().any(|l| l == "### Commands") {
411                continue;
412            }
413            seen += 1;
414            let c = Commands::parse(&text);
415            assert!(
416                c.bootstrap.is_some() && c.build.is_some() && c.test.is_some() && c.lint.is_some(),
417                "{}: {c:?}",
418                f.display()
419            );
420        }
421        assert!(seen > 20, "{seen} fixtures");
422        let calc = model::read_text(&root.join("example/specs/calc/sdd.md")).unwrap();
423        assert_eq!(
424            Commands::parse(&calc).test.as_deref(),
425            Some("python3 -m unittest discover -s tests -t .")
426        );
427    }
428}