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