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}
975
976const UNAVAILABLE_FOR_SECS: u64 = 60 * 60;
978
979fn completion_word(how: Completion, token: &str, now: u64) -> String {
981 match how {
982 Completion::Warned => format!("warned:{token}"),
983 Completion::FailedUnderWarn => format!("failed-under-warn:{token}"),
984 Completion::Unavailable => format!("unavailable:{now}:{token}"),
985 }
986}
987
988fn completion_answers(word: &str, token: &str, severity: crate::check::Severity, now: u64) -> bool {
990 if word.strip_prefix("warned:") == Some(token) {
991 return true;
992 }
993 if word.strip_prefix("failed-under-warn:") == Some(token) {
994 return severity == crate::check::Severity::Warn;
995 }
996 word.strip_prefix("unavailable:")
997 .and_then(|rest| rest.split_once(':'))
998 .is_some_and(|(at, tok)| {
999 tok == token
1000 && at
1001 .parse::<u64>()
1002 .is_ok_and(|at| now.saturating_sub(at) <= UNAVAILABLE_FOR_SECS)
1003 })
1004}
1005
1006fn now_secs() -> u64 {
1007 std::time::SystemTime::now()
1008 .duration_since(std::time::UNIX_EPOCH)
1009 .map(|d| d.as_secs())
1010 .unwrap_or(0)
1011}
1012
1013pub fn record_done(tree: &str, tokens: &[String], how: Completion) -> Result<(), String> {
1019 if tokens.is_empty() {
1020 return Ok(());
1021 }
1022 let now = now_secs();
1023 let mut note = note_in(DONE_REF, tree);
1024 if how == Completion::Unavailable {
1025 note.tokens.retain(|word| {
1026 !word
1027 .strip_prefix("unavailable:")
1028 .and_then(|rest| rest.split_once(':'))
1029 .is_some_and(|(_, token)| tokens.iter().any(|t| t == token))
1030 });
1031 }
1032 let words: Vec<String> = tokens
1033 .iter()
1034 .map(|t| completion_word(how, t, now))
1035 .collect();
1036 note.add_tokens(&words);
1037 if write_note_in(DONE_REF, tree, ¬e) {
1038 Ok(())
1039 } else {
1040 Err(format!(
1041 "git refused to record the completed gates on {tree}"
1042 ))
1043 }
1044}
1045
1046pub fn done_on_every(commits: &[String], token: &str, severity: crate::check::Severity) -> bool {
1051 let now = now_secs();
1052 !commits.is_empty()
1053 && commits.iter().all(|c| {
1054 crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]).is_some_and(|tree| {
1055 stamp_in(|s| s.done_ref, &tree)
1056 .tokens
1057 .iter()
1058 .any(|word| completion_answers(word, token, severity, now))
1059 })
1060 })
1061}
1062
1063pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
1069 let mut out = HashMap::new();
1070 if commits.is_empty() {
1071 return out;
1072 }
1073 let Some(list) = crate::git::stdout(&["notes", "--ref", WRITE.notes_ref, "list"]) else {
1074 crate::hooks::common::warn(
1084 "git would not list the gate stamps — every gated check will run again",
1085 );
1086 return out;
1087 };
1088 let noted: HashSet<&str> = list
1089 .lines()
1090 .filter_map(|l| l.split_whitespace().nth(1))
1091 .collect();
1092 let mut trees: HashMap<String, String> = HashMap::new();
1096 {
1097 let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
1098 args.extend(commits.iter().map(String::as_str));
1099 if let Some(out) = crate::git::stdout(&args) {
1100 for line in out.lines() {
1101 let mut it = line.split_whitespace();
1102 if let (Some(c), Some(t)) = (it.next(), it.next()) {
1103 trees.insert(c.to_string(), t.to_string());
1104 }
1105 }
1106 }
1107 }
1111
1112 let by_inputs = inputs_ref_exists();
1118
1119 for commit in commits {
1120 let mut tokens: Vec<String> = Vec::new();
1139 let mut keys: Vec<&str> = Vec::new();
1140 if noted.contains(commit.as_str()) {
1141 keys.push(commit);
1142 }
1143 if let Some(tree) = trees.get(commit).filter(|t| noted.contains(t.as_str())) {
1144 keys.push(tree);
1145 }
1146 for key in keys {
1147 for t in stamp_at(key).tokens {
1148 if !tokens.contains(&t) {
1149 tokens.push(t);
1150 }
1151 }
1152 }
1153 if by_inputs {
1154 if let Some(tree) = trees.get(commit) {
1155 for t in input_tokens(tree) {
1156 if !tokens.contains(&t) {
1157 tokens.push(t);
1158 }
1159 }
1160 }
1161 }
1162 if tokens.is_empty() {
1163 continue;
1164 }
1165 out.insert(commit.clone(), tokens);
1166 }
1167 out
1168}
1169
1170pub fn forget() -> bool {
1175 let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
1176 let mut deleted = false;
1178 for r in full_refs(&WRITE) {
1179 deleted |= crate::git::succeeds(&["update-ref", "-d", &r]);
1180 }
1181 marker || deleted
1182}
1183
1184fn full_refs(set: &GateNames) -> [String; 4] {
1186 [set.notes_ref, set.inputs_ref, set.cluster_ref, set.done_ref]
1187 .map(|short| format!("refs/notes/{short}"))
1188}
1189
1190pub(crate) fn cluster_tokens(tree: &str) -> Vec<String> {
1193 stamp_in(|s| s.cluster_ref, tree).tokens
1194}
1195
1196pub(crate) fn stamp_cluster(tree: &str, token: &str, provenance: &str) -> bool {
1199 let mut note = note_in(CLUSTER_REF, tree);
1200 note.add_tokens(&[token.to_string()]);
1201 let line = format!("{PROVENANCE} {token} {provenance}");
1202 note.provenance
1203 .retain(|l| l.split_whitespace().nth(1) != Some(token));
1204 note.provenance.push(line);
1205 write_note_in(CLUSTER_REF, tree, ¬e)
1206}
1207
1208pub(crate) fn cluster_stamps_for(commits: &[String]) -> HashMap<String, (String, Vec<String>)> {
1212 let mut out = HashMap::new();
1213 for commit in commits {
1214 let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")]) else {
1215 continue;
1216 };
1217 let tokens = cluster_tokens(&tree);
1218 if !tokens.is_empty() {
1219 out.insert(commit.clone(), (tree, tokens));
1220 }
1221 }
1222 out
1223}
1224
1225pub fn forget_in(repo: &std::path::Path) -> bool {
1227 let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
1228 .is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
1229 let mut deleted = false;
1230 for r in full_refs(&WRITE) {
1231 deleted |= crate::git::succeeds_in(repo, &["update-ref", "-d", &r]);
1232 }
1233 marker || deleted
1234}
1235
1236#[cfg(test)]
1237mod tests {
1238 use super::*;
1239 use std::path::Path;
1240
1241 #[test]
1245 fn a_completion_answers_only_while_it_should() {
1246 use crate::check::Severity::{Block, Warn};
1247 let now = 1_700_000_000;
1248 let word = |how| completion_word(how, "gate-tok", now);
1249 assert!(completion_answers(
1250 &word(Completion::Warned),
1251 "gate-tok",
1252 Block,
1253 now
1254 ));
1255 assert!(completion_answers(
1256 &word(Completion::FailedUnderWarn),
1257 "gate-tok",
1258 Warn,
1259 now
1260 ));
1261 assert!(!completion_answers(
1262 &word(Completion::FailedUnderWarn),
1263 "gate-tok",
1264 Block,
1265 now
1266 ));
1267 let unavailable = word(Completion::Unavailable);
1268 assert!(completion_answers(
1269 &unavailable,
1270 "gate-tok",
1271 Block,
1272 now + 3600
1273 ));
1274 assert!(!completion_answers(
1275 &unavailable,
1276 "gate-tok",
1277 Block,
1278 now + 3601
1279 ));
1280 assert!(!completion_answers(
1281 &word(Completion::Warned),
1282 "other-tok",
1283 Warn,
1284 now
1285 ));
1286 }
1287
1288 fn repo(name: &str) -> PathBuf {
1291 let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
1292 let _ = std::fs::remove_dir_all(&dir);
1293 std::fs::create_dir_all(&dir).unwrap();
1294 git(&dir, &["init", "-q", "--template=", "."]);
1295 git(&dir, &["config", "user.email", "t@t.test"]);
1296 git(&dir, &["config", "user.name", "t"]);
1297 dir
1298 }
1299
1300 fn git(dir: &Path, args: &[&str]) -> String {
1309 let out = std::process::Command::new("git")
1310 .arg("-C")
1311 .arg(dir)
1312 .args(args)
1313 .output()
1314 .expect("git");
1315 assert!(
1316 out.status.success(),
1317 "fixture: git {args:?} in {} exited {:?}: {}",
1318 dir.display(),
1319 out.status.code(),
1320 String::from_utf8_lossy(&out.stderr).trim()
1321 );
1322 String::from_utf8_lossy(&out.stdout).trim().to_string()
1323 }
1324
1325 fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
1329 let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
1330 let prev = std::env::current_dir().unwrap();
1331 std::env::set_current_dir(dir).unwrap();
1332 let r = f();
1333 std::env::set_current_dir(prev).unwrap();
1334 r
1335 }
1336
1337 #[test]
1338 fn the_commit_note_does_not_hide_the_tree_notes_push_tokens() {
1339 let dir = repo("union");
1340 std::fs::write(dir.join("a.ts"), "x").unwrap();
1341 git(&dir, &["add", "a.ts"]);
1342 in_repo(&dir, || {
1343 record(&["test"]);
1344 git(&dir, &["commit", "-qm", "chore: a"]);
1345 bind_to_head();
1346 let head = git(&dir, &["rev-parse", "HEAD"]);
1347 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1348 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1351 assert_eq!(note_at(&head).tokens, vec!["test".to_string()]);
1352 let stamps = stamps_for(std::slice::from_ref(&head));
1353 assert_eq!(
1354 stamps.get(&head).map(Vec::as_slice),
1355 Some(&["test".to_string(), "pre-push-cargo-test".to_string()][..]),
1356 "both notes speak for the same tree"
1357 );
1358 });
1359 let _ = std::fs::remove_dir_all(&dir);
1360 }
1361
1362 #[test]
1366 fn an_unavailable_record_replaces_its_predecessor_only() {
1367 let dir = repo("done-unavailable");
1368 std::fs::write(dir.join("a.ts"), "x").unwrap();
1369 git(&dir, &["add", "a.ts"]);
1370 git(&dir, &["commit", "-qm", "chore: a"]);
1371 in_repo(&dir, || {
1372 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1373 let one = |t: &str| vec![t.to_string()];
1374 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("first");
1375 record_done(&tree, &one("lint@b"), Completion::Unavailable).expect("other gate");
1376 record_done(&tree, &one("lint@b"), Completion::Warned).expect("a warning");
1377 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("again");
1378 let words = note_in(DONE_REF, &tree).tokens;
1379 let unavailable_for = |token: &str| {
1380 words
1381 .iter()
1382 .filter(|w| w.starts_with("unavailable:") && w.ends_with(&format!(":{token}")))
1383 .count()
1384 };
1385 assert_eq!(unavailable_for("suite@a"), 1, "{words:?}");
1386 assert_eq!(unavailable_for("lint@b"), 1, "{words:?}");
1387 assert!(words.contains(&"warned:lint@b".to_string()), "{words:?}");
1388 });
1389 let _ = std::fs::remove_dir_all(&dir); }
1391
1392 #[test]
1393 fn a_commit_with_only_a_tree_note_still_reads_the_tree_tokens() {
1394 let dir = repo("tree-only");
1395 std::fs::write(dir.join("a.ts"), "x").unwrap();
1396 git(&dir, &["add", "a.ts"]);
1397 git(&dir, &["commit", "-qm", "chore: a"]);
1398 in_repo(&dir, || {
1399 let head = git(&dir, &["rev-parse", "HEAD"]);
1400 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1401 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1402 let stamps = stamps_for(std::slice::from_ref(&head));
1403 assert_eq!(
1404 stamps.get(&head).map(Vec::as_slice),
1405 Some(&["pre-push-cargo-test".to_string()][..])
1406 );
1407 });
1408 let _ = std::fs::remove_dir_all(&dir);
1409 }
1410
1411 #[test]
1412 fn a_commit_with_only_a_commit_note_still_reads_its_tokens() {
1413 let dir = repo("commit-only");
1414 std::fs::write(dir.join("a.ts"), "x").unwrap();
1415 git(&dir, &["add", "a.ts"]);
1416 git(&dir, &["commit", "-qm", "chore: a"]);
1417 in_repo(&dir, || {
1418 let head = git(&dir, &["rev-parse", "HEAD"]);
1419 let mut note = Note::default();
1420 note.add_tokens(&["typecheck".to_string()]);
1421 assert!(write_note(&head, ¬e));
1422 let stamps = stamps_for(std::slice::from_ref(&head));
1423 assert_eq!(
1424 stamps.get(&head).map(Vec::as_slice),
1425 Some(&["typecheck".to_string()][..])
1426 );
1427 });
1428 let _ = std::fs::remove_dir_all(&dir);
1429 }
1430
1431 #[test]
1432 fn a_token_on_both_notes_is_read_once() {
1433 let dir = repo("dedup");
1434 std::fs::write(dir.join("a.ts"), "x").unwrap();
1435 git(&dir, &["add", "a.ts"]);
1436 in_repo(&dir, || {
1437 record(&["test"]);
1438 git(&dir, &["commit", "-qm", "chore: a"]);
1439 bind_to_head(); let head = git(&dir, &["rev-parse", "HEAD"]);
1441 let stamps = stamps_for(std::slice::from_ref(&head));
1442 assert_eq!(
1443 stamps.get(&head).map(Vec::as_slice),
1444 Some(&["test".to_string()][..])
1445 );
1446 });
1447 let _ = std::fs::remove_dir_all(&dir);
1448 }
1449
1450 #[test]
1451 fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
1452 let dir = repo("roundtrip");
1453 std::fs::write(dir.join("a.ts"), "x").unwrap();
1454 git(&dir, &["add", "a.ts"]);
1455 in_repo(&dir, || {
1456 record(&["typecheck", "test"]);
1457 git(&dir, &["commit", "-qm", "chore: a"]);
1458 let stamped = bind_to_head();
1459 assert_eq!(
1460 stamped,
1461 vec!["typecheck".to_string(), "test".to_string()],
1462 "bind_to_head reports the scripts it stamped"
1463 );
1464 let head = git(&dir, &["rev-parse", "HEAD"]);
1465 let stamps = stamps_for(std::slice::from_ref(&head));
1466 assert_eq!(
1467 stamps.get(&head).map(Vec::as_slice),
1468 Some(&["typecheck".to_string(), "test".to_string()][..])
1469 );
1470 assert!(!dir.join(".git").join(MARKER).exists());
1477 });
1478 let _ = std::fs::remove_dir_all(&dir);
1479 }
1480
1481 #[test]
1482 fn a_marker_for_a_different_tree_stamps_nothing() {
1483 let dir = repo("stale");
1484 std::fs::write(dir.join("a.ts"), "x").unwrap();
1485 git(&dir, &["add", "a.ts"]);
1486 in_repo(&dir, || {
1487 record(&["typecheck"]);
1488 std::fs::write(dir.join("a.ts"), "y").unwrap();
1491 git(&dir, &["add", "a.ts"]);
1492 git(&dir, &["commit", "-qm", "chore: different"]);
1493 assert!(
1494 bind_to_head().is_empty(),
1495 "bind_to_head reports nothing when the tree moved"
1496 );
1497 let head = git(&dir, &["rev-parse", "HEAD"]);
1498 assert!(
1499 stamps_for(&[head]).is_empty(),
1500 "a stale marker must not vouch"
1501 );
1502 assert!(
1503 !dir.join(".git").join(MARKER).exists(),
1504 "consumed either way"
1505 );
1506 });
1507 let _ = std::fs::remove_dir_all(&dir);
1508 }
1509
1510 #[test]
1511 fn an_empty_record_clears_a_previous_marker() {
1512 let dir = repo("clears");
1513 std::fs::write(dir.join("a.ts"), "x").unwrap();
1514 git(&dir, &["add", "a.ts"]);
1515 in_repo(&dir, || {
1516 record(&["typecheck"]);
1517 assert!(dir.join(".git").join(MARKER).exists());
1518 record(&[]);
1519 assert!(!dir.join(".git").join(MARKER).exists());
1520 });
1521 let _ = std::fs::remove_dir_all(&dir);
1522 }
1523
1524 #[test]
1529 fn a_marker_in_an_unknown_format_stamps_nothing() {
1530 let dir = repo("wrongformat");
1531 std::fs::write(dir.join("a.ts"), "x").unwrap();
1532 git(&dir, &["add", "a.ts"]);
1533 in_repo(&dir, || {
1534 let tree = git(&dir, &["write-tree"]);
1535 let marker = dir.join(".git").join(MARKER);
1536 std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
1537 git(&dir, &["commit", "-qm", "chore: a"]);
1538 bind_to_head();
1539 let head = git(&dir, &["rev-parse", "HEAD"]);
1540 assert!(
1541 stamps_for(std::slice::from_ref(&head)).is_empty(),
1542 "an unknown format was trusted"
1543 );
1544 assert!(!marker.exists(), "consumed either way");
1545 });
1546 let _ = std::fs::remove_dir_all(&dir);
1547 }
1548
1549 #[test]
1553 fn a_foreign_note_is_not_a_stamp() {
1554 let dir = repo("foreignnote");
1555 std::fs::write(dir.join("a.ts"), "x").unwrap();
1556 git(&dir, &["add", "a.ts"]);
1557 in_repo(&dir, || {
1558 git(&dir, &["commit", "-qm", "chore: a"]);
1559 git(
1560 &dir,
1561 &[
1562 "notes",
1563 "--ref",
1564 NOTES_REF,
1565 "add",
1566 "-m",
1567 "typecheck test",
1568 "HEAD",
1569 ],
1570 );
1571 let head = git(&dir, &["rev-parse", "HEAD"]);
1572 assert!(
1573 stamps_for(std::slice::from_ref(&head)).is_empty(),
1574 "a note without the format token was trusted"
1575 );
1576 });
1577 let _ = std::fs::remove_dir_all(&dir);
1578 }
1579
1580 #[test]
1584 fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
1585 let dir = repo("no-stamps");
1586 std::fs::write(dir.join("a.ts"), "x").unwrap();
1587 git(&dir, &["add", "a.ts"]);
1588 git(&dir, &["commit", "-qm", "chore: a"]);
1589 in_repo(&dir, || {
1590 assert_eq!(
1591 crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
1592 Some(""),
1593 "an absent notes ref must be an ANSWER, not a failure — the \
1594 no-stamps path and the git-is-broken path are told apart by it"
1595 );
1596 let head = git(&dir, &["rev-parse", "HEAD"]);
1597 assert!(stamps_for(&[head]).is_empty());
1598 });
1599 let _ = std::fs::remove_dir_all(&dir);
1600 }
1601
1602 #[test]
1609 fn a_note_from_before_the_run_lines_parses_unchanged() {
1610 let note = Note::parse("greengate-gate-v1 typecheck test");
1611 assert_eq!(note.tokens, vec!["typecheck", "test"]);
1612 assert!(note.runs.is_empty());
1613 assert_eq!(note.render(), "greengate-gate-v1 typecheck test");
1616 }
1617
1618 #[test]
1620 fn run_lines_are_read_without_disturbing_the_tokens() {
1621 let body = "greengate-gate-v1 pre-push-cargo-test\n\
1622 run 1726900000 pre-push-cargo-test pass 412391\n\
1623 run 1726903600 pre-push-audit-js fail 903\n";
1624 let note = Note::parse(body);
1625 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1626 assert_eq!(note.runs.len(), 2);
1627 assert_eq!(
1628 note.runs[0],
1629 Run {
1630 at: 1_726_900_000,
1631 gate: "pre-push-cargo-test".into(),
1632 outcome: RunOutcome::Passed,
1633 ms: 412_391,
1634 }
1635 );
1636 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1637 assert_eq!(note.render(), body.trim_end());
1638 }
1639
1640 #[test]
1644 fn an_unreadable_run_line_is_dropped_and_the_rest_survives() {
1645 let note = Note::parse(
1646 "greengate-gate-v1 test\n\
1647 run 1726900000 pre-push-cargo-test pass 400\n\
1648 run tomorrow pre-push-cargo-test pass 400\n\
1649 run 1726900001 pre-push-cargo-test sideways 400\n\
1650 banana\n\
1651 run 1726900002 pre-push-cargo-test fail 500\n",
1652 );
1653 assert_eq!(note.tokens, vec!["test"]);
1654 assert_eq!(note.runs.len(), 2, "{:?}", note.runs);
1655 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1656 }
1657
1658 #[test]
1662 fn a_deferral_is_never_a_token_and_outlives_the_run_trim() {
1663 let mut note = Note::parse("greengate-gate-v1 lint\ndeferred cargo-test\n");
1664 assert_eq!(note.tokens, vec!["lint"]);
1665 assert_eq!(note.deferred, vec!["cargo-test"]);
1666 let runs: Vec<Run> = (0..MAX_RUNS as u64 + 10)
1667 .map(|i| Run {
1668 at: 1_726_900_000 + i,
1669 gate: "pre-push-audit-js".into(),
1670 outcome: RunOutcome::Passed,
1671 ms: 1,
1672 })
1673 .collect();
1674 note.add_runs(&runs);
1675 let again = Note::parse(¬e.render());
1676 assert_eq!(again.runs.len(), MAX_RUNS);
1677 assert_eq!(again.deferred, vec!["cargo-test"]);
1678 assert_eq!(again.tokens, vec!["lint"]);
1679 }
1680
1681 #[test]
1684 fn a_foreign_note_yields_no_runs() {
1685 let note = Note::parse("hello\nrun 1726900000 pre-push-cargo-test pass 400\n");
1686 assert!(note.tokens.is_empty() && note.runs.is_empty());
1687 }
1688
1689 #[test]
1694 fn a_stamp_and_its_evidence_survive_each_other() {
1695 let dir = repo("evidence");
1696 std::fs::write(dir.join("a.ts"), "x").unwrap();
1697 git(&dir, &["add", "a.ts"]);
1698 in_repo(&dir, || {
1699 git(&dir, &["commit", "-qm", "chore: a"]);
1700 let head = git(&dir, &["rev-parse", "HEAD"]);
1701 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1702 record_runs(
1703 &tree,
1704 &[Run {
1705 at: 1_726_900_000,
1706 gate: "pre-push-cargo-test".into(),
1707 outcome: RunOutcome::Failed,
1708 ms: 412_391,
1709 }],
1710 );
1711 assert!(stamp_push(&head, &tree, &["pre-push-cargo-test".into()]));
1713 let note = note_at(&tree);
1714 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1715 assert_eq!(note.runs.len(), 1, "the evidence survived the stamp");
1716 let stamps = stamps_for(std::slice::from_ref(&head));
1718 assert_eq!(
1719 stamps.get(&head).map(Vec::as_slice),
1720 Some(&["pre-push-cargo-test".to_string()][..])
1721 );
1722 });
1723 let _ = std::fs::remove_dir_all(&dir);
1724 }
1725
1726 #[test]
1730 fn a_recorded_run_is_not_a_stamp() {
1731 let dir = repo("not-a-stamp");
1732 std::fs::write(dir.join("a.ts"), "x").unwrap();
1733 git(&dir, &["add", "a.ts"]);
1734 in_repo(&dir, || {
1735 git(&dir, &["commit", "-qm", "chore: a"]);
1736 let head = git(&dir, &["rev-parse", "HEAD"]);
1737 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1738 record_runs(
1739 &tree,
1740 &[Run {
1741 at: 1_726_900_000,
1742 gate: "pre-push-cargo-test".into(),
1743 outcome: RunOutcome::Passed,
1744 ms: 412_391,
1745 }],
1746 );
1747 assert!(
1748 stamps_for(std::slice::from_ref(&head)).is_empty(),
1749 "a run line vouched for a gate — evidence must never gate"
1750 );
1751 assert!(
1752 !vouched_for_staged_tree().contains("pre-push-cargo-test"),
1753 "a run line vouched at commit time"
1754 );
1755 let history = crate::gate_evidence::history_in(&dir);
1757 assert_eq!(history.runs.len(), 1);
1758 assert_eq!(history.runs[0].0, tree, "keyed by the content it ran on");
1759 });
1760 let _ = std::fs::remove_dir_all(&dir);
1761 }
1762
1763 #[test]
1764 fn forget_removes_the_stamps() {
1765 let dir = repo("forget");
1766 std::fs::write(dir.join("a.ts"), "x").unwrap();
1767 git(&dir, &["add", "a.ts"]);
1768 in_repo(&dir, || {
1769 record(&["typecheck"]);
1770 git(&dir, &["commit", "-qm", "chore: a"]);
1771 bind_to_head();
1772 let head = git(&dir, &["rev-parse", "HEAD"]);
1773 assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
1774 forget();
1775 assert!(stamps_for(&[head]).is_empty());
1776 });
1777 let _ = std::fs::remove_dir_all(&dir);
1778 }
1779
1780 #[test]
1794 fn a_stamp_survives_a_commit_being_rewritten_with_the_same_tree() {
1795 let dir = repo("squashed");
1796 std::fs::write(dir.join("a.ts"), "x").unwrap();
1797 git(&dir, &["add", "a.ts"]);
1798 in_repo(&dir, || {
1799 record(&["test"]);
1800 git(&dir, &["commit", "-qm", "feat: on a branch"]);
1801 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1802 let branch_tip = git(&dir, &["rev-parse", "HEAD"]);
1803
1804 git(
1808 &dir,
1809 &[
1810 "commit",
1811 "-q",
1812 "--amend",
1813 "-m",
1814 "feat: squashed by the forge",
1815 ],
1816 );
1817 let merged = git(&dir, &["rev-parse", "HEAD"]);
1818 assert_ne!(merged, branch_tip, "the fixture must produce a new commit");
1819 assert_eq!(
1820 git(&dir, &["rev-parse", "HEAD^{tree}"]),
1821 git(&dir, &["rev-parse", &format!("{branch_tip}^{{tree}}")]),
1822 "…carrying the same tree, which is the whole premise"
1823 );
1824
1825 let stamps = stamps_for(std::slice::from_ref(&merged));
1826 assert_eq!(
1827 stamps.get(&merged).map(Vec::as_slice),
1828 Some(&["test".to_string()][..]),
1829 "the stamp must follow the content, not the commit hash"
1830 );
1831 });
1832 let _ = std::fs::remove_dir_all(&dir);
1833 }
1834
1835 #[test]
1839 fn a_different_tree_gets_no_stamp_from_the_fallback() {
1840 let dir = repo("othertree");
1841 std::fs::write(dir.join("a.ts"), "x").unwrap();
1842 git(&dir, &["add", "a.ts"]);
1843 in_repo(&dir, || {
1844 record(&["test"]);
1845 git(&dir, &["commit", "-qm", "chore: stamped"]);
1846 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1847
1848 std::fs::write(dir.join("b.ts"), "y").unwrap();
1851 git(&dir, &["add", "b.ts"]);
1852 git(&dir, &["commit", "-qm", "chore: unjudged"]);
1853 let unstamped = git(&dir, &["rev-parse", "HEAD"]);
1854
1855 assert!(
1856 stamps_for(std::slice::from_ref(&unstamped)).is_empty(),
1857 "a tree nobody stamped must not inherit one"
1858 );
1859 });
1860 let _ = std::fs::remove_dir_all(&dir);
1861 }
1862
1863 fn declared(name: &str, spec: &str) -> PathBuf {
1869 let dir = repo(name);
1870 std::fs::create_dir_all(dir.join(".github")).unwrap();
1871 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
1872 std::fs::write(dir.join("a.ts"), "x").unwrap();
1873 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
1874 std::fs::write(dir.join(".github/greensummit-inputs"), spec).unwrap();
1875 git(&dir, &["add", "-A"]);
1876 in_repo(&dir, || {
1877 record(&["test@abc"]);
1878 git(&dir, &["commit", "-qm", "feat: judged"]);
1879 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1880 });
1881 dir
1882 }
1883
1884 fn plan_only_commit(dir: &Path) -> String {
1887 std::fs::write(dir.join("docs/plans/p.md"), "plan v2, closing").unwrap();
1888 git(dir, &["add", "docs/plans/p.md"]);
1889 git(dir, &["commit", "-qm", "docs(plan): done"]);
1890 git(dir, &["rev-parse", "HEAD"])
1891 }
1892
1893 #[test]
1894 fn a_plan_only_commit_reuses_the_stamp_of_a_declared_gate() {
1895 let dir = declared("plan-only", "test a.ts\n");
1896 in_repo(&dir, || {
1897 let head = plan_only_commit(&dir);
1898 let stamps = stamps_for(std::slice::from_ref(&head));
1899 assert_eq!(
1900 stamps.get(&head).map(Vec::as_slice),
1901 Some(&["test@abc".to_string()][..]),
1902 "the closing commit changed the tree and none of the declared inputs"
1903 );
1904 });
1905 let _ = std::fs::remove_dir_all(&dir);
1906 }
1907
1908 #[test]
1909 fn the_staged_tree_of_a_plan_only_commit_is_vouched_for() {
1910 let dir = declared("staged", "test a.ts\n");
1911 in_repo(&dir, || {
1912 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1913 git(&dir, &["add", "docs/plans/p.md"]);
1914 assert!(vouched_for_staged_tree().contains("test@abc"));
1915 });
1916 let _ = std::fs::remove_dir_all(&dir);
1917 }
1918
1919 #[test]
1920 fn partial_staging_is_judged_on_the_index_not_the_working_copy() {
1921 let dir = declared("partial", "test a.ts\n");
1922 in_repo(&dir, || {
1923 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1926 git(&dir, &["add", "docs/plans/p.md"]);
1927 std::fs::write(dir.join("a.ts"), "unstaged edit").unwrap();
1928 assert!(vouched_for_staged_tree().contains("test@abc"));
1929
1930 std::fs::write(dir.join("a.ts"), "staged edit").unwrap();
1933 git(&dir, &["add", "a.ts"]);
1934 std::fs::write(dir.join("a.ts"), "x").unwrap();
1935 assert!(!vouched_for_staged_tree().contains("test@abc"));
1936 });
1937 let _ = std::fs::remove_dir_all(&dir);
1938 }
1939
1940 #[test]
1941 fn a_changed_declared_input_misses() {
1942 let dir = declared("input-changed", "test a.ts\n");
1943 in_repo(&dir, || {
1944 std::fs::write(dir.join("a.ts"), "changed").unwrap();
1945 git(&dir, &["add", "a.ts"]);
1946 git(&dir, &["commit", "-qm", "feat: unjudged"]);
1947 let head = git(&dir, &["rev-parse", "HEAD"]);
1948 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1949 });
1950 let _ = std::fs::remove_dir_all(&dir);
1951 }
1952
1953 #[test]
1954 fn a_changed_declaration_misses() {
1955 let dir = declared("declaration-changed", "test a.ts\n");
1956 in_repo(&dir, || {
1957 std::fs::write(dir.join("b.ts"), "y").unwrap();
1960 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts b.ts\n").unwrap();
1961 git(&dir, &["add", "-A"]);
1962 git(&dir, &["commit", "-qm", "chore: widen the declaration"]);
1963 let head = git(&dir, &["rev-parse", "HEAD"]);
1964 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1965 });
1966 let _ = std::fs::remove_dir_all(&dir);
1967 }
1968
1969 #[test]
1970 fn a_declared_config_file_is_an_input_like_any_other() {
1971 let dir = declared("config", "test a.ts amont.conf\n");
1974 in_repo(&dir, || {
1975 assert!(!inputs_ref_exists());
1978
1979 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
1980 git(&dir, &["add", "amont.conf"]);
1981 record(&["test@abc"]);
1982 git(&dir, &["commit", "-qm", "chore: config"]);
1983 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1984
1985 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1986 git(&dir, &["add", "docs/plans/p.md"]);
1987 git(&dir, &["commit", "-qm", "docs(plan): done"]);
1988 let plan = git(&dir, &["rev-parse", "HEAD"]);
1989 assert!(stamps_for(std::slice::from_ref(&plan)).contains_key(&plan));
1990
1991 std::fs::write(dir.join("amont.conf"), "scope = lib\n").unwrap();
1992 git(&dir, &["add", "amont.conf"]);
1993 git(&dir, &["commit", "-qm", "chore: scope-only change"]);
1994 let scope = git(&dir, &["rev-parse", "HEAD"]);
1995 assert!(
1996 stamps_for(std::slice::from_ref(&scope)).is_empty(),
1997 "a scope-only change must miss"
1998 );
1999 });
2000 let _ = std::fs::remove_dir_all(&dir);
2001 }
2002
2003 #[test]
2004 fn a_declared_stamp_is_read_back_as_its_complete_token() {
2005 let dir = declared("identity", "test a.ts\n");
2011 in_repo(&dir, || {
2012 let head = plan_only_commit(&dir);
2013 let tokens = stamps_for(std::slice::from_ref(&head))
2014 .remove(&head)
2015 .unwrap_or_default();
2016 assert_eq!(tokens, vec!["test@abc".to_string()]);
2017
2018 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2019 assert!(stamp_tree(&tree, &["test@def".to_string()]));
2020 let tokens = tree_tokens(&tree);
2021 assert!(tokens.contains(&"test@abc".to_string()));
2022 assert!(tokens.contains(&"test@def".to_string()));
2023 assert!(!tokens.contains(&"test@zzz".to_string()));
2024 assert!(!tokens.contains(&"test".to_string()));
2025 });
2026 let _ = std::fs::remove_dir_all(&dir);
2027 }
2028
2029 #[test]
2030 fn a_gate_that_does_not_declare_the_manifest_is_not_offered_the_route() {
2031 let dir = repo("manifest-undeclared");
2035 std::fs::create_dir_all(dir.join(".github")).unwrap();
2036 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2037 std::fs::write(dir.join("a.ts"), "x").unwrap();
2038 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2039 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2040 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2041 git(&dir, &["add", "-A"]);
2042 in_repo(&dir, || {
2043 record(&["test@abc"]);
2044 git(&dir, &["commit", "-qm", "feat: judged"]);
2045 bind_to_head();
2046 assert!(!inputs_ref_exists(), "the route must not open");
2047 let head = plan_only_commit(&dir);
2048 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2049 });
2050 let _ = std::fs::remove_dir_all(&dir);
2051 }
2052
2053 #[test]
2054 fn a_gate_declaring_the_manifest_opens_the_route() {
2055 let dir = declared("manifest-declared", "test a.ts amont.conf\n");
2058 in_repo(&dir, || {
2059 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2060 git(&dir, &["add", "amont.conf"]);
2061 record(&["test@abc"]);
2062 git(&dir, &["commit", "-qm", "chore: config"]);
2063 bind_to_head();
2064 assert!(inputs_ref_exists());
2065 });
2066 let _ = std::fs::remove_dir_all(&dir);
2067 }
2068
2069 #[test]
2070 fn an_undeclared_gate_keeps_whole_tree_behaviour() {
2071 let dir = declared("undeclared", "test a.ts\n");
2072 in_repo(&dir, || {
2073 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2076 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2077 let head = plan_only_commit(&dir);
2078 let tokens = stamps_for(std::slice::from_ref(&head))
2079 .remove(&head)
2080 .unwrap_or_default();
2081 assert!(tokens.contains(&"test@abc".to_string()));
2082 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2083 });
2084 let _ = std::fs::remove_dir_all(&dir);
2085 }
2086
2087 #[test]
2088 fn an_invalid_or_ambiguous_spec_falls_back_to_whole_tree_behaviour() {
2089 let dir = declared("invalid", "test src/*\n");
2091 in_repo(&dir, || {
2092 assert!(!inputs_ref_exists(), "no valid spec, nothing is filed");
2093 let head = plan_only_commit(&dir);
2094 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2095 });
2096 let _ = std::fs::remove_dir_all(&dir);
2097
2098 let dir = repo("ambiguous");
2100 std::fs::create_dir_all(dir.join(".github")).unwrap();
2101 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2102 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2103 std::fs::write(dir.join("a.ts"), "x").unwrap();
2104 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2105 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2106 std::fs::write(dir.join(".forgejo/greensummit-inputs"), "test a.ts\n").unwrap();
2107 git(&dir, &["add", "-A"]);
2108 in_repo(&dir, || {
2109 record(&["test@abc"]);
2110 git(&dir, &["commit", "-qm", "feat: judged"]);
2111 bind_to_head();
2112 assert!(!inputs_ref_exists());
2113 let head = plan_only_commit(&dir);
2114 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2115 });
2116 let _ = std::fs::remove_dir_all(&dir);
2117 }
2118
2119 #[test]
2120 fn a_gate_that_did_not_pass_leaves_no_declared_input_stamp() {
2121 let dir = repo("failed");
2122 std::fs::create_dir_all(dir.join(".github")).unwrap();
2123 std::fs::write(dir.join("a.ts"), "x").unwrap();
2124 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2125 git(&dir, &["add", "-A"]);
2126 in_repo(&dir, || {
2127 record(&[]);
2129 git(&dir, &["commit", "-qm", "feat: unjudged"]);
2130 assert!(bind_to_head().is_empty());
2131 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2132 let head = git(&dir, &["rev-parse", "HEAD"]);
2133 assert!(!stamp_push(&head, &tree, &[]));
2134 assert!(!inputs_ref_exists());
2135 });
2136 let _ = std::fs::remove_dir_all(&dir);
2137 }
2138
2139 #[test]
2140 fn stamp_tree_and_tree_tokens_use_the_inputs_ref() {
2141 let dir = declared("rehearsal", "test a.ts\n");
2142 in_repo(&dir, || {
2143 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2145 assert!(stamp_tree(&tree, &["test@rehearsed".to_string()]));
2146 plan_only_commit(&dir);
2148 let later = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2149 assert_ne!(later, tree);
2150 assert!(tree_tokens(&later).contains(&"test@rehearsed".to_string()));
2151 });
2152 let _ = std::fs::remove_dir_all(&dir);
2153 }
2154
2155 #[test]
2156 fn the_inputs_ref_is_keyed_the_way_attest_keys_its_own() {
2157 let dir = declared("key", "test a.ts\n");
2158 in_repo(&dir, || {
2159 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2160 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2161 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2162 let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
2163 let listed = git(&dir, &["notes", "--ref", INPUTS_REF, "list"]);
2164 assert!(
2165 listed
2166 .lines()
2167 .any(|l| l.split_whitespace().nth(1) == Some(key.as_str())),
2168 "{listed}"
2169 );
2170 });
2171 let _ = std::fs::remove_dir_all(&dir);
2172 }
2173
2174 #[test]
2175 fn a_foreign_token_in_the_inputs_ref_vouches_for_nothing() {
2176 let dir = declared("foreign", "test a.ts\n");
2177 in_repo(&dir, || {
2178 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2179 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2180 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2181 let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
2182 let mut note = note_in(INPUTS_REF, &key);
2184 note.add_tokens(&["publish@evil".to_string()]);
2185 assert!(write_note_in(INPUTS_REF, &key, ¬e));
2186 assert!(!tree_tokens(&tree).contains(&"publish@evil".to_string()));
2187 });
2188 let _ = std::fs::remove_dir_all(&dir);
2189 }
2190
2191 #[test]
2192 fn forget_removes_the_inputs_ref_too() {
2193 let dir = declared("forget-inputs", "test a.ts\n");
2194 in_repo(&dir, || {
2195 assert!(inputs_ref_exists());
2196 assert!(forget());
2197 assert!(!inputs_ref_exists());
2198 });
2199 let _ = std::fs::remove_dir_all(&dir);
2200 }
2201
2202 fn canonical(name: &str, conf: Option<&str>) -> PathBuf {
2205 let dir = repo(name);
2206 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2207 std::fs::write(dir.join("a.ts"), "x").unwrap();
2208 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
2209 if let Some(conf) = conf {
2210 std::fs::write(dir.join("amont.conf"), conf).unwrap();
2211 }
2212 git(&dir, &["add", "-A"]);
2213 in_repo(&dir, || {
2214 record(&["test@abc"]);
2215 git(&dir, &["commit", "-qm", "feat: judged"]);
2216 assert_eq!(bind_to_head(), vec!["test".to_string()]);
2217 });
2218 dir
2219 }
2220
2221 fn vouched(dir: &Path, commit: &str) -> Vec<String> {
2222 in_repo(dir, || {
2223 stamps_for(std::slice::from_ref(&commit.to_string()))
2224 .remove(commit)
2225 .unwrap_or_default()
2226 })
2227 }
2228
2229 #[test]
2230 fn with_no_spec_a_plans_only_commit_is_vouched_for_canonically() {
2231 let dir = canonical("canon-plan-edit", None);
2232 in_repo(&dir, || {
2233 assert!(inputs_ref_exists(), "the canonical stamp is filed");
2234 let head = plan_only_commit(&dir);
2235 assert_eq!(
2236 stamps_for(std::slice::from_ref(&head))
2237 .remove(&head)
2238 .unwrap_or_default(),
2239 vec!["test@abc".to_string()]
2240 );
2241 std::fs::write(dir.join("docs/plans/p.md"), "plan v3").unwrap();
2243 git(&dir, &["add", "docs/plans/p.md"]);
2244 assert!(vouched_for_staged_tree().contains("test@abc"));
2245 });
2246 let _ = std::fs::remove_dir_all(&dir);
2247 }
2248
2249 #[test]
2250 fn a_plan_added_deleted_or_renamed_is_not_vouched_for() {
2251 let dir = canonical("canon-plan-exists", None);
2252 std::fs::write(dir.join("docs/plans/q.md"), "second plan").unwrap();
2253 git(&dir, &["add", "docs/plans/q.md"]);
2254 git(&dir, &["commit", "-qm", "docs(plan): add"]);
2255 let added = git(&dir, &["rev-parse", "HEAD"]);
2256 assert!(vouched(&dir, &added).is_empty(), "a plan added");
2257 git(&dir, &["mv", "docs/plans/p.md", "docs/plans/r.md"]);
2258 git(&dir, &["commit", "-qm", "docs(plan): rename"]);
2259 let renamed = git(&dir, &["rev-parse", "HEAD"]);
2260 assert!(vouched(&dir, &renamed).is_empty(), "a plan renamed");
2261 let _ = std::fs::remove_dir_all(&dir);
2262 }
2263
2264 #[test]
2265 fn with_no_spec_any_other_change_is_not_vouched_for() {
2266 let dir = canonical("canon-code-edit", Some("gate test = make test\n"));
2267 std::fs::write(dir.join("a.ts"), "changed").unwrap();
2268 git(&dir, &["commit", "-qam", "feat: code"]);
2269 let code = git(&dir, &["rev-parse", "HEAD"]);
2270 assert!(vouched(&dir, &code).is_empty(), "a source edit");
2271 std::fs::write(dir.join("amont.conf"), "gate test = make other\n").unwrap();
2273 git(&dir, &["commit", "-qam", "chore: config"]);
2274 let conf = git(&dir, &["rev-parse", "HEAD"]);
2275 assert!(vouched(&dir, &conf).is_empty(), "a manifest edit");
2276 let _ = std::fs::remove_dir_all(&dir);
2277 }
2278
2279 #[test]
2280 fn plan_exempt_off_closes_the_canonical_route() {
2281 for (name, conf) in [
2282 ("off", "set planExempt off\n"),
2283 ("spelled", "SET PLANEXEMPT\tOff\r\n"),
2284 ("after", "set planExempt on\nset planExempt off\n"),
2285 ] {
2286 let dir = canonical(&format!("canon-off-{name}"), Some(conf));
2287 in_repo(&dir, || {
2288 assert!(!inputs_ref_exists(), "{name}: nothing is filed");
2289 let head = plan_only_commit(&dir);
2290 assert!(
2291 stamps_for(std::slice::from_ref(&head)).is_empty(),
2292 "{name}: a plans-only commit is a new tree"
2293 );
2294 });
2295 let _ = std::fs::remove_dir_all(&dir);
2296 }
2297 for (name, conf) in [
2299 ("on", "set planExempt on\n"),
2300 ("comment", "set planExempt off # no\n"),
2301 ("commented", "# set planExempt off\n"),
2302 ] {
2303 let dir = canonical(&format!("canon-on-{name}"), Some(conf));
2304 let head = plan_only_commit(&dir);
2305 assert!(!vouched(&dir, &head).is_empty(), "{name}: still canonical");
2306 let _ = std::fs::remove_dir_all(&dir);
2307 }
2308 }
2309
2310 #[test]
2311 fn a_spec_that_cannot_be_used_means_no_canonical_stamps() {
2312 let dir = repo("canon-unreadable-spec");
2314 std::fs::create_dir_all(dir.join(".github/greensummit-inputs")).unwrap();
2315 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2316 std::fs::write(dir.join(".github/greensummit-inputs/x"), "x").unwrap();
2317 std::fs::write(dir.join("a.ts"), "x").unwrap();
2318 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2319 git(&dir, &["add", "-A"]);
2320 in_repo(&dir, || {
2321 record(&["test@abc"]);
2322 git(&dir, &["commit", "-qm", "feat: judged"]);
2323 bind_to_head();
2324 assert!(!inputs_ref_exists(), "an unreadable spec opens nothing");
2325 let head = plan_only_commit(&dir);
2326 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2327 });
2328 let _ = std::fs::remove_dir_all(&dir);
2329 }
2330
2331 #[test]
2332 fn two_specs_mean_no_canonical_stamps() {
2333 let dir = repo("canon-ambiguous");
2334 std::fs::create_dir_all(dir.join(".github")).unwrap();
2335 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2336 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2337 std::fs::write(dir.join("a.ts"), "x").unwrap();
2338 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2339 std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
2340 std::fs::write(dir.join(".forgejo/greensummit-inputs"), "test a.ts\n").unwrap();
2341 git(&dir, &["add", "-A"]);
2342 in_repo(&dir, || {
2343 record(&["test@abc"]);
2344 git(&dir, &["commit", "-qm", "feat: judged"]);
2345 bind_to_head();
2346 assert!(!inputs_ref_exists());
2347 let head = plan_only_commit(&dir);
2348 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2349 });
2350 let _ = std::fs::remove_dir_all(&dir);
2351 }
2352
2353 #[test]
2354 fn a_valid_spec_keeps_precedence_over_the_canonical_route() {
2355 let dir = declared("canon-precedence", "test a.ts\n");
2357 in_repo(&dir, || {
2358 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2359 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2360 let head = plan_only_commit(&dir);
2361 let tokens = stamps_for(std::slice::from_ref(&head))
2362 .remove(&head)
2363 .unwrap_or_default();
2364 assert!(tokens.contains(&"test@abc".to_string()));
2365 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2366 });
2367 let _ = std::fs::remove_dir_all(&dir);
2368 }
2369
2370 fn unstamped(name: &str) -> (PathBuf, String, String) {
2375 let dir = repo(name);
2376 std::fs::write(dir.join("a.ts"), "x").unwrap();
2377 git(&dir, &["add", "a.ts"]);
2378 git(&dir, &["commit", "-qm", "feat: a"]);
2379 let head = git(&dir, &["rev-parse", "HEAD"]);
2380 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2381 (dir, head, tree)
2382 }
2383
2384 fn plant(dir: &Path, notes_ref: &str, key: &str, body: &str) {
2386 git(
2387 dir,
2388 &["notes", "--ref", notes_ref, "add", "-f", "-m", body, key],
2389 );
2390 }
2391
2392 fn stamps_of(commit: &str) -> Vec<String> {
2393 stamps_for(&[commit.to_string()])
2394 .remove(commit)
2395 .unwrap_or_default()
2396 }
2397
2398 #[test]
2399 fn a_pass_is_found_under_each_gate_ref() {
2400 let set = &WRITE;
2401 let (dir, head, tree) = unstamped("either-0");
2402 plant(
2403 &dir,
2404 set.notes_ref,
2405 &head,
2406 &format!("{} test@c", set.format),
2407 );
2408 plant(
2409 &dir,
2410 set.notes_ref,
2411 &tree,
2412 &format!("{} test@t", set.format),
2413 );
2414 plant(
2415 &dir,
2416 set.cluster_ref,
2417 &tree,
2418 &format!("{} suite@k", set.format),
2419 );
2420 plant(
2421 &dir,
2422 set.done_ref,
2423 &tree,
2424 &format!("{} warned:lint@w", set.format),
2425 );
2426 in_repo(&dir, || {
2427 let mut got = stamps_of(&head);
2428 got.sort();
2429 assert_eq!(got, ["test@c", "test@t"], "{}", set.notes_ref);
2430 assert_eq!(tree_tokens(&tree), ["test@t"], "{}", set.notes_ref);
2431 assert_eq!(cluster_tokens(&tree), ["suite@k"], "{}", set.cluster_ref);
2432 assert!(
2433 done_on_every(
2434 std::slice::from_ref(&head),
2435 "lint@w",
2436 crate::check::Severity::Block
2437 ),
2438 "{}",
2439 set.done_ref
2440 );
2441 });
2442 let _ = std::fs::remove_dir_all(&dir); }
2444
2445 const LEGACY: GateNames = GateNames {
2448 format: "amont-gate-v1",
2449 notes_ref: "amont-gate",
2450 inputs_ref: "amont-gate-inputs",
2451 cluster_ref: "amont-gate-cluster",
2452 done_ref: "amont-gate-done",
2453 canon_domain: "amont-gate-canon",
2454 attest: greensummit::format::Names {
2455 format: "amont-attest-v2",
2456 notes_ref: "amont-attest",
2457 inputs_ref: "amont-attest-inputs",
2458 namespace: "amont-attest",
2459 input_domain: "amont-attest-input",
2460 canon_domain: "amont-attest-canon",
2461 producer: "amont",
2462 },
2463 };
2464
2465 #[test]
2466 fn a_stamp_under_the_old_names_is_not_read() {
2467 let (dir, head, tree) = unstamped("old-refs");
2468 for key in [&head, &tree] {
2469 plant(
2470 &dir,
2471 LEGACY.notes_ref,
2472 key,
2473 &format!("{} test@old", LEGACY.format),
2474 );
2475 }
2476 plant(
2477 &dir,
2478 LEGACY.cluster_ref,
2479 &tree,
2480 &format!("{} suite@old", LEGACY.format),
2481 );
2482 in_repo(&dir, || {
2483 assert!(stamps_of(&head).is_empty());
2484 assert!(tree_tokens(&tree).is_empty());
2485 assert!(cluster_tokens(&tree).is_empty());
2486 });
2487 let _ = std::fs::remove_dir_all(&dir); }
2489
2490 #[test]
2491 fn with_notes_under_both_refs_the_green_note_is_read() {
2492 let (dir, head, tree) = unstamped("both-refs");
2493 for key in [&head, &tree] {
2494 plant(
2495 &dir,
2496 LEGACY.notes_ref,
2497 key,
2498 &format!("{} test@old", LEGACY.format),
2499 );
2500 plant(
2501 &dir,
2502 GREEN.notes_ref,
2503 key,
2504 &format!("{} test@new", GREEN.format),
2505 );
2506 }
2507 plant(
2508 &dir,
2509 LEGACY.cluster_ref,
2510 &tree,
2511 &format!("{} suite@old", LEGACY.format),
2512 );
2513 plant(
2514 &dir,
2515 GREEN.cluster_ref,
2516 &tree,
2517 &format!("{} suite@new", GREEN.format),
2518 );
2519 in_repo(&dir, || {
2520 assert_eq!(stamps_of(&head), ["test@new"]);
2521 assert_eq!(tree_tokens(&tree), ["test@new"]);
2522 assert_eq!(cluster_tokens(&tree), ["suite@new"]);
2523 });
2524 let _ = std::fs::remove_dir_all(&dir); }
2526
2527 #[test]
2528 fn a_note_whose_header_is_the_other_sets_reads_as_unstamped() {
2529 for (i, (sits_in, header_of)) in [(LEGACY, GREEN), (GREEN, LEGACY)].iter().enumerate() {
2530 let (dir, head, tree) = unstamped(&format!("mixed-{i}"));
2531 for key in [&head, &tree] {
2532 plant(
2533 &dir,
2534 sits_in.notes_ref,
2535 key,
2536 &format!("{} test@x", header_of.format),
2537 );
2538 }
2539 plant(
2540 &dir,
2541 sits_in.cluster_ref,
2542 &tree,
2543 &format!("{} suite@x", header_of.format),
2544 );
2545 in_repo(&dir, || {
2546 assert!(stamps_of(&head).is_empty(), "{}", sits_in.notes_ref);
2547 assert!(tree_tokens(&tree).is_empty(), "{}", sits_in.notes_ref);
2548 assert!(cluster_tokens(&tree).is_empty(), "{}", sits_in.cluster_ref);
2549 });
2550 let _ = std::fs::remove_dir_all(&dir); }
2552 }
2553
2554 #[test]
2557 fn the_inputs_ref_is_read_under_its_own_key() {
2558 let dir = declared("green-inputs", "test a.ts\n");
2559 in_repo(&dir, || {
2560 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2561 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2562 let fp = crate::attest_inputs::fingerprint(&tree, &spec, "test").expect("fp");
2563 let green = crate::attest_inputs::input_key(&GREEN.attest, "test", &fp).expect("key");
2564 let legacy = crate::attest_inputs::input_key(&LEGACY.attest, "test", &fp).expect("key");
2565 assert_ne!(green, legacy, "each set keys with its own domain");
2566 let head = plan_only_commit(&dir);
2567 plant(
2569 &dir,
2570 GREEN.inputs_ref,
2571 &legacy,
2572 &format!("{} test@wrongkey", GREEN.format),
2573 );
2574 assert_eq!(stamps_of(&head), ["test@abc"]);
2575 plant(
2576 &dir,
2577 GREEN.inputs_ref,
2578 &green,
2579 &format!("{} test@green", GREEN.format),
2580 );
2581 assert_eq!(stamps_of(&head), ["test@green"]);
2582 });
2583 let _ = std::fs::remove_dir_all(&dir); }
2585
2586 #[test]
2587 fn a_green_canonical_note_is_read_under_the_green_domain() {
2588 let dir = canonical("green-canon", None);
2589 in_repo(&dir, || {
2590 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2591 let canon = crate::attest_inputs::canonical_route(&tree).expect("canon");
2592 let key =
2593 crate::attest_inputs::canon_gate_key(GREEN.canon_domain, &canon).expect("key");
2594 plant(
2595 &dir,
2596 GREEN.inputs_ref,
2597 &key,
2598 &format!("{} test@green", GREEN.format),
2599 );
2600 let head = plan_only_commit(&dir);
2601 assert_eq!(stamps_of(&head), ["test@green"]);
2602 });
2603 let _ = std::fs::remove_dir_all(&dir); }
2605
2606 #[test]
2609 fn history_reads_runs_under_the_written_names_only() {
2610 let (dir, _head, tree) = unstamped("history-both");
2611 let other = git(&dir, &["rev-parse", "HEAD"]);
2612 plant(
2613 &dir,
2614 LEGACY.notes_ref,
2615 &other,
2616 &format!("{}\nrun 100 old-gate pass 7", LEGACY.format),
2617 );
2618 plant(
2619 &dir,
2620 GREEN.notes_ref,
2621 &tree,
2622 &format!("{}\nrun 200 new-gate pass 9", GREEN.format),
2623 );
2624 plant(
2626 &dir,
2627 GREEN.notes_ref,
2628 &other,
2629 &format!("{}\nrun 300 mixed-gate pass 1", LEGACY.format),
2630 );
2631 let history = crate::gate_evidence::history_in(&dir);
2632 let mut got: Vec<(String, String)> = history
2633 .runs
2634 .iter()
2635 .map(|(k, r)| (k.clone(), r.gate.clone()))
2636 .collect();
2637 got.sort();
2638 assert_eq!(got, [(tree, "new-gate".to_string())]);
2639 let _ = std::fs::remove_dir_all(&dir); }
2641
2642 #[test]
2643 fn forget_removes_the_written_refs() {
2644 let (dir, _head, tree) = unstamped("forget-written");
2645 plant(
2646 &dir,
2647 GREEN.notes_ref,
2648 &tree,
2649 &format!("{} test@g", GREEN.format),
2650 );
2651 plant(&dir, WRITE.done_ref, &tree, "done");
2652 in_repo(&dir, || {
2653 assert_eq!(tree_tokens(&tree).len(), 1);
2654 assert!(forget());
2655 assert!(tree_tokens(&tree).is_empty(), "{:?}", tree_tokens(&tree));
2656 });
2657 for r in full_refs(&WRITE) {
2658 let out = std::process::Command::new("git")
2659 .args(["-C"])
2660 .arg(&dir)
2661 .args(["rev-parse", "--verify", "-q", &r])
2662 .output()
2663 .unwrap();
2664 assert!(!out.status.success(), "{r} survived forget");
2665 }
2666 let _ = std::fs::remove_dir_all(&dir); }
2668
2669 #[test]
2670 fn writes_go_under_the_green_names_and_each_full_ref_names_its_ref() {
2671 assert_eq!(WRITE, GREEN);
2672 assert_eq!(FORMAT, "greengate-gate-v1");
2673 for (full, short) in [
2674 (NOTES_FULL_REF, NOTES_REF),
2675 (INPUTS_FULL_REF, INPUTS_REF),
2676 (CLUSTER_FULL_REF, CLUSTER_REF),
2677 (DONE_FULL_REF, DONE_REF),
2678 ] {
2679 assert_eq!(full, format!("refs/notes/{short}"));
2680 assert!(full.starts_with("refs/notes/greengate-gate"), "{full}");
2681 }
2682 let (dir, head, tree) = unstamped("write-green");
2685 plant(
2686 &dir,
2687 LEGACY.notes_ref,
2688 &tree,
2689 &format!("{} test@old", LEGACY.format),
2690 );
2691 in_repo(&dir, || {
2692 assert!(stamp_push(&head, &tree, &["suite@p".to_string()]));
2693 let written = git(&dir, &["notes", "--ref", GREEN.notes_ref, "show", &tree]);
2694 assert_eq!(written, format!("{} suite@p", GREEN.format));
2695 let old = git(&dir, &["notes", "--ref", LEGACY.notes_ref, "show", &tree]);
2697 assert_eq!(old, format!("{} test@old", LEGACY.format));
2698 });
2699 let _ = std::fs::remove_dir_all(&dir); }
2701}