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(crate) const READ: [GateNames; 1] = [WRITE];
136
137pub const FORMAT: &str = WRITE.format;
141
142pub const NOTES_REF: &str = WRITE.notes_ref;
144
145pub const NOTES_FULL_REF: &str = "refs/notes/greengate-gate";
148
149pub const INPUTS_REF: &str = WRITE.inputs_ref;
157
158pub const CLUSTER_REF: &str = WRITE.cluster_ref;
163pub const CLUSTER_FULL_REF: &str = "refs/notes/greengate-gate-cluster";
164
165pub const DONE_REF: &str = WRITE.done_ref;
173pub const DONE_FULL_REF: &str = "refs/notes/greengate-gate-done";
174
175pub const PROVENANCE: &str = "provenance";
179pub const INPUTS_FULL_REF: &str = "refs/notes/greengate-gate-inputs";
180
181const MARKER: &str = crate::names::GATE_MARKER;
183
184const PUSH_STAMPS: &str = "greengate.pushStamps";
188
189pub fn push_stamps_enabled(settings: &crate::config::Settings) -> bool {
191 crate::config::boolean_or(settings, PUSH_STAMPS, true)
192}
193
194const COMMIT_STAMPS: &str = "greengate.commitStamps";
199
200pub fn commit_stamps_enabled(settings: &crate::config::Settings) -> bool {
203 crate::config::boolean_or(settings, COMMIT_STAMPS, true)
204}
205
206const RUN: &str = "run";
209
210const MAX_RUNS: usize = 64;
215
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223pub enum RunOutcome {
224 Passed,
225 Failed,
226 Warned,
227 Fixed,
228 Unavailable,
229 Inert,
230 Cold,
234 Busy,
236 Skew,
238 Withheld,
241 Cancelled,
243 Slow,
246 Deferred,
248}
249
250impl RunOutcome {
251 pub fn as_str(self) -> &'static str {
252 match self {
253 RunOutcome::Passed => "pass",
254 RunOutcome::Failed => "fail",
255 RunOutcome::Warned => "warn",
256 RunOutcome::Fixed => "fixed",
257 RunOutcome::Unavailable => "unavailable",
258 RunOutcome::Inert => "inert",
259 RunOutcome::Cold => "cold",
260 RunOutcome::Busy => "busy",
261 RunOutcome::Skew => "skew",
262 RunOutcome::Withheld => "withheld",
263 RunOutcome::Cancelled => "cancelled",
264 RunOutcome::Slow => "slow",
265 RunOutcome::Deferred => "deferred",
266 }
267 }
268
269 pub fn parse(s: &str) -> Option<RunOutcome> {
273 Some(match s {
274 "pass" => RunOutcome::Passed,
275 "fail" => RunOutcome::Failed,
276 "warn" => RunOutcome::Warned,
277 "fixed" => RunOutcome::Fixed,
278 "unavailable" => RunOutcome::Unavailable,
279 "inert" => RunOutcome::Inert,
280 "cold" => RunOutcome::Cold,
281 "busy" => RunOutcome::Busy,
282 "skew" => RunOutcome::Skew,
283 "withheld" => RunOutcome::Withheld,
284 "cancelled" => RunOutcome::Cancelled,
285 "slow" => RunOutcome::Slow,
286 "deferred" => RunOutcome::Deferred,
287 _ => return None,
288 })
289 }
290
291 pub fn is_verdict(self) -> bool {
295 matches!(self, RunOutcome::Passed | RunOutcome::Failed)
296 }
297}
298
299#[derive(Debug, Clone, PartialEq, Eq)]
306pub struct Run {
307 pub at: u64,
309 pub gate: String,
310 pub outcome: RunOutcome,
311 pub ms: u64,
312}
313
314impl Run {
315 fn render(&self) -> String {
316 format!(
317 "{RUN} {} {} {} {}",
318 self.at,
319 self.gate,
320 self.outcome.as_str(),
321 self.ms
322 )
323 }
324
325 fn parse(line: &str) -> Option<Run> {
328 let mut t = line.split_whitespace();
329 if t.next() != Some(RUN) {
330 return None;
331 }
332 let at = t.next()?.parse().ok()?;
333 let gate = t.next()?.to_string();
334 let outcome = RunOutcome::parse(t.next()?)?;
335 let ms = t.next()?.parse().ok()?;
336 Some(Run {
337 at,
338 gate,
339 outcome,
340 ms,
341 })
342 }
343}
344
345#[derive(Debug, Clone, Default, PartialEq, Eq)]
354pub struct Note {
355 pub tokens: Vec<String>,
356 pub deferred: Vec<String>,
359 pub runs: Vec<Run>,
360 pub provenance: Vec<String>,
362}
363
364const DEFERRED: &str = "deferred";
366
367impl Note {
368 pub fn parse(body: &str) -> Note {
372 Note::parse_as(body, FORMAT)
373 }
374
375 pub(crate) fn parse_as(body: &str, format: &str) -> Note {
379 let mut lines = body.lines();
380 let Some(first) = lines.next() else {
381 return Note::default();
382 };
383 let mut tokens = first.split_whitespace();
384 if tokens.next() != Some(format) {
385 return Note::default();
386 }
387 let mut deferred = Vec::new();
388 let mut runs = Vec::new();
389 let mut provenance = Vec::new();
390 for line in lines {
391 if is_provenance(line) {
392 provenance.push(line.trim().to_string());
393 continue;
394 }
395 let mut t = line.split_whitespace();
396 match (t.next(), t.next(), t.next()) {
397 (Some(DEFERRED), Some(gate), None) => {
398 if !deferred.iter().any(|d| d == gate) {
399 deferred.push(gate.to_string());
400 }
401 }
402 _ => runs.extend(Run::parse(line)),
403 }
404 }
405 Note {
406 tokens: tokens.map(str::to_string).collect(),
407 deferred,
408 runs,
409 provenance,
410 }
411 }
412
413 pub fn render(&self) -> String {
416 let mut body = format!("{FORMAT} {}", self.tokens.join(" "));
417 for gate in &self.deferred {
418 body.push('\n');
419 body.push_str(&format!("{DEFERRED} {gate}"));
420 }
421 for run in &self.runs {
422 body.push('\n');
423 body.push_str(&run.render());
424 }
425 for line in &self.provenance {
426 body.push('\n');
427 body.push_str(line);
428 }
429 body
430 }
431
432 fn add_tokens(&mut self, tokens: &[String]) {
433 for t in tokens {
434 if !self.tokens.iter().any(|have| have == t) {
435 self.tokens.push(t.clone());
436 }
437 }
438 }
439
440 fn add_runs(&mut self, runs: &[Run]) {
442 self.runs.extend(runs.iter().cloned());
443 if self.runs.len() > MAX_RUNS {
444 self.runs.drain(..self.runs.len() - MAX_RUNS);
445 }
446 }
447}
448
449pub fn is_provenance(line: &str) -> bool {
452 line.split_whitespace().next() == Some(PROVENANCE)
453}
454
455fn note_at(key: &str) -> Note {
461 note_in(NOTES_REF, key)
462}
463
464fn note_in(notes_ref: &str, key: &str) -> Note {
465 crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
466 .map(|body| Note::parse(&body))
467 .unwrap_or_default()
468}
469
470fn stamp_in(which: fn(&GateNames) -> &'static str, key: &str) -> Note {
474 READ.iter()
475 .find_map(|set| read_in(set, which(set), key))
476 .unwrap_or_default()
477}
478
479fn read_in(set: &GateNames, notes_ref: &str, key: &str) -> Option<Note> {
486 crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
487 .map(|body| Note::parse_as(&body, set.format))
488}
489
490fn stamp_at(key: &str) -> Note {
492 stamp_in(|s| s.notes_ref, key)
493}
494
495fn input_tokens(tree: &str) -> Vec<String> {
504 let Some(spec) = crate::attest_inputs::spec_at(tree) else {
505 return canon_tokens(tree);
506 };
507 let mut out: Vec<String> = Vec::new();
508 for (gate, _) in &spec.gates {
509 if !manifest_is_an_input(tree, &spec, gate) {
510 continue;
511 }
512 let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
513 continue;
514 };
515 let note = READ.iter().find_map(|set| {
518 let key = crate::attest_inputs::input_key(&set.attest, gate, &fp)?;
519 read_in(set, set.inputs_ref, &key)
520 });
521 for t in note.unwrap_or_default().tokens {
522 if crate::gate_identity::base(&t) == gate.as_str() && !out.contains(&t) {
523 out.push(t);
524 }
525 }
526 }
527 out
528}
529
530fn canon_tokens(tree: &str) -> Vec<String> {
537 let Some(canon) = crate::attest_inputs::canonical_route(tree) else {
538 return Vec::new();
539 };
540 READ.iter()
541 .find_map(|set| {
542 let key = crate::attest_inputs::canon_gate_key(set.canon_domain, &canon)?;
543 read_in(set, set.inputs_ref, &key)
544 })
545 .map(|note| note.tokens)
546 .unwrap_or_default()
547}
548
549fn canon_key_of(tree: &str) -> Option<String> {
552 let canon = crate::attest_inputs::canonical_route(tree)?;
553 crate::attest_inputs::canon_gate_key(WRITE.canon_domain, &canon)
554}
555
556fn file_canon(tree: &str, tokens: &[String]) {
560 let Some(key) = canon_key_of(tree) else {
561 return;
562 };
563 let mut note = note_in(INPUTS_REF, &key);
564 note.add_tokens(tokens);
565 let _ = write_note_in(INPUTS_REF, &key, ¬e);
566}
567
568fn file_inputs(tree: &str, tokens: &[String]) {
573 if tokens.is_empty() {
574 return;
575 }
576 let Some(spec) = crate::attest_inputs::spec_at(tree) else {
577 file_canon(tree, tokens);
578 return;
579 };
580 for (gate, _) in &spec.gates {
581 let mine: Vec<String> = tokens
582 .iter()
583 .filter(|t| crate::gate_identity::base(t) == gate.as_str())
584 .cloned()
585 .collect();
586 if mine.is_empty() || !manifest_is_an_input(tree, &spec, gate) {
587 continue;
588 }
589 let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
590 continue;
591 };
592 let Some(key) = crate::attest_inputs::input_key(&WRITE.attest, gate, &fp) else {
593 continue;
594 };
595 let mut note = note_in(INPUTS_REF, &key);
596 note.add_tokens(&mine);
597 let _ = write_note_in(INPUTS_REF, &key, ¬e);
598 }
599}
600
601fn manifest_is_an_input(tree: &str, spec: &crate::attest_inputs::Spec, gate: &str) -> bool {
607 let tracked = [crate::manifest::MANIFEST, crate::names::old::MANIFEST]
609 .into_iter()
610 .find(|name| crate::git::succeeds(&["cat-file", "-e", &format!("{tree}:{name}")]));
611 tracked.map_or(true, |name| {
612 crate::attest_inputs::declares(spec, gate, name)
613 })
614}
615
616fn inputs_ref_exists() -> bool {
621 READ.iter().any(|set| {
622 crate::git::succeeds(&[
623 "rev-parse",
624 "-q",
625 "--verify",
626 &format!("refs/notes/{}", set.inputs_ref),
627 ])
628 })
629}
630
631pub fn tree_tokens(tree: &str) -> Vec<String> {
635 let mut tokens = stamp_at(tree).tokens;
636 if inputs_ref_exists() {
637 for t in input_tokens(tree) {
638 if !tokens.contains(&t) {
639 tokens.push(t);
640 }
641 }
642 }
643 tokens
644}
645
646pub fn stamp_tree(tree: &str, tokens: &[String]) -> bool {
650 let mut note = note_at(tree);
651 note.add_tokens(tokens);
652 let ok = write_note(tree, ¬e);
653 file_inputs(tree, tokens);
654 ok
655}
656
657fn write_note(key: &str, note: &Note) -> bool {
659 write_note_in(NOTES_REF, key, note)
660}
661
662fn write_note_in(notes_ref: &str, key: &str, note: &Note) -> bool {
663 let body = note.render();
664 crate::git::succeeds(&["notes", "--ref", notes_ref, "add", "-f", "-m", &body, key])
665}
666
667pub fn record_runs(key: &str, runs: &[Run]) {
678 let runs: Vec<Run> = runs
683 .iter()
684 .filter(|r| !r.gate.is_empty() && !r.gate.contains(char::is_whitespace))
685 .cloned()
686 .collect();
687 if runs.is_empty() {
688 return;
689 }
690 let mut note = note_at(key);
691 note.add_runs(&runs);
692 let _ = write_note(key, ¬e);
693}
694
695pub fn record_deferred(tree: &str, gates: &[String]) {
699 let gates: Vec<&String> = gates
700 .iter()
701 .filter(|g| !g.is_empty() && !g.contains(char::is_whitespace))
702 .collect();
703 if gates.is_empty() {
704 return;
705 }
706 let mut note = note_at(tree);
707 for g in gates {
708 if !note.deferred.contains(g) {
709 note.deferred.push(g.clone());
710 }
711 }
712 let _ = write_note(tree, ¬e); }
714
715pub fn deferred_on(tree: &str) -> Vec<String> {
718 stamp_at(tree).deferred
719}
720
721pub fn deferred_for(commits: &[String], gate: &str) -> HashSet<String> {
725 let mut out = HashSet::new();
726 if commits.is_empty() {
727 return out;
728 }
729 let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
730 args.extend(commits.iter().map(String::as_str));
731 let Some(list) = crate::git::stdout(&args) else {
732 return out;
733 };
734 for line in list.lines() {
735 let mut it = line.split_whitespace();
736 let (Some(commit), Some(tree)) = (it.next(), it.next()) else {
737 continue;
738 };
739 if [commit, tree]
740 .iter()
741 .any(|key| stamp_at(key).deferred.iter().any(|d| d == gate))
742 {
743 out.insert(commit.to_string());
744 }
745 }
746 out
747}
748
749fn marker_path() -> Option<PathBuf> {
753 let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
754 Some(std::path::Path::new(&dir).join(MARKER))
755}
756
757pub fn record(scripts: &[&str]) {
768 let Some(path) = marker_path() else { return };
769 if scripts.is_empty() {
770 let _ = std::fs::remove_file(&path);
771 return;
772 }
773 let Some(tree) = crate::git::stdout(&["write-tree"]) else {
777 crate::hooks::common::warn(
781 "git would not name the staged tree — this commit records no gate stamp",
782 );
783 let _ = std::fs::remove_file(&path);
784 return;
785 };
786 let mut body = format!("{FORMAT}\n{tree}\n");
787 for s in scripts {
788 body.push_str(s);
789 body.push('\n');
790 }
791 let _ = std::fs::write(&path, body);
792}
793
794pub fn vouched_for_staged_tree() -> HashSet<String> {
822 let mut out = HashSet::new();
823 let Some(tree) = crate::git::stdout(&["write-tree"]) else {
824 return out;
825 };
826 if let Some(path) = marker_path() {
827 if let Ok(body) = std::fs::read_to_string(&path) {
828 let mut lines = body.lines();
829 if lines.next() == Some(FORMAT) && lines.next() == Some(tree.as_str()) {
830 out.extend(
831 lines
832 .filter(|l| !l.trim().is_empty() && !is_provenance(l))
833 .map(str::to_string),
834 );
835 }
836 }
837 }
838 out.extend(stamp_at(&tree).tokens);
847 if inputs_ref_exists() {
853 out.extend(input_tokens(&tree));
854 }
855 out
856}
857
858pub fn bind_to_head() -> Vec<String> {
869 let Some(path) = marker_path() else {
870 return Vec::new();
871 };
872 let Ok(body) = std::fs::read_to_string(&path) else {
873 return Vec::new(); };
875 let _ = std::fs::remove_file(&path);
876 let mut lines = body.lines();
877 if lines.next() != Some(FORMAT) {
878 return Vec::new();
879 }
880 let Some(tree) = lines.next() else {
881 return Vec::new();
882 };
883 let scripts: Vec<&str> = lines
884 .filter(|l| !l.trim().is_empty() && !is_provenance(l))
885 .collect();
886 if scripts.is_empty() {
887 return Vec::new();
888 }
889 let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
890 crate::hooks::common::warn(
891 "git would not name this commit's tree — no gate stamp was written",
892 );
893 return Vec::new();
894 };
895 if head_tree != tree {
898 return Vec::new();
899 }
900 let scripts: Vec<String> = scripts.iter().map(|s| s.to_string()).collect();
901 let mut tree_note = note_at(&head_tree);
926 tree_note.add_tokens(&scripts);
927 let _ = write_note(&head_tree, &tree_note);
928 file_inputs(&head_tree, &scripts);
929 let mut head_note = note_at("HEAD");
930 head_note.add_tokens(&scripts);
931 if !write_note("HEAD", &head_note) {
932 crate::hooks::common::warn(
935 "git refused to write the gate stamp — these checks will run again at push",
936 );
937 return Vec::new();
938 }
939 scripts
942 .iter()
943 .map(|s| crate::gate_identity::base(s).to_string())
944 .collect()
945}
946
947pub fn stamp_push(commit: &str, tree: &str, gates: &[String]) -> bool {
956 if gates.is_empty() {
957 return false;
958 }
959 let mut written = false;
960 for key in [tree, commit] {
961 let mut note = note_at(key);
962 note.add_tokens(gates);
963 let ok = write_note(key, ¬e);
964 if key == commit {
965 written = ok;
966 }
967 }
968 file_inputs(tree, gates);
969 if !written {
970 crate::hooks::common::warn(
971 "git refused to write the push stamp — these gates will run again on the next push",
972 );
973 }
974 written
975}
976
977#[derive(Debug, Clone, Copy, PartialEq, Eq)]
980pub enum Completion {
981 Warned,
983 FailedUnderWarn,
986 Unavailable,
989}
990
991const UNAVAILABLE_FOR_SECS: u64 = 60 * 60;
993
994fn completion_word(how: Completion, token: &str, now: u64) -> String {
996 match how {
997 Completion::Warned => format!("warned:{token}"),
998 Completion::FailedUnderWarn => format!("failed-under-warn:{token}"),
999 Completion::Unavailable => format!("unavailable:{now}:{token}"),
1000 }
1001}
1002
1003fn completion_answers(word: &str, token: &str, severity: crate::check::Severity, now: u64) -> bool {
1005 if word.strip_prefix("warned:") == Some(token) {
1006 return true;
1007 }
1008 if word.strip_prefix("failed-under-warn:") == Some(token) {
1009 return severity == crate::check::Severity::Warn;
1010 }
1011 word.strip_prefix("unavailable:")
1012 .and_then(|rest| rest.split_once(':'))
1013 .is_some_and(|(at, tok)| {
1014 tok == token
1015 && at
1016 .parse::<u64>()
1017 .is_ok_and(|at| now.saturating_sub(at) <= UNAVAILABLE_FOR_SECS)
1018 })
1019}
1020
1021fn now_secs() -> u64 {
1022 std::time::SystemTime::now()
1023 .duration_since(std::time::UNIX_EPOCH)
1024 .map(|d| d.as_secs())
1025 .unwrap_or(0)
1026}
1027
1028pub fn record_done(tree: &str, tokens: &[String], how: Completion) -> Result<(), String> {
1034 if tokens.is_empty() {
1035 return Ok(());
1036 }
1037 let now = now_secs();
1038 let mut note = note_in(DONE_REF, tree);
1039 if how == Completion::Unavailable {
1040 note.tokens.retain(|word| {
1041 !word
1042 .strip_prefix("unavailable:")
1043 .and_then(|rest| rest.split_once(':'))
1044 .is_some_and(|(_, token)| tokens.iter().any(|t| t == token))
1045 });
1046 }
1047 let words: Vec<String> = tokens
1048 .iter()
1049 .map(|t| completion_word(how, t, now))
1050 .collect();
1051 note.add_tokens(&words);
1052 if write_note_in(DONE_REF, tree, ¬e) {
1053 Ok(())
1054 } else {
1055 Err(format!(
1056 "git refused to record the completed gates on {tree}"
1057 ))
1058 }
1059}
1060
1061pub fn done_on_every(commits: &[String], token: &str, severity: crate::check::Severity) -> bool {
1066 let now = now_secs();
1067 !commits.is_empty()
1068 && commits.iter().all(|c| {
1069 crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]).is_some_and(|tree| {
1070 stamp_in(|s| s.done_ref, &tree)
1071 .tokens
1072 .iter()
1073 .any(|word| completion_answers(word, token, severity, now))
1074 })
1075 })
1076}
1077
1078pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
1084 let mut out = HashMap::new();
1085 if commits.is_empty() {
1086 return out;
1087 }
1088 let lists: Option<Vec<String>> = READ
1091 .iter()
1092 .map(|set| crate::git::stdout(&["notes", "--ref", set.notes_ref, "list"]))
1093 .collect();
1094 let Some(lists) = lists else {
1095 crate::hooks::common::warn(
1105 "git would not list the gate stamps — every gated check will run again",
1106 );
1107 return out;
1108 };
1109 let noted: HashSet<&str> = lists
1110 .iter()
1111 .flat_map(|list| list.lines())
1112 .filter_map(|l| l.split_whitespace().nth(1))
1113 .collect();
1114 let mut trees: HashMap<String, String> = HashMap::new();
1118 {
1119 let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
1120 args.extend(commits.iter().map(String::as_str));
1121 if let Some(out) = crate::git::stdout(&args) {
1122 for line in out.lines() {
1123 let mut it = line.split_whitespace();
1124 if let (Some(c), Some(t)) = (it.next(), it.next()) {
1125 trees.insert(c.to_string(), t.to_string());
1126 }
1127 }
1128 }
1129 }
1133
1134 let by_inputs = inputs_ref_exists();
1140
1141 for commit in commits {
1142 let mut tokens: Vec<String> = Vec::new();
1161 let mut keys: Vec<&str> = Vec::new();
1162 if noted.contains(commit.as_str()) {
1163 keys.push(commit);
1164 }
1165 if let Some(tree) = trees.get(commit).filter(|t| noted.contains(t.as_str())) {
1166 keys.push(tree);
1167 }
1168 for key in keys {
1169 for t in stamp_at(key).tokens {
1170 if !tokens.contains(&t) {
1171 tokens.push(t);
1172 }
1173 }
1174 }
1175 if by_inputs {
1176 if let Some(tree) = trees.get(commit) {
1177 for t in input_tokens(tree) {
1178 if !tokens.contains(&t) {
1179 tokens.push(t);
1180 }
1181 }
1182 }
1183 }
1184 if tokens.is_empty() {
1185 continue;
1186 }
1187 out.insert(commit.clone(), tokens);
1188 }
1189 out
1190}
1191
1192pub fn forget() -> bool {
1197 let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
1198 let mut deleted = false;
1200 for set in READ {
1201 for r in full_refs(&set) {
1202 deleted |= crate::git::succeeds(&["update-ref", "-d", &r]);
1203 }
1204 }
1205 marker || deleted
1206}
1207
1208fn full_refs(set: &GateNames) -> [String; 4] {
1210 [set.notes_ref, set.inputs_ref, set.cluster_ref, set.done_ref]
1211 .map(|short| format!("refs/notes/{short}"))
1212}
1213
1214pub(crate) fn cluster_tokens(tree: &str) -> Vec<String> {
1217 stamp_in(|s| s.cluster_ref, tree).tokens
1218}
1219
1220pub(crate) fn stamp_cluster(tree: &str, token: &str, provenance: &str) -> bool {
1223 let mut note = note_in(CLUSTER_REF, tree);
1224 note.add_tokens(&[token.to_string()]);
1225 let line = format!("{PROVENANCE} {token} {provenance}");
1226 note.provenance
1227 .retain(|l| l.split_whitespace().nth(1) != Some(token));
1228 note.provenance.push(line);
1229 write_note_in(CLUSTER_REF, tree, ¬e)
1230}
1231
1232pub(crate) fn cluster_stamps_for(commits: &[String]) -> HashMap<String, (String, Vec<String>)> {
1236 let mut out = HashMap::new();
1237 for commit in commits {
1238 let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")]) else {
1239 continue;
1240 };
1241 let tokens = cluster_tokens(&tree);
1242 if !tokens.is_empty() {
1243 out.insert(commit.clone(), (tree, tokens));
1244 }
1245 }
1246 out
1247}
1248
1249pub fn forget_in(repo: &std::path::Path) -> bool {
1251 let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
1252 .is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
1253 let mut deleted = false;
1254 for set in READ {
1255 for r in full_refs(&set) {
1256 deleted |= crate::git::succeeds_in(repo, &["update-ref", "-d", &r]);
1257 }
1258 }
1259 marker || deleted
1260}
1261
1262#[cfg(test)]
1263mod tests {
1264 use super::*;
1265 use std::path::Path;
1266
1267 #[test]
1271 fn a_completion_answers_only_while_it_should() {
1272 use crate::check::Severity::{Block, Warn};
1273 let now = 1_700_000_000;
1274 let word = |how| completion_word(how, "gate-tok", now);
1275 assert!(completion_answers(
1276 &word(Completion::Warned),
1277 "gate-tok",
1278 Block,
1279 now
1280 ));
1281 assert!(completion_answers(
1282 &word(Completion::FailedUnderWarn),
1283 "gate-tok",
1284 Warn,
1285 now
1286 ));
1287 assert!(!completion_answers(
1288 &word(Completion::FailedUnderWarn),
1289 "gate-tok",
1290 Block,
1291 now
1292 ));
1293 let unavailable = word(Completion::Unavailable);
1294 assert!(completion_answers(
1295 &unavailable,
1296 "gate-tok",
1297 Block,
1298 now + 3600
1299 ));
1300 assert!(!completion_answers(
1301 &unavailable,
1302 "gate-tok",
1303 Block,
1304 now + 3601
1305 ));
1306 assert!(!completion_answers(
1307 &word(Completion::Warned),
1308 "other-tok",
1309 Warn,
1310 now
1311 ));
1312 }
1313
1314 fn repo(name: &str) -> PathBuf {
1317 let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
1318 let _ = std::fs::remove_dir_all(&dir);
1319 std::fs::create_dir_all(&dir).unwrap();
1320 git(&dir, &["init", "-q", "--template=", "."]);
1321 git(&dir, &["config", "user.email", "t@t.test"]);
1322 git(&dir, &["config", "user.name", "t"]);
1323 dir
1324 }
1325
1326 fn git(dir: &Path, args: &[&str]) -> String {
1335 let out = std::process::Command::new("git")
1336 .arg("-C")
1337 .arg(dir)
1338 .args(args)
1339 .output()
1340 .expect("git");
1341 assert!(
1342 out.status.success(),
1343 "fixture: git {args:?} in {} exited {:?}: {}",
1344 dir.display(),
1345 out.status.code(),
1346 String::from_utf8_lossy(&out.stderr).trim()
1347 );
1348 String::from_utf8_lossy(&out.stdout).trim().to_string()
1349 }
1350
1351 fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
1355 let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
1356 let prev = std::env::current_dir().unwrap();
1357 std::env::set_current_dir(dir).unwrap();
1358 let r = f();
1359 std::env::set_current_dir(prev).unwrap();
1360 r
1361 }
1362
1363 #[test]
1364 fn the_commit_note_does_not_hide_the_tree_notes_push_tokens() {
1365 let dir = repo("union");
1366 std::fs::write(dir.join("a.ts"), "x").unwrap();
1367 git(&dir, &["add", "a.ts"]);
1368 in_repo(&dir, || {
1369 record(&["test"]);
1370 git(&dir, &["commit", "-qm", "chore: a"]);
1371 bind_to_head();
1372 let head = git(&dir, &["rev-parse", "HEAD"]);
1373 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1374 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1377 assert_eq!(note_at(&head).tokens, vec!["test".to_string()]);
1378 let stamps = stamps_for(std::slice::from_ref(&head));
1379 assert_eq!(
1380 stamps.get(&head).map(Vec::as_slice),
1381 Some(&["test".to_string(), "pre-push-cargo-test".to_string()][..]),
1382 "both notes speak for the same tree"
1383 );
1384 });
1385 let _ = std::fs::remove_dir_all(&dir);
1386 }
1387
1388 #[test]
1392 fn an_unavailable_record_replaces_its_predecessor_only() {
1393 let dir = repo("done-unavailable");
1394 std::fs::write(dir.join("a.ts"), "x").unwrap();
1395 git(&dir, &["add", "a.ts"]);
1396 git(&dir, &["commit", "-qm", "chore: a"]);
1397 in_repo(&dir, || {
1398 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1399 let one = |t: &str| vec![t.to_string()];
1400 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("first");
1401 record_done(&tree, &one("lint@b"), Completion::Unavailable).expect("other gate");
1402 record_done(&tree, &one("lint@b"), Completion::Warned).expect("a warning");
1403 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("again");
1404 let words = note_in(DONE_REF, &tree).tokens;
1405 let unavailable_for = |token: &str| {
1406 words
1407 .iter()
1408 .filter(|w| w.starts_with("unavailable:") && w.ends_with(&format!(":{token}")))
1409 .count()
1410 };
1411 assert_eq!(unavailable_for("suite@a"), 1, "{words:?}");
1412 assert_eq!(unavailable_for("lint@b"), 1, "{words:?}");
1413 assert!(words.contains(&"warned:lint@b".to_string()), "{words:?}");
1414 });
1415 let _ = std::fs::remove_dir_all(&dir); }
1417
1418 #[test]
1419 fn a_commit_with_only_a_tree_note_still_reads_the_tree_tokens() {
1420 let dir = repo("tree-only");
1421 std::fs::write(dir.join("a.ts"), "x").unwrap();
1422 git(&dir, &["add", "a.ts"]);
1423 git(&dir, &["commit", "-qm", "chore: a"]);
1424 in_repo(&dir, || {
1425 let head = git(&dir, &["rev-parse", "HEAD"]);
1426 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1427 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1428 let stamps = stamps_for(std::slice::from_ref(&head));
1429 assert_eq!(
1430 stamps.get(&head).map(Vec::as_slice),
1431 Some(&["pre-push-cargo-test".to_string()][..])
1432 );
1433 });
1434 let _ = std::fs::remove_dir_all(&dir);
1435 }
1436
1437 #[test]
1438 fn a_commit_with_only_a_commit_note_still_reads_its_tokens() {
1439 let dir = repo("commit-only");
1440 std::fs::write(dir.join("a.ts"), "x").unwrap();
1441 git(&dir, &["add", "a.ts"]);
1442 git(&dir, &["commit", "-qm", "chore: a"]);
1443 in_repo(&dir, || {
1444 let head = git(&dir, &["rev-parse", "HEAD"]);
1445 let mut note = Note::default();
1446 note.add_tokens(&["typecheck".to_string()]);
1447 assert!(write_note(&head, ¬e));
1448 let stamps = stamps_for(std::slice::from_ref(&head));
1449 assert_eq!(
1450 stamps.get(&head).map(Vec::as_slice),
1451 Some(&["typecheck".to_string()][..])
1452 );
1453 });
1454 let _ = std::fs::remove_dir_all(&dir);
1455 }
1456
1457 #[test]
1458 fn a_token_on_both_notes_is_read_once() {
1459 let dir = repo("dedup");
1460 std::fs::write(dir.join("a.ts"), "x").unwrap();
1461 git(&dir, &["add", "a.ts"]);
1462 in_repo(&dir, || {
1463 record(&["test"]);
1464 git(&dir, &["commit", "-qm", "chore: a"]);
1465 bind_to_head(); let head = git(&dir, &["rev-parse", "HEAD"]);
1467 let stamps = stamps_for(std::slice::from_ref(&head));
1468 assert_eq!(
1469 stamps.get(&head).map(Vec::as_slice),
1470 Some(&["test".to_string()][..])
1471 );
1472 });
1473 let _ = std::fs::remove_dir_all(&dir);
1474 }
1475
1476 #[test]
1477 fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
1478 let dir = repo("roundtrip");
1479 std::fs::write(dir.join("a.ts"), "x").unwrap();
1480 git(&dir, &["add", "a.ts"]);
1481 in_repo(&dir, || {
1482 record(&["typecheck", "test"]);
1483 git(&dir, &["commit", "-qm", "chore: a"]);
1484 let stamped = bind_to_head();
1485 assert_eq!(
1486 stamped,
1487 vec!["typecheck".to_string(), "test".to_string()],
1488 "bind_to_head reports the scripts it stamped"
1489 );
1490 let head = git(&dir, &["rev-parse", "HEAD"]);
1491 let stamps = stamps_for(std::slice::from_ref(&head));
1492 assert_eq!(
1493 stamps.get(&head).map(Vec::as_slice),
1494 Some(&["typecheck".to_string(), "test".to_string()][..])
1495 );
1496 assert!(!dir.join(".git").join(MARKER).exists());
1503 });
1504 let _ = std::fs::remove_dir_all(&dir);
1505 }
1506
1507 #[test]
1508 fn a_marker_for_a_different_tree_stamps_nothing() {
1509 let dir = repo("stale");
1510 std::fs::write(dir.join("a.ts"), "x").unwrap();
1511 git(&dir, &["add", "a.ts"]);
1512 in_repo(&dir, || {
1513 record(&["typecheck"]);
1514 std::fs::write(dir.join("a.ts"), "y").unwrap();
1517 git(&dir, &["add", "a.ts"]);
1518 git(&dir, &["commit", "-qm", "chore: different"]);
1519 assert!(
1520 bind_to_head().is_empty(),
1521 "bind_to_head reports nothing when the tree moved"
1522 );
1523 let head = git(&dir, &["rev-parse", "HEAD"]);
1524 assert!(
1525 stamps_for(&[head]).is_empty(),
1526 "a stale marker must not vouch"
1527 );
1528 assert!(
1529 !dir.join(".git").join(MARKER).exists(),
1530 "consumed either way"
1531 );
1532 });
1533 let _ = std::fs::remove_dir_all(&dir);
1534 }
1535
1536 #[test]
1537 fn an_empty_record_clears_a_previous_marker() {
1538 let dir = repo("clears");
1539 std::fs::write(dir.join("a.ts"), "x").unwrap();
1540 git(&dir, &["add", "a.ts"]);
1541 in_repo(&dir, || {
1542 record(&["typecheck"]);
1543 assert!(dir.join(".git").join(MARKER).exists());
1544 record(&[]);
1545 assert!(!dir.join(".git").join(MARKER).exists());
1546 });
1547 let _ = std::fs::remove_dir_all(&dir);
1548 }
1549
1550 #[test]
1555 fn a_marker_in_an_unknown_format_stamps_nothing() {
1556 let dir = repo("wrongformat");
1557 std::fs::write(dir.join("a.ts"), "x").unwrap();
1558 git(&dir, &["add", "a.ts"]);
1559 in_repo(&dir, || {
1560 let tree = git(&dir, &["write-tree"]);
1561 let marker = dir.join(".git").join(MARKER);
1562 std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
1563 git(&dir, &["commit", "-qm", "chore: a"]);
1564 bind_to_head();
1565 let head = git(&dir, &["rev-parse", "HEAD"]);
1566 assert!(
1567 stamps_for(std::slice::from_ref(&head)).is_empty(),
1568 "an unknown format was trusted"
1569 );
1570 assert!(!marker.exists(), "consumed either way");
1571 });
1572 let _ = std::fs::remove_dir_all(&dir);
1573 }
1574
1575 #[test]
1579 fn a_foreign_note_is_not_a_stamp() {
1580 let dir = repo("foreignnote");
1581 std::fs::write(dir.join("a.ts"), "x").unwrap();
1582 git(&dir, &["add", "a.ts"]);
1583 in_repo(&dir, || {
1584 git(&dir, &["commit", "-qm", "chore: a"]);
1585 git(
1586 &dir,
1587 &[
1588 "notes",
1589 "--ref",
1590 NOTES_REF,
1591 "add",
1592 "-m",
1593 "typecheck test",
1594 "HEAD",
1595 ],
1596 );
1597 let head = git(&dir, &["rev-parse", "HEAD"]);
1598 assert!(
1599 stamps_for(std::slice::from_ref(&head)).is_empty(),
1600 "a note without the format token was trusted"
1601 );
1602 });
1603 let _ = std::fs::remove_dir_all(&dir);
1604 }
1605
1606 #[test]
1610 fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
1611 let dir = repo("no-stamps");
1612 std::fs::write(dir.join("a.ts"), "x").unwrap();
1613 git(&dir, &["add", "a.ts"]);
1614 git(&dir, &["commit", "-qm", "chore: a"]);
1615 in_repo(&dir, || {
1616 assert_eq!(
1617 crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
1618 Some(""),
1619 "an absent notes ref must be an ANSWER, not a failure — the \
1620 no-stamps path and the git-is-broken path are told apart by it"
1621 );
1622 let head = git(&dir, &["rev-parse", "HEAD"]);
1623 assert!(stamps_for(&[head]).is_empty());
1624 });
1625 let _ = std::fs::remove_dir_all(&dir);
1626 }
1627
1628 #[test]
1635 fn a_note_from_before_the_run_lines_parses_unchanged() {
1636 let note = Note::parse("greengate-gate-v1 typecheck test");
1637 assert_eq!(note.tokens, vec!["typecheck", "test"]);
1638 assert!(note.runs.is_empty());
1639 assert_eq!(note.render(), "greengate-gate-v1 typecheck test");
1642 }
1643
1644 #[test]
1646 fn run_lines_are_read_without_disturbing_the_tokens() {
1647 let body = "greengate-gate-v1 pre-push-cargo-test\n\
1648 run 1726900000 pre-push-cargo-test pass 412391\n\
1649 run 1726903600 pre-push-audit-js fail 903\n";
1650 let note = Note::parse(body);
1651 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1652 assert_eq!(note.runs.len(), 2);
1653 assert_eq!(
1654 note.runs[0],
1655 Run {
1656 at: 1_726_900_000,
1657 gate: "pre-push-cargo-test".into(),
1658 outcome: RunOutcome::Passed,
1659 ms: 412_391,
1660 }
1661 );
1662 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1663 assert_eq!(note.render(), body.trim_end());
1664 }
1665
1666 #[test]
1670 fn an_unreadable_run_line_is_dropped_and_the_rest_survives() {
1671 let note = Note::parse(
1672 "greengate-gate-v1 test\n\
1673 run 1726900000 pre-push-cargo-test pass 400\n\
1674 run tomorrow pre-push-cargo-test pass 400\n\
1675 run 1726900001 pre-push-cargo-test sideways 400\n\
1676 banana\n\
1677 run 1726900002 pre-push-cargo-test fail 500\n",
1678 );
1679 assert_eq!(note.tokens, vec!["test"]);
1680 assert_eq!(note.runs.len(), 2, "{:?}", note.runs);
1681 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1682 }
1683
1684 #[test]
1688 fn a_deferral_is_never_a_token_and_outlives_the_run_trim() {
1689 let mut note = Note::parse("greengate-gate-v1 lint\ndeferred cargo-test\n");
1690 assert_eq!(note.tokens, vec!["lint"]);
1691 assert_eq!(note.deferred, vec!["cargo-test"]);
1692 let runs: Vec<Run> = (0..MAX_RUNS as u64 + 10)
1693 .map(|i| Run {
1694 at: 1_726_900_000 + i,
1695 gate: "pre-push-audit-js".into(),
1696 outcome: RunOutcome::Passed,
1697 ms: 1,
1698 })
1699 .collect();
1700 note.add_runs(&runs);
1701 let again = Note::parse(¬e.render());
1702 assert_eq!(again.runs.len(), MAX_RUNS);
1703 assert_eq!(again.deferred, vec!["cargo-test"]);
1704 assert_eq!(again.tokens, vec!["lint"]);
1705 }
1706
1707 #[test]
1710 fn a_foreign_note_yields_no_runs() {
1711 let note = Note::parse("hello\nrun 1726900000 pre-push-cargo-test pass 400\n");
1712 assert!(note.tokens.is_empty() && note.runs.is_empty());
1713 }
1714
1715 #[test]
1720 fn a_stamp_and_its_evidence_survive_each_other() {
1721 let dir = repo("evidence");
1722 std::fs::write(dir.join("a.ts"), "x").unwrap();
1723 git(&dir, &["add", "a.ts"]);
1724 in_repo(&dir, || {
1725 git(&dir, &["commit", "-qm", "chore: a"]);
1726 let head = git(&dir, &["rev-parse", "HEAD"]);
1727 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1728 record_runs(
1729 &tree,
1730 &[Run {
1731 at: 1_726_900_000,
1732 gate: "pre-push-cargo-test".into(),
1733 outcome: RunOutcome::Failed,
1734 ms: 412_391,
1735 }],
1736 );
1737 assert!(stamp_push(&head, &tree, &["pre-push-cargo-test".into()]));
1739 let note = note_at(&tree);
1740 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1741 assert_eq!(note.runs.len(), 1, "the evidence survived the stamp");
1742 let stamps = stamps_for(std::slice::from_ref(&head));
1744 assert_eq!(
1745 stamps.get(&head).map(Vec::as_slice),
1746 Some(&["pre-push-cargo-test".to_string()][..])
1747 );
1748 });
1749 let _ = std::fs::remove_dir_all(&dir);
1750 }
1751
1752 #[test]
1756 fn a_recorded_run_is_not_a_stamp() {
1757 let dir = repo("not-a-stamp");
1758 std::fs::write(dir.join("a.ts"), "x").unwrap();
1759 git(&dir, &["add", "a.ts"]);
1760 in_repo(&dir, || {
1761 git(&dir, &["commit", "-qm", "chore: a"]);
1762 let head = git(&dir, &["rev-parse", "HEAD"]);
1763 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1764 record_runs(
1765 &tree,
1766 &[Run {
1767 at: 1_726_900_000,
1768 gate: "pre-push-cargo-test".into(),
1769 outcome: RunOutcome::Passed,
1770 ms: 412_391,
1771 }],
1772 );
1773 assert!(
1774 stamps_for(std::slice::from_ref(&head)).is_empty(),
1775 "a run line vouched for a gate — evidence must never gate"
1776 );
1777 assert!(
1778 !vouched_for_staged_tree().contains("pre-push-cargo-test"),
1779 "a run line vouched at commit time"
1780 );
1781 let history = crate::gate_evidence::history_in(&dir);
1783 assert_eq!(history.runs.len(), 1);
1784 assert_eq!(history.runs[0].0, tree, "keyed by the content it ran on");
1785 });
1786 let _ = std::fs::remove_dir_all(&dir);
1787 }
1788
1789 #[test]
1790 fn forget_removes_the_stamps() {
1791 let dir = repo("forget");
1792 std::fs::write(dir.join("a.ts"), "x").unwrap();
1793 git(&dir, &["add", "a.ts"]);
1794 in_repo(&dir, || {
1795 record(&["typecheck"]);
1796 git(&dir, &["commit", "-qm", "chore: a"]);
1797 bind_to_head();
1798 let head = git(&dir, &["rev-parse", "HEAD"]);
1799 assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
1800 forget();
1801 assert!(stamps_for(&[head]).is_empty());
1802 });
1803 let _ = std::fs::remove_dir_all(&dir);
1804 }
1805
1806 #[test]
1820 fn a_stamp_survives_a_commit_being_rewritten_with_the_same_tree() {
1821 let dir = repo("squashed");
1822 std::fs::write(dir.join("a.ts"), "x").unwrap();
1823 git(&dir, &["add", "a.ts"]);
1824 in_repo(&dir, || {
1825 record(&["test"]);
1826 git(&dir, &["commit", "-qm", "feat: on a branch"]);
1827 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1828 let branch_tip = git(&dir, &["rev-parse", "HEAD"]);
1829
1830 git(
1834 &dir,
1835 &[
1836 "commit",
1837 "-q",
1838 "--amend",
1839 "-m",
1840 "feat: squashed by the forge",
1841 ],
1842 );
1843 let merged = git(&dir, &["rev-parse", "HEAD"]);
1844 assert_ne!(merged, branch_tip, "the fixture must produce a new commit");
1845 assert_eq!(
1846 git(&dir, &["rev-parse", "HEAD^{tree}"]),
1847 git(&dir, &["rev-parse", &format!("{branch_tip}^{{tree}}")]),
1848 "…carrying the same tree, which is the whole premise"
1849 );
1850
1851 let stamps = stamps_for(std::slice::from_ref(&merged));
1852 assert_eq!(
1853 stamps.get(&merged).map(Vec::as_slice),
1854 Some(&["test".to_string()][..]),
1855 "the stamp must follow the content, not the commit hash"
1856 );
1857 });
1858 let _ = std::fs::remove_dir_all(&dir);
1859 }
1860
1861 #[test]
1865 fn a_different_tree_gets_no_stamp_from_the_fallback() {
1866 let dir = repo("othertree");
1867 std::fs::write(dir.join("a.ts"), "x").unwrap();
1868 git(&dir, &["add", "a.ts"]);
1869 in_repo(&dir, || {
1870 record(&["test"]);
1871 git(&dir, &["commit", "-qm", "chore: stamped"]);
1872 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1873
1874 std::fs::write(dir.join("b.ts"), "y").unwrap();
1877 git(&dir, &["add", "b.ts"]);
1878 git(&dir, &["commit", "-qm", "chore: unjudged"]);
1879 let unstamped = git(&dir, &["rev-parse", "HEAD"]);
1880
1881 assert!(
1882 stamps_for(std::slice::from_ref(&unstamped)).is_empty(),
1883 "a tree nobody stamped must not inherit one"
1884 );
1885 });
1886 let _ = std::fs::remove_dir_all(&dir);
1887 }
1888
1889 fn declared(name: &str, spec: &str) -> PathBuf {
1895 let dir = repo(name);
1896 std::fs::create_dir_all(dir.join(".github")).unwrap();
1897 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
1898 std::fs::write(dir.join("a.ts"), "x").unwrap();
1899 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
1900 std::fs::write(dir.join(".github/greensummit-inputs"), spec).unwrap();
1901 git(&dir, &["add", "-A"]);
1902 in_repo(&dir, || {
1903 record(&["test@abc"]);
1904 git(&dir, &["commit", "-qm", "feat: judged"]);
1905 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1906 });
1907 dir
1908 }
1909
1910 fn plan_only_commit(dir: &Path) -> String {
1913 std::fs::write(dir.join("docs/plans/p.md"), "plan v2, closing").unwrap();
1914 git(dir, &["add", "docs/plans/p.md"]);
1915 git(dir, &["commit", "-qm", "docs(plan): done"]);
1916 git(dir, &["rev-parse", "HEAD"])
1917 }
1918
1919 #[test]
1920 fn a_plan_only_commit_reuses_the_stamp_of_a_declared_gate() {
1921 let dir = declared("plan-only", "test a.ts\n");
1922 in_repo(&dir, || {
1923 let head = plan_only_commit(&dir);
1924 let stamps = stamps_for(std::slice::from_ref(&head));
1925 assert_eq!(
1926 stamps.get(&head).map(Vec::as_slice),
1927 Some(&["test@abc".to_string()][..]),
1928 "the closing commit changed the tree and none of the declared inputs"
1929 );
1930 });
1931 let _ = std::fs::remove_dir_all(&dir);
1932 }
1933
1934 #[test]
1935 fn the_staged_tree_of_a_plan_only_commit_is_vouched_for() {
1936 let dir = declared("staged", "test a.ts\n");
1937 in_repo(&dir, || {
1938 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1939 git(&dir, &["add", "docs/plans/p.md"]);
1940 assert!(vouched_for_staged_tree().contains("test@abc"));
1941 });
1942 let _ = std::fs::remove_dir_all(&dir);
1943 }
1944
1945 #[test]
1946 fn partial_staging_is_judged_on_the_index_not_the_working_copy() {
1947 let dir = declared("partial", "test a.ts\n");
1948 in_repo(&dir, || {
1949 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1952 git(&dir, &["add", "docs/plans/p.md"]);
1953 std::fs::write(dir.join("a.ts"), "unstaged edit").unwrap();
1954 assert!(vouched_for_staged_tree().contains("test@abc"));
1955
1956 std::fs::write(dir.join("a.ts"), "staged edit").unwrap();
1959 git(&dir, &["add", "a.ts"]);
1960 std::fs::write(dir.join("a.ts"), "x").unwrap();
1961 assert!(!vouched_for_staged_tree().contains("test@abc"));
1962 });
1963 let _ = std::fs::remove_dir_all(&dir);
1964 }
1965
1966 #[test]
1967 fn a_changed_declared_input_misses() {
1968 let dir = declared("input-changed", "test a.ts\n");
1969 in_repo(&dir, || {
1970 std::fs::write(dir.join("a.ts"), "changed").unwrap();
1971 git(&dir, &["add", "a.ts"]);
1972 git(&dir, &["commit", "-qm", "feat: unjudged"]);
1973 let head = git(&dir, &["rev-parse", "HEAD"]);
1974 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1975 });
1976 let _ = std::fs::remove_dir_all(&dir);
1977 }
1978
1979 #[test]
1980 fn a_changed_declaration_misses() {
1981 let dir = declared("declaration-changed", "test a.ts\n");
1982 in_repo(&dir, || {
1983 std::fs::write(dir.join("b.ts"), "y").unwrap();
1986 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts b.ts\n").unwrap();
1987 git(&dir, &["add", "-A"]);
1988 git(&dir, &["commit", "-qm", "chore: widen the declaration"]);
1989 let head = git(&dir, &["rev-parse", "HEAD"]);
1990 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1991 });
1992 let _ = std::fs::remove_dir_all(&dir);
1993 }
1994
1995 #[test]
1996 fn a_declared_config_file_is_an_input_like_any_other() {
1997 let dir = declared("config", "test a.ts amont.conf\n");
2000 in_repo(&dir, || {
2001 assert!(!inputs_ref_exists());
2004
2005 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2006 git(&dir, &["add", "amont.conf"]);
2007 record(&["test@abc"]);
2008 git(&dir, &["commit", "-qm", "chore: config"]);
2009 assert_eq!(bind_to_head(), vec!["test".to_string()]);
2010
2011 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
2012 git(&dir, &["add", "docs/plans/p.md"]);
2013 git(&dir, &["commit", "-qm", "docs(plan): done"]);
2014 let plan = git(&dir, &["rev-parse", "HEAD"]);
2015 assert!(stamps_for(std::slice::from_ref(&plan)).contains_key(&plan));
2016
2017 std::fs::write(dir.join("amont.conf"), "scope = lib\n").unwrap();
2018 git(&dir, &["add", "amont.conf"]);
2019 git(&dir, &["commit", "-qm", "chore: scope-only change"]);
2020 let scope = git(&dir, &["rev-parse", "HEAD"]);
2021 assert!(
2022 stamps_for(std::slice::from_ref(&scope)).is_empty(),
2023 "a scope-only change must miss"
2024 );
2025 });
2026 let _ = std::fs::remove_dir_all(&dir);
2027 }
2028
2029 #[test]
2030 fn a_declared_stamp_is_read_back_as_its_complete_token() {
2031 let dir = declared("identity", "test a.ts\n");
2037 in_repo(&dir, || {
2038 let head = plan_only_commit(&dir);
2039 let tokens = stamps_for(std::slice::from_ref(&head))
2040 .remove(&head)
2041 .unwrap_or_default();
2042 assert_eq!(tokens, vec!["test@abc".to_string()]);
2043
2044 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2045 assert!(stamp_tree(&tree, &["test@def".to_string()]));
2046 let tokens = tree_tokens(&tree);
2047 assert!(tokens.contains(&"test@abc".to_string()));
2048 assert!(tokens.contains(&"test@def".to_string()));
2049 assert!(!tokens.contains(&"test@zzz".to_string()));
2050 assert!(!tokens.contains(&"test".to_string()));
2051 });
2052 let _ = std::fs::remove_dir_all(&dir);
2053 }
2054
2055 #[test]
2056 fn a_gate_that_does_not_declare_the_manifest_is_not_offered_the_route() {
2057 let dir = repo("manifest-undeclared");
2061 std::fs::create_dir_all(dir.join(".github")).unwrap();
2062 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2063 std::fs::write(dir.join("a.ts"), "x").unwrap();
2064 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2065 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2066 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2067 git(&dir, &["add", "-A"]);
2068 in_repo(&dir, || {
2069 record(&["test@abc"]);
2070 git(&dir, &["commit", "-qm", "feat: judged"]);
2071 bind_to_head();
2072 assert!(!inputs_ref_exists(), "the route must not open");
2073 let head = plan_only_commit(&dir);
2074 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2075 });
2076 let _ = std::fs::remove_dir_all(&dir);
2077 }
2078
2079 #[test]
2080 fn a_gate_declaring_the_manifest_opens_the_route() {
2081 let dir = declared("manifest-declared", "test a.ts amont.conf\n");
2084 in_repo(&dir, || {
2085 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2086 git(&dir, &["add", "amont.conf"]);
2087 record(&["test@abc"]);
2088 git(&dir, &["commit", "-qm", "chore: config"]);
2089 bind_to_head();
2090 assert!(inputs_ref_exists());
2091 });
2092 let _ = std::fs::remove_dir_all(&dir);
2093 }
2094
2095 #[test]
2096 fn an_undeclared_gate_keeps_whole_tree_behaviour() {
2097 let dir = declared("undeclared", "test a.ts\n");
2098 in_repo(&dir, || {
2099 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2102 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2103 let head = plan_only_commit(&dir);
2104 let tokens = stamps_for(std::slice::from_ref(&head))
2105 .remove(&head)
2106 .unwrap_or_default();
2107 assert!(tokens.contains(&"test@abc".to_string()));
2108 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2109 });
2110 let _ = std::fs::remove_dir_all(&dir);
2111 }
2112
2113 #[test]
2114 fn an_invalid_or_ambiguous_spec_falls_back_to_whole_tree_behaviour() {
2115 let dir = declared("invalid", "test src/*\n");
2117 in_repo(&dir, || {
2118 assert!(!inputs_ref_exists(), "no valid spec, nothing is filed");
2119 let head = plan_only_commit(&dir);
2120 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2121 });
2122 let _ = std::fs::remove_dir_all(&dir);
2123
2124 let dir = repo("ambiguous");
2126 std::fs::create_dir_all(dir.join(".github")).unwrap();
2127 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2128 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2129 std::fs::write(dir.join("a.ts"), "x").unwrap();
2130 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2131 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2132 std::fs::write(dir.join(".forgejo/greensummit-inputs"), "test a.ts\n").unwrap();
2133 git(&dir, &["add", "-A"]);
2134 in_repo(&dir, || {
2135 record(&["test@abc"]);
2136 git(&dir, &["commit", "-qm", "feat: judged"]);
2137 bind_to_head();
2138 assert!(!inputs_ref_exists());
2139 let head = plan_only_commit(&dir);
2140 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2141 });
2142 let _ = std::fs::remove_dir_all(&dir);
2143 }
2144
2145 #[test]
2146 fn a_gate_that_did_not_pass_leaves_no_declared_input_stamp() {
2147 let dir = repo("failed");
2148 std::fs::create_dir_all(dir.join(".github")).unwrap();
2149 std::fs::write(dir.join("a.ts"), "x").unwrap();
2150 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2151 git(&dir, &["add", "-A"]);
2152 in_repo(&dir, || {
2153 record(&[]);
2155 git(&dir, &["commit", "-qm", "feat: unjudged"]);
2156 assert!(bind_to_head().is_empty());
2157 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2158 let head = git(&dir, &["rev-parse", "HEAD"]);
2159 assert!(!stamp_push(&head, &tree, &[]));
2160 assert!(!inputs_ref_exists());
2161 });
2162 let _ = std::fs::remove_dir_all(&dir);
2163 }
2164
2165 #[test]
2166 fn stamp_tree_and_tree_tokens_use_the_inputs_ref() {
2167 let dir = declared("rehearsal", "test a.ts\n");
2168 in_repo(&dir, || {
2169 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2171 assert!(stamp_tree(&tree, &["test@rehearsed".to_string()]));
2172 plan_only_commit(&dir);
2174 let later = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2175 assert_ne!(later, tree);
2176 assert!(tree_tokens(&later).contains(&"test@rehearsed".to_string()));
2177 });
2178 let _ = std::fs::remove_dir_all(&dir);
2179 }
2180
2181 #[test]
2182 fn the_inputs_ref_is_keyed_the_way_attest_keys_its_own() {
2183 let dir = declared("key", "test a.ts\n");
2184 in_repo(&dir, || {
2185 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2186 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2187 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2188 let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
2189 let listed = git(&dir, &["notes", "--ref", INPUTS_REF, "list"]);
2190 assert!(
2191 listed
2192 .lines()
2193 .any(|l| l.split_whitespace().nth(1) == Some(key.as_str())),
2194 "{listed}"
2195 );
2196 });
2197 let _ = std::fs::remove_dir_all(&dir);
2198 }
2199
2200 #[test]
2201 fn a_foreign_token_in_the_inputs_ref_vouches_for_nothing() {
2202 let dir = declared("foreign", "test a.ts\n");
2203 in_repo(&dir, || {
2204 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2205 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2206 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2207 let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
2208 let mut note = note_in(INPUTS_REF, &key);
2210 note.add_tokens(&["publish@evil".to_string()]);
2211 assert!(write_note_in(INPUTS_REF, &key, ¬e));
2212 assert!(!tree_tokens(&tree).contains(&"publish@evil".to_string()));
2213 });
2214 let _ = std::fs::remove_dir_all(&dir);
2215 }
2216
2217 #[test]
2218 fn forget_removes_the_inputs_ref_too() {
2219 let dir = declared("forget-inputs", "test a.ts\n");
2220 in_repo(&dir, || {
2221 assert!(inputs_ref_exists());
2222 assert!(forget());
2223 assert!(!inputs_ref_exists());
2224 });
2225 let _ = std::fs::remove_dir_all(&dir);
2226 }
2227
2228 fn canonical(name: &str, conf: Option<&str>) -> PathBuf {
2231 let dir = repo(name);
2232 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2233 std::fs::write(dir.join("a.ts"), "x").unwrap();
2234 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
2235 if let Some(conf) = conf {
2236 std::fs::write(dir.join("amont.conf"), conf).unwrap();
2237 }
2238 git(&dir, &["add", "-A"]);
2239 in_repo(&dir, || {
2240 record(&["test@abc"]);
2241 git(&dir, &["commit", "-qm", "feat: judged"]);
2242 assert_eq!(bind_to_head(), vec!["test".to_string()]);
2243 });
2244 dir
2245 }
2246
2247 fn vouched(dir: &Path, commit: &str) -> Vec<String> {
2248 in_repo(dir, || {
2249 stamps_for(std::slice::from_ref(&commit.to_string()))
2250 .remove(commit)
2251 .unwrap_or_default()
2252 })
2253 }
2254
2255 #[test]
2256 fn with_no_spec_a_plans_only_commit_is_vouched_for_canonically() {
2257 let dir = canonical("canon-plan-edit", None);
2258 in_repo(&dir, || {
2259 assert!(inputs_ref_exists(), "the canonical stamp is filed");
2260 let head = plan_only_commit(&dir);
2261 assert_eq!(
2262 stamps_for(std::slice::from_ref(&head))
2263 .remove(&head)
2264 .unwrap_or_default(),
2265 vec!["test@abc".to_string()]
2266 );
2267 std::fs::write(dir.join("docs/plans/p.md"), "plan v3").unwrap();
2269 git(&dir, &["add", "docs/plans/p.md"]);
2270 assert!(vouched_for_staged_tree().contains("test@abc"));
2271 });
2272 let _ = std::fs::remove_dir_all(&dir);
2273 }
2274
2275 #[test]
2276 fn a_plan_added_deleted_or_renamed_is_not_vouched_for() {
2277 let dir = canonical("canon-plan-exists", None);
2278 std::fs::write(dir.join("docs/plans/q.md"), "second plan").unwrap();
2279 git(&dir, &["add", "docs/plans/q.md"]);
2280 git(&dir, &["commit", "-qm", "docs(plan): add"]);
2281 let added = git(&dir, &["rev-parse", "HEAD"]);
2282 assert!(vouched(&dir, &added).is_empty(), "a plan added");
2283 git(&dir, &["mv", "docs/plans/p.md", "docs/plans/r.md"]);
2284 git(&dir, &["commit", "-qm", "docs(plan): rename"]);
2285 let renamed = git(&dir, &["rev-parse", "HEAD"]);
2286 assert!(vouched(&dir, &renamed).is_empty(), "a plan renamed");
2287 let _ = std::fs::remove_dir_all(&dir);
2288 }
2289
2290 #[test]
2291 fn with_no_spec_any_other_change_is_not_vouched_for() {
2292 let dir = canonical("canon-code-edit", Some("gate test = make test\n"));
2293 std::fs::write(dir.join("a.ts"), "changed").unwrap();
2294 git(&dir, &["commit", "-qam", "feat: code"]);
2295 let code = git(&dir, &["rev-parse", "HEAD"]);
2296 assert!(vouched(&dir, &code).is_empty(), "a source edit");
2297 std::fs::write(dir.join("amont.conf"), "gate test = make other\n").unwrap();
2299 git(&dir, &["commit", "-qam", "chore: config"]);
2300 let conf = git(&dir, &["rev-parse", "HEAD"]);
2301 assert!(vouched(&dir, &conf).is_empty(), "a manifest edit");
2302 let _ = std::fs::remove_dir_all(&dir);
2303 }
2304
2305 #[test]
2306 fn plan_exempt_off_closes_the_canonical_route() {
2307 for (name, conf) in [
2308 ("off", "set planExempt off\n"),
2309 ("spelled", "SET PLANEXEMPT\tOff\r\n"),
2310 ("after", "set planExempt on\nset planExempt off\n"),
2311 ] {
2312 let dir = canonical(&format!("canon-off-{name}"), Some(conf));
2313 in_repo(&dir, || {
2314 assert!(!inputs_ref_exists(), "{name}: nothing is filed");
2315 let head = plan_only_commit(&dir);
2316 assert!(
2317 stamps_for(std::slice::from_ref(&head)).is_empty(),
2318 "{name}: a plans-only commit is a new tree"
2319 );
2320 });
2321 let _ = std::fs::remove_dir_all(&dir);
2322 }
2323 for (name, conf) in [
2325 ("on", "set planExempt on\n"),
2326 ("comment", "set planExempt off # no\n"),
2327 ("commented", "# set planExempt off\n"),
2328 ] {
2329 let dir = canonical(&format!("canon-on-{name}"), Some(conf));
2330 let head = plan_only_commit(&dir);
2331 assert!(!vouched(&dir, &head).is_empty(), "{name}: still canonical");
2332 let _ = std::fs::remove_dir_all(&dir);
2333 }
2334 }
2335
2336 #[test]
2337 fn a_spec_that_cannot_be_used_means_no_canonical_stamps() {
2338 let dir = repo("canon-unreadable-spec");
2340 std::fs::create_dir_all(dir.join(".github/greensummit-inputs")).unwrap();
2341 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2342 std::fs::write(dir.join(".github/greensummit-inputs/x"), "x").unwrap();
2343 std::fs::write(dir.join("a.ts"), "x").unwrap();
2344 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2345 git(&dir, &["add", "-A"]);
2346 in_repo(&dir, || {
2347 record(&["test@abc"]);
2348 git(&dir, &["commit", "-qm", "feat: judged"]);
2349 bind_to_head();
2350 assert!(!inputs_ref_exists(), "an unreadable spec opens nothing");
2351 let head = plan_only_commit(&dir);
2352 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2353 });
2354 let _ = std::fs::remove_dir_all(&dir);
2355 }
2356
2357 #[test]
2358 fn two_specs_mean_no_canonical_stamps() {
2359 let dir = repo("canon-ambiguous");
2360 std::fs::create_dir_all(dir.join(".github")).unwrap();
2361 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2362 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2363 std::fs::write(dir.join("a.ts"), "x").unwrap();
2364 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2365 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2366 std::fs::write(dir.join(".forgejo/greensummit-inputs"), "test a.ts\n").unwrap();
2367 git(&dir, &["add", "-A"]);
2368 in_repo(&dir, || {
2369 record(&["test@abc"]);
2370 git(&dir, &["commit", "-qm", "feat: judged"]);
2371 bind_to_head();
2372 assert!(!inputs_ref_exists());
2373 let head = plan_only_commit(&dir);
2374 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2375 });
2376 let _ = std::fs::remove_dir_all(&dir);
2377 }
2378
2379 #[test]
2380 fn a_valid_spec_keeps_precedence_over_the_canonical_route() {
2381 let dir = declared("canon-precedence", "test a.ts\n");
2383 in_repo(&dir, || {
2384 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2385 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2386 let head = plan_only_commit(&dir);
2387 let tokens = stamps_for(std::slice::from_ref(&head))
2388 .remove(&head)
2389 .unwrap_or_default();
2390 assert!(tokens.contains(&"test@abc".to_string()));
2391 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2392 });
2393 let _ = std::fs::remove_dir_all(&dir);
2394 }
2395
2396 fn unstamped(name: &str) -> (PathBuf, String, String) {
2401 let dir = repo(name);
2402 std::fs::write(dir.join("a.ts"), "x").unwrap();
2403 git(&dir, &["add", "a.ts"]);
2404 git(&dir, &["commit", "-qm", "feat: a"]);
2405 let head = git(&dir, &["rev-parse", "HEAD"]);
2406 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2407 (dir, head, tree)
2408 }
2409
2410 fn plant(dir: &Path, notes_ref: &str, key: &str, body: &str) {
2412 git(
2413 dir,
2414 &["notes", "--ref", notes_ref, "add", "-f", "-m", body, key],
2415 );
2416 }
2417
2418 fn stamps_of(commit: &str) -> Vec<String> {
2419 stamps_for(&[commit.to_string()])
2420 .remove(commit)
2421 .unwrap_or_default()
2422 }
2423
2424 #[test]
2425 fn a_pass_is_found_under_either_gate_ref() {
2426 for (i, set) in READ.iter().enumerate() {
2427 let (dir, head, tree) = unstamped(&format!("either-{i}"));
2428 plant(
2429 &dir,
2430 set.notes_ref,
2431 &head,
2432 &format!("{} test@c", set.format),
2433 );
2434 plant(
2435 &dir,
2436 set.notes_ref,
2437 &tree,
2438 &format!("{} test@t", set.format),
2439 );
2440 plant(
2441 &dir,
2442 set.cluster_ref,
2443 &tree,
2444 &format!("{} suite@k", set.format),
2445 );
2446 plant(
2447 &dir,
2448 set.done_ref,
2449 &tree,
2450 &format!("{} warned:lint@w", set.format),
2451 );
2452 in_repo(&dir, || {
2453 let mut got = stamps_of(&head);
2454 got.sort();
2455 assert_eq!(got, ["test@c", "test@t"], "{}", set.notes_ref);
2456 assert_eq!(tree_tokens(&tree), ["test@t"], "{}", set.notes_ref);
2457 assert_eq!(cluster_tokens(&tree), ["suite@k"], "{}", set.cluster_ref);
2458 assert!(
2459 done_on_every(
2460 std::slice::from_ref(&head),
2461 "lint@w",
2462 crate::check::Severity::Block
2463 ),
2464 "{}",
2465 set.done_ref
2466 );
2467 });
2468 let _ = std::fs::remove_dir_all(&dir); }
2470 }
2471
2472 const LEGACY: GateNames = GateNames {
2475 format: "amont-gate-v1",
2476 notes_ref: "amont-gate",
2477 inputs_ref: "amont-gate-inputs",
2478 cluster_ref: "amont-gate-cluster",
2479 done_ref: "amont-gate-done",
2480 canon_domain: "amont-gate-canon",
2481 attest: greensummit::format::Names {
2482 format: "amont-attest-v2",
2483 notes_ref: "amont-attest",
2484 inputs_ref: "amont-attest-inputs",
2485 namespace: "amont-attest",
2486 input_domain: "amont-attest-input",
2487 canon_domain: "amont-attest-canon",
2488 producer: "amont",
2489 },
2490 };
2491
2492 #[test]
2493 fn a_stamp_under_the_old_names_is_not_read() {
2494 let (dir, head, tree) = unstamped("old-refs");
2495 for key in [&head, &tree] {
2496 plant(
2497 &dir,
2498 LEGACY.notes_ref,
2499 key,
2500 &format!("{} test@old", LEGACY.format),
2501 );
2502 }
2503 plant(
2504 &dir,
2505 LEGACY.cluster_ref,
2506 &tree,
2507 &format!("{} suite@old", LEGACY.format),
2508 );
2509 in_repo(&dir, || {
2510 assert!(stamps_of(&head).is_empty());
2511 assert!(tree_tokens(&tree).is_empty());
2512 assert!(cluster_tokens(&tree).is_empty());
2513 });
2514 let _ = std::fs::remove_dir_all(&dir); }
2516
2517 #[test]
2518 fn with_notes_under_both_refs_the_green_note_is_read() {
2519 let (dir, head, tree) = unstamped("both-refs");
2520 for key in [&head, &tree] {
2521 plant(
2522 &dir,
2523 LEGACY.notes_ref,
2524 key,
2525 &format!("{} test@old", LEGACY.format),
2526 );
2527 plant(
2528 &dir,
2529 GREEN.notes_ref,
2530 key,
2531 &format!("{} test@new", GREEN.format),
2532 );
2533 }
2534 plant(
2535 &dir,
2536 LEGACY.cluster_ref,
2537 &tree,
2538 &format!("{} suite@old", LEGACY.format),
2539 );
2540 plant(
2541 &dir,
2542 GREEN.cluster_ref,
2543 &tree,
2544 &format!("{} suite@new", GREEN.format),
2545 );
2546 in_repo(&dir, || {
2547 assert_eq!(stamps_of(&head), ["test@new"]);
2548 assert_eq!(tree_tokens(&tree), ["test@new"]);
2549 assert_eq!(cluster_tokens(&tree), ["suite@new"]);
2550 });
2551 let _ = std::fs::remove_dir_all(&dir); }
2553
2554 #[test]
2555 fn a_note_whose_header_is_the_other_sets_reads_as_unstamped() {
2556 for (i, (sits_in, header_of)) in [(LEGACY, GREEN), (GREEN, LEGACY)].iter().enumerate() {
2557 let (dir, head, tree) = unstamped(&format!("mixed-{i}"));
2558 for key in [&head, &tree] {
2559 plant(
2560 &dir,
2561 sits_in.notes_ref,
2562 key,
2563 &format!("{} test@x", header_of.format),
2564 );
2565 }
2566 plant(
2567 &dir,
2568 sits_in.cluster_ref,
2569 &tree,
2570 &format!("{} suite@x", header_of.format),
2571 );
2572 in_repo(&dir, || {
2573 assert!(stamps_of(&head).is_empty(), "{}", sits_in.notes_ref);
2574 assert!(tree_tokens(&tree).is_empty(), "{}", sits_in.notes_ref);
2575 assert!(cluster_tokens(&tree).is_empty(), "{}", sits_in.cluster_ref);
2576 });
2577 let _ = std::fs::remove_dir_all(&dir); }
2579 }
2580
2581 #[test]
2584 fn the_inputs_ref_is_read_under_its_own_key() {
2585 let dir = declared("green-inputs", "test a.ts\n");
2586 in_repo(&dir, || {
2587 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2588 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2589 let fp = crate::attest_inputs::fingerprint(&tree, &spec, "test").expect("fp");
2590 let green = crate::attest_inputs::input_key(&GREEN.attest, "test", &fp).expect("key");
2591 let legacy = crate::attest_inputs::input_key(&LEGACY.attest, "test", &fp).expect("key");
2592 assert_ne!(green, legacy, "each set keys with its own domain");
2593 let head = plan_only_commit(&dir);
2594 plant(
2596 &dir,
2597 GREEN.inputs_ref,
2598 &legacy,
2599 &format!("{} test@wrongkey", GREEN.format),
2600 );
2601 assert_eq!(stamps_of(&head), ["test@abc"]);
2602 plant(
2603 &dir,
2604 GREEN.inputs_ref,
2605 &green,
2606 &format!("{} test@green", GREEN.format),
2607 );
2608 assert_eq!(stamps_of(&head), ["test@green"]);
2609 });
2610 let _ = std::fs::remove_dir_all(&dir); }
2612
2613 #[test]
2614 fn a_green_canonical_note_is_read_under_the_green_domain() {
2615 let dir = canonical("green-canon", None);
2616 in_repo(&dir, || {
2617 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2618 let canon = crate::attest_inputs::canonical_route(&tree).expect("canon");
2619 let key =
2620 crate::attest_inputs::canon_gate_key(GREEN.canon_domain, &canon).expect("key");
2621 plant(
2622 &dir,
2623 GREEN.inputs_ref,
2624 &key,
2625 &format!("{} test@green", GREEN.format),
2626 );
2627 let head = plan_only_commit(&dir);
2628 assert_eq!(stamps_of(&head), ["test@green"]);
2629 });
2630 let _ = std::fs::remove_dir_all(&dir); }
2632
2633 #[test]
2636 fn history_reads_runs_under_the_written_names_only() {
2637 let (dir, _head, tree) = unstamped("history-both");
2638 let other = git(&dir, &["rev-parse", "HEAD"]);
2639 plant(
2640 &dir,
2641 LEGACY.notes_ref,
2642 &other,
2643 &format!("{}\nrun 100 old-gate pass 7", LEGACY.format),
2644 );
2645 plant(
2646 &dir,
2647 GREEN.notes_ref,
2648 &tree,
2649 &format!("{}\nrun 200 new-gate pass 9", GREEN.format),
2650 );
2651 plant(
2653 &dir,
2654 GREEN.notes_ref,
2655 &other,
2656 &format!("{}\nrun 300 mixed-gate pass 1", LEGACY.format),
2657 );
2658 let history = crate::gate_evidence::history_in(&dir);
2659 let mut got: Vec<(String, String)> = history
2660 .runs
2661 .iter()
2662 .map(|(k, r)| (k.clone(), r.gate.clone()))
2663 .collect();
2664 got.sort();
2665 assert_eq!(got, [(tree, "new-gate".to_string())]);
2666 let _ = std::fs::remove_dir_all(&dir); }
2668
2669 #[test]
2670 fn forget_removes_the_written_refs() {
2671 let (dir, _head, tree) = unstamped("forget-written");
2672 plant(
2673 &dir,
2674 GREEN.notes_ref,
2675 &tree,
2676 &format!("{} test@g", GREEN.format),
2677 );
2678 for set in READ {
2679 plant(&dir, set.done_ref, &tree, "done");
2680 }
2681 in_repo(&dir, || {
2682 assert_eq!(tree_tokens(&tree).len(), 1);
2683 assert!(forget());
2684 assert!(tree_tokens(&tree).is_empty(), "{:?}", tree_tokens(&tree));
2685 });
2686 for set in READ {
2687 for r in full_refs(&set) {
2688 let out = std::process::Command::new("git")
2689 .args(["-C"])
2690 .arg(&dir)
2691 .args(["rev-parse", "--verify", "-q", &r])
2692 .output()
2693 .unwrap();
2694 assert!(!out.status.success(), "{r} survived forget");
2695 }
2696 }
2697 let _ = std::fs::remove_dir_all(&dir); }
2699
2700 #[test]
2701 fn writes_go_under_the_green_names_and_each_full_ref_names_its_ref() {
2702 assert_eq!(WRITE, GREEN);
2703 assert_eq!(FORMAT, "greengate-gate-v1");
2704 for (full, short) in [
2705 (NOTES_FULL_REF, NOTES_REF),
2706 (INPUTS_FULL_REF, INPUTS_REF),
2707 (CLUSTER_FULL_REF, CLUSTER_REF),
2708 (DONE_FULL_REF, DONE_REF),
2709 ] {
2710 assert_eq!(full, format!("refs/notes/{short}"));
2711 assert!(full.starts_with("refs/notes/greengate-gate"), "{full}");
2712 }
2713 let (dir, head, tree) = unstamped("write-green");
2716 plant(
2717 &dir,
2718 LEGACY.notes_ref,
2719 &tree,
2720 &format!("{} test@old", LEGACY.format),
2721 );
2722 in_repo(&dir, || {
2723 assert!(stamp_push(&head, &tree, &["suite@p".to_string()]));
2724 let written = git(&dir, &["notes", "--ref", GREEN.notes_ref, "show", &tree]);
2725 assert_eq!(written, format!("{} suite@p", GREEN.format));
2726 let old = git(&dir, &["notes", "--ref", LEGACY.notes_ref, "show", &tree]);
2728 assert_eq!(old, format!("{} test@old", LEGACY.format));
2729 });
2730 let _ = std::fs::remove_dir_all(&dir); }
2732}