1use 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>, 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 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".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(), source_ref: parent.source_ref.clone(), provenance: None,
130 };
131 child.id = compute_id(&child);
132 store
133 .write_tick(&child)
134 .map_err(|e| format!("writing tick: {e}"))?;
135 Ok(child)
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 fn repo_with_unbound() -> (std::path::PathBuf, String) {
143 use std::sync::atomic::{AtomicU64, Ordering};
144 static N: AtomicU64 = AtomicU64::new(0);
145 let p = std::env::temp_dir().join(format!(
146 "ev-guard-{}-{}",
147 std::process::id(),
148 N.fetch_add(1, Ordering::Relaxed)
149 ));
150 let _ = std::fs::remove_dir_all(&p);
151 std::fs::create_dir_all(&p).unwrap();
152 Store::at(&p).init().unwrap();
153 let args: Vec<String> = [
154 "--assume",
155 "schema stays frozen",
156 "--assume",
157 "team ok",
158 "--revisit",
159 "Q3",
160 "--blame",
161 "Wang Yu",
162 ]
163 .iter()
164 .map(|x| x.to_string())
165 .collect();
166 let t = crate::capture::run(&p, Some("build our own retrieval"), &args).unwrap();
167 (p, t.id)
168 }
169 fn args(selector: &str, id: &str, target: Option<&str>) -> GuardArgs {
170 GuardArgs {
171 selector: selector.into(),
172 id: id.into(),
173 target: target.map(|s| s.into()),
174 counter_test: "pytest x::counter".into(),
175 platforms: vec!["linux-ci".into()],
176 triggered_by: vec!["f".into()],
177 surfaces: vec!["s".into()],
178 verified_at_sha: Some("d308afac1b2c3d4e5f60718293a4b5c6d7e8f901".into()),
179 blame: Some("Wang Yu".into()),
180 authority: None,
181 }
182 }
183
184 #[test]
185 fn guard_should_bind_a_named_unbound_ground_and_write_a_child_when_the_target_is_named() {
186 let (p, id) = repo_with_unbound();
188
189 let child = run(
191 &p,
192 args(
193 "pytest tests/test_schema_frozen.py",
194 &id,
195 Some("schema stays frozen"),
196 ),
197 )
198 .expect("ok");
199
200 assert_eq!(child.parent_id, id);
202 let i = child
203 .grounds
204 .iter()
205 .position(|g| g.claim == "schema stays frozen")
206 .unwrap();
207 assert!(matches!(child.grounds[i].check, Some(Check::Test { .. })));
208 }
209
210 #[test]
211 fn guard_should_still_error_without_a_counter_test() {
212 let (p, id) = repo_with_unbound();
216 let mut a = args("pytest x", &id, Some("schema stays frozen"));
217 a.counter_test = " ".into(); let e = run(&p, a);
221
222 assert!(e.is_err());
224 }
225
226 #[test]
227 fn guard_should_refuse_the_target_when_the_ground_is_human_rechecked() {
228 let (p, id) = repo_with_unbound();
230
231 let e = run(&p, args("pytest x", &id, Some("team ok")));
233
234 assert!(e.is_err());
236 }
237
238 #[test]
239 fn guard_should_require_a_target_when_more_than_one_ground_is_unbound() {
240 let (p, _id) = repo_with_unbound();
242 let t2 = crate::capture::run(
243 &p,
244 Some("d2"),
245 &["--assume", "a", "--assume", "b", "--blame", "Wang Yu"]
246 .iter()
247 .map(|x| x.to_string())
248 .collect::<Vec<_>>(),
249 )
250 .unwrap();
251
252 let e = run(&p, args("pytest x", &t2.id, None));
254
255 assert!(e.is_err());
257 }
258
259 #[test]
260 fn guard_should_refuse_the_target_when_it_is_not_head() {
261 let p = repo_with_unbound().0;
263 let t1 = crate::capture::run(
264 &p,
265 Some("d1"),
266 &["--assume", "a", "--blame", "Wang Yu"]
267 .iter()
268 .map(|x| x.to_string())
269 .collect::<Vec<_>>(),
270 )
271 .unwrap();
272 let _t2 = crate::capture::run(
273 &p,
274 Some("d2"),
275 &["--assume", "b", "--blame", "Wang Yu"]
276 .iter()
277 .map(|x| x.to_string())
278 .collect::<Vec<_>>(),
279 )
280 .unwrap();
281
282 let e = run(&p, args("pytest x", &t1.id, Some("a")));
284
285 assert!(e.is_err());
287 }
288
289 #[test]
290 fn guard_should_refuse_the_target_when_the_ground_is_a_rejected_road() {
291 let p = repo_with_unbound().0;
293 let t = crate::capture::run(
294 &p,
295 Some("d"),
296 &["--reject", "x: y", "--blame", "Wang Yu"]
297 .iter()
298 .map(|x| x.to_string())
299 .collect::<Vec<_>>(),
300 )
301 .unwrap();
302
303 let e = run(&p, args("pytest x", &t.id, Some("y")));
305
306 assert!(e.is_err());
308 }
309}