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