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: git_attest::format::Names,
112}
113
114pub(crate) const LEGACY: GateNames = GateNames {
117 format: "amont-gate-v1",
118 notes_ref: "amont-gate",
119 inputs_ref: "amont-gate-inputs",
120 cluster_ref: "amont-gate-cluster",
121 done_ref: "amont-gate-done",
122 canon_domain: "amont-gate-canon",
123 attest: git_attest::format::LEGACY,
124};
125
126pub(crate) const GREEN: GateNames = GateNames {
128 format: "greengate-gate-v1",
129 notes_ref: "greengate-gate",
130 inputs_ref: "greengate-gate-inputs",
131 cluster_ref: "greengate-gate-cluster",
132 done_ref: "greengate-gate-done",
133 canon_domain: "greengate-gate-canon",
134 attest: git_attest::format::GREEN,
135};
136
137pub(crate) const WRITE: GateNames = GREEN;
141
142pub(crate) const READ: [GateNames; 2] = [GREEN, LEGACY];
145
146pub const FORMAT: &str = WRITE.format;
150
151pub const NOTES_REF: &str = WRITE.notes_ref;
153
154pub const NOTES_FULL_REF: &str = "refs/notes/greengate-gate";
157
158pub const INPUTS_REF: &str = WRITE.inputs_ref;
166
167pub const CLUSTER_REF: &str = WRITE.cluster_ref;
172pub const CLUSTER_FULL_REF: &str = "refs/notes/greengate-gate-cluster";
173
174pub const DONE_REF: &str = WRITE.done_ref;
182pub const DONE_FULL_REF: &str = "refs/notes/greengate-gate-done";
183
184pub const PROVENANCE: &str = "provenance";
188pub const INPUTS_FULL_REF: &str = "refs/notes/greengate-gate-inputs";
189
190const MARKER: &str = crate::names::GATE_MARKER;
192
193const PUSH_STAMPS: &str = "greengate.pushStamps";
197
198pub fn push_stamps_enabled(settings: &crate::config::Settings) -> bool {
200 crate::config::boolean_or(settings, PUSH_STAMPS, true)
201}
202
203const COMMIT_STAMPS: &str = "greengate.commitStamps";
208
209pub fn commit_stamps_enabled(settings: &crate::config::Settings) -> bool {
212 crate::config::boolean_or(settings, COMMIT_STAMPS, true)
213}
214
215const RUN: &str = "run";
218
219const MAX_RUNS: usize = 64;
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232pub enum RunOutcome {
233 Passed,
234 Failed,
235 Warned,
236 Fixed,
237 Unavailable,
238 Inert,
239 Cold,
243 Busy,
245 Skew,
247 Withheld,
250 Cancelled,
252 Slow,
255 Deferred,
257}
258
259impl RunOutcome {
260 pub fn as_str(self) -> &'static str {
261 match self {
262 RunOutcome::Passed => "pass",
263 RunOutcome::Failed => "fail",
264 RunOutcome::Warned => "warn",
265 RunOutcome::Fixed => "fixed",
266 RunOutcome::Unavailable => "unavailable",
267 RunOutcome::Inert => "inert",
268 RunOutcome::Cold => "cold",
269 RunOutcome::Busy => "busy",
270 RunOutcome::Skew => "skew",
271 RunOutcome::Withheld => "withheld",
272 RunOutcome::Cancelled => "cancelled",
273 RunOutcome::Slow => "slow",
274 RunOutcome::Deferred => "deferred",
275 }
276 }
277
278 pub fn parse(s: &str) -> Option<RunOutcome> {
282 Some(match s {
283 "pass" => RunOutcome::Passed,
284 "fail" => RunOutcome::Failed,
285 "warn" => RunOutcome::Warned,
286 "fixed" => RunOutcome::Fixed,
287 "unavailable" => RunOutcome::Unavailable,
288 "inert" => RunOutcome::Inert,
289 "cold" => RunOutcome::Cold,
290 "busy" => RunOutcome::Busy,
291 "skew" => RunOutcome::Skew,
292 "withheld" => RunOutcome::Withheld,
293 "cancelled" => RunOutcome::Cancelled,
294 "slow" => RunOutcome::Slow,
295 "deferred" => RunOutcome::Deferred,
296 _ => return None,
297 })
298 }
299
300 pub fn is_verdict(self) -> bool {
304 matches!(self, RunOutcome::Passed | RunOutcome::Failed)
305 }
306}
307
308#[derive(Debug, Clone, PartialEq, Eq)]
315pub struct Run {
316 pub at: u64,
318 pub gate: String,
319 pub outcome: RunOutcome,
320 pub ms: u64,
321}
322
323impl Run {
324 fn render(&self) -> String {
325 format!(
326 "{RUN} {} {} {} {}",
327 self.at,
328 self.gate,
329 self.outcome.as_str(),
330 self.ms
331 )
332 }
333
334 fn parse(line: &str) -> Option<Run> {
337 let mut t = line.split_whitespace();
338 if t.next() != Some(RUN) {
339 return None;
340 }
341 let at = t.next()?.parse().ok()?;
342 let gate = t.next()?.to_string();
343 let outcome = RunOutcome::parse(t.next()?)?;
344 let ms = t.next()?.parse().ok()?;
345 Some(Run {
346 at,
347 gate,
348 outcome,
349 ms,
350 })
351 }
352}
353
354#[derive(Debug, Clone, Default, PartialEq, Eq)]
363pub struct Note {
364 pub tokens: Vec<String>,
365 pub deferred: Vec<String>,
368 pub runs: Vec<Run>,
369 pub provenance: Vec<String>,
371}
372
373const DEFERRED: &str = "deferred";
375
376impl Note {
377 pub fn parse(body: &str) -> Note {
381 Note::parse_as(body, FORMAT)
382 }
383
384 pub(crate) fn parse_as(body: &str, format: &str) -> Note {
388 let mut lines = body.lines();
389 let Some(first) = lines.next() else {
390 return Note::default();
391 };
392 let mut tokens = first.split_whitespace();
393 if tokens.next() != Some(format) {
394 return Note::default();
395 }
396 let mut deferred = Vec::new();
397 let mut runs = Vec::new();
398 let mut provenance = Vec::new();
399 for line in lines {
400 if is_provenance(line) {
401 provenance.push(line.trim().to_string());
402 continue;
403 }
404 let mut t = line.split_whitespace();
405 match (t.next(), t.next(), t.next()) {
406 (Some(DEFERRED), Some(gate), None) => {
407 if !deferred.iter().any(|d| d == gate) {
408 deferred.push(gate.to_string());
409 }
410 }
411 _ => runs.extend(Run::parse(line)),
412 }
413 }
414 Note {
415 tokens: tokens.map(str::to_string).collect(),
416 deferred,
417 runs,
418 provenance,
419 }
420 }
421
422 pub fn render(&self) -> String {
425 let mut body = format!("{FORMAT} {}", self.tokens.join(" "));
426 for gate in &self.deferred {
427 body.push('\n');
428 body.push_str(&format!("{DEFERRED} {gate}"));
429 }
430 for run in &self.runs {
431 body.push('\n');
432 body.push_str(&run.render());
433 }
434 for line in &self.provenance {
435 body.push('\n');
436 body.push_str(line);
437 }
438 body
439 }
440
441 fn add_tokens(&mut self, tokens: &[String]) {
442 for t in tokens {
443 if !self.tokens.iter().any(|have| have == t) {
444 self.tokens.push(t.clone());
445 }
446 }
447 }
448
449 fn add_runs(&mut self, runs: &[Run]) {
451 self.runs.extend(runs.iter().cloned());
452 if self.runs.len() > MAX_RUNS {
453 self.runs.drain(..self.runs.len() - MAX_RUNS);
454 }
455 }
456}
457
458pub fn is_provenance(line: &str) -> bool {
461 line.split_whitespace().next() == Some(PROVENANCE)
462}
463
464fn note_at(key: &str) -> Note {
470 note_in(NOTES_REF, key)
471}
472
473fn note_in(notes_ref: &str, key: &str) -> Note {
474 crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
475 .map(|body| Note::parse(&body))
476 .unwrap_or_default()
477}
478
479fn stamp_in(which: fn(&GateNames) -> &'static str, key: &str) -> Note {
485 READ.iter()
486 .find_map(|set| read_in(set, which(set), key))
487 .unwrap_or_default()
488}
489
490fn read_in(set: &GateNames, notes_ref: &str, key: &str) -> Option<Note> {
498 crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
499 .map(|body| Note::parse_as(&body, set.format))
500}
501
502fn stamp_at(key: &str) -> Note {
504 stamp_in(|s| s.notes_ref, key)
505}
506
507fn input_tokens(tree: &str) -> Vec<String> {
516 let Some(spec) = crate::attest_inputs::spec_at(tree) else {
517 return canon_tokens(tree);
518 };
519 let mut out: Vec<String> = Vec::new();
520 for (gate, _) in &spec.gates {
521 if !manifest_is_an_input(tree, &spec, gate) {
522 continue;
523 }
524 let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
525 continue;
526 };
527 let note = READ.iter().find_map(|set| {
530 let key = crate::attest_inputs::input_key(&set.attest, gate, &fp)?;
531 read_in(set, set.inputs_ref, &key)
532 });
533 for t in note.unwrap_or_default().tokens {
534 if crate::gate_identity::base(&t) == gate.as_str() && !out.contains(&t) {
535 out.push(t);
536 }
537 }
538 }
539 out
540}
541
542fn canon_tokens(tree: &str) -> Vec<String> {
549 let Some(canon) = crate::attest_inputs::canonical_route(tree) else {
550 return Vec::new();
551 };
552 READ.iter()
553 .find_map(|set| {
554 let key = crate::attest_inputs::canon_gate_key(set.canon_domain, &canon)?;
555 read_in(set, set.inputs_ref, &key)
556 })
557 .map(|note| note.tokens)
558 .unwrap_or_default()
559}
560
561fn canon_key_of(tree: &str) -> Option<String> {
564 let canon = crate::attest_inputs::canonical_route(tree)?;
565 crate::attest_inputs::canon_gate_key(WRITE.canon_domain, &canon)
566}
567
568fn file_canon(tree: &str, tokens: &[String]) {
572 let Some(key) = canon_key_of(tree) else {
573 return;
574 };
575 let mut note = note_in(INPUTS_REF, &key);
576 note.add_tokens(tokens);
577 let _ = write_note_in(INPUTS_REF, &key, ¬e);
578}
579
580fn file_inputs(tree: &str, tokens: &[String]) {
585 if tokens.is_empty() {
586 return;
587 }
588 let Some(spec) = crate::attest_inputs::spec_at(tree) else {
589 file_canon(tree, tokens);
590 return;
591 };
592 for (gate, _) in &spec.gates {
593 let mine: Vec<String> = tokens
594 .iter()
595 .filter(|t| crate::gate_identity::base(t) == gate.as_str())
596 .cloned()
597 .collect();
598 if mine.is_empty() || !manifest_is_an_input(tree, &spec, gate) {
599 continue;
600 }
601 let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
602 continue;
603 };
604 let Some(key) = crate::attest_inputs::input_key(&WRITE.attest, gate, &fp) else {
605 continue;
606 };
607 let mut note = note_in(INPUTS_REF, &key);
608 note.add_tokens(&mine);
609 let _ = write_note_in(INPUTS_REF, &key, ¬e);
610 }
611}
612
613fn manifest_is_an_input(tree: &str, spec: &crate::attest_inputs::Spec, gate: &str) -> bool {
619 let tracked = [crate::manifest::MANIFEST, crate::names::old::MANIFEST]
621 .into_iter()
622 .find(|name| crate::git::succeeds(&["cat-file", "-e", &format!("{tree}:{name}")]));
623 tracked.map_or(true, |name| {
624 crate::attest_inputs::declares(spec, gate, name)
625 })
626}
627
628fn inputs_ref_exists() -> bool {
633 READ.iter().any(|set| {
634 crate::git::succeeds(&[
635 "rev-parse",
636 "-q",
637 "--verify",
638 &format!("refs/notes/{}", set.inputs_ref),
639 ])
640 })
641}
642
643pub fn tree_tokens(tree: &str) -> Vec<String> {
647 let mut tokens = stamp_at(tree).tokens;
648 if inputs_ref_exists() {
649 for t in input_tokens(tree) {
650 if !tokens.contains(&t) {
651 tokens.push(t);
652 }
653 }
654 }
655 tokens
656}
657
658pub fn stamp_tree(tree: &str, tokens: &[String]) -> bool {
662 let mut note = note_at(tree);
663 note.add_tokens(tokens);
664 let ok = write_note(tree, ¬e);
665 file_inputs(tree, tokens);
666 ok
667}
668
669fn write_note(key: &str, note: &Note) -> bool {
671 write_note_in(NOTES_REF, key, note)
672}
673
674fn write_note_in(notes_ref: &str, key: &str, note: &Note) -> bool {
675 let body = note.render();
676 crate::git::succeeds(&["notes", "--ref", notes_ref, "add", "-f", "-m", &body, key])
677}
678
679pub fn record_runs(key: &str, runs: &[Run]) {
690 let runs: Vec<Run> = runs
695 .iter()
696 .filter(|r| !r.gate.is_empty() && !r.gate.contains(char::is_whitespace))
697 .cloned()
698 .collect();
699 if runs.is_empty() {
700 return;
701 }
702 let mut note = note_at(key);
703 note.add_runs(&runs);
704 let _ = write_note(key, ¬e);
705}
706
707pub fn record_deferred(tree: &str, gates: &[String]) {
711 let gates: Vec<&String> = gates
712 .iter()
713 .filter(|g| !g.is_empty() && !g.contains(char::is_whitespace))
714 .collect();
715 if gates.is_empty() {
716 return;
717 }
718 let mut note = note_at(tree);
719 for g in gates {
720 if !note.deferred.contains(g) {
721 note.deferred.push(g.clone());
722 }
723 }
724 let _ = write_note(tree, ¬e); }
726
727pub fn deferred_on(tree: &str) -> Vec<String> {
730 stamp_at(tree).deferred
731}
732
733pub fn deferred_for(commits: &[String], gate: &str) -> HashSet<String> {
737 let mut out = HashSet::new();
738 if commits.is_empty() {
739 return out;
740 }
741 let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
742 args.extend(commits.iter().map(String::as_str));
743 let Some(list) = crate::git::stdout(&args) else {
744 return out;
745 };
746 for line in list.lines() {
747 let mut it = line.split_whitespace();
748 let (Some(commit), Some(tree)) = (it.next(), it.next()) else {
749 continue;
750 };
751 if [commit, tree]
752 .iter()
753 .any(|key| stamp_at(key).deferred.iter().any(|d| d == gate))
754 {
755 out.insert(commit.to_string());
756 }
757 }
758 out
759}
760
761fn marker_path() -> Option<PathBuf> {
765 let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
766 Some(std::path::Path::new(&dir).join(MARKER))
767}
768
769pub fn record(scripts: &[&str]) {
780 let Some(path) = marker_path() else { return };
781 if scripts.is_empty() {
782 let _ = std::fs::remove_file(&path);
783 return;
784 }
785 let Some(tree) = crate::git::stdout(&["write-tree"]) else {
789 crate::hooks::common::warn(
793 "git would not name the staged tree — this commit records no gate stamp",
794 );
795 let _ = std::fs::remove_file(&path);
796 return;
797 };
798 let mut body = format!("{FORMAT}\n{tree}\n");
799 for s in scripts {
800 body.push_str(s);
801 body.push('\n');
802 }
803 let _ = std::fs::write(&path, body);
804}
805
806pub fn vouched_for_staged_tree() -> HashSet<String> {
834 let mut out = HashSet::new();
835 let Some(tree) = crate::git::stdout(&["write-tree"]) else {
836 return out;
837 };
838 if let Some(path) = marker_path() {
839 if let Ok(body) = std::fs::read_to_string(&path) {
840 let mut lines = body.lines();
841 if lines.next() == Some(FORMAT) && lines.next() == Some(tree.as_str()) {
842 out.extend(
843 lines
844 .filter(|l| !l.trim().is_empty() && !is_provenance(l))
845 .map(str::to_string),
846 );
847 }
848 }
849 }
850 out.extend(stamp_at(&tree).tokens);
859 if inputs_ref_exists() {
865 out.extend(input_tokens(&tree));
866 }
867 out
868}
869
870pub fn bind_to_head() -> Vec<String> {
881 let Some(path) = marker_path() else {
882 return Vec::new();
883 };
884 let Ok(body) = std::fs::read_to_string(&path) else {
885 return Vec::new(); };
887 let _ = std::fs::remove_file(&path);
888 let mut lines = body.lines();
889 if lines.next() != Some(FORMAT) {
890 return Vec::new();
891 }
892 let Some(tree) = lines.next() else {
893 return Vec::new();
894 };
895 let scripts: Vec<&str> = lines
896 .filter(|l| !l.trim().is_empty() && !is_provenance(l))
897 .collect();
898 if scripts.is_empty() {
899 return Vec::new();
900 }
901 let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
902 crate::hooks::common::warn(
903 "git would not name this commit's tree — no gate stamp was written",
904 );
905 return Vec::new();
906 };
907 if head_tree != tree {
910 return Vec::new();
911 }
912 let scripts: Vec<String> = scripts.iter().map(|s| s.to_string()).collect();
913 let mut tree_note = note_at(&head_tree);
938 tree_note.add_tokens(&scripts);
939 let _ = write_note(&head_tree, &tree_note);
940 file_inputs(&head_tree, &scripts);
941 let mut head_note = note_at("HEAD");
942 head_note.add_tokens(&scripts);
943 if !write_note("HEAD", &head_note) {
944 crate::hooks::common::warn(
947 "git refused to write the gate stamp — these checks will run again at push",
948 );
949 return Vec::new();
950 }
951 scripts
954 .iter()
955 .map(|s| crate::gate_identity::base(s).to_string())
956 .collect()
957}
958
959pub fn stamp_push(commit: &str, tree: &str, gates: &[String]) -> bool {
968 if gates.is_empty() {
969 return false;
970 }
971 let mut written = false;
972 for key in [tree, commit] {
973 let mut note = note_at(key);
974 note.add_tokens(gates);
975 let ok = write_note(key, ¬e);
976 if key == commit {
977 written = ok;
978 }
979 }
980 file_inputs(tree, gates);
981 if !written {
982 crate::hooks::common::warn(
983 "git refused to write the push stamp — these gates will run again on the next push",
984 );
985 }
986 written
987}
988
989#[derive(Debug, Clone, Copy, PartialEq, Eq)]
992pub enum Completion {
993 Warned,
995 FailedUnderWarn,
998 Unavailable,
1001}
1002
1003const UNAVAILABLE_FOR_SECS: u64 = 60 * 60;
1005
1006fn completion_word(how: Completion, token: &str, now: u64) -> String {
1008 match how {
1009 Completion::Warned => format!("warned:{token}"),
1010 Completion::FailedUnderWarn => format!("failed-under-warn:{token}"),
1011 Completion::Unavailable => format!("unavailable:{now}:{token}"),
1012 }
1013}
1014
1015fn completion_answers(word: &str, token: &str, severity: crate::check::Severity, now: u64) -> bool {
1017 if word.strip_prefix("warned:") == Some(token) {
1018 return true;
1019 }
1020 if word.strip_prefix("failed-under-warn:") == Some(token) {
1021 return severity == crate::check::Severity::Warn;
1022 }
1023 word.strip_prefix("unavailable:")
1024 .and_then(|rest| rest.split_once(':'))
1025 .is_some_and(|(at, tok)| {
1026 tok == token
1027 && at
1028 .parse::<u64>()
1029 .is_ok_and(|at| now.saturating_sub(at) <= UNAVAILABLE_FOR_SECS)
1030 })
1031}
1032
1033fn now_secs() -> u64 {
1034 std::time::SystemTime::now()
1035 .duration_since(std::time::UNIX_EPOCH)
1036 .map(|d| d.as_secs())
1037 .unwrap_or(0)
1038}
1039
1040pub fn record_done(tree: &str, tokens: &[String], how: Completion) -> Result<(), String> {
1046 if tokens.is_empty() {
1047 return Ok(());
1048 }
1049 let now = now_secs();
1050 let mut note = note_in(DONE_REF, tree);
1051 if how == Completion::Unavailable {
1052 note.tokens.retain(|word| {
1053 !word
1054 .strip_prefix("unavailable:")
1055 .and_then(|rest| rest.split_once(':'))
1056 .is_some_and(|(_, token)| tokens.iter().any(|t| t == token))
1057 });
1058 }
1059 let words: Vec<String> = tokens
1060 .iter()
1061 .map(|t| completion_word(how, t, now))
1062 .collect();
1063 note.add_tokens(&words);
1064 if write_note_in(DONE_REF, tree, ¬e) {
1065 Ok(())
1066 } else {
1067 Err(format!(
1068 "git refused to record the completed gates on {tree}"
1069 ))
1070 }
1071}
1072
1073pub fn done_on_every(commits: &[String], token: &str, severity: crate::check::Severity) -> bool {
1078 let now = now_secs();
1079 !commits.is_empty()
1080 && commits.iter().all(|c| {
1081 crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]).is_some_and(|tree| {
1082 stamp_in(|s| s.done_ref, &tree)
1083 .tokens
1084 .iter()
1085 .any(|word| completion_answers(word, token, severity, now))
1086 })
1087 })
1088}
1089
1090pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
1096 let mut out = HashMap::new();
1097 if commits.is_empty() {
1098 return out;
1099 }
1100 let lists: Option<Vec<String>> = READ
1103 .iter()
1104 .map(|set| crate::git::stdout(&["notes", "--ref", set.notes_ref, "list"]))
1105 .collect();
1106 let Some(lists) = lists else {
1107 crate::hooks::common::warn(
1117 "git would not list the gate stamps — every gated check will run again",
1118 );
1119 return out;
1120 };
1121 let noted: HashSet<&str> = lists
1122 .iter()
1123 .flat_map(|list| list.lines())
1124 .filter_map(|l| l.split_whitespace().nth(1))
1125 .collect();
1126 let mut trees: HashMap<String, String> = HashMap::new();
1130 {
1131 let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
1132 args.extend(commits.iter().map(String::as_str));
1133 if let Some(out) = crate::git::stdout(&args) {
1134 for line in out.lines() {
1135 let mut it = line.split_whitespace();
1136 if let (Some(c), Some(t)) = (it.next(), it.next()) {
1137 trees.insert(c.to_string(), t.to_string());
1138 }
1139 }
1140 }
1141 }
1145
1146 let by_inputs = inputs_ref_exists();
1152
1153 for commit in commits {
1154 let mut tokens: Vec<String> = Vec::new();
1173 let mut keys: Vec<&str> = Vec::new();
1174 if noted.contains(commit.as_str()) {
1175 keys.push(commit);
1176 }
1177 if let Some(tree) = trees.get(commit).filter(|t| noted.contains(t.as_str())) {
1178 keys.push(tree);
1179 }
1180 for key in keys {
1181 for t in stamp_at(key).tokens {
1182 if !tokens.contains(&t) {
1183 tokens.push(t);
1184 }
1185 }
1186 }
1187 if by_inputs {
1188 if let Some(tree) = trees.get(commit) {
1189 for t in input_tokens(tree) {
1190 if !tokens.contains(&t) {
1191 tokens.push(t);
1192 }
1193 }
1194 }
1195 }
1196 if tokens.is_empty() {
1197 continue;
1198 }
1199 out.insert(commit.clone(), tokens);
1200 }
1201 out
1202}
1203
1204pub fn forget() -> bool {
1209 let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
1210 let mut deleted = false;
1212 for set in READ {
1213 for r in full_refs(&set) {
1214 deleted |= crate::git::succeeds(&["update-ref", "-d", &r]);
1215 }
1216 }
1217 marker || deleted
1218}
1219
1220fn full_refs(set: &GateNames) -> [String; 4] {
1222 [set.notes_ref, set.inputs_ref, set.cluster_ref, set.done_ref]
1223 .map(|short| format!("refs/notes/{short}"))
1224}
1225
1226pub(crate) fn cluster_tokens(tree: &str) -> Vec<String> {
1229 stamp_in(|s| s.cluster_ref, tree).tokens
1230}
1231
1232pub(crate) fn stamp_cluster(tree: &str, token: &str, provenance: &str) -> bool {
1235 let mut note = note_in(CLUSTER_REF, tree);
1236 note.add_tokens(&[token.to_string()]);
1237 let line = format!("{PROVENANCE} {token} {provenance}");
1238 note.provenance
1239 .retain(|l| l.split_whitespace().nth(1) != Some(token));
1240 note.provenance.push(line);
1241 write_note_in(CLUSTER_REF, tree, ¬e)
1242}
1243
1244pub(crate) fn cluster_stamps_for(commits: &[String]) -> HashMap<String, (String, Vec<String>)> {
1248 let mut out = HashMap::new();
1249 for commit in commits {
1250 let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")]) else {
1251 continue;
1252 };
1253 let tokens = cluster_tokens(&tree);
1254 if !tokens.is_empty() {
1255 out.insert(commit.clone(), (tree, tokens));
1256 }
1257 }
1258 out
1259}
1260
1261pub fn forget_in(repo: &std::path::Path) -> bool {
1263 let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
1264 .is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
1265 let mut deleted = false;
1266 for set in READ {
1267 for r in full_refs(&set) {
1268 deleted |= crate::git::succeeds_in(repo, &["update-ref", "-d", &r]);
1269 }
1270 }
1271 marker || deleted
1272}
1273
1274#[cfg(test)]
1275mod tests {
1276 use super::*;
1277 use std::path::Path;
1278
1279 #[test]
1283 fn a_completion_answers_only_while_it_should() {
1284 use crate::check::Severity::{Block, Warn};
1285 let now = 1_700_000_000;
1286 let word = |how| completion_word(how, "gate-tok", now);
1287 assert!(completion_answers(
1288 &word(Completion::Warned),
1289 "gate-tok",
1290 Block,
1291 now
1292 ));
1293 assert!(completion_answers(
1294 &word(Completion::FailedUnderWarn),
1295 "gate-tok",
1296 Warn,
1297 now
1298 ));
1299 assert!(!completion_answers(
1300 &word(Completion::FailedUnderWarn),
1301 "gate-tok",
1302 Block,
1303 now
1304 ));
1305 let unavailable = word(Completion::Unavailable);
1306 assert!(completion_answers(
1307 &unavailable,
1308 "gate-tok",
1309 Block,
1310 now + 3600
1311 ));
1312 assert!(!completion_answers(
1313 &unavailable,
1314 "gate-tok",
1315 Block,
1316 now + 3601
1317 ));
1318 assert!(!completion_answers(
1319 &word(Completion::Warned),
1320 "other-tok",
1321 Warn,
1322 now
1323 ));
1324 }
1325
1326 fn repo(name: &str) -> PathBuf {
1329 let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
1330 let _ = std::fs::remove_dir_all(&dir);
1331 std::fs::create_dir_all(&dir).unwrap();
1332 git(&dir, &["init", "-q", "--template=", "."]);
1333 git(&dir, &["config", "user.email", "t@t.test"]);
1334 git(&dir, &["config", "user.name", "t"]);
1335 dir
1336 }
1337
1338 fn git(dir: &Path, args: &[&str]) -> String {
1347 let out = std::process::Command::new("git")
1348 .arg("-C")
1349 .arg(dir)
1350 .args(args)
1351 .output()
1352 .expect("git");
1353 assert!(
1354 out.status.success(),
1355 "fixture: git {args:?} in {} exited {:?}: {}",
1356 dir.display(),
1357 out.status.code(),
1358 String::from_utf8_lossy(&out.stderr).trim()
1359 );
1360 String::from_utf8_lossy(&out.stdout).trim().to_string()
1361 }
1362
1363 fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
1367 let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
1368 let prev = std::env::current_dir().unwrap();
1369 std::env::set_current_dir(dir).unwrap();
1370 let r = f();
1371 std::env::set_current_dir(prev).unwrap();
1372 r
1373 }
1374
1375 #[test]
1376 fn the_commit_note_does_not_hide_the_tree_notes_push_tokens() {
1377 let dir = repo("union");
1378 std::fs::write(dir.join("a.ts"), "x").unwrap();
1379 git(&dir, &["add", "a.ts"]);
1380 in_repo(&dir, || {
1381 record(&["test"]);
1382 git(&dir, &["commit", "-qm", "chore: a"]);
1383 bind_to_head();
1384 let head = git(&dir, &["rev-parse", "HEAD"]);
1385 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1386 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1389 assert_eq!(note_at(&head).tokens, vec!["test".to_string()]);
1390 let stamps = stamps_for(std::slice::from_ref(&head));
1391 assert_eq!(
1392 stamps.get(&head).map(Vec::as_slice),
1393 Some(&["test".to_string(), "pre-push-cargo-test".to_string()][..]),
1394 "both notes speak for the same tree"
1395 );
1396 });
1397 let _ = std::fs::remove_dir_all(&dir);
1398 }
1399
1400 #[test]
1404 fn an_unavailable_record_replaces_its_predecessor_only() {
1405 let dir = repo("done-unavailable");
1406 std::fs::write(dir.join("a.ts"), "x").unwrap();
1407 git(&dir, &["add", "a.ts"]);
1408 git(&dir, &["commit", "-qm", "chore: a"]);
1409 in_repo(&dir, || {
1410 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1411 let one = |t: &str| vec![t.to_string()];
1412 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("first");
1413 record_done(&tree, &one("lint@b"), Completion::Unavailable).expect("other gate");
1414 record_done(&tree, &one("lint@b"), Completion::Warned).expect("a warning");
1415 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("again");
1416 let words = note_in(DONE_REF, &tree).tokens;
1417 let unavailable_for = |token: &str| {
1418 words
1419 .iter()
1420 .filter(|w| w.starts_with("unavailable:") && w.ends_with(&format!(":{token}")))
1421 .count()
1422 };
1423 assert_eq!(unavailable_for("suite@a"), 1, "{words:?}");
1424 assert_eq!(unavailable_for("lint@b"), 1, "{words:?}");
1425 assert!(words.contains(&"warned:lint@b".to_string()), "{words:?}");
1426 });
1427 let _ = std::fs::remove_dir_all(&dir); }
1429
1430 #[test]
1431 fn a_commit_with_only_a_tree_note_still_reads_the_tree_tokens() {
1432 let dir = repo("tree-only");
1433 std::fs::write(dir.join("a.ts"), "x").unwrap();
1434 git(&dir, &["add", "a.ts"]);
1435 git(&dir, &["commit", "-qm", "chore: a"]);
1436 in_repo(&dir, || {
1437 let head = git(&dir, &["rev-parse", "HEAD"]);
1438 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1439 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1440 let stamps = stamps_for(std::slice::from_ref(&head));
1441 assert_eq!(
1442 stamps.get(&head).map(Vec::as_slice),
1443 Some(&["pre-push-cargo-test".to_string()][..])
1444 );
1445 });
1446 let _ = std::fs::remove_dir_all(&dir);
1447 }
1448
1449 #[test]
1450 fn a_commit_with_only_a_commit_note_still_reads_its_tokens() {
1451 let dir = repo("commit-only");
1452 std::fs::write(dir.join("a.ts"), "x").unwrap();
1453 git(&dir, &["add", "a.ts"]);
1454 git(&dir, &["commit", "-qm", "chore: a"]);
1455 in_repo(&dir, || {
1456 let head = git(&dir, &["rev-parse", "HEAD"]);
1457 let mut note = Note::default();
1458 note.add_tokens(&["typecheck".to_string()]);
1459 assert!(write_note(&head, ¬e));
1460 let stamps = stamps_for(std::slice::from_ref(&head));
1461 assert_eq!(
1462 stamps.get(&head).map(Vec::as_slice),
1463 Some(&["typecheck".to_string()][..])
1464 );
1465 });
1466 let _ = std::fs::remove_dir_all(&dir);
1467 }
1468
1469 #[test]
1470 fn a_token_on_both_notes_is_read_once() {
1471 let dir = repo("dedup");
1472 std::fs::write(dir.join("a.ts"), "x").unwrap();
1473 git(&dir, &["add", "a.ts"]);
1474 in_repo(&dir, || {
1475 record(&["test"]);
1476 git(&dir, &["commit", "-qm", "chore: a"]);
1477 bind_to_head(); let head = git(&dir, &["rev-parse", "HEAD"]);
1479 let stamps = stamps_for(std::slice::from_ref(&head));
1480 assert_eq!(
1481 stamps.get(&head).map(Vec::as_slice),
1482 Some(&["test".to_string()][..])
1483 );
1484 });
1485 let _ = std::fs::remove_dir_all(&dir);
1486 }
1487
1488 #[test]
1489 fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
1490 let dir = repo("roundtrip");
1491 std::fs::write(dir.join("a.ts"), "x").unwrap();
1492 git(&dir, &["add", "a.ts"]);
1493 in_repo(&dir, || {
1494 record(&["typecheck", "test"]);
1495 git(&dir, &["commit", "-qm", "chore: a"]);
1496 let stamped = bind_to_head();
1497 assert_eq!(
1498 stamped,
1499 vec!["typecheck".to_string(), "test".to_string()],
1500 "bind_to_head reports the scripts it stamped"
1501 );
1502 let head = git(&dir, &["rev-parse", "HEAD"]);
1503 let stamps = stamps_for(std::slice::from_ref(&head));
1504 assert_eq!(
1505 stamps.get(&head).map(Vec::as_slice),
1506 Some(&["typecheck".to_string(), "test".to_string()][..])
1507 );
1508 assert!(!dir.join(".git").join(MARKER).exists());
1515 });
1516 let _ = std::fs::remove_dir_all(&dir);
1517 }
1518
1519 #[test]
1520 fn a_marker_for_a_different_tree_stamps_nothing() {
1521 let dir = repo("stale");
1522 std::fs::write(dir.join("a.ts"), "x").unwrap();
1523 git(&dir, &["add", "a.ts"]);
1524 in_repo(&dir, || {
1525 record(&["typecheck"]);
1526 std::fs::write(dir.join("a.ts"), "y").unwrap();
1529 git(&dir, &["add", "a.ts"]);
1530 git(&dir, &["commit", "-qm", "chore: different"]);
1531 assert!(
1532 bind_to_head().is_empty(),
1533 "bind_to_head reports nothing when the tree moved"
1534 );
1535 let head = git(&dir, &["rev-parse", "HEAD"]);
1536 assert!(
1537 stamps_for(&[head]).is_empty(),
1538 "a stale marker must not vouch"
1539 );
1540 assert!(
1541 !dir.join(".git").join(MARKER).exists(),
1542 "consumed either way"
1543 );
1544 });
1545 let _ = std::fs::remove_dir_all(&dir);
1546 }
1547
1548 #[test]
1549 fn an_empty_record_clears_a_previous_marker() {
1550 let dir = repo("clears");
1551 std::fs::write(dir.join("a.ts"), "x").unwrap();
1552 git(&dir, &["add", "a.ts"]);
1553 in_repo(&dir, || {
1554 record(&["typecheck"]);
1555 assert!(dir.join(".git").join(MARKER).exists());
1556 record(&[]);
1557 assert!(!dir.join(".git").join(MARKER).exists());
1558 });
1559 let _ = std::fs::remove_dir_all(&dir);
1560 }
1561
1562 #[test]
1567 fn a_marker_in_an_unknown_format_stamps_nothing() {
1568 let dir = repo("wrongformat");
1569 std::fs::write(dir.join("a.ts"), "x").unwrap();
1570 git(&dir, &["add", "a.ts"]);
1571 in_repo(&dir, || {
1572 let tree = git(&dir, &["write-tree"]);
1573 let marker = dir.join(".git").join(MARKER);
1574 std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
1575 git(&dir, &["commit", "-qm", "chore: a"]);
1576 bind_to_head();
1577 let head = git(&dir, &["rev-parse", "HEAD"]);
1578 assert!(
1579 stamps_for(std::slice::from_ref(&head)).is_empty(),
1580 "an unknown format was trusted"
1581 );
1582 assert!(!marker.exists(), "consumed either way");
1583 });
1584 let _ = std::fs::remove_dir_all(&dir);
1585 }
1586
1587 #[test]
1591 fn a_foreign_note_is_not_a_stamp() {
1592 let dir = repo("foreignnote");
1593 std::fs::write(dir.join("a.ts"), "x").unwrap();
1594 git(&dir, &["add", "a.ts"]);
1595 in_repo(&dir, || {
1596 git(&dir, &["commit", "-qm", "chore: a"]);
1597 git(
1598 &dir,
1599 &[
1600 "notes",
1601 "--ref",
1602 NOTES_REF,
1603 "add",
1604 "-m",
1605 "typecheck test",
1606 "HEAD",
1607 ],
1608 );
1609 let head = git(&dir, &["rev-parse", "HEAD"]);
1610 assert!(
1611 stamps_for(std::slice::from_ref(&head)).is_empty(),
1612 "a note without the format token was trusted"
1613 );
1614 });
1615 let _ = std::fs::remove_dir_all(&dir);
1616 }
1617
1618 #[test]
1622 fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
1623 let dir = repo("no-stamps");
1624 std::fs::write(dir.join("a.ts"), "x").unwrap();
1625 git(&dir, &["add", "a.ts"]);
1626 git(&dir, &["commit", "-qm", "chore: a"]);
1627 in_repo(&dir, || {
1628 assert_eq!(
1629 crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
1630 Some(""),
1631 "an absent notes ref must be an ANSWER, not a failure — the \
1632 no-stamps path and the git-is-broken path are told apart by it"
1633 );
1634 let head = git(&dir, &["rev-parse", "HEAD"]);
1635 assert!(stamps_for(&[head]).is_empty());
1636 });
1637 let _ = std::fs::remove_dir_all(&dir);
1638 }
1639
1640 #[test]
1647 fn a_note_from_before_the_run_lines_parses_unchanged() {
1648 let note = Note::parse("greengate-gate-v1 typecheck test");
1649 assert_eq!(note.tokens, vec!["typecheck", "test"]);
1650 assert!(note.runs.is_empty());
1651 assert_eq!(note.render(), "greengate-gate-v1 typecheck test");
1654 }
1655
1656 #[test]
1658 fn run_lines_are_read_without_disturbing_the_tokens() {
1659 let body = "greengate-gate-v1 pre-push-cargo-test\n\
1660 run 1726900000 pre-push-cargo-test pass 412391\n\
1661 run 1726903600 pre-push-audit-js fail 903\n";
1662 let note = Note::parse(body);
1663 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1664 assert_eq!(note.runs.len(), 2);
1665 assert_eq!(
1666 note.runs[0],
1667 Run {
1668 at: 1_726_900_000,
1669 gate: "pre-push-cargo-test".into(),
1670 outcome: RunOutcome::Passed,
1671 ms: 412_391,
1672 }
1673 );
1674 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1675 assert_eq!(note.render(), body.trim_end());
1676 }
1677
1678 #[test]
1682 fn an_unreadable_run_line_is_dropped_and_the_rest_survives() {
1683 let note = Note::parse(
1684 "greengate-gate-v1 test\n\
1685 run 1726900000 pre-push-cargo-test pass 400\n\
1686 run tomorrow pre-push-cargo-test pass 400\n\
1687 run 1726900001 pre-push-cargo-test sideways 400\n\
1688 banana\n\
1689 run 1726900002 pre-push-cargo-test fail 500\n",
1690 );
1691 assert_eq!(note.tokens, vec!["test"]);
1692 assert_eq!(note.runs.len(), 2, "{:?}", note.runs);
1693 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1694 }
1695
1696 #[test]
1700 fn a_deferral_is_never_a_token_and_outlives_the_run_trim() {
1701 let mut note = Note::parse("greengate-gate-v1 lint\ndeferred cargo-test\n");
1702 assert_eq!(note.tokens, vec!["lint"]);
1703 assert_eq!(note.deferred, vec!["cargo-test"]);
1704 let runs: Vec<Run> = (0..MAX_RUNS as u64 + 10)
1705 .map(|i| Run {
1706 at: 1_726_900_000 + i,
1707 gate: "pre-push-audit-js".into(),
1708 outcome: RunOutcome::Passed,
1709 ms: 1,
1710 })
1711 .collect();
1712 note.add_runs(&runs);
1713 let again = Note::parse(¬e.render());
1714 assert_eq!(again.runs.len(), MAX_RUNS);
1715 assert_eq!(again.deferred, vec!["cargo-test"]);
1716 assert_eq!(again.tokens, vec!["lint"]);
1717 }
1718
1719 #[test]
1722 fn a_foreign_note_yields_no_runs() {
1723 let note = Note::parse("hello\nrun 1726900000 pre-push-cargo-test pass 400\n");
1724 assert!(note.tokens.is_empty() && note.runs.is_empty());
1725 }
1726
1727 #[test]
1732 fn a_stamp_and_its_evidence_survive_each_other() {
1733 let dir = repo("evidence");
1734 std::fs::write(dir.join("a.ts"), "x").unwrap();
1735 git(&dir, &["add", "a.ts"]);
1736 in_repo(&dir, || {
1737 git(&dir, &["commit", "-qm", "chore: a"]);
1738 let head = git(&dir, &["rev-parse", "HEAD"]);
1739 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1740 record_runs(
1741 &tree,
1742 &[Run {
1743 at: 1_726_900_000,
1744 gate: "pre-push-cargo-test".into(),
1745 outcome: RunOutcome::Failed,
1746 ms: 412_391,
1747 }],
1748 );
1749 assert!(stamp_push(&head, &tree, &["pre-push-cargo-test".into()]));
1751 let note = note_at(&tree);
1752 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1753 assert_eq!(note.runs.len(), 1, "the evidence survived the stamp");
1754 let stamps = stamps_for(std::slice::from_ref(&head));
1756 assert_eq!(
1757 stamps.get(&head).map(Vec::as_slice),
1758 Some(&["pre-push-cargo-test".to_string()][..])
1759 );
1760 });
1761 let _ = std::fs::remove_dir_all(&dir);
1762 }
1763
1764 #[test]
1768 fn a_recorded_run_is_not_a_stamp() {
1769 let dir = repo("not-a-stamp");
1770 std::fs::write(dir.join("a.ts"), "x").unwrap();
1771 git(&dir, &["add", "a.ts"]);
1772 in_repo(&dir, || {
1773 git(&dir, &["commit", "-qm", "chore: a"]);
1774 let head = git(&dir, &["rev-parse", "HEAD"]);
1775 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1776 record_runs(
1777 &tree,
1778 &[Run {
1779 at: 1_726_900_000,
1780 gate: "pre-push-cargo-test".into(),
1781 outcome: RunOutcome::Passed,
1782 ms: 412_391,
1783 }],
1784 );
1785 assert!(
1786 stamps_for(std::slice::from_ref(&head)).is_empty(),
1787 "a run line vouched for a gate — evidence must never gate"
1788 );
1789 assert!(
1790 !vouched_for_staged_tree().contains("pre-push-cargo-test"),
1791 "a run line vouched at commit time"
1792 );
1793 let history = crate::gate_evidence::history_in(&dir);
1795 assert_eq!(history.runs.len(), 1);
1796 assert_eq!(history.runs[0].0, tree, "keyed by the content it ran on");
1797 });
1798 let _ = std::fs::remove_dir_all(&dir);
1799 }
1800
1801 #[test]
1802 fn forget_removes_the_stamps() {
1803 let dir = repo("forget");
1804 std::fs::write(dir.join("a.ts"), "x").unwrap();
1805 git(&dir, &["add", "a.ts"]);
1806 in_repo(&dir, || {
1807 record(&["typecheck"]);
1808 git(&dir, &["commit", "-qm", "chore: a"]);
1809 bind_to_head();
1810 let head = git(&dir, &["rev-parse", "HEAD"]);
1811 assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
1812 forget();
1813 assert!(stamps_for(&[head]).is_empty());
1814 });
1815 let _ = std::fs::remove_dir_all(&dir);
1816 }
1817
1818 #[test]
1832 fn a_stamp_survives_a_commit_being_rewritten_with_the_same_tree() {
1833 let dir = repo("squashed");
1834 std::fs::write(dir.join("a.ts"), "x").unwrap();
1835 git(&dir, &["add", "a.ts"]);
1836 in_repo(&dir, || {
1837 record(&["test"]);
1838 git(&dir, &["commit", "-qm", "feat: on a branch"]);
1839 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1840 let branch_tip = git(&dir, &["rev-parse", "HEAD"]);
1841
1842 git(
1846 &dir,
1847 &[
1848 "commit",
1849 "-q",
1850 "--amend",
1851 "-m",
1852 "feat: squashed by the forge",
1853 ],
1854 );
1855 let merged = git(&dir, &["rev-parse", "HEAD"]);
1856 assert_ne!(merged, branch_tip, "the fixture must produce a new commit");
1857 assert_eq!(
1858 git(&dir, &["rev-parse", "HEAD^{tree}"]),
1859 git(&dir, &["rev-parse", &format!("{branch_tip}^{{tree}}")]),
1860 "…carrying the same tree, which is the whole premise"
1861 );
1862
1863 let stamps = stamps_for(std::slice::from_ref(&merged));
1864 assert_eq!(
1865 stamps.get(&merged).map(Vec::as_slice),
1866 Some(&["test".to_string()][..]),
1867 "the stamp must follow the content, not the commit hash"
1868 );
1869 });
1870 let _ = std::fs::remove_dir_all(&dir);
1871 }
1872
1873 #[test]
1877 fn a_different_tree_gets_no_stamp_from_the_fallback() {
1878 let dir = repo("othertree");
1879 std::fs::write(dir.join("a.ts"), "x").unwrap();
1880 git(&dir, &["add", "a.ts"]);
1881 in_repo(&dir, || {
1882 record(&["test"]);
1883 git(&dir, &["commit", "-qm", "chore: stamped"]);
1884 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1885
1886 std::fs::write(dir.join("b.ts"), "y").unwrap();
1889 git(&dir, &["add", "b.ts"]);
1890 git(&dir, &["commit", "-qm", "chore: unjudged"]);
1891 let unstamped = git(&dir, &["rev-parse", "HEAD"]);
1892
1893 assert!(
1894 stamps_for(std::slice::from_ref(&unstamped)).is_empty(),
1895 "a tree nobody stamped must not inherit one"
1896 );
1897 });
1898 let _ = std::fs::remove_dir_all(&dir);
1899 }
1900
1901 fn declared(name: &str, spec: &str) -> PathBuf {
1907 let dir = repo(name);
1908 std::fs::create_dir_all(dir.join(".github")).unwrap();
1909 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
1910 std::fs::write(dir.join("a.ts"), "x").unwrap();
1911 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
1912 std::fs::write(dir.join(".github/attest-inputs"), spec).unwrap();
1913 git(&dir, &["add", "-A"]);
1914 in_repo(&dir, || {
1915 record(&["test@abc"]);
1916 git(&dir, &["commit", "-qm", "feat: judged"]);
1917 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1918 });
1919 dir
1920 }
1921
1922 fn plan_only_commit(dir: &Path) -> String {
1925 std::fs::write(dir.join("docs/plans/p.md"), "plan v2, closing").unwrap();
1926 git(dir, &["add", "docs/plans/p.md"]);
1927 git(dir, &["commit", "-qm", "docs(plan): done"]);
1928 git(dir, &["rev-parse", "HEAD"])
1929 }
1930
1931 #[test]
1932 fn a_plan_only_commit_reuses_the_stamp_of_a_declared_gate() {
1933 let dir = declared("plan-only", "test a.ts\n");
1934 in_repo(&dir, || {
1935 let head = plan_only_commit(&dir);
1936 let stamps = stamps_for(std::slice::from_ref(&head));
1937 assert_eq!(
1938 stamps.get(&head).map(Vec::as_slice),
1939 Some(&["test@abc".to_string()][..]),
1940 "the closing commit changed the tree and none of the declared inputs"
1941 );
1942 });
1943 let _ = std::fs::remove_dir_all(&dir);
1944 }
1945
1946 #[test]
1947 fn the_staged_tree_of_a_plan_only_commit_is_vouched_for() {
1948 let dir = declared("staged", "test a.ts\n");
1949 in_repo(&dir, || {
1950 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1951 git(&dir, &["add", "docs/plans/p.md"]);
1952 assert!(vouched_for_staged_tree().contains("test@abc"));
1953 });
1954 let _ = std::fs::remove_dir_all(&dir);
1955 }
1956
1957 #[test]
1958 fn partial_staging_is_judged_on_the_index_not_the_working_copy() {
1959 let dir = declared("partial", "test a.ts\n");
1960 in_repo(&dir, || {
1961 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1964 git(&dir, &["add", "docs/plans/p.md"]);
1965 std::fs::write(dir.join("a.ts"), "unstaged edit").unwrap();
1966 assert!(vouched_for_staged_tree().contains("test@abc"));
1967
1968 std::fs::write(dir.join("a.ts"), "staged edit").unwrap();
1971 git(&dir, &["add", "a.ts"]);
1972 std::fs::write(dir.join("a.ts"), "x").unwrap();
1973 assert!(!vouched_for_staged_tree().contains("test@abc"));
1974 });
1975 let _ = std::fs::remove_dir_all(&dir);
1976 }
1977
1978 #[test]
1979 fn a_changed_declared_input_misses() {
1980 let dir = declared("input-changed", "test a.ts\n");
1981 in_repo(&dir, || {
1982 std::fs::write(dir.join("a.ts"), "changed").unwrap();
1983 git(&dir, &["add", "a.ts"]);
1984 git(&dir, &["commit", "-qm", "feat: unjudged"]);
1985 let head = git(&dir, &["rev-parse", "HEAD"]);
1986 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1987 });
1988 let _ = std::fs::remove_dir_all(&dir);
1989 }
1990
1991 #[test]
1992 fn a_changed_declaration_misses() {
1993 let dir = declared("declaration-changed", "test a.ts\n");
1994 in_repo(&dir, || {
1995 std::fs::write(dir.join("b.ts"), "y").unwrap();
1998 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts b.ts\n").unwrap();
1999 git(&dir, &["add", "-A"]);
2000 git(&dir, &["commit", "-qm", "chore: widen the declaration"]);
2001 let head = git(&dir, &["rev-parse", "HEAD"]);
2002 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2003 });
2004 let _ = std::fs::remove_dir_all(&dir);
2005 }
2006
2007 #[test]
2008 fn a_declared_config_file_is_an_input_like_any_other() {
2009 let dir = declared("config", "test a.ts amont.conf\n");
2012 in_repo(&dir, || {
2013 assert!(!inputs_ref_exists());
2016
2017 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2018 git(&dir, &["add", "amont.conf"]);
2019 record(&["test@abc"]);
2020 git(&dir, &["commit", "-qm", "chore: config"]);
2021 assert_eq!(bind_to_head(), vec!["test".to_string()]);
2022
2023 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
2024 git(&dir, &["add", "docs/plans/p.md"]);
2025 git(&dir, &["commit", "-qm", "docs(plan): done"]);
2026 let plan = git(&dir, &["rev-parse", "HEAD"]);
2027 assert!(stamps_for(std::slice::from_ref(&plan)).contains_key(&plan));
2028
2029 std::fs::write(dir.join("amont.conf"), "scope = lib\n").unwrap();
2030 git(&dir, &["add", "amont.conf"]);
2031 git(&dir, &["commit", "-qm", "chore: scope-only change"]);
2032 let scope = git(&dir, &["rev-parse", "HEAD"]);
2033 assert!(
2034 stamps_for(std::slice::from_ref(&scope)).is_empty(),
2035 "a scope-only change must miss"
2036 );
2037 });
2038 let _ = std::fs::remove_dir_all(&dir);
2039 }
2040
2041 #[test]
2042 fn a_declared_stamp_is_read_back_as_its_complete_token() {
2043 let dir = declared("identity", "test a.ts\n");
2049 in_repo(&dir, || {
2050 let head = plan_only_commit(&dir);
2051 let tokens = stamps_for(std::slice::from_ref(&head))
2052 .remove(&head)
2053 .unwrap_or_default();
2054 assert_eq!(tokens, vec!["test@abc".to_string()]);
2055
2056 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2057 assert!(stamp_tree(&tree, &["test@def".to_string()]));
2058 let tokens = tree_tokens(&tree);
2059 assert!(tokens.contains(&"test@abc".to_string()));
2060 assert!(tokens.contains(&"test@def".to_string()));
2061 assert!(!tokens.contains(&"test@zzz".to_string()));
2062 assert!(!tokens.contains(&"test".to_string()));
2063 });
2064 let _ = std::fs::remove_dir_all(&dir);
2065 }
2066
2067 #[test]
2068 fn a_gate_that_does_not_declare_the_manifest_is_not_offered_the_route() {
2069 let dir = repo("manifest-undeclared");
2073 std::fs::create_dir_all(dir.join(".github")).unwrap();
2074 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2075 std::fs::write(dir.join("a.ts"), "x").unwrap();
2076 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2077 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2078 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2079 git(&dir, &["add", "-A"]);
2080 in_repo(&dir, || {
2081 record(&["test@abc"]);
2082 git(&dir, &["commit", "-qm", "feat: judged"]);
2083 bind_to_head();
2084 assert!(!inputs_ref_exists(), "the route must not open");
2085 let head = plan_only_commit(&dir);
2086 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2087 });
2088 let _ = std::fs::remove_dir_all(&dir);
2089 }
2090
2091 #[test]
2092 fn a_gate_declaring_the_manifest_opens_the_route() {
2093 let dir = declared("manifest-declared", "test a.ts amont.conf\n");
2096 in_repo(&dir, || {
2097 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
2098 git(&dir, &["add", "amont.conf"]);
2099 record(&["test@abc"]);
2100 git(&dir, &["commit", "-qm", "chore: config"]);
2101 bind_to_head();
2102 assert!(inputs_ref_exists());
2103 });
2104 let _ = std::fs::remove_dir_all(&dir);
2105 }
2106
2107 #[test]
2108 fn an_undeclared_gate_keeps_whole_tree_behaviour() {
2109 let dir = declared("undeclared", "test a.ts\n");
2110 in_repo(&dir, || {
2111 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2114 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2115 let head = plan_only_commit(&dir);
2116 let tokens = stamps_for(std::slice::from_ref(&head))
2117 .remove(&head)
2118 .unwrap_or_default();
2119 assert!(tokens.contains(&"test@abc".to_string()));
2120 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2121 });
2122 let _ = std::fs::remove_dir_all(&dir);
2123 }
2124
2125 #[test]
2126 fn an_invalid_or_ambiguous_spec_falls_back_to_whole_tree_behaviour() {
2127 let dir = declared("invalid", "test src/*\n");
2129 in_repo(&dir, || {
2130 assert!(!inputs_ref_exists(), "no valid spec, nothing is filed");
2131 let head = plan_only_commit(&dir);
2132 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2133 });
2134 let _ = std::fs::remove_dir_all(&dir);
2135
2136 let dir = repo("ambiguous");
2138 std::fs::create_dir_all(dir.join(".github")).unwrap();
2139 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2140 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2141 std::fs::write(dir.join("a.ts"), "x").unwrap();
2142 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2143 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2144 std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
2145 git(&dir, &["add", "-A"]);
2146 in_repo(&dir, || {
2147 record(&["test@abc"]);
2148 git(&dir, &["commit", "-qm", "feat: judged"]);
2149 bind_to_head();
2150 assert!(!inputs_ref_exists());
2151 let head = plan_only_commit(&dir);
2152 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2153 });
2154 let _ = std::fs::remove_dir_all(&dir);
2155 }
2156
2157 #[test]
2158 fn a_gate_that_did_not_pass_leaves_no_declared_input_stamp() {
2159 let dir = repo("failed");
2160 std::fs::create_dir_all(dir.join(".github")).unwrap();
2161 std::fs::write(dir.join("a.ts"), "x").unwrap();
2162 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2163 git(&dir, &["add", "-A"]);
2164 in_repo(&dir, || {
2165 record(&[]);
2167 git(&dir, &["commit", "-qm", "feat: unjudged"]);
2168 assert!(bind_to_head().is_empty());
2169 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2170 let head = git(&dir, &["rev-parse", "HEAD"]);
2171 assert!(!stamp_push(&head, &tree, &[]));
2172 assert!(!inputs_ref_exists());
2173 });
2174 let _ = std::fs::remove_dir_all(&dir);
2175 }
2176
2177 #[test]
2178 fn stamp_tree_and_tree_tokens_use_the_inputs_ref() {
2179 let dir = declared("rehearsal", "test a.ts\n");
2180 in_repo(&dir, || {
2181 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2183 assert!(stamp_tree(&tree, &["test@rehearsed".to_string()]));
2184 plan_only_commit(&dir);
2186 let later = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2187 assert_ne!(later, tree);
2188 assert!(tree_tokens(&later).contains(&"test@rehearsed".to_string()));
2189 });
2190 let _ = std::fs::remove_dir_all(&dir);
2191 }
2192
2193 #[test]
2194 fn the_inputs_ref_is_keyed_the_way_attest_keys_its_own() {
2195 let dir = declared("key", "test a.ts\n");
2196 in_repo(&dir, || {
2197 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2198 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2199 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2200 let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
2201 let listed = git(&dir, &["notes", "--ref", INPUTS_REF, "list"]);
2202 assert!(
2203 listed
2204 .lines()
2205 .any(|l| l.split_whitespace().nth(1) == Some(key.as_str())),
2206 "{listed}"
2207 );
2208 });
2209 let _ = std::fs::remove_dir_all(&dir);
2210 }
2211
2212 #[test]
2213 fn a_foreign_token_in_the_inputs_ref_vouches_for_nothing() {
2214 let dir = declared("foreign", "test a.ts\n");
2215 in_repo(&dir, || {
2216 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2217 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2218 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2219 let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
2220 let mut note = note_in(INPUTS_REF, &key);
2222 note.add_tokens(&["publish@evil".to_string()]);
2223 assert!(write_note_in(INPUTS_REF, &key, ¬e));
2224 assert!(!tree_tokens(&tree).contains(&"publish@evil".to_string()));
2225 });
2226 let _ = std::fs::remove_dir_all(&dir);
2227 }
2228
2229 #[test]
2230 fn forget_removes_the_inputs_ref_too() {
2231 let dir = declared("forget-inputs", "test a.ts\n");
2232 in_repo(&dir, || {
2233 assert!(inputs_ref_exists());
2234 assert!(forget());
2235 assert!(!inputs_ref_exists());
2236 });
2237 let _ = std::fs::remove_dir_all(&dir);
2238 }
2239
2240 fn canonical(name: &str, conf: Option<&str>) -> PathBuf {
2243 let dir = repo(name);
2244 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2245 std::fs::write(dir.join("a.ts"), "x").unwrap();
2246 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
2247 if let Some(conf) = conf {
2248 std::fs::write(dir.join("amont.conf"), conf).unwrap();
2249 }
2250 git(&dir, &["add", "-A"]);
2251 in_repo(&dir, || {
2252 record(&["test@abc"]);
2253 git(&dir, &["commit", "-qm", "feat: judged"]);
2254 assert_eq!(bind_to_head(), vec!["test".to_string()]);
2255 });
2256 dir
2257 }
2258
2259 fn vouched(dir: &Path, commit: &str) -> Vec<String> {
2260 in_repo(dir, || {
2261 stamps_for(std::slice::from_ref(&commit.to_string()))
2262 .remove(commit)
2263 .unwrap_or_default()
2264 })
2265 }
2266
2267 #[test]
2268 fn with_no_spec_a_plans_only_commit_is_vouched_for_canonically() {
2269 let dir = canonical("canon-plan-edit", None);
2270 in_repo(&dir, || {
2271 assert!(inputs_ref_exists(), "the canonical stamp is filed");
2272 let head = plan_only_commit(&dir);
2273 assert_eq!(
2274 stamps_for(std::slice::from_ref(&head))
2275 .remove(&head)
2276 .unwrap_or_default(),
2277 vec!["test@abc".to_string()]
2278 );
2279 std::fs::write(dir.join("docs/plans/p.md"), "plan v3").unwrap();
2281 git(&dir, &["add", "docs/plans/p.md"]);
2282 assert!(vouched_for_staged_tree().contains("test@abc"));
2283 });
2284 let _ = std::fs::remove_dir_all(&dir);
2285 }
2286
2287 #[test]
2288 fn a_plan_added_deleted_or_renamed_is_not_vouched_for() {
2289 let dir = canonical("canon-plan-exists", None);
2290 std::fs::write(dir.join("docs/plans/q.md"), "second plan").unwrap();
2291 git(&dir, &["add", "docs/plans/q.md"]);
2292 git(&dir, &["commit", "-qm", "docs(plan): add"]);
2293 let added = git(&dir, &["rev-parse", "HEAD"]);
2294 assert!(vouched(&dir, &added).is_empty(), "a plan added");
2295 git(&dir, &["mv", "docs/plans/p.md", "docs/plans/r.md"]);
2296 git(&dir, &["commit", "-qm", "docs(plan): rename"]);
2297 let renamed = git(&dir, &["rev-parse", "HEAD"]);
2298 assert!(vouched(&dir, &renamed).is_empty(), "a plan renamed");
2299 let _ = std::fs::remove_dir_all(&dir);
2300 }
2301
2302 #[test]
2303 fn with_no_spec_any_other_change_is_not_vouched_for() {
2304 let dir = canonical("canon-code-edit", Some("gate test = make test\n"));
2305 std::fs::write(dir.join("a.ts"), "changed").unwrap();
2306 git(&dir, &["commit", "-qam", "feat: code"]);
2307 let code = git(&dir, &["rev-parse", "HEAD"]);
2308 assert!(vouched(&dir, &code).is_empty(), "a source edit");
2309 std::fs::write(dir.join("amont.conf"), "gate test = make other\n").unwrap();
2311 git(&dir, &["commit", "-qam", "chore: config"]);
2312 let conf = git(&dir, &["rev-parse", "HEAD"]);
2313 assert!(vouched(&dir, &conf).is_empty(), "a manifest edit");
2314 let _ = std::fs::remove_dir_all(&dir);
2315 }
2316
2317 #[test]
2318 fn plan_exempt_off_closes_the_canonical_route() {
2319 for (name, conf) in [
2320 ("off", "set planExempt off\n"),
2321 ("spelled", "SET PLANEXEMPT\tOff\r\n"),
2322 ("after", "set planExempt on\nset planExempt off\n"),
2323 ] {
2324 let dir = canonical(&format!("canon-off-{name}"), Some(conf));
2325 in_repo(&dir, || {
2326 assert!(!inputs_ref_exists(), "{name}: nothing is filed");
2327 let head = plan_only_commit(&dir);
2328 assert!(
2329 stamps_for(std::slice::from_ref(&head)).is_empty(),
2330 "{name}: a plans-only commit is a new tree"
2331 );
2332 });
2333 let _ = std::fs::remove_dir_all(&dir);
2334 }
2335 for (name, conf) in [
2337 ("on", "set planExempt on\n"),
2338 ("comment", "set planExempt off # no\n"),
2339 ("commented", "# set planExempt off\n"),
2340 ] {
2341 let dir = canonical(&format!("canon-on-{name}"), Some(conf));
2342 let head = plan_only_commit(&dir);
2343 assert!(!vouched(&dir, &head).is_empty(), "{name}: still canonical");
2344 let _ = std::fs::remove_dir_all(&dir);
2345 }
2346 }
2347
2348 #[test]
2349 fn a_spec_that_cannot_be_used_means_no_canonical_stamps() {
2350 let dir = repo("canon-unreadable-spec");
2352 std::fs::create_dir_all(dir.join(".github/attest-inputs")).unwrap();
2353 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2354 std::fs::write(dir.join(".github/attest-inputs/x"), "x").unwrap();
2355 std::fs::write(dir.join("a.ts"), "x").unwrap();
2356 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2357 git(&dir, &["add", "-A"]);
2358 in_repo(&dir, || {
2359 record(&["test@abc"]);
2360 git(&dir, &["commit", "-qm", "feat: judged"]);
2361 bind_to_head();
2362 assert!(!inputs_ref_exists(), "an unreadable spec opens nothing");
2363 let head = plan_only_commit(&dir);
2364 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2365 });
2366 let _ = std::fs::remove_dir_all(&dir);
2367 }
2368
2369 #[test]
2370 fn two_specs_mean_no_canonical_stamps() {
2371 let dir = repo("canon-ambiguous");
2372 std::fs::create_dir_all(dir.join(".github")).unwrap();
2373 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2374 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2375 std::fs::write(dir.join("a.ts"), "x").unwrap();
2376 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2377 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2378 std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
2379 git(&dir, &["add", "-A"]);
2380 in_repo(&dir, || {
2381 record(&["test@abc"]);
2382 git(&dir, &["commit", "-qm", "feat: judged"]);
2383 bind_to_head();
2384 assert!(!inputs_ref_exists());
2385 let head = plan_only_commit(&dir);
2386 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2387 });
2388 let _ = std::fs::remove_dir_all(&dir);
2389 }
2390
2391 #[test]
2392 fn a_valid_spec_keeps_precedence_over_the_canonical_route() {
2393 let dir = declared("canon-precedence", "test a.ts\n");
2395 in_repo(&dir, || {
2396 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2397 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2398 let head = plan_only_commit(&dir);
2399 let tokens = stamps_for(std::slice::from_ref(&head))
2400 .remove(&head)
2401 .unwrap_or_default();
2402 assert!(tokens.contains(&"test@abc".to_string()));
2403 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2404 });
2405 let _ = std::fs::remove_dir_all(&dir);
2406 }
2407
2408 fn unstamped(name: &str) -> (PathBuf, String, String) {
2414 let dir = repo(name);
2415 std::fs::write(dir.join("a.ts"), "x").unwrap();
2416 git(&dir, &["add", "a.ts"]);
2417 git(&dir, &["commit", "-qm", "feat: a"]);
2418 let head = git(&dir, &["rev-parse", "HEAD"]);
2419 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2420 (dir, head, tree)
2421 }
2422
2423 fn plant(dir: &Path, notes_ref: &str, key: &str, body: &str) {
2425 git(
2426 dir,
2427 &["notes", "--ref", notes_ref, "add", "-f", "-m", body, key],
2428 );
2429 }
2430
2431 fn stamps_of(commit: &str) -> Vec<String> {
2432 stamps_for(&[commit.to_string()])
2433 .remove(commit)
2434 .unwrap_or_default()
2435 }
2436
2437 #[test]
2438 fn a_pass_is_found_under_either_gate_ref() {
2439 for (i, set) in READ.iter().enumerate() {
2440 let (dir, head, tree) = unstamped(&format!("either-{i}"));
2441 plant(
2442 &dir,
2443 set.notes_ref,
2444 &head,
2445 &format!("{} test@c", set.format),
2446 );
2447 plant(
2448 &dir,
2449 set.notes_ref,
2450 &tree,
2451 &format!("{} test@t", set.format),
2452 );
2453 plant(
2454 &dir,
2455 set.cluster_ref,
2456 &tree,
2457 &format!("{} suite@k", set.format),
2458 );
2459 plant(
2460 &dir,
2461 set.done_ref,
2462 &tree,
2463 &format!("{} warned:lint@w", set.format),
2464 );
2465 in_repo(&dir, || {
2466 let mut got = stamps_of(&head);
2467 got.sort();
2468 assert_eq!(got, ["test@c", "test@t"], "{}", set.notes_ref);
2469 assert_eq!(tree_tokens(&tree), ["test@t"], "{}", set.notes_ref);
2470 assert_eq!(cluster_tokens(&tree), ["suite@k"], "{}", set.cluster_ref);
2471 assert!(
2472 done_on_every(
2473 std::slice::from_ref(&head),
2474 "lint@w",
2475 crate::check::Severity::Block
2476 ),
2477 "{}",
2478 set.done_ref
2479 );
2480 });
2481 let _ = std::fs::remove_dir_all(&dir); }
2483 }
2484
2485 #[test]
2486 fn with_notes_under_both_refs_the_green_note_is_read() {
2487 let (dir, head, tree) = unstamped("both-refs");
2488 for key in [&head, &tree] {
2489 plant(
2490 &dir,
2491 LEGACY.notes_ref,
2492 key,
2493 &format!("{} test@old", LEGACY.format),
2494 );
2495 plant(
2496 &dir,
2497 GREEN.notes_ref,
2498 key,
2499 &format!("{} test@new", GREEN.format),
2500 );
2501 }
2502 plant(
2503 &dir,
2504 LEGACY.cluster_ref,
2505 &tree,
2506 &format!("{} suite@old", LEGACY.format),
2507 );
2508 plant(
2509 &dir,
2510 GREEN.cluster_ref,
2511 &tree,
2512 &format!("{} suite@new", GREEN.format),
2513 );
2514 in_repo(&dir, || {
2515 assert_eq!(stamps_of(&head), ["test@new"]);
2516 assert_eq!(tree_tokens(&tree), ["test@new"]);
2517 assert_eq!(cluster_tokens(&tree), ["suite@new"]);
2518 });
2519 let _ = std::fs::remove_dir_all(&dir); }
2521
2522 #[test]
2523 fn a_note_whose_header_is_the_other_sets_reads_as_unstamped() {
2524 for (i, (sits_in, header_of)) in [(LEGACY, GREEN), (GREEN, LEGACY)].iter().enumerate() {
2525 let (dir, head, tree) = unstamped(&format!("mixed-{i}"));
2526 for key in [&head, &tree] {
2527 plant(
2528 &dir,
2529 sits_in.notes_ref,
2530 key,
2531 &format!("{} test@x", header_of.format),
2532 );
2533 }
2534 plant(
2535 &dir,
2536 sits_in.cluster_ref,
2537 &tree,
2538 &format!("{} suite@x", header_of.format),
2539 );
2540 in_repo(&dir, || {
2541 assert!(stamps_of(&head).is_empty(), "{}", sits_in.notes_ref);
2542 assert!(tree_tokens(&tree).is_empty(), "{}", sits_in.notes_ref);
2543 assert!(cluster_tokens(&tree).is_empty(), "{}", sits_in.cluster_ref);
2544 });
2545 let _ = std::fs::remove_dir_all(&dir); }
2547 }
2548
2549 #[test]
2553 fn the_green_inputs_ref_is_read_first_under_its_own_key() {
2554 let dir = declared("green-inputs", "test a.ts\n");
2555 in_repo(&dir, || {
2556 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2557 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2558 let fp = crate::attest_inputs::fingerprint(&tree, &spec, "test").expect("fp");
2559 let green = crate::attest_inputs::input_key(&GREEN.attest, "test", &fp).expect("key");
2560 let legacy = crate::attest_inputs::input_key(&LEGACY.attest, "test", &fp).expect("key");
2561 assert_ne!(green, legacy, "each set keys with its own domain");
2562 let head = plan_only_commit(&dir);
2563 plant(
2565 &dir,
2566 GREEN.inputs_ref,
2567 &legacy,
2568 &format!("{} test@wrongkey", GREEN.format),
2569 );
2570 assert_eq!(stamps_of(&head), ["test@abc"]);
2571 plant(
2572 &dir,
2573 GREEN.inputs_ref,
2574 &green,
2575 &format!("{} test@green", GREEN.format),
2576 );
2577 assert_eq!(stamps_of(&head), ["test@green"]);
2578 });
2579 let _ = std::fs::remove_dir_all(&dir); }
2581
2582 #[test]
2583 fn a_green_canonical_note_is_read_under_the_green_domain() {
2584 let dir = canonical("green-canon", None);
2585 in_repo(&dir, || {
2586 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2587 let canon = crate::attest_inputs::canonical_route(&tree).expect("canon");
2588 let key =
2589 crate::attest_inputs::canon_gate_key(GREEN.canon_domain, &canon).expect("key");
2590 plant(
2591 &dir,
2592 GREEN.inputs_ref,
2593 &key,
2594 &format!("{} test@green", GREEN.format),
2595 );
2596 let head = plan_only_commit(&dir);
2597 assert_eq!(stamps_of(&head), ["test@green"]);
2598 });
2599 let _ = std::fs::remove_dir_all(&dir); }
2601
2602 #[test]
2606 fn history_reads_runs_under_both_name_sets() {
2607 let (dir, _head, tree) = unstamped("history-both");
2608 let other = git(&dir, &["rev-parse", "HEAD"]);
2609 plant(
2610 &dir,
2611 LEGACY.notes_ref,
2612 &other,
2613 &format!("{}\nrun 100 old-gate pass 7", LEGACY.format),
2614 );
2615 plant(
2616 &dir,
2617 GREEN.notes_ref,
2618 &tree,
2619 &format!("{}\nrun 200 new-gate pass 9", GREEN.format),
2620 );
2621 plant(
2623 &dir,
2624 GREEN.notes_ref,
2625 &other,
2626 &format!("{}\nrun 300 mixed-gate pass 1", LEGACY.format),
2627 );
2628 let history = crate::gate_evidence::history_in(&dir);
2629 let mut got: Vec<(String, String)> = history
2630 .runs
2631 .iter()
2632 .map(|(k, r)| (k.clone(), r.gate.clone()))
2633 .collect();
2634 got.sort();
2635 let mut want = vec![
2636 (other, "old-gate".to_string()),
2637 (tree, "new-gate".to_string()),
2638 ];
2639 want.sort();
2640 assert_eq!(got, want);
2641 let _ = std::fs::remove_dir_all(&dir); }
2643
2644 #[test]
2645 fn forget_removes_the_refs_of_both_name_sets() {
2646 let (dir, _head, tree) = unstamped("forget-both");
2647 plant(
2648 &dir,
2649 GREEN.notes_ref,
2650 &tree,
2651 &format!("{} test@g", GREEN.format),
2652 );
2653 plant(
2654 &dir,
2655 LEGACY.notes_ref,
2656 &tree,
2657 &format!("{} test@l", LEGACY.format),
2658 );
2659 for set in READ {
2660 plant(&dir, set.done_ref, &tree, "done");
2661 }
2662 in_repo(&dir, || {
2663 assert_eq!(tree_tokens(&tree).len(), 1);
2664 assert!(forget());
2665 assert!(tree_tokens(&tree).is_empty(), "{:?}", tree_tokens(&tree));
2666 });
2667 for set in READ {
2668 for r in full_refs(&set) {
2669 let out = std::process::Command::new("git")
2670 .args(["-C"])
2671 .arg(&dir)
2672 .args(["rev-parse", "--verify", "-q", &r])
2673 .output()
2674 .unwrap();
2675 assert!(!out.status.success(), "{r} survived forget");
2676 }
2677 }
2678 let _ = std::fs::remove_dir_all(&dir); }
2680
2681 #[test]
2682 fn writes_go_under_the_green_names_and_each_full_ref_names_its_ref() {
2683 assert_eq!(WRITE, GREEN);
2684 assert_eq!(FORMAT, "greengate-gate-v1");
2685 for (full, short) in [
2686 (NOTES_FULL_REF, NOTES_REF),
2687 (INPUTS_FULL_REF, INPUTS_REF),
2688 (CLUSTER_FULL_REF, CLUSTER_REF),
2689 (DONE_FULL_REF, DONE_REF),
2690 ] {
2691 assert_eq!(full, format!("refs/notes/{short}"));
2692 assert!(full.starts_with("refs/notes/greengate-gate"), "{full}");
2693 }
2694 let (dir, head, tree) = unstamped("write-green");
2697 plant(
2698 &dir,
2699 LEGACY.notes_ref,
2700 &tree,
2701 &format!("{} test@old", LEGACY.format),
2702 );
2703 in_repo(&dir, || {
2704 assert!(stamp_push(&head, &tree, &["suite@p".to_string()]));
2705 let written = git(&dir, &["notes", "--ref", GREEN.notes_ref, "show", &tree]);
2706 assert_eq!(written, format!("{} suite@p", GREEN.format));
2707 let old = git(&dir, &["notes", "--ref", LEGACY.notes_ref, "show", &tree]);
2709 assert_eq!(old, format!("{} test@old", LEGACY.format));
2710 });
2711 let _ = std::fs::remove_dir_all(&dir); }
2713}