1use std::collections::{HashMap, HashSet};
87use std::path::PathBuf;
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub(crate) struct GateNames {
97 pub format: &'static str,
99 pub notes_ref: &'static str,
101 pub inputs_ref: &'static str,
103 pub cluster_ref: &'static str,
105 pub done_ref: &'static str,
107 pub canon_domain: &'static str,
109 pub attest: greensummit::format::Names,
112}
113
114pub(crate) const GREEN: GateNames = GateNames {
118 format: "greengate-gate-v1",
119 notes_ref: "greengate-gate",
120 inputs_ref: "greengate-gate-inputs",
121 cluster_ref: "greengate-gate-cluster",
122 done_ref: "greengate-gate-done",
123 canon_domain: "greengate-gate-canon",
124 attest: greensummit::format::SUMMIT,
125};
126
127pub(crate) const WRITE: GateNames = GREEN;
131
132pub const FORMAT: &str = WRITE.format;
136
137pub const NOTES_REF: &str = WRITE.notes_ref;
139
140pub const NOTES_FULL_REF: &str = "refs/notes/greengate-gate";
143
144pub const INPUTS_REF: &str = WRITE.inputs_ref;
152
153pub const CLUSTER_REF: &str = WRITE.cluster_ref;
158pub const CLUSTER_FULL_REF: &str = "refs/notes/greengate-gate-cluster";
159
160pub const DONE_REF: &str = WRITE.done_ref;
168pub const DONE_FULL_REF: &str = "refs/notes/greengate-gate-done";
169
170pub const PROVENANCE: &str = "provenance";
174pub const INPUTS_FULL_REF: &str = "refs/notes/greengate-gate-inputs";
175
176const MARKER: &str = crate::names::GATE_MARKER;
178
179const PUSH_STAMPS: &str = "greengate.pushStamps";
183
184pub fn push_stamps_enabled(settings: &crate::config::Settings) -> bool {
186 crate::config::boolean_or(settings, PUSH_STAMPS, true)
187}
188
189const COMMIT_STAMPS: &str = "greengate.commitStamps";
194
195pub fn commit_stamps_enabled(settings: &crate::config::Settings) -> bool {
198 crate::config::boolean_or(settings, COMMIT_STAMPS, true)
199}
200
201const RUN: &str = "run";
204
205const MAX_RUNS: usize = 64;
210
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum RunOutcome {
219 Passed,
220 Failed,
221 Warned,
222 Fixed,
223 Unavailable,
224 Inert,
225 Cold,
229 Busy,
231 Skew,
233 Withheld,
236 Cancelled,
238 Slow,
241 Deferred,
243}
244
245impl RunOutcome {
246 pub fn as_str(self) -> &'static str {
247 match self {
248 RunOutcome::Passed => "pass",
249 RunOutcome::Failed => "fail",
250 RunOutcome::Warned => "warn",
251 RunOutcome::Fixed => "fixed",
252 RunOutcome::Unavailable => "unavailable",
253 RunOutcome::Inert => "inert",
254 RunOutcome::Cold => "cold",
255 RunOutcome::Busy => "busy",
256 RunOutcome::Skew => "skew",
257 RunOutcome::Withheld => "withheld",
258 RunOutcome::Cancelled => "cancelled",
259 RunOutcome::Slow => "slow",
260 RunOutcome::Deferred => "deferred",
261 }
262 }
263
264 pub fn parse(s: &str) -> Option<RunOutcome> {
268 Some(match s {
269 "pass" => RunOutcome::Passed,
270 "fail" => RunOutcome::Failed,
271 "warn" => RunOutcome::Warned,
272 "fixed" => RunOutcome::Fixed,
273 "unavailable" => RunOutcome::Unavailable,
274 "inert" => RunOutcome::Inert,
275 "cold" => RunOutcome::Cold,
276 "busy" => RunOutcome::Busy,
277 "skew" => RunOutcome::Skew,
278 "withheld" => RunOutcome::Withheld,
279 "cancelled" => RunOutcome::Cancelled,
280 "slow" => RunOutcome::Slow,
281 "deferred" => RunOutcome::Deferred,
282 _ => return None,
283 })
284 }
285
286 pub fn is_verdict(self) -> bool {
290 matches!(self, RunOutcome::Passed | RunOutcome::Failed)
291 }
292}
293
294#[derive(Debug, Clone, PartialEq, Eq)]
301pub struct Run {
302 pub at: u64,
304 pub gate: String,
305 pub outcome: RunOutcome,
306 pub ms: u64,
307}
308
309impl Run {
310 fn render(&self) -> String {
311 format!(
312 "{RUN} {} {} {} {}",
313 self.at,
314 self.gate,
315 self.outcome.as_str(),
316 self.ms
317 )
318 }
319
320 fn parse(line: &str) -> Option<Run> {
323 let mut t = line.split_whitespace();
324 if t.next() != Some(RUN) {
325 return None;
326 }
327 let at = t.next()?.parse().ok()?;
328 let gate = t.next()?.to_string();
329 let outcome = RunOutcome::parse(t.next()?)?;
330 let ms = t.next()?.parse().ok()?;
331 Some(Run {
332 at,
333 gate,
334 outcome,
335 ms,
336 })
337 }
338}
339
340#[derive(Debug, Clone, Default, PartialEq, Eq)]
349pub struct Note {
350 pub tokens: Vec<String>,
351 pub deferred: Vec<String>,
354 pub runs: Vec<Run>,
355 pub provenance: Vec<String>,
357}
358
359const DEFERRED: &str = "deferred";
361
362impl Note {
363 pub fn parse(body: &str) -> Note {
367 Note::parse_as(body, FORMAT)
368 }
369
370 pub(crate) fn parse_as(body: &str, format: &str) -> Note {
374 let mut lines = body.lines();
375 let Some(first) = lines.next() else {
376 return Note::default();
377 };
378 let mut tokens = first.split_whitespace();
379 if tokens.next() != Some(format) {
380 return Note::default();
381 }
382 let mut deferred = Vec::new();
383 let mut runs = Vec::new();
384 let mut provenance = Vec::new();
385 for line in lines {
386 if is_provenance(line) {
387 provenance.push(line.trim().to_string());
388 continue;
389 }
390 let mut t = line.split_whitespace();
391 match (t.next(), t.next(), t.next()) {
392 (Some(DEFERRED), Some(gate), None) => {
393 if !deferred.iter().any(|d| d == gate) {
394 deferred.push(gate.to_string());
395 }
396 }
397 _ => runs.extend(Run::parse(line)),
398 }
399 }
400 Note {
401 tokens: tokens.map(str::to_string).collect(),
402 deferred,
403 runs,
404 provenance,
405 }
406 }
407
408 pub fn render(&self) -> String {
411 let mut body = format!("{FORMAT} {}", self.tokens.join(" "));
412 for gate in &self.deferred {
413 body.push('\n');
414 body.push_str(&format!("{DEFERRED} {gate}"));
415 }
416 for run in &self.runs {
417 body.push('\n');
418 body.push_str(&run.render());
419 }
420 for line in &self.provenance {
421 body.push('\n');
422 body.push_str(line);
423 }
424 body
425 }
426
427 fn add_tokens(&mut self, tokens: &[String]) {
428 for t in tokens {
429 if !self.tokens.iter().any(|have| have == t) {
430 self.tokens.push(t.clone());
431 }
432 }
433 }
434
435 fn add_runs(&mut self, runs: &[Run]) {
437 self.runs.extend(runs.iter().cloned());
438 if self.runs.len() > MAX_RUNS {
439 self.runs.drain(..self.runs.len() - MAX_RUNS);
440 }
441 }
442}
443
444pub fn is_provenance(line: &str) -> bool {
447 line.split_whitespace().next() == Some(PROVENANCE)
448}
449
450fn note_at(key: &str) -> Note {
456 note_in(NOTES_REF, key)
457}
458
459fn note_in(notes_ref: &str, key: &str) -> Note {
460 crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
461 .map(|body| Note::parse(&body))
462 .unwrap_or_default()
463}
464
465fn stamp_in(which: fn(&GateNames) -> &'static str, key: &str) -> Note {
469 read_in(&WRITE, which(&WRITE), key).unwrap_or_default()
470}
471
472fn read_in(set: &GateNames, notes_ref: &str, key: &str) -> Option<Note> {
479 crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
480 .map(|body| Note::parse_as(&body, set.format))
481}
482
483fn stamp_at(key: &str) -> Note {
485 stamp_in(|s| s.notes_ref, key)
486}
487
488fn input_tokens(tree: &str) -> Vec<String> {
497 let Some(spec) = crate::attest_inputs::spec_at(tree) else {
498 return canon_tokens(tree);
499 };
500 let mut out: Vec<String> = Vec::new();
501 for (gate, _) in &spec.gates {
502 if !manifest_is_an_input(tree, &spec, gate) {
503 continue;
504 }
505 let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
506 continue;
507 };
508 let note = crate::attest_inputs::input_key(&WRITE.attest, gate, &fp)
510 .and_then(|key| read_in(&WRITE, WRITE.inputs_ref, &key));
511 for t in note.unwrap_or_default().tokens {
512 if crate::gate_identity::base(&t) == gate.as_str() && !out.contains(&t) {
513 out.push(t);
514 }
515 }
516 }
517 out
518}
519
520fn canon_tokens(tree: &str) -> Vec<String> {
527 let Some(canon) = crate::attest_inputs::canonical_route(tree) else {
528 return Vec::new();
529 };
530 crate::attest_inputs::canon_gate_key(WRITE.canon_domain, &canon)
531 .and_then(|key| read_in(&WRITE, WRITE.inputs_ref, &key))
532 .map(|note| note.tokens)
533 .unwrap_or_default()
534}
535
536fn canon_key_of(tree: &str) -> Option<String> {
539 let canon = crate::attest_inputs::canonical_route(tree)?;
540 crate::attest_inputs::canon_gate_key(WRITE.canon_domain, &canon)
541}
542
543fn file_canon(tree: &str, tokens: &[String]) {
547 let Some(key) = canon_key_of(tree) else {
548 return;
549 };
550 let mut note = note_in(INPUTS_REF, &key);
551 note.add_tokens(tokens);
552 let _ = write_note_in(INPUTS_REF, &key, ¬e);
553}
554
555fn file_inputs(tree: &str, tokens: &[String]) {
560 if tokens.is_empty() {
561 return;
562 }
563 let Some(spec) = crate::attest_inputs::spec_at(tree) else {
564 file_canon(tree, tokens);
565 return;
566 };
567 for (gate, _) in &spec.gates {
568 let mine: Vec<String> = tokens
569 .iter()
570 .filter(|t| crate::gate_identity::base(t) == gate.as_str())
571 .cloned()
572 .collect();
573 if mine.is_empty() || !manifest_is_an_input(tree, &spec, gate) {
574 continue;
575 }
576 let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
577 continue;
578 };
579 let Some(key) = crate::attest_inputs::input_key(&WRITE.attest, gate, &fp) else {
580 continue;
581 };
582 let mut note = note_in(INPUTS_REF, &key);
583 note.add_tokens(&mine);
584 let _ = write_note_in(INPUTS_REF, &key, ¬e);
585 }
586}
587
588fn manifest_is_an_input(tree: &str, spec: &crate::attest_inputs::Spec, gate: &str) -> bool {
594 let tracked = [crate::manifest::MANIFEST, crate::names::old::MANIFEST]
596 .into_iter()
597 .find(|name| crate::git::succeeds(&["cat-file", "-e", &format!("{tree}:{name}")]));
598 tracked.map_or(true, |name| {
599 crate::attest_inputs::declares(spec, gate, name)
600 })
601}
602
603fn inputs_ref_exists() -> bool {
608 crate::git::succeeds(&[
609 "rev-parse",
610 "-q",
611 "--verify",
612 &format!("refs/notes/{}", WRITE.inputs_ref),
613 ])
614}
615
616pub fn tree_tokens(tree: &str) -> Vec<String> {
620 let mut tokens = stamp_at(tree).tokens;
621 if inputs_ref_exists() {
622 for t in input_tokens(tree) {
623 if !tokens.contains(&t) {
624 tokens.push(t);
625 }
626 }
627 }
628 tokens
629}
630
631pub fn stamp_tree(tree: &str, tokens: &[String]) -> bool {
635 let mut note = note_at(tree);
636 note.add_tokens(tokens);
637 let ok = write_note(tree, ¬e);
638 file_inputs(tree, tokens);
639 ok
640}
641
642fn write_note(key: &str, note: &Note) -> bool {
644 write_note_in(NOTES_REF, key, note)
645}
646
647fn write_note_in(notes_ref: &str, key: &str, note: &Note) -> bool {
648 let body = note.render();
649 crate::git::succeeds(&["notes", "--ref", notes_ref, "add", "-f", "-m", &body, key])
650}
651
652pub fn record_runs(key: &str, runs: &[Run]) {
663 let runs: Vec<Run> = runs
668 .iter()
669 .filter(|r| !r.gate.is_empty() && !r.gate.contains(char::is_whitespace))
670 .cloned()
671 .collect();
672 if runs.is_empty() {
673 return;
674 }
675 let mut note = note_at(key);
676 note.add_runs(&runs);
677 let _ = write_note(key, ¬e);
678}
679
680pub fn record_deferred(tree: &str, gates: &[String]) {
684 let gates: Vec<&String> = gates
685 .iter()
686 .filter(|g| !g.is_empty() && !g.contains(char::is_whitespace))
687 .collect();
688 if gates.is_empty() {
689 return;
690 }
691 let mut note = note_at(tree);
692 for g in gates {
693 if !note.deferred.contains(g) {
694 note.deferred.push(g.clone());
695 }
696 }
697 let _ = write_note(tree, ¬e); }
699
700pub fn deferred_on(tree: &str) -> Vec<String> {
703 stamp_at(tree).deferred
704}
705
706pub fn deferred_for(commits: &[String], gate: &str) -> HashSet<String> {
710 let mut out = HashSet::new();
711 if commits.is_empty() {
712 return out;
713 }
714 let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
715 args.extend(commits.iter().map(String::as_str));
716 let Some(list) = crate::git::stdout(&args) else {
717 return out;
718 };
719 for line in list.lines() {
720 let mut it = line.split_whitespace();
721 let (Some(commit), Some(tree)) = (it.next(), it.next()) else {
722 continue;
723 };
724 if [commit, tree]
725 .iter()
726 .any(|key| stamp_at(key).deferred.iter().any(|d| d == gate))
727 {
728 out.insert(commit.to_string());
729 }
730 }
731 out
732}
733
734fn marker_path() -> Option<PathBuf> {
738 let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
739 Some(std::path::Path::new(&dir).join(MARKER))
740}
741
742pub fn record(scripts: &[&str]) {
753 let Some(path) = marker_path() else { return };
754 if scripts.is_empty() {
755 let _ = std::fs::remove_file(&path);
756 return;
757 }
758 let Some(tree) = crate::git::stdout(&["write-tree"]) else {
762 crate::hooks::common::warn(
766 "git would not name the staged tree — this commit records no gate stamp",
767 );
768 let _ = std::fs::remove_file(&path);
769 return;
770 };
771 let mut body = format!("{FORMAT}\n{tree}\n");
772 for s in scripts {
773 body.push_str(s);
774 body.push('\n');
775 }
776 let _ = std::fs::write(&path, body);
777}
778
779pub fn vouched_for_staged_tree() -> HashSet<String> {
807 let mut out = HashSet::new();
808 let Some(tree) = crate::git::stdout(&["write-tree"]) else {
809 return out;
810 };
811 if let Some(path) = marker_path() {
812 if let Ok(body) = std::fs::read_to_string(&path) {
813 let mut lines = body.lines();
814 if lines.next() == Some(FORMAT) && lines.next() == Some(tree.as_str()) {
815 out.extend(
816 lines
817 .filter(|l| !l.trim().is_empty() && !is_provenance(l))
818 .map(str::to_string),
819 );
820 }
821 }
822 }
823 out.extend(stamp_at(&tree).tokens);
832 if inputs_ref_exists() {
838 out.extend(input_tokens(&tree));
839 }
840 out
841}
842
843pub fn bind_to_head() -> Vec<String> {
854 let Some(path) = marker_path() else {
855 return Vec::new();
856 };
857 let Ok(body) = std::fs::read_to_string(&path) else {
858 return Vec::new(); };
860 let _ = std::fs::remove_file(&path);
861 let mut lines = body.lines();
862 if lines.next() != Some(FORMAT) {
863 return Vec::new();
864 }
865 let Some(tree) = lines.next() else {
866 return Vec::new();
867 };
868 let scripts: Vec<&str> = lines
869 .filter(|l| !l.trim().is_empty() && !is_provenance(l))
870 .collect();
871 if scripts.is_empty() {
872 return Vec::new();
873 }
874 let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
875 crate::hooks::common::warn(
876 "git would not name this commit's tree — no gate stamp was written",
877 );
878 return Vec::new();
879 };
880 if head_tree != tree {
883 return Vec::new();
884 }
885 let scripts: Vec<String> = scripts.iter().map(|s| s.to_string()).collect();
886 let mut tree_note = note_at(&head_tree);
911 tree_note.add_tokens(&scripts);
912 let _ = write_note(&head_tree, &tree_note);
913 file_inputs(&head_tree, &scripts);
914 let mut head_note = note_at("HEAD");
915 head_note.add_tokens(&scripts);
916 if !write_note("HEAD", &head_note) {
917 crate::hooks::common::warn(
920 "git refused to write the gate stamp — these checks will run again at push",
921 );
922 return Vec::new();
923 }
924 scripts
927 .iter()
928 .map(|s| crate::gate_identity::base(s).to_string())
929 .collect()
930}
931
932pub fn stamp_push(commit: &str, tree: &str, gates: &[String]) -> bool {
941 if gates.is_empty() {
942 return false;
943 }
944 let mut written = false;
945 for key in [tree, commit] {
946 let mut note = note_at(key);
947 note.add_tokens(gates);
948 let ok = write_note(key, ¬e);
949 if key == commit {
950 written = ok;
951 }
952 }
953 file_inputs(tree, gates);
954 if !written {
955 crate::hooks::common::warn(
956 "git refused to write the push stamp — these gates will run again on the next push",
957 );
958 }
959 written
960}
961
962#[derive(Debug, Clone, Copy, PartialEq, Eq)]
965pub enum Completion {
966 Warned,
968 FailedUnderWarn,
971 Unavailable,
974 Deferred,
979}
980
981const UNAVAILABLE_FOR_SECS: u64 = 60 * 60;
983
984fn completion_word(how: Completion, token: &str, now: u64) -> String {
986 match how {
987 Completion::Warned => format!("warned:{token}"),
988 Completion::FailedUnderWarn => format!("failed-under-warn:{token}"),
989 Completion::Unavailable => format!("unavailable:{now}:{token}"),
990 Completion::Deferred => format!("deferred:{now}:{token}"),
991 }
992}
993
994fn completion_answers(word: &str, token: &str, severity: crate::check::Severity, now: u64) -> bool {
996 if word.strip_prefix("warned:") == Some(token) {
997 return true;
998 }
999 if word.strip_prefix("failed-under-warn:") == Some(token) {
1000 return severity == crate::check::Severity::Warn;
1001 }
1002 word.strip_prefix("unavailable:")
1003 .or_else(|| word.strip_prefix("deferred:"))
1004 .and_then(|rest| rest.split_once(':'))
1005 .is_some_and(|(at, tok)| {
1006 tok == token
1007 && at
1008 .parse::<u64>()
1009 .is_ok_and(|at| now.saturating_sub(at) <= UNAVAILABLE_FOR_SECS)
1010 })
1011}
1012
1013fn now_secs() -> u64 {
1014 std::time::SystemTime::now()
1015 .duration_since(std::time::UNIX_EPOCH)
1016 .map(|d| d.as_secs())
1017 .unwrap_or(0)
1018}
1019
1020pub fn record_done(tree: &str, tokens: &[String], how: Completion) -> Result<(), String> {
1026 if tokens.is_empty() {
1027 return Ok(());
1028 }
1029 let now = now_secs();
1030 let mut note = note_in(DONE_REF, tree);
1031 let dated = match how {
1032 Completion::Unavailable => Some("unavailable:"),
1033 Completion::Deferred => Some("deferred:"),
1034 Completion::Warned | Completion::FailedUnderWarn => None,
1035 };
1036 if let Some(prefix) = dated {
1037 note.tokens.retain(|word| {
1038 !word
1039 .strip_prefix(prefix)
1040 .and_then(|rest| rest.split_once(':'))
1041 .is_some_and(|(_, token)| tokens.iter().any(|t| t == token))
1042 });
1043 }
1044 let words: Vec<String> = tokens
1045 .iter()
1046 .map(|t| completion_word(how, t, now))
1047 .collect();
1048 note.add_tokens(&words);
1049 if write_note_in(DONE_REF, tree, ¬e) {
1050 Ok(())
1051 } else {
1052 Err(format!(
1053 "git refused to record the completed gates on {tree}"
1054 ))
1055 }
1056}
1057
1058pub fn done_on_every(commits: &[String], token: &str, severity: crate::check::Severity) -> bool {
1063 let now = now_secs();
1064 !commits.is_empty()
1065 && commits.iter().all(|c| {
1066 crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]).is_some_and(|tree| {
1067 stamp_in(|s| s.done_ref, &tree)
1068 .tokens
1069 .iter()
1070 .any(|word| completion_answers(word, token, severity, now))
1071 })
1072 })
1073}
1074
1075pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
1081 let mut out = HashMap::new();
1082 if commits.is_empty() {
1083 return out;
1084 }
1085 let Some(list) = crate::git::stdout(&["notes", "--ref", WRITE.notes_ref, "list"]) else {
1086 crate::hooks::common::warn(
1096 "git would not list the gate stamps — every gated check will run again",
1097 );
1098 return out;
1099 };
1100 let noted: HashSet<&str> = list
1101 .lines()
1102 .filter_map(|l| l.split_whitespace().nth(1))
1103 .collect();
1104 let mut trees: HashMap<String, String> = HashMap::new();
1108 {
1109 let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
1110 args.extend(commits.iter().map(String::as_str));
1111 if let Some(out) = crate::git::stdout(&args) {
1112 for line in out.lines() {
1113 let mut it = line.split_whitespace();
1114 if let (Some(c), Some(t)) = (it.next(), it.next()) {
1115 trees.insert(c.to_string(), t.to_string());
1116 }
1117 }
1118 }
1119 }
1123
1124 let by_inputs = inputs_ref_exists();
1130
1131 for commit in commits {
1132 let mut tokens: Vec<String> = Vec::new();
1151 let mut keys: Vec<&str> = Vec::new();
1152 if noted.contains(commit.as_str()) {
1153 keys.push(commit);
1154 }
1155 if let Some(tree) = trees.get(commit).filter(|t| noted.contains(t.as_str())) {
1156 keys.push(tree);
1157 }
1158 for key in keys {
1159 for t in stamp_at(key).tokens {
1160 if !tokens.contains(&t) {
1161 tokens.push(t);
1162 }
1163 }
1164 }
1165 if by_inputs {
1166 if let Some(tree) = trees.get(commit) {
1167 for t in input_tokens(tree) {
1168 if !tokens.contains(&t) {
1169 tokens.push(t);
1170 }
1171 }
1172 }
1173 }
1174 if tokens.is_empty() {
1175 continue;
1176 }
1177 out.insert(commit.clone(), tokens);
1178 }
1179 out
1180}
1181
1182pub fn forget() -> bool {
1187 let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
1188 let mut deleted = false;
1190 for r in full_refs(&WRITE) {
1191 deleted |= crate::git::succeeds(&["update-ref", "-d", &r]);
1192 }
1193 marker || deleted
1194}
1195
1196fn full_refs(set: &GateNames) -> [String; 4] {
1198 [set.notes_ref, set.inputs_ref, set.cluster_ref, set.done_ref]
1199 .map(|short| format!("refs/notes/{short}"))
1200}
1201
1202pub(crate) fn cluster_tokens(tree: &str) -> Vec<String> {
1205 stamp_in(|s| s.cluster_ref, tree).tokens
1206}
1207
1208pub(crate) fn stamp_cluster(tree: &str, token: &str, provenance: &str) -> bool {
1211 let mut note = note_in(CLUSTER_REF, tree);
1212 note.add_tokens(&[token.to_string()]);
1213 let line = format!("{PROVENANCE} {token} {provenance}");
1214 note.provenance
1215 .retain(|l| l.split_whitespace().nth(1) != Some(token));
1216 note.provenance.push(line);
1217 write_note_in(CLUSTER_REF, tree, ¬e)
1218}
1219
1220pub(crate) fn cluster_stamps_for(commits: &[String]) -> HashMap<String, (String, Vec<String>)> {
1224 let mut out = HashMap::new();
1225 for commit in commits {
1226 let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")]) else {
1227 continue;
1228 };
1229 let tokens = cluster_tokens(&tree);
1230 if !tokens.is_empty() {
1231 out.insert(commit.clone(), (tree, tokens));
1232 }
1233 }
1234 out
1235}
1236
1237pub fn forget_in(repo: &std::path::Path) -> bool {
1239 let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
1240 .is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
1241 let mut deleted = false;
1242 for r in full_refs(&WRITE) {
1243 deleted |= crate::git::succeeds_in(repo, &["update-ref", "-d", &r]);
1244 }
1245 marker || deleted
1246}
1247
1248#[cfg(test)]
1249mod tests {
1250 use super::*;
1251 use std::path::Path;
1252
1253 #[test]
1257 fn a_completion_answers_only_while_it_should() {
1258 use crate::check::Severity::{Block, Warn};
1259 let now = 1_700_000_000;
1260 let word = |how| completion_word(how, "gate-tok", now);
1261 assert!(completion_answers(
1262 &word(Completion::Warned),
1263 "gate-tok",
1264 Block,
1265 now
1266 ));
1267 assert!(completion_answers(
1268 &word(Completion::FailedUnderWarn),
1269 "gate-tok",
1270 Warn,
1271 now
1272 ));
1273 assert!(!completion_answers(
1274 &word(Completion::FailedUnderWarn),
1275 "gate-tok",
1276 Block,
1277 now
1278 ));
1279 let unavailable = word(Completion::Unavailable);
1280 assert!(completion_answers(
1281 &unavailable,
1282 "gate-tok",
1283 Block,
1284 now + 3600
1285 ));
1286 assert!(!completion_answers(
1287 &unavailable,
1288 "gate-tok",
1289 Block,
1290 now + 3601
1291 ));
1292 let deferred = word(Completion::Deferred);
1294 assert!(deferred.starts_with("deferred:"), "{deferred}");
1295 assert!(completion_answers(&deferred, "gate-tok", Block, now + 3600));
1296 assert!(!completion_answers(
1297 &deferred,
1298 "gate-tok",
1299 Block,
1300 now + 3601
1301 ));
1302 assert!(!completion_answers(&deferred, "other-tok", Warn, now));
1303 assert!(!completion_answers(
1304 &word(Completion::Warned),
1305 "other-tok",
1306 Warn,
1307 now
1308 ));
1309 }
1310
1311 fn repo(name: &str) -> PathBuf {
1314 let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
1315 let _ = std::fs::remove_dir_all(&dir);
1316 std::fs::create_dir_all(&dir).unwrap();
1317 git(&dir, &["init", "-q", "--template=", "."]);
1318 git(&dir, &["config", "user.email", "t@t.test"]);
1319 git(&dir, &["config", "user.name", "t"]);
1320 dir
1321 }
1322
1323 fn git(dir: &Path, args: &[&str]) -> String {
1332 let out = std::process::Command::new("git")
1333 .arg("-C")
1334 .arg(dir)
1335 .args(args)
1336 .output()
1337 .expect("git");
1338 assert!(
1339 out.status.success(),
1340 "fixture: git {args:?} in {} exited {:?}: {}",
1341 dir.display(),
1342 out.status.code(),
1343 String::from_utf8_lossy(&out.stderr).trim()
1344 );
1345 String::from_utf8_lossy(&out.stdout).trim().to_string()
1346 }
1347
1348 fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
1352 let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
1353 let prev = std::env::current_dir().unwrap();
1354 std::env::set_current_dir(dir).unwrap();
1355 let r = f();
1356 std::env::set_current_dir(prev).unwrap();
1357 r
1358 }
1359
1360 #[test]
1361 fn the_commit_note_does_not_hide_the_tree_notes_push_tokens() {
1362 let dir = repo("union");
1363 std::fs::write(dir.join("a.ts"), "x").unwrap();
1364 git(&dir, &["add", "a.ts"]);
1365 in_repo(&dir, || {
1366 record(&["test"]);
1367 git(&dir, &["commit", "-qm", "chore: a"]);
1368 bind_to_head();
1369 let head = git(&dir, &["rev-parse", "HEAD"]);
1370 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1371 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1374 assert_eq!(note_at(&head).tokens, vec!["test".to_string()]);
1375 let stamps = stamps_for(std::slice::from_ref(&head));
1376 assert_eq!(
1377 stamps.get(&head).map(Vec::as_slice),
1378 Some(&["test".to_string(), "pre-push-cargo-test".to_string()][..]),
1379 "both notes speak for the same tree"
1380 );
1381 });
1382 let _ = std::fs::remove_dir_all(&dir);
1383 }
1384
1385 #[test]
1389 fn an_unavailable_record_replaces_its_predecessor_only() {
1390 let dir = repo("done-unavailable");
1391 std::fs::write(dir.join("a.ts"), "x").unwrap();
1392 git(&dir, &["add", "a.ts"]);
1393 git(&dir, &["commit", "-qm", "chore: a"]);
1394 in_repo(&dir, || {
1395 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1396 let one = |t: &str| vec![t.to_string()];
1397 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("first");
1398 record_done(&tree, &one("lint@b"), Completion::Unavailable).expect("other gate");
1399 record_done(&tree, &one("lint@b"), Completion::Warned).expect("a warning");
1400 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("again");
1401 let words = note_in(DONE_REF, &tree).tokens;
1402 let unavailable_for = |token: &str| {
1403 words
1404 .iter()
1405 .filter(|w| w.starts_with("unavailable:") && w.ends_with(&format!(":{token}")))
1406 .count()
1407 };
1408 assert_eq!(unavailable_for("suite@a"), 1, "{words:?}");
1409 assert_eq!(unavailable_for("lint@b"), 1, "{words:?}");
1410 assert!(words.contains(&"warned:lint@b".to_string()), "{words:?}");
1411 });
1412 let _ = std::fs::remove_dir_all(&dir); }
1414
1415 #[test]
1416 fn a_commit_with_only_a_tree_note_still_reads_the_tree_tokens() {
1417 let dir = repo("tree-only");
1418 std::fs::write(dir.join("a.ts"), "x").unwrap();
1419 git(&dir, &["add", "a.ts"]);
1420 git(&dir, &["commit", "-qm", "chore: a"]);
1421 in_repo(&dir, || {
1422 let head = git(&dir, &["rev-parse", "HEAD"]);
1423 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1424 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1425 let stamps = stamps_for(std::slice::from_ref(&head));
1426 assert_eq!(
1427 stamps.get(&head).map(Vec::as_slice),
1428 Some(&["pre-push-cargo-test".to_string()][..])
1429 );
1430 });
1431 let _ = std::fs::remove_dir_all(&dir);
1432 }
1433
1434 #[test]
1435 fn a_commit_with_only_a_commit_note_still_reads_its_tokens() {
1436 let dir = repo("commit-only");
1437 std::fs::write(dir.join("a.ts"), "x").unwrap();
1438 git(&dir, &["add", "a.ts"]);
1439 git(&dir, &["commit", "-qm", "chore: a"]);
1440 in_repo(&dir, || {
1441 let head = git(&dir, &["rev-parse", "HEAD"]);
1442 let mut note = Note::default();
1443 note.add_tokens(&["typecheck".to_string()]);
1444 assert!(write_note(&head, ¬e));
1445 let stamps = stamps_for(std::slice::from_ref(&head));
1446 assert_eq!(
1447 stamps.get(&head).map(Vec::as_slice),
1448 Some(&["typecheck".to_string()][..])
1449 );
1450 });
1451 let _ = std::fs::remove_dir_all(&dir);
1452 }
1453
1454 #[test]
1455 fn a_token_on_both_notes_is_read_once() {
1456 let dir = repo("dedup");
1457 std::fs::write(dir.join("a.ts"), "x").unwrap();
1458 git(&dir, &["add", "a.ts"]);
1459 in_repo(&dir, || {
1460 record(&["test"]);
1461 git(&dir, &["commit", "-qm", "chore: a"]);
1462 bind_to_head(); let head = git(&dir, &["rev-parse", "HEAD"]);
1464 let stamps = stamps_for(std::slice::from_ref(&head));
1465 assert_eq!(
1466 stamps.get(&head).map(Vec::as_slice),
1467 Some(&["test".to_string()][..])
1468 );
1469 });
1470 let _ = std::fs::remove_dir_all(&dir);
1471 }
1472
1473 #[test]
1474 fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
1475 let dir = repo("roundtrip");
1476 std::fs::write(dir.join("a.ts"), "x").unwrap();
1477 git(&dir, &["add", "a.ts"]);
1478 in_repo(&dir, || {
1479 record(&["typecheck", "test"]);
1480 git(&dir, &["commit", "-qm", "chore: a"]);
1481 let stamped = bind_to_head();
1482 assert_eq!(
1483 stamped,
1484 vec!["typecheck".to_string(), "test".to_string()],
1485 "bind_to_head reports the scripts it stamped"
1486 );
1487 let head = git(&dir, &["rev-parse", "HEAD"]);
1488 let stamps = stamps_for(std::slice::from_ref(&head));
1489 assert_eq!(
1490 stamps.get(&head).map(Vec::as_slice),
1491 Some(&["typecheck".to_string(), "test".to_string()][..])
1492 );
1493 assert!(!dir.join(".git").join(MARKER).exists());
1500 });
1501 let _ = std::fs::remove_dir_all(&dir);
1502 }
1503
1504 #[test]
1505 fn a_marker_for_a_different_tree_stamps_nothing() {
1506 let dir = repo("stale");
1507 std::fs::write(dir.join("a.ts"), "x").unwrap();
1508 git(&dir, &["add", "a.ts"]);
1509 in_repo(&dir, || {
1510 record(&["typecheck"]);
1511 std::fs::write(dir.join("a.ts"), "y").unwrap();
1514 git(&dir, &["add", "a.ts"]);
1515 git(&dir, &["commit", "-qm", "chore: different"]);
1516 assert!(
1517 bind_to_head().is_empty(),
1518 "bind_to_head reports nothing when the tree moved"
1519 );
1520 let head = git(&dir, &["rev-parse", "HEAD"]);
1521 assert!(
1522 stamps_for(&[head]).is_empty(),
1523 "a stale marker must not vouch"
1524 );
1525 assert!(
1526 !dir.join(".git").join(MARKER).exists(),
1527 "consumed either way"
1528 );
1529 });
1530 let _ = std::fs::remove_dir_all(&dir);
1531 }
1532
1533 #[test]
1534 fn an_empty_record_clears_a_previous_marker() {
1535 let dir = repo("clears");
1536 std::fs::write(dir.join("a.ts"), "x").unwrap();
1537 git(&dir, &["add", "a.ts"]);
1538 in_repo(&dir, || {
1539 record(&["typecheck"]);
1540 assert!(dir.join(".git").join(MARKER).exists());
1541 record(&[]);
1542 assert!(!dir.join(".git").join(MARKER).exists());
1543 });
1544 let _ = std::fs::remove_dir_all(&dir);
1545 }
1546
1547 #[test]
1552 fn a_marker_in_an_unknown_format_stamps_nothing() {
1553 let dir = repo("wrongformat");
1554 std::fs::write(dir.join("a.ts"), "x").unwrap();
1555 git(&dir, &["add", "a.ts"]);
1556 in_repo(&dir, || {
1557 let tree = git(&dir, &["write-tree"]);
1558 let marker = dir.join(".git").join(MARKER);
1559 std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
1560 git(&dir, &["commit", "-qm", "chore: a"]);
1561 bind_to_head();
1562 let head = git(&dir, &["rev-parse", "HEAD"]);
1563 assert!(
1564 stamps_for(std::slice::from_ref(&head)).is_empty(),
1565 "an unknown format was trusted"
1566 );
1567 assert!(!marker.exists(), "consumed either way");
1568 });
1569 let _ = std::fs::remove_dir_all(&dir);
1570 }
1571
1572 #[test]
1576 fn a_foreign_note_is_not_a_stamp() {
1577 let dir = repo("foreignnote");
1578 std::fs::write(dir.join("a.ts"), "x").unwrap();
1579 git(&dir, &["add", "a.ts"]);
1580 in_repo(&dir, || {
1581 git(&dir, &["commit", "-qm", "chore: a"]);
1582 git(
1583 &dir,
1584 &[
1585 "notes",
1586 "--ref",
1587 NOTES_REF,
1588 "add",
1589 "-m",
1590 "typecheck test",
1591 "HEAD",
1592 ],
1593 );
1594 let head = git(&dir, &["rev-parse", "HEAD"]);
1595 assert!(
1596 stamps_for(std::slice::from_ref(&head)).is_empty(),
1597 "a note without the format token was trusted"
1598 );
1599 });
1600 let _ = std::fs::remove_dir_all(&dir);
1601 }
1602
1603 #[test]
1607 fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
1608 let dir = repo("no-stamps");
1609 std::fs::write(dir.join("a.ts"), "x").unwrap();
1610 git(&dir, &["add", "a.ts"]);
1611 git(&dir, &["commit", "-qm", "chore: a"]);
1612 in_repo(&dir, || {
1613 assert_eq!(
1614 crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
1615 Some(""),
1616 "an absent notes ref must be an ANSWER, not a failure — the \
1617 no-stamps path and the git-is-broken path are told apart by it"
1618 );
1619 let head = git(&dir, &["rev-parse", "HEAD"]);
1620 assert!(stamps_for(&[head]).is_empty());
1621 });
1622 let _ = std::fs::remove_dir_all(&dir);
1623 }
1624
1625 #[test]
1632 fn a_note_from_before_the_run_lines_parses_unchanged() {
1633 let note = Note::parse("greengate-gate-v1 typecheck test");
1634 assert_eq!(note.tokens, vec!["typecheck", "test"]);
1635 assert!(note.runs.is_empty());
1636 assert_eq!(note.render(), "greengate-gate-v1 typecheck test");
1639 }
1640
1641 #[test]
1643 fn run_lines_are_read_without_disturbing_the_tokens() {
1644 let body = "greengate-gate-v1 pre-push-cargo-test\n\
1645 run 1726900000 pre-push-cargo-test pass 412391\n\
1646 run 1726903600 pre-push-audit-js fail 903\n";
1647 let note = Note::parse(body);
1648 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1649 assert_eq!(note.runs.len(), 2);
1650 assert_eq!(
1651 note.runs[0],
1652 Run {
1653 at: 1_726_900_000,
1654 gate: "pre-push-cargo-test".into(),
1655 outcome: RunOutcome::Passed,
1656 ms: 412_391,
1657 }
1658 );
1659 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1660 assert_eq!(note.render(), body.trim_end());
1661 }
1662
1663 #[test]
1667 fn an_unreadable_run_line_is_dropped_and_the_rest_survives() {
1668 let note = Note::parse(
1669 "greengate-gate-v1 test\n\
1670 run 1726900000 pre-push-cargo-test pass 400\n\
1671 run tomorrow pre-push-cargo-test pass 400\n\
1672 run 1726900001 pre-push-cargo-test sideways 400\n\
1673 banana\n\
1674 run 1726900002 pre-push-cargo-test fail 500\n",
1675 );
1676 assert_eq!(note.tokens, vec!["test"]);
1677 assert_eq!(note.runs.len(), 2, "{:?}", note.runs);
1678 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1679 }
1680
1681 #[test]
1685 fn a_deferral_is_never_a_token_and_outlives_the_run_trim() {
1686 let mut note = Note::parse("greengate-gate-v1 lint\ndeferred cargo-test\n");
1687 assert_eq!(note.tokens, vec!["lint"]);
1688 assert_eq!(note.deferred, vec!["cargo-test"]);
1689 let runs: Vec<Run> = (0..MAX_RUNS as u64 + 10)
1690 .map(|i| Run {
1691 at: 1_726_900_000 + i,
1692 gate: "pre-push-audit-js".into(),
1693 outcome: RunOutcome::Passed,
1694 ms: 1,
1695 })
1696 .collect();
1697 note.add_runs(&runs);
1698 let again = Note::parse(¬e.render());
1699 assert_eq!(again.runs.len(), MAX_RUNS);
1700 assert_eq!(again.deferred, vec!["cargo-test"]);
1701 assert_eq!(again.tokens, vec!["lint"]);
1702 }
1703
1704 #[test]
1707 fn a_foreign_note_yields_no_runs() {
1708 let note = Note::parse("hello\nrun 1726900000 pre-push-cargo-test pass 400\n");
1709 assert!(note.tokens.is_empty() && note.runs.is_empty());
1710 }
1711
1712 #[test]
1717 fn a_stamp_and_its_evidence_survive_each_other() {
1718 let dir = repo("evidence");
1719 std::fs::write(dir.join("a.ts"), "x").unwrap();
1720 git(&dir, &["add", "a.ts"]);
1721 in_repo(&dir, || {
1722 git(&dir, &["commit", "-qm", "chore: a"]);
1723 let head = git(&dir, &["rev-parse", "HEAD"]);
1724 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1725 record_runs(
1726 &tree,
1727 &[Run {
1728 at: 1_726_900_000,
1729 gate: "pre-push-cargo-test".into(),
1730 outcome: RunOutcome::Failed,
1731 ms: 412_391,
1732 }],
1733 );
1734 assert!(stamp_push(&head, &tree, &["pre-push-cargo-test".into()]));
1736 let note = note_at(&tree);
1737 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1738 assert_eq!(note.runs.len(), 1, "the evidence survived the stamp");
1739 let stamps = stamps_for(std::slice::from_ref(&head));
1741 assert_eq!(
1742 stamps.get(&head).map(Vec::as_slice),
1743 Some(&["pre-push-cargo-test".to_string()][..])
1744 );
1745 });
1746 let _ = std::fs::remove_dir_all(&dir);
1747 }
1748
1749 #[test]
1753 fn a_recorded_run_is_not_a_stamp() {
1754 let dir = repo("not-a-stamp");
1755 std::fs::write(dir.join("a.ts"), "x").unwrap();
1756 git(&dir, &["add", "a.ts"]);
1757 in_repo(&dir, || {
1758 git(&dir, &["commit", "-qm", "chore: a"]);
1759 let head = git(&dir, &["rev-parse", "HEAD"]);
1760 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1761 record_runs(
1762 &tree,
1763 &[Run {
1764 at: 1_726_900_000,
1765 gate: "pre-push-cargo-test".into(),
1766 outcome: RunOutcome::Passed,
1767 ms: 412_391,
1768 }],
1769 );
1770 assert!(
1771 stamps_for(std::slice::from_ref(&head)).is_empty(),
1772 "a run line vouched for a gate — evidence must never gate"
1773 );
1774 assert!(
1775 !vouched_for_staged_tree().contains("pre-push-cargo-test"),
1776 "a run line vouched at commit time"
1777 );
1778 let history = crate::gate_evidence::history_in(&dir);
1780 assert_eq!(history.runs.len(), 1);
1781 assert_eq!(history.runs[0].0, tree, "keyed by the content it ran on");
1782 });
1783 let _ = std::fs::remove_dir_all(&dir);
1784 }
1785
1786 #[test]
1787 fn forget_removes_the_stamps() {
1788 let dir = repo("forget");
1789 std::fs::write(dir.join("a.ts"), "x").unwrap();
1790 git(&dir, &["add", "a.ts"]);
1791 in_repo(&dir, || {
1792 record(&["typecheck"]);
1793 git(&dir, &["commit", "-qm", "chore: a"]);
1794 bind_to_head();
1795 let head = git(&dir, &["rev-parse", "HEAD"]);
1796 assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
1797 forget();
1798 assert!(stamps_for(&[head]).is_empty());
1799 });
1800 let _ = std::fs::remove_dir_all(&dir);
1801 }
1802
1803 #[test]
1817 fn a_stamp_survives_a_commit_being_rewritten_with_the_same_tree() {
1818 let dir = repo("squashed");
1819 std::fs::write(dir.join("a.ts"), "x").unwrap();
1820 git(&dir, &["add", "a.ts"]);
1821 in_repo(&dir, || {
1822 record(&["test"]);
1823 git(&dir, &["commit", "-qm", "feat: on a branch"]);
1824 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1825 let branch_tip = git(&dir, &["rev-parse", "HEAD"]);
1826
1827 git(
1831 &dir,
1832 &[
1833 "commit",
1834 "-q",
1835 "--amend",
1836 "-m",
1837 "feat: squashed by the forge",
1838 ],
1839 );
1840 let merged = git(&dir, &["rev-parse", "HEAD"]);
1841 assert_ne!(merged, branch_tip, "the fixture must produce a new commit");
1842 assert_eq!(
1843 git(&dir, &["rev-parse", "HEAD^{tree}"]),
1844 git(&dir, &["rev-parse", &format!("{branch_tip}^{{tree}}")]),
1845 "…carrying the same tree, which is the whole premise"
1846 );
1847
1848 let stamps = stamps_for(std::slice::from_ref(&merged));
1849 assert_eq!(
1850 stamps.get(&merged).map(Vec::as_slice),
1851 Some(&["test".to_string()][..]),
1852 "the stamp must follow the content, not the commit hash"
1853 );
1854 });
1855 let _ = std::fs::remove_dir_all(&dir);
1856 }
1857
1858 #[test]
1862 fn a_different_tree_gets_no_stamp_from_the_fallback() {
1863 let dir = repo("othertree");
1864 std::fs::write(dir.join("a.ts"), "x").unwrap();
1865 git(&dir, &["add", "a.ts"]);
1866 in_repo(&dir, || {
1867 record(&["test"]);
1868 git(&dir, &["commit", "-qm", "chore: stamped"]);
1869 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1870
1871 std::fs::write(dir.join("b.ts"), "y").unwrap();
1874 git(&dir, &["add", "b.ts"]);
1875 git(&dir, &["commit", "-qm", "chore: unjudged"]);
1876 let unstamped = git(&dir, &["rev-parse", "HEAD"]);
1877
1878 assert!(
1879 stamps_for(std::slice::from_ref(&unstamped)).is_empty(),
1880 "a tree nobody stamped must not inherit one"
1881 );
1882 });
1883 let _ = std::fs::remove_dir_all(&dir);
1884 }
1885
1886 fn declared(name: &str, spec: &str) -> PathBuf {
1892 let dir = repo(name);
1893 std::fs::create_dir_all(dir.join(".github")).unwrap();
1894 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
1895 std::fs::write(dir.join("a.ts"), "x").unwrap();
1896 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
1897 std::fs::write(dir.join(".github/greensummit-inputs"), spec).unwrap();
1898 git(&dir, &["add", "-A"]);
1899 in_repo(&dir, || {
1900 record(&["test@abc"]);
1901 git(&dir, &["commit", "-qm", "feat: judged"]);
1902 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1903 });
1904 dir
1905 }
1906
1907 fn plan_only_commit(dir: &Path) -> String {
1910 std::fs::write(dir.join("docs/plans/p.md"), "plan v2, closing").unwrap();
1911 git(dir, &["add", "docs/plans/p.md"]);
1912 git(dir, &["commit", "-qm", "docs(plan): done"]);
1913 git(dir, &["rev-parse", "HEAD"])
1914 }
1915
1916 #[test]
1917 fn a_plan_only_commit_reuses_the_stamp_of_a_declared_gate() {
1918 let dir = declared("plan-only", "test a.ts\n");
1919 in_repo(&dir, || {
1920 let head = plan_only_commit(&dir);
1921 let stamps = stamps_for(std::slice::from_ref(&head));
1922 assert_eq!(
1923 stamps.get(&head).map(Vec::as_slice),
1924 Some(&["test@abc".to_string()][..]),
1925 "the closing commit changed the tree and none of the declared inputs"
1926 );
1927 });
1928 let _ = std::fs::remove_dir_all(&dir);
1929 }
1930
1931 #[test]
1932 fn the_staged_tree_of_a_plan_only_commit_is_vouched_for() {
1933 let dir = declared("staged", "test a.ts\n");
1934 in_repo(&dir, || {
1935 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1936 git(&dir, &["add", "docs/plans/p.md"]);
1937 assert!(vouched_for_staged_tree().contains("test@abc"));
1938 });
1939 let _ = std::fs::remove_dir_all(&dir);
1940 }
1941
1942 #[test]
1943 fn partial_staging_is_judged_on_the_index_not_the_working_copy() {
1944 let dir = declared("partial", "test a.ts\n");
1945 in_repo(&dir, || {
1946 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1949 git(&dir, &["add", "docs/plans/p.md"]);
1950 std::fs::write(dir.join("a.ts"), "unstaged edit").unwrap();
1951 assert!(vouched_for_staged_tree().contains("test@abc"));
1952
1953 std::fs::write(dir.join("a.ts"), "staged edit").unwrap();
1956 git(&dir, &["add", "a.ts"]);
1957 std::fs::write(dir.join("a.ts"), "x").unwrap();
1958 assert!(!vouched_for_staged_tree().contains("test@abc"));
1959 });
1960 let _ = std::fs::remove_dir_all(&dir);
1961 }
1962
1963 #[test]
1964 fn a_changed_declared_input_misses() {
1965 let dir = declared("input-changed", "test a.ts\n");
1966 in_repo(&dir, || {
1967 std::fs::write(dir.join("a.ts"), "changed").unwrap();
1968 git(&dir, &["add", "a.ts"]);
1969 git(&dir, &["commit", "-qm", "feat: unjudged"]);
1970 let head = git(&dir, &["rev-parse", "HEAD"]);
1971 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1972 });
1973 let _ = std::fs::remove_dir_all(&dir);
1974 }
1975
1976 #[test]
1977 fn a_changed_declaration_misses() {
1978 let dir = declared("declaration-changed", "test a.ts\n");
1979 in_repo(&dir, || {
1980 std::fs::write(dir.join("b.ts"), "y").unwrap();
1983 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts b.ts\n").unwrap();
1984 git(&dir, &["add", "-A"]);
1985 git(&dir, &["commit", "-qm", "chore: widen the declaration"]);
1986 let head = git(&dir, &["rev-parse", "HEAD"]);
1987 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1988 });
1989 let _ = std::fs::remove_dir_all(&dir);
1990 }
1991
1992 #[test]
1993 fn a_declared_config_file_is_an_input_like_any_other() {
1994 let dir = declared("config", "test a.ts amont.conf\n");
1997 in_repo(&dir, || {
1998 assert!(!inputs_ref_exists());
2001
2002 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2003 git(&dir, &["add", "amont.conf"]);
2004 record(&["test@abc"]);
2005 git(&dir, &["commit", "-qm", "chore: config"]);
2006 assert_eq!(bind_to_head(), vec!["test".to_string()]);
2007
2008 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
2009 git(&dir, &["add", "docs/plans/p.md"]);
2010 git(&dir, &["commit", "-qm", "docs(plan): done"]);
2011 let plan = git(&dir, &["rev-parse", "HEAD"]);
2012 assert!(stamps_for(std::slice::from_ref(&plan)).contains_key(&plan));
2013
2014 std::fs::write(dir.join("amont.conf"), "scope = lib\n").unwrap();
2015 git(&dir, &["add", "amont.conf"]);
2016 git(&dir, &["commit", "-qm", "chore: scope-only change"]);
2017 let scope = git(&dir, &["rev-parse", "HEAD"]);
2018 assert!(
2019 stamps_for(std::slice::from_ref(&scope)).is_empty(),
2020 "a scope-only change must miss"
2021 );
2022 });
2023 let _ = std::fs::remove_dir_all(&dir);
2024 }
2025
2026 #[test]
2027 fn a_declared_stamp_is_read_back_as_its_complete_token() {
2028 let dir = declared("identity", "test a.ts\n");
2034 in_repo(&dir, || {
2035 let head = plan_only_commit(&dir);
2036 let tokens = stamps_for(std::slice::from_ref(&head))
2037 .remove(&head)
2038 .unwrap_or_default();
2039 assert_eq!(tokens, vec!["test@abc".to_string()]);
2040
2041 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2042 assert!(stamp_tree(&tree, &["test@def".to_string()]));
2043 let tokens = tree_tokens(&tree);
2044 assert!(tokens.contains(&"test@abc".to_string()));
2045 assert!(tokens.contains(&"test@def".to_string()));
2046 assert!(!tokens.contains(&"test@zzz".to_string()));
2047 assert!(!tokens.contains(&"test".to_string()));
2048 });
2049 let _ = std::fs::remove_dir_all(&dir);
2050 }
2051
2052 #[test]
2053 fn a_gate_that_does_not_declare_the_manifest_is_not_offered_the_route() {
2054 let dir = repo("manifest-undeclared");
2058 std::fs::create_dir_all(dir.join(".github")).unwrap();
2059 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2060 std::fs::write(dir.join("a.ts"), "x").unwrap();
2061 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2062 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2063 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2064 git(&dir, &["add", "-A"]);
2065 in_repo(&dir, || {
2066 record(&["test@abc"]);
2067 git(&dir, &["commit", "-qm", "feat: judged"]);
2068 bind_to_head();
2069 assert!(!inputs_ref_exists(), "the route must not open");
2070 let head = plan_only_commit(&dir);
2071 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2072 });
2073 let _ = std::fs::remove_dir_all(&dir);
2074 }
2075
2076 #[test]
2077 fn a_gate_declaring_the_manifest_opens_the_route() {
2078 let dir = declared("manifest-declared", "test a.ts amont.conf\n");
2081 in_repo(&dir, || {
2082 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2083 git(&dir, &["add", "amont.conf"]);
2084 record(&["test@abc"]);
2085 git(&dir, &["commit", "-qm", "chore: config"]);
2086 bind_to_head();
2087 assert!(inputs_ref_exists());
2088 });
2089 let _ = std::fs::remove_dir_all(&dir);
2090 }
2091
2092 #[test]
2093 fn an_undeclared_gate_keeps_whole_tree_behaviour() {
2094 let dir = declared("undeclared", "test a.ts\n");
2095 in_repo(&dir, || {
2096 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2099 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2100 let head = plan_only_commit(&dir);
2101 let tokens = stamps_for(std::slice::from_ref(&head))
2102 .remove(&head)
2103 .unwrap_or_default();
2104 assert!(tokens.contains(&"test@abc".to_string()));
2105 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2106 });
2107 let _ = std::fs::remove_dir_all(&dir);
2108 }
2109
2110 #[test]
2111 fn an_invalid_or_ambiguous_spec_falls_back_to_whole_tree_behaviour() {
2112 let dir = declared("invalid", "test src/*\n");
2114 in_repo(&dir, || {
2115 assert!(!inputs_ref_exists(), "no valid spec, nothing is filed");
2116 let head = plan_only_commit(&dir);
2117 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2118 });
2119 let _ = std::fs::remove_dir_all(&dir);
2120
2121 let dir = repo("ambiguous");
2123 std::fs::create_dir_all(dir.join(".github")).unwrap();
2124 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2125 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2126 std::fs::write(dir.join("a.ts"), "x").unwrap();
2127 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2128 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2129 std::fs::write(dir.join(".forgejo/greensummit-inputs"), "test a.ts\n").unwrap();
2130 git(&dir, &["add", "-A"]);
2131 in_repo(&dir, || {
2132 record(&["test@abc"]);
2133 git(&dir, &["commit", "-qm", "feat: judged"]);
2134 bind_to_head();
2135 assert!(!inputs_ref_exists());
2136 let head = plan_only_commit(&dir);
2137 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2138 });
2139 let _ = std::fs::remove_dir_all(&dir);
2140 }
2141
2142 #[test]
2143 fn a_gate_that_did_not_pass_leaves_no_declared_input_stamp() {
2144 let dir = repo("failed");
2145 std::fs::create_dir_all(dir.join(".github")).unwrap();
2146 std::fs::write(dir.join("a.ts"), "x").unwrap();
2147 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2148 git(&dir, &["add", "-A"]);
2149 in_repo(&dir, || {
2150 record(&[]);
2152 git(&dir, &["commit", "-qm", "feat: unjudged"]);
2153 assert!(bind_to_head().is_empty());
2154 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2155 let head = git(&dir, &["rev-parse", "HEAD"]);
2156 assert!(!stamp_push(&head, &tree, &[]));
2157 assert!(!inputs_ref_exists());
2158 });
2159 let _ = std::fs::remove_dir_all(&dir);
2160 }
2161
2162 #[test]
2163 fn stamp_tree_and_tree_tokens_use_the_inputs_ref() {
2164 let dir = declared("rehearsal", "test a.ts\n");
2165 in_repo(&dir, || {
2166 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2168 assert!(stamp_tree(&tree, &["test@rehearsed".to_string()]));
2169 plan_only_commit(&dir);
2171 let later = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2172 assert_ne!(later, tree);
2173 assert!(tree_tokens(&later).contains(&"test@rehearsed".to_string()));
2174 });
2175 let _ = std::fs::remove_dir_all(&dir);
2176 }
2177
2178 #[test]
2179 fn the_inputs_ref_is_keyed_the_way_attest_keys_its_own() {
2180 let dir = declared("key", "test a.ts\n");
2181 in_repo(&dir, || {
2182 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2183 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2184 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2185 let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
2186 let listed = git(&dir, &["notes", "--ref", INPUTS_REF, "list"]);
2187 assert!(
2188 listed
2189 .lines()
2190 .any(|l| l.split_whitespace().nth(1) == Some(key.as_str())),
2191 "{listed}"
2192 );
2193 });
2194 let _ = std::fs::remove_dir_all(&dir);
2195 }
2196
2197 #[test]
2198 fn a_foreign_token_in_the_inputs_ref_vouches_for_nothing() {
2199 let dir = declared("foreign", "test a.ts\n");
2200 in_repo(&dir, || {
2201 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2202 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2203 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2204 let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
2205 let mut note = note_in(INPUTS_REF, &key);
2207 note.add_tokens(&["publish@evil".to_string()]);
2208 assert!(write_note_in(INPUTS_REF, &key, ¬e));
2209 assert!(!tree_tokens(&tree).contains(&"publish@evil".to_string()));
2210 });
2211 let _ = std::fs::remove_dir_all(&dir);
2212 }
2213
2214 #[test]
2215 fn forget_removes_the_inputs_ref_too() {
2216 let dir = declared("forget-inputs", "test a.ts\n");
2217 in_repo(&dir, || {
2218 assert!(inputs_ref_exists());
2219 assert!(forget());
2220 assert!(!inputs_ref_exists());
2221 });
2222 let _ = std::fs::remove_dir_all(&dir);
2223 }
2224
2225 fn canonical(name: &str, conf: Option<&str>) -> PathBuf {
2228 let dir = repo(name);
2229 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2230 std::fs::write(dir.join("a.ts"), "x").unwrap();
2231 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
2232 if let Some(conf) = conf {
2233 std::fs::write(dir.join("amont.conf"), conf).unwrap();
2234 }
2235 git(&dir, &["add", "-A"]);
2236 in_repo(&dir, || {
2237 record(&["test@abc"]);
2238 git(&dir, &["commit", "-qm", "feat: judged"]);
2239 assert_eq!(bind_to_head(), vec!["test".to_string()]);
2240 });
2241 dir
2242 }
2243
2244 fn vouched(dir: &Path, commit: &str) -> Vec<String> {
2245 in_repo(dir, || {
2246 stamps_for(std::slice::from_ref(&commit.to_string()))
2247 .remove(commit)
2248 .unwrap_or_default()
2249 })
2250 }
2251
2252 #[test]
2253 fn with_no_spec_a_plans_only_commit_is_vouched_for_canonically() {
2254 let dir = canonical("canon-plan-edit", None);
2255 in_repo(&dir, || {
2256 assert!(inputs_ref_exists(), "the canonical stamp is filed");
2257 let head = plan_only_commit(&dir);
2258 assert_eq!(
2259 stamps_for(std::slice::from_ref(&head))
2260 .remove(&head)
2261 .unwrap_or_default(),
2262 vec!["test@abc".to_string()]
2263 );
2264 std::fs::write(dir.join("docs/plans/p.md"), "plan v3").unwrap();
2266 git(&dir, &["add", "docs/plans/p.md"]);
2267 assert!(vouched_for_staged_tree().contains("test@abc"));
2268 });
2269 let _ = std::fs::remove_dir_all(&dir);
2270 }
2271
2272 #[test]
2273 fn a_plan_added_deleted_or_renamed_is_not_vouched_for() {
2274 let dir = canonical("canon-plan-exists", None);
2275 std::fs::write(dir.join("docs/plans/q.md"), "second plan").unwrap();
2276 git(&dir, &["add", "docs/plans/q.md"]);
2277 git(&dir, &["commit", "-qm", "docs(plan): add"]);
2278 let added = git(&dir, &["rev-parse", "HEAD"]);
2279 assert!(vouched(&dir, &added).is_empty(), "a plan added");
2280 git(&dir, &["mv", "docs/plans/p.md", "docs/plans/r.md"]);
2281 git(&dir, &["commit", "-qm", "docs(plan): rename"]);
2282 let renamed = git(&dir, &["rev-parse", "HEAD"]);
2283 assert!(vouched(&dir, &renamed).is_empty(), "a plan renamed");
2284 let _ = std::fs::remove_dir_all(&dir);
2285 }
2286
2287 #[test]
2288 fn with_no_spec_any_other_change_is_not_vouched_for() {
2289 let dir = canonical("canon-code-edit", Some("gate test = make test\n"));
2290 std::fs::write(dir.join("a.ts"), "changed").unwrap();
2291 git(&dir, &["commit", "-qam", "feat: code"]);
2292 let code = git(&dir, &["rev-parse", "HEAD"]);
2293 assert!(vouched(&dir, &code).is_empty(), "a source edit");
2294 std::fs::write(dir.join("amont.conf"), "gate test = make other\n").unwrap();
2296 git(&dir, &["commit", "-qam", "chore: config"]);
2297 let conf = git(&dir, &["rev-parse", "HEAD"]);
2298 assert!(vouched(&dir, &conf).is_empty(), "a manifest edit");
2299 let _ = std::fs::remove_dir_all(&dir);
2300 }
2301
2302 #[test]
2303 fn plan_exempt_off_closes_the_canonical_route() {
2304 for (name, conf) in [
2305 ("off", "set planExempt off\n"),
2306 ("spelled", "SET PLANEXEMPT\tOff\r\n"),
2307 ("after", "set planExempt on\nset planExempt off\n"),
2308 ] {
2309 let dir = canonical(&format!("canon-off-{name}"), Some(conf));
2310 in_repo(&dir, || {
2311 assert!(!inputs_ref_exists(), "{name}: nothing is filed");
2312 let head = plan_only_commit(&dir);
2313 assert!(
2314 stamps_for(std::slice::from_ref(&head)).is_empty(),
2315 "{name}: a plans-only commit is a new tree"
2316 );
2317 });
2318 let _ = std::fs::remove_dir_all(&dir);
2319 }
2320 for (name, conf) in [
2322 ("on", "set planExempt on\n"),
2323 ("comment", "set planExempt off # no\n"),
2324 ("commented", "# set planExempt off\n"),
2325 ] {
2326 let dir = canonical(&format!("canon-on-{name}"), Some(conf));
2327 let head = plan_only_commit(&dir);
2328 assert!(!vouched(&dir, &head).is_empty(), "{name}: still canonical");
2329 let _ = std::fs::remove_dir_all(&dir);
2330 }
2331 }
2332
2333 #[test]
2334 fn a_spec_that_cannot_be_used_means_no_canonical_stamps() {
2335 let dir = repo("canon-unreadable-spec");
2337 std::fs::create_dir_all(dir.join(".github/greensummit-inputs")).unwrap();
2338 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2339 std::fs::write(dir.join(".github/greensummit-inputs/x"), "x").unwrap();
2340 std::fs::write(dir.join("a.ts"), "x").unwrap();
2341 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2342 git(&dir, &["add", "-A"]);
2343 in_repo(&dir, || {
2344 record(&["test@abc"]);
2345 git(&dir, &["commit", "-qm", "feat: judged"]);
2346 bind_to_head();
2347 assert!(!inputs_ref_exists(), "an unreadable spec opens nothing");
2348 let head = plan_only_commit(&dir);
2349 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2350 });
2351 let _ = std::fs::remove_dir_all(&dir);
2352 }
2353
2354 #[test]
2355 fn two_specs_mean_no_canonical_stamps() {
2356 let dir = repo("canon-ambiguous");
2357 std::fs::create_dir_all(dir.join(".github")).unwrap();
2358 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2359 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2360 std::fs::write(dir.join("a.ts"), "x").unwrap();
2361 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2362 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2363 std::fs::write(dir.join(".forgejo/greensummit-inputs"), "test a.ts\n").unwrap();
2364 git(&dir, &["add", "-A"]);
2365 in_repo(&dir, || {
2366 record(&["test@abc"]);
2367 git(&dir, &["commit", "-qm", "feat: judged"]);
2368 bind_to_head();
2369 assert!(!inputs_ref_exists());
2370 let head = plan_only_commit(&dir);
2371 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2372 });
2373 let _ = std::fs::remove_dir_all(&dir);
2374 }
2375
2376 #[test]
2377 fn a_valid_spec_keeps_precedence_over_the_canonical_route() {
2378 let dir = declared("canon-precedence", "test a.ts\n");
2380 in_repo(&dir, || {
2381 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2382 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2383 let head = plan_only_commit(&dir);
2384 let tokens = stamps_for(std::slice::from_ref(&head))
2385 .remove(&head)
2386 .unwrap_or_default();
2387 assert!(tokens.contains(&"test@abc".to_string()));
2388 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2389 });
2390 let _ = std::fs::remove_dir_all(&dir);
2391 }
2392
2393 fn unstamped(name: &str) -> (PathBuf, String, String) {
2398 let dir = repo(name);
2399 std::fs::write(dir.join("a.ts"), "x").unwrap();
2400 git(&dir, &["add", "a.ts"]);
2401 git(&dir, &["commit", "-qm", "feat: a"]);
2402 let head = git(&dir, &["rev-parse", "HEAD"]);
2403 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2404 (dir, head, tree)
2405 }
2406
2407 fn plant(dir: &Path, notes_ref: &str, key: &str, body: &str) {
2409 git(
2410 dir,
2411 &["notes", "--ref", notes_ref, "add", "-f", "-m", body, key],
2412 );
2413 }
2414
2415 fn stamps_of(commit: &str) -> Vec<String> {
2416 stamps_for(&[commit.to_string()])
2417 .remove(commit)
2418 .unwrap_or_default()
2419 }
2420
2421 #[test]
2422 fn a_pass_is_found_under_each_gate_ref() {
2423 let set = &WRITE;
2424 let (dir, head, tree) = unstamped("either-0");
2425 plant(
2426 &dir,
2427 set.notes_ref,
2428 &head,
2429 &format!("{} test@c", set.format),
2430 );
2431 plant(
2432 &dir,
2433 set.notes_ref,
2434 &tree,
2435 &format!("{} test@t", set.format),
2436 );
2437 plant(
2438 &dir,
2439 set.cluster_ref,
2440 &tree,
2441 &format!("{} suite@k", set.format),
2442 );
2443 plant(
2444 &dir,
2445 set.done_ref,
2446 &tree,
2447 &format!("{} warned:lint@w", set.format),
2448 );
2449 in_repo(&dir, || {
2450 let mut got = stamps_of(&head);
2451 got.sort();
2452 assert_eq!(got, ["test@c", "test@t"], "{}", set.notes_ref);
2453 assert_eq!(tree_tokens(&tree), ["test@t"], "{}", set.notes_ref);
2454 assert_eq!(cluster_tokens(&tree), ["suite@k"], "{}", set.cluster_ref);
2455 assert!(
2456 done_on_every(
2457 std::slice::from_ref(&head),
2458 "lint@w",
2459 crate::check::Severity::Block
2460 ),
2461 "{}",
2462 set.done_ref
2463 );
2464 });
2465 let _ = std::fs::remove_dir_all(&dir); }
2467
2468 const LEGACY: GateNames = GateNames {
2471 format: "amont-gate-v1",
2472 notes_ref: "amont-gate",
2473 inputs_ref: "amont-gate-inputs",
2474 cluster_ref: "amont-gate-cluster",
2475 done_ref: "amont-gate-done",
2476 canon_domain: "amont-gate-canon",
2477 attest: greensummit::format::Names {
2478 format: "amont-attest-v2",
2479 notes_ref: "amont-attest",
2480 inputs_ref: "amont-attest-inputs",
2481 namespace: "amont-attest",
2482 input_domain: "amont-attest-input",
2483 canon_domain: "amont-attest-canon",
2484 producer: "amont",
2485 },
2486 };
2487
2488 #[test]
2489 fn a_stamp_under_the_old_names_is_not_read() {
2490 let (dir, head, tree) = unstamped("old-refs");
2491 for key in [&head, &tree] {
2492 plant(
2493 &dir,
2494 LEGACY.notes_ref,
2495 key,
2496 &format!("{} test@old", LEGACY.format),
2497 );
2498 }
2499 plant(
2500 &dir,
2501 LEGACY.cluster_ref,
2502 &tree,
2503 &format!("{} suite@old", LEGACY.format),
2504 );
2505 in_repo(&dir, || {
2506 assert!(stamps_of(&head).is_empty());
2507 assert!(tree_tokens(&tree).is_empty());
2508 assert!(cluster_tokens(&tree).is_empty());
2509 });
2510 let _ = std::fs::remove_dir_all(&dir); }
2512
2513 #[test]
2514 fn with_notes_under_both_refs_the_green_note_is_read() {
2515 let (dir, head, tree) = unstamped("both-refs");
2516 for key in [&head, &tree] {
2517 plant(
2518 &dir,
2519 LEGACY.notes_ref,
2520 key,
2521 &format!("{} test@old", LEGACY.format),
2522 );
2523 plant(
2524 &dir,
2525 GREEN.notes_ref,
2526 key,
2527 &format!("{} test@new", GREEN.format),
2528 );
2529 }
2530 plant(
2531 &dir,
2532 LEGACY.cluster_ref,
2533 &tree,
2534 &format!("{} suite@old", LEGACY.format),
2535 );
2536 plant(
2537 &dir,
2538 GREEN.cluster_ref,
2539 &tree,
2540 &format!("{} suite@new", GREEN.format),
2541 );
2542 in_repo(&dir, || {
2543 assert_eq!(stamps_of(&head), ["test@new"]);
2544 assert_eq!(tree_tokens(&tree), ["test@new"]);
2545 assert_eq!(cluster_tokens(&tree), ["suite@new"]);
2546 });
2547 let _ = std::fs::remove_dir_all(&dir); }
2549
2550 #[test]
2551 fn a_note_whose_header_is_the_other_sets_reads_as_unstamped() {
2552 for (i, (sits_in, header_of)) in [(LEGACY, GREEN), (GREEN, LEGACY)].iter().enumerate() {
2553 let (dir, head, tree) = unstamped(&format!("mixed-{i}"));
2554 for key in [&head, &tree] {
2555 plant(
2556 &dir,
2557 sits_in.notes_ref,
2558 key,
2559 &format!("{} test@x", header_of.format),
2560 );
2561 }
2562 plant(
2563 &dir,
2564 sits_in.cluster_ref,
2565 &tree,
2566 &format!("{} suite@x", header_of.format),
2567 );
2568 in_repo(&dir, || {
2569 assert!(stamps_of(&head).is_empty(), "{}", sits_in.notes_ref);
2570 assert!(tree_tokens(&tree).is_empty(), "{}", sits_in.notes_ref);
2571 assert!(cluster_tokens(&tree).is_empty(), "{}", sits_in.cluster_ref);
2572 });
2573 let _ = std::fs::remove_dir_all(&dir); }
2575 }
2576
2577 #[test]
2580 fn the_inputs_ref_is_read_under_its_own_key() {
2581 let dir = declared("green-inputs", "test a.ts\n");
2582 in_repo(&dir, || {
2583 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2584 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2585 let fp = crate::attest_inputs::fingerprint(&tree, &spec, "test").expect("fp");
2586 let green = crate::attest_inputs::input_key(&GREEN.attest, "test", &fp).expect("key");
2587 let legacy = crate::attest_inputs::input_key(&LEGACY.attest, "test", &fp).expect("key");
2588 assert_ne!(green, legacy, "each set keys with its own domain");
2589 let head = plan_only_commit(&dir);
2590 plant(
2592 &dir,
2593 GREEN.inputs_ref,
2594 &legacy,
2595 &format!("{} test@wrongkey", GREEN.format),
2596 );
2597 assert_eq!(stamps_of(&head), ["test@abc"]);
2598 plant(
2599 &dir,
2600 GREEN.inputs_ref,
2601 &green,
2602 &format!("{} test@green", GREEN.format),
2603 );
2604 assert_eq!(stamps_of(&head), ["test@green"]);
2605 });
2606 let _ = std::fs::remove_dir_all(&dir); }
2608
2609 #[test]
2610 fn a_green_canonical_note_is_read_under_the_green_domain() {
2611 let dir = canonical("green-canon", None);
2612 in_repo(&dir, || {
2613 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2614 let canon = crate::attest_inputs::canonical_route(&tree).expect("canon");
2615 let key =
2616 crate::attest_inputs::canon_gate_key(GREEN.canon_domain, &canon).expect("key");
2617 plant(
2618 &dir,
2619 GREEN.inputs_ref,
2620 &key,
2621 &format!("{} test@green", GREEN.format),
2622 );
2623 let head = plan_only_commit(&dir);
2624 assert_eq!(stamps_of(&head), ["test@green"]);
2625 });
2626 let _ = std::fs::remove_dir_all(&dir); }
2628
2629 #[test]
2632 fn history_reads_runs_under_the_written_names_only() {
2633 let (dir, _head, tree) = unstamped("history-both");
2634 let other = git(&dir, &["rev-parse", "HEAD"]);
2635 plant(
2636 &dir,
2637 LEGACY.notes_ref,
2638 &other,
2639 &format!("{}\nrun 100 old-gate pass 7", LEGACY.format),
2640 );
2641 plant(
2642 &dir,
2643 GREEN.notes_ref,
2644 &tree,
2645 &format!("{}\nrun 200 new-gate pass 9", GREEN.format),
2646 );
2647 plant(
2649 &dir,
2650 GREEN.notes_ref,
2651 &other,
2652 &format!("{}\nrun 300 mixed-gate pass 1", LEGACY.format),
2653 );
2654 let history = crate::gate_evidence::history_in(&dir);
2655 let mut got: Vec<(String, String)> = history
2656 .runs
2657 .iter()
2658 .map(|(k, r)| (k.clone(), r.gate.clone()))
2659 .collect();
2660 got.sort();
2661 assert_eq!(got, [(tree, "new-gate".to_string())]);
2662 let _ = std::fs::remove_dir_all(&dir); }
2664
2665 #[test]
2666 fn forget_removes_the_written_refs() {
2667 let (dir, _head, tree) = unstamped("forget-written");
2668 plant(
2669 &dir,
2670 GREEN.notes_ref,
2671 &tree,
2672 &format!("{} test@g", GREEN.format),
2673 );
2674 plant(&dir, WRITE.done_ref, &tree, "done");
2675 in_repo(&dir, || {
2676 assert_eq!(tree_tokens(&tree).len(), 1);
2677 assert!(forget());
2678 assert!(tree_tokens(&tree).is_empty(), "{:?}", tree_tokens(&tree));
2679 });
2680 for r in full_refs(&WRITE) {
2681 let out = std::process::Command::new("git")
2682 .args(["-C"])
2683 .arg(&dir)
2684 .args(["rev-parse", "--verify", "-q", &r])
2685 .output()
2686 .unwrap();
2687 assert!(!out.status.success(), "{r} survived forget");
2688 }
2689 let _ = std::fs::remove_dir_all(&dir); }
2691
2692 #[test]
2693 fn writes_go_under_the_green_names_and_each_full_ref_names_its_ref() {
2694 assert_eq!(WRITE, GREEN);
2695 assert_eq!(FORMAT, "greengate-gate-v1");
2696 for (full, short) in [
2697 (NOTES_FULL_REF, NOTES_REF),
2698 (INPUTS_FULL_REF, INPUTS_REF),
2699 (CLUSTER_FULL_REF, CLUSTER_REF),
2700 (DONE_FULL_REF, DONE_REF),
2701 ] {
2702 assert_eq!(full, format!("refs/notes/{short}"));
2703 assert!(full.starts_with("refs/notes/greengate-gate"), "{full}");
2704 }
2705 let (dir, head, tree) = unstamped("write-green");
2708 plant(
2709 &dir,
2710 LEGACY.notes_ref,
2711 &tree,
2712 &format!("{} test@old", LEGACY.format),
2713 );
2714 in_repo(&dir, || {
2715 assert!(stamp_push(&head, &tree, &["suite@p".to_string()]));
2716 let written = git(&dir, &["notes", "--ref", GREEN.notes_ref, "show", &tree]);
2717 assert_eq!(written, format!("{} suite@p", GREEN.format));
2718 let old = git(&dir, &["notes", "--ref", LEGACY.notes_ref, "show", &tree]);
2720 assert_eq!(old, format!("{} test@old", LEGACY.format));
2721 });
2722 let _ = std::fs::remove_dir_all(&dir); }
2724}