Skip to main content

ev/
guard.rs

1//! `ev guard "<selector>" <id> [<ground>]` — attach an existing test to a ground as a
2//! data check (after the fact). Because `check` is hashed, this writes a NEW CHILD.
3use crate::canonical::compute_id;
4use crate::store::Store;
5use crate::tick::{Check, Ground, Liveness, Tick};
6use std::path::Path;
7
8pub struct GuardArgs {
9    pub selector: String,
10    pub id: String,
11    pub target: Option<String>, // ground claim or index; required if >1 unbound ground
12    pub counter_test: String,
13    pub platforms: Vec<String>,
14    pub triggered_by: Vec<String>,
15    pub surfaces: Vec<String>,
16    pub verified_at_sha: Option<String>,
17    pub blame: Option<String>,
18    pub authority: Option<String>,
19}
20
21fn resolve_target(grounds: &[Ground], target: &Option<String>) -> Result<usize, String> {
22    let unbound: Vec<usize> = grounds
23        .iter()
24        .enumerate()
25        .filter(|(_, g)| g.check.is_none())
26        .map(|(i, _)| i)
27        .collect();
28    match target {
29        None => match unbound.as_slice() {
30            [one] => Ok(*one),
31            [] => Err("no unbound ground to guard".into()),
32            _ => Err("more than one unbound ground — name the target (claim or index)".into()),
33        },
34        Some(t) => {
35            if let Ok(idx) = t.parse::<usize>() {
36                if idx < grounds.len() {
37                    return Ok(idx);
38                }
39                return Err(format!("ground index {idx} out of range"));
40            }
41            let matches: Vec<usize> = grounds
42                .iter()
43                .enumerate()
44                .filter(|(_, g)| g.claim == *t)
45                .map(|(i, _)| i)
46                .collect();
47            match matches.as_slice() {
48                [one] => Ok(*one),
49                [] => Err(format!("no ground with claim {t:?}")),
50                _ => Err(format!("ambiguous: multiple grounds with claim {t:?}")),
51            }
52        }
53    }
54}
55
56pub fn run(repo: &Path, a: GuardArgs) -> Result<Tick, String> {
57    let store = Store::at(repo);
58    let parent = store
59        .read_tick(&a.id)
60        .map_err(|e| format!("{e}"))?
61        .ok_or(format!("no tick with id {}", a.id))?;
62    let head = store
63        .read_head()
64        .map_err(|e| format!("reading HEAD: {e}"))?;
65    if a.id != head {
66        return Err(format!(
67            "guard can only amend the current HEAD decision; {} is not HEAD ({})",
68            a.id, head
69        ));
70    }
71    let idx = resolve_target(&parent.grounds, &a.target)?;
72    let g = &parent.grounds[idx];
73    // R2: a human-rechecked (person) ground can never be force-bound to a test.
74    if let Some(Check::Person { .. }) = g.check {
75        return Err("a human-rechecked ground cannot carry a test (R2 hard error)".into());
76    }
77    if g.supports.starts_with("rejected:") {
78        return Err("a road-not-taken (rejected) ground cannot carry a test in 0.1.0 — reserved for a future rejection-rationale liveness feature".into());
79    }
80    if g.check.is_some() {
81        return Err("ground already has a check".into());
82    }
83    if a.counter_test.trim().is_empty() {
84        return Err("a test binding requires a counter-test (no vacuous binding)".into());
85    }
86    if a.platforms.is_empty() || a.triggered_by.is_empty() || a.surfaces.is_empty() {
87        return Err(
88            "a test binding requires at least one platform, triggered-by, and surface".into(),
89        );
90    }
91    if let Some(val) = &a.authority {
92        crate::capture::validate_authority(val)?;
93    }
94    let verified_at_sha = crate::capture::resolve_sha(repo, &a.verified_at_sha)?;
95    let blame = crate::capture::resolve_blame(repo, a.blame)?;
96
97    let mut grounds = parent.grounds.clone();
98    grounds[idx] = Ground {
99        claim: grounds[idx].claim.clone(),
100        supports: grounds[idx].supports.clone(),
101        check: Some(Check::Test {
102            reference: a.selector,
103            verified_at_sha,
104            counter_test: Some(a.counter_test),
105            liveness: Liveness {
106                platforms: a.platforms,
107                triggered_by: a.triggered_by,
108                surfaces: a.surfaces,
109            },
110        }),
111    };
112    let held_since = time::OffsetDateTime::now_utc()
113        .format(&time::format_description::well_known::Rfc3339)
114        .map_err(|e| format!("timestamp: {e}"))?;
115    let mut child = Tick {
116        id: String::new(),
117        parent_id: parent.id.clone(),
118        observe: parent.observe.clone(),
119        decision: parent.decision.clone(),
120        grounds,
121        status: "live".into(),
122        held_since,
123        blame,
124        authority: a.authority,
125        jurisdiction: parent.jurisdiction.clone(), // a sibling tag of the decision; inherited by the child
126        round_id: parent.round_id.clone(), // the join/dedup key of the decision; inherited by the child
127    };
128    child.id = compute_id(&child);
129    store
130        .write_tick(&child)
131        .map_err(|e| format!("writing tick: {e}"))?;
132    Ok(child)
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    fn repo_with_unbound() -> (std::path::PathBuf, String) {
140        use std::sync::atomic::{AtomicU64, Ordering};
141        static N: AtomicU64 = AtomicU64::new(0);
142        let p = std::env::temp_dir().join(format!(
143            "ev-guard-{}-{}",
144            std::process::id(),
145            N.fetch_add(1, Ordering::Relaxed)
146        ));
147        let _ = std::fs::remove_dir_all(&p);
148        std::fs::create_dir_all(&p).unwrap();
149        Store::at(&p).init().unwrap();
150        let args: Vec<String> = [
151            "--assume",
152            "schema stays frozen",
153            "--assume",
154            "team ok",
155            "--revisit",
156            "Q3",
157            "--blame",
158            "Wang Yu",
159        ]
160        .iter()
161        .map(|x| x.to_string())
162        .collect();
163        let t = crate::capture::run(&p, Some("build our own retrieval"), &args).unwrap();
164        (p, t.id)
165    }
166    fn args(selector: &str, id: &str, target: Option<&str>) -> GuardArgs {
167        GuardArgs {
168            selector: selector.into(),
169            id: id.into(),
170            target: target.map(|s| s.into()),
171            counter_test: "pytest x::counter".into(),
172            platforms: vec!["linux-ci".into()],
173            triggered_by: vec!["f".into()],
174            surfaces: vec!["s".into()],
175            verified_at_sha: Some("d308afac1b2c3d4e5f60718293a4b5c6d7e8f901".into()),
176            blame: Some("Wang Yu".into()),
177            authority: None,
178        }
179    }
180
181    #[test]
182    fn guard_should_bind_a_named_unbound_ground_and_write_a_child_when_the_target_is_named() {
183        // given: a HEAD tick with an unbound "schema stays frozen" ground
184        let (p, id) = repo_with_unbound();
185
186        // when: that named ground is guarded
187        let child = run(
188            &p,
189            args(
190                "pytest tests/test_schema_frozen.py",
191                &id,
192                Some("schema stays frozen"),
193            ),
194        )
195        .expect("ok");
196
197        // then: a child is written and the named ground now carries a test check
198        assert_eq!(child.parent_id, id);
199        let i = child
200            .grounds
201            .iter()
202            .position(|g| g.claim == "schema stays frozen")
203            .unwrap();
204        assert!(matches!(child.grounds[i].check, Some(Check::Test { .. })));
205    }
206
207    #[test]
208    fn guard_should_still_error_without_a_counter_test() {
209        // given: the migrate-only harvested path now exists; pin that the guard path is UNCHANGED
210        // — guard.rs:83-85 stays byte-for-byte strict, so an empty counter-test STILL errors here
211        // (harvesting drops the counter-test ONLY on the migrate path, never on `ev guard`).
212        let (p, id) = repo_with_unbound();
213        let mut a = args("pytest x", &id, Some("schema stays frozen"));
214        a.counter_test = "   ".into(); // an empty/whitespace counter-test is a vacuous binding
215
216        // when: that ground is guarded with no real counter-test
217        let e = run(&p, a);
218
219        // then: it errors — no vacuous binding on the guard path
220        assert!(e.is_err());
221    }
222
223    #[test]
224    fn guard_should_refuse_the_target_when_the_ground_is_human_rechecked() {
225        // given: a HEAD tick whose "team ok" ground is a human-rechecked (person) check
226        let (p, id) = repo_with_unbound();
227
228        // when: that person ground is guarded with a test
229        let e = run(&p, args("pytest x", &id, Some("team ok")));
230
231        // then: it is refused
232        assert!(e.is_err());
233    }
234
235    #[test]
236    fn guard_should_require_a_target_when_more_than_one_ground_is_unbound() {
237        // given: a HEAD tick with two unbound grounds and no target named
238        let (p, _id) = repo_with_unbound();
239        let t2 = crate::capture::run(
240            &p,
241            Some("d2"),
242            &["--assume", "a", "--assume", "b", "--blame", "Wang Yu"]
243                .iter()
244                .map(|x| x.to_string())
245                .collect::<Vec<_>>(),
246        )
247        .unwrap();
248
249        // when: the guard is run without naming a target
250        let e = run(&p, args("pytest x", &t2.id, None));
251
252        // then: it is refused
253        assert!(e.is_err());
254    }
255
256    #[test]
257    fn guard_should_refuse_the_target_when_it_is_not_head() {
258        // given: two decisions in a chain, so the first is no longer HEAD
259        let p = repo_with_unbound().0;
260        let t1 = crate::capture::run(
261            &p,
262            Some("d1"),
263            &["--assume", "a", "--blame", "Wang Yu"]
264                .iter()
265                .map(|x| x.to_string())
266                .collect::<Vec<_>>(),
267        )
268        .unwrap();
269        let _t2 = crate::capture::run(
270            &p,
271            Some("d2"),
272            &["--assume", "b", "--blame", "Wang Yu"]
273                .iter()
274                .map(|x| x.to_string())
275                .collect::<Vec<_>>(),
276        )
277        .unwrap();
278
279        // when: the non-HEAD first tick is guarded
280        let e = run(&p, args("pytest x", &t1.id, Some("a")));
281
282        // then: it is refused
283        assert!(e.is_err());
284    }
285
286    #[test]
287    fn guard_should_refuse_the_target_when_the_ground_is_a_rejected_road() {
288        // given: a HEAD tick whose only ground is a rejected road
289        let p = repo_with_unbound().0;
290        let t = crate::capture::run(
291            &p,
292            Some("d"),
293            &["--reject", "x: y", "--blame", "Wang Yu"]
294                .iter()
295                .map(|x| x.to_string())
296                .collect::<Vec<_>>(),
297        )
298        .unwrap();
299
300        // when: that rejected ground is guarded with a test
301        let e = run(&p, args("pytest x", &t.id, Some("y")));
302
303        // then: it is refused
304        assert!(e.is_err());
305    }
306}