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 let Some(val) = &a.authority {
80 crate::capture::validate_authority(val)?;
81 }
82 if g.supports.starts_with("rejected:") && a.authority.as_deref() != Some("user-ruled") {
88 return Err(
89 "a rejected road can carry a tripwire test only when guarded with --authority user-ruled"
90 .into(),
91 );
92 }
93 if g.check.is_some() {
94 return Err("ground already has a check".into());
95 }
96 if a.counter_test.trim().is_empty() {
97 return Err("a test binding requires a counter-test (no vacuous binding)".into());
98 }
99 if a.platforms.is_empty() || a.triggered_by.is_empty() || a.surfaces.is_empty() {
100 return Err(
101 "a test binding requires at least one platform, triggered-by, and surface".into(),
102 );
103 }
104 let verified_at_sha = crate::capture::resolve_sha(repo, &a.verified_at_sha)?;
105 let blame = crate::capture::resolve_blame(repo, a.blame)?;
106
107 let mut grounds = parent.grounds.clone();
108 grounds[idx] = Ground {
109 claim: grounds[idx].claim.clone(),
110 supports: grounds[idx].supports.clone(),
111 check: Some(Check::Test {
112 reference: a.selector,
113 verified_at_sha,
114 counter_test: Some(a.counter_test),
115 liveness: Liveness {
116 platforms: a.platforms,
117 triggered_by: a.triggered_by,
118 surfaces: a.surfaces,
119 },
120 }),
121 };
122 let held_since = time::OffsetDateTime::now_utc()
123 .format(&time::format_description::well_known::Rfc3339)
124 .map_err(|e| format!("timestamp: {e}"))?;
125 let mut child = Tick {
126 id: String::new(),
127 parent_id: parent.id.clone(),
128 observe: parent.observe.clone(),
129 decision: parent.decision.clone(),
130 grounds,
131 status: "live".into(),
132 held_since,
133 blame,
134 authority: a.authority,
135 jurisdiction: parent.jurisdiction.clone(), source_ref: parent.source_ref.clone(), provenance: None,
140 };
141 child.id = compute_id(&child);
142 store
143 .write_tick(&child)
144 .map_err(|e| format!("writing tick: {e}"))?;
145 Ok(child)
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151
152 fn repo_with_unbound() -> (std::path::PathBuf, String) {
153 use std::sync::atomic::{AtomicU64, Ordering};
154 static N: AtomicU64 = AtomicU64::new(0);
155 let p = std::env::temp_dir().join(format!(
156 "ev-guard-{}-{}",
157 std::process::id(),
158 N.fetch_add(1, Ordering::Relaxed)
159 ));
160 let _ = std::fs::remove_dir_all(&p);
161 std::fs::create_dir_all(&p).unwrap();
162 Store::at(&p).init().unwrap();
163 let args: Vec<String> = [
164 "--assume",
165 "schema stays frozen",
166 "--assume",
167 "team ok",
168 "--revisit",
169 "Q3",
170 "--blame",
171 "Wang Yu",
172 ]
173 .iter()
174 .map(|x| x.to_string())
175 .collect();
176 let t = crate::capture::run(&p, Some("build our own retrieval"), &args).unwrap();
177 (p, t.id)
178 }
179 fn args(selector: &str, id: &str, target: Option<&str>) -> GuardArgs {
180 GuardArgs {
181 selector: selector.into(),
182 id: id.into(),
183 target: target.map(|s| s.into()),
184 counter_test: "pytest x::counter".into(),
185 platforms: vec!["linux-ci".into()],
186 triggered_by: vec!["f".into()],
187 surfaces: vec!["s".into()],
188 verified_at_sha: Some("d308afac1b2c3d4e5f60718293a4b5c6d7e8f901".into()),
189 blame: Some("Wang Yu".into()),
190 authority: None,
191 }
192 }
193
194 #[test]
195 fn guard_should_bind_a_named_unbound_ground_and_write_a_child_when_the_target_is_named() {
196 let (p, id) = repo_with_unbound();
198
199 let child = run(
201 &p,
202 args(
203 "pytest tests/test_schema_frozen.py",
204 &id,
205 Some("schema stays frozen"),
206 ),
207 )
208 .expect("ok");
209
210 assert_eq!(child.parent_id, id);
212 let i = child
213 .grounds
214 .iter()
215 .position(|g| g.claim == "schema stays frozen")
216 .unwrap();
217 assert!(matches!(child.grounds[i].check, Some(Check::Test { .. })));
218 }
219
220 #[test]
221 fn guard_should_still_error_without_a_counter_test() {
222 let (p, id) = repo_with_unbound();
226 let mut a = args("pytest x", &id, Some("schema stays frozen"));
227 a.counter_test = " ".into(); let e = run(&p, a);
231
232 assert!(e.is_err());
234 }
235
236 #[test]
237 fn guard_should_refuse_the_target_when_the_ground_is_human_rechecked() {
238 let (p, id) = repo_with_unbound();
240
241 let e = run(&p, args("pytest x", &id, Some("team ok")));
243
244 assert!(e.is_err());
246 }
247
248 #[test]
249 fn guard_should_require_a_target_when_more_than_one_ground_is_unbound() {
250 let (p, _id) = repo_with_unbound();
252 let t2 = crate::capture::run(
253 &p,
254 Some("d2"),
255 &["--assume", "a", "--assume", "b", "--blame", "Wang Yu"]
256 .iter()
257 .map(|x| x.to_string())
258 .collect::<Vec<_>>(),
259 )
260 .unwrap();
261
262 let e = run(&p, args("pytest x", &t2.id, None));
264
265 assert!(e.is_err());
267 }
268
269 #[test]
270 fn guard_should_refuse_the_target_when_it_is_not_head() {
271 let p = repo_with_unbound().0;
273 let t1 = crate::capture::run(
274 &p,
275 Some("d1"),
276 &["--assume", "a", "--blame", "Wang Yu"]
277 .iter()
278 .map(|x| x.to_string())
279 .collect::<Vec<_>>(),
280 )
281 .unwrap();
282 let _t2 = crate::capture::run(
283 &p,
284 Some("d2"),
285 &["--assume", "b", "--blame", "Wang Yu"]
286 .iter()
287 .map(|x| x.to_string())
288 .collect::<Vec<_>>(),
289 )
290 .unwrap();
291
292 let e = run(&p, args("pytest x", &t1.id, Some("a")));
294
295 assert!(e.is_err());
297 }
298
299 #[test]
300 fn guard_should_refuse_a_rejected_road_tripwire_when_authority_is_absent() {
301 let p = repo_with_unbound().0;
303 let t = crate::capture::run(
304 &p,
305 Some("d"),
306 &["--reject", "x: y", "--blame", "Wang Yu"]
307 .iter()
308 .map(|x| x.to_string())
309 .collect::<Vec<_>>(),
310 )
311 .unwrap();
312
313 let e = run(&p, args("pytest x", &t.id, Some("y")));
315
316 assert!(e.is_err());
318 }
319
320 #[test]
321 fn guard_should_bind_a_tripwire_to_a_rejected_road_when_authority_is_user_ruled() {
322 let p = repo_with_unbound().0;
324 let t = crate::capture::run(
325 &p,
326 Some("d"),
327 &["--reject", "x: y", "--blame", "Wang Yu"]
328 .iter()
329 .map(|x| x.to_string())
330 .collect::<Vec<_>>(),
331 )
332 .unwrap();
333
334 let mut a = args("pytest x", &t.id, Some("y"));
336 a.authority = Some("user-ruled".into());
337 let child = run(&p, a).expect("a user-ruled rejected-road tripwire binds");
338
339 assert_eq!(child.parent_id, t.id);
341 let g = child
342 .grounds
343 .iter()
344 .find(|g| g.supports.starts_with("rejected:"))
345 .expect("a rejected road");
346 assert!(matches!(g.check, Some(Check::Test { .. })));
347 assert_eq!(child.provenance, None);
349 }
350}