1use std::collections::{HashMap, HashSet};
87use std::path::PathBuf;
88
89pub const FORMAT: &str = "amont-gate-v1";
93
94pub const NOTES_REF: &str = "amont-gate";
96
97pub const NOTES_FULL_REF: &str = "refs/notes/amont-gate";
99
100pub const INPUTS_REF: &str = "amont-gate-inputs";
108
109pub const CLUSTER_REF: &str = "amont-gate-cluster";
114pub const CLUSTER_FULL_REF: &str = "refs/notes/amont-gate-cluster";
115
116pub const DONE_REF: &str = "amont-gate-done";
124pub const DONE_FULL_REF: &str = "refs/notes/amont-gate-done";
125
126pub const PROVENANCE: &str = "provenance";
130pub const INPUTS_FULL_REF: &str = "refs/notes/amont-gate-inputs";
131
132const MARKER: &str = crate::names::GATE_MARKER;
134
135const PUSH_STAMPS: &str = "greengate.pushStamps";
139
140pub fn push_stamps_enabled(settings: &crate::config::Settings) -> bool {
142 crate::config::boolean_or(settings, PUSH_STAMPS, true)
143}
144
145const COMMIT_STAMPS: &str = "greengate.commitStamps";
150
151pub fn commit_stamps_enabled(settings: &crate::config::Settings) -> bool {
154 crate::config::boolean_or(settings, COMMIT_STAMPS, true)
155}
156
157const RUN: &str = "run";
160
161const MAX_RUNS: usize = 64;
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub enum RunOutcome {
175 Passed,
176 Failed,
177 Warned,
178 Fixed,
179 Unavailable,
180 Inert,
181 Cold,
185 Busy,
187 Skew,
189 Withheld,
192 Cancelled,
194 Slow,
197 Deferred,
199}
200
201impl RunOutcome {
202 pub fn as_str(self) -> &'static str {
203 match self {
204 RunOutcome::Passed => "pass",
205 RunOutcome::Failed => "fail",
206 RunOutcome::Warned => "warn",
207 RunOutcome::Fixed => "fixed",
208 RunOutcome::Unavailable => "unavailable",
209 RunOutcome::Inert => "inert",
210 RunOutcome::Cold => "cold",
211 RunOutcome::Busy => "busy",
212 RunOutcome::Skew => "skew",
213 RunOutcome::Withheld => "withheld",
214 RunOutcome::Cancelled => "cancelled",
215 RunOutcome::Slow => "slow",
216 RunOutcome::Deferred => "deferred",
217 }
218 }
219
220 pub fn parse(s: &str) -> Option<RunOutcome> {
224 Some(match s {
225 "pass" => RunOutcome::Passed,
226 "fail" => RunOutcome::Failed,
227 "warn" => RunOutcome::Warned,
228 "fixed" => RunOutcome::Fixed,
229 "unavailable" => RunOutcome::Unavailable,
230 "inert" => RunOutcome::Inert,
231 "cold" => RunOutcome::Cold,
232 "busy" => RunOutcome::Busy,
233 "skew" => RunOutcome::Skew,
234 "withheld" => RunOutcome::Withheld,
235 "cancelled" => RunOutcome::Cancelled,
236 "slow" => RunOutcome::Slow,
237 "deferred" => RunOutcome::Deferred,
238 _ => return None,
239 })
240 }
241
242 pub fn is_verdict(self) -> bool {
246 matches!(self, RunOutcome::Passed | RunOutcome::Failed)
247 }
248}
249
250#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct Run {
258 pub at: u64,
260 pub gate: String,
261 pub outcome: RunOutcome,
262 pub ms: u64,
263}
264
265impl Run {
266 fn render(&self) -> String {
267 format!(
268 "{RUN} {} {} {} {}",
269 self.at,
270 self.gate,
271 self.outcome.as_str(),
272 self.ms
273 )
274 }
275
276 fn parse(line: &str) -> Option<Run> {
279 let mut t = line.split_whitespace();
280 if t.next() != Some(RUN) {
281 return None;
282 }
283 let at = t.next()?.parse().ok()?;
284 let gate = t.next()?.to_string();
285 let outcome = RunOutcome::parse(t.next()?)?;
286 let ms = t.next()?.parse().ok()?;
287 Some(Run {
288 at,
289 gate,
290 outcome,
291 ms,
292 })
293 }
294}
295
296#[derive(Debug, Clone, Default, PartialEq, Eq)]
305pub struct Note {
306 pub tokens: Vec<String>,
307 pub deferred: Vec<String>,
310 pub runs: Vec<Run>,
311 pub provenance: Vec<String>,
313}
314
315const DEFERRED: &str = "deferred";
317
318impl Note {
319 pub fn parse(body: &str) -> Note {
323 let mut lines = body.lines();
324 let Some(first) = lines.next() else {
325 return Note::default();
326 };
327 let mut tokens = first.split_whitespace();
328 if tokens.next() != Some(FORMAT) {
329 return Note::default();
330 }
331 let mut deferred = Vec::new();
332 let mut runs = Vec::new();
333 let mut provenance = Vec::new();
334 for line in lines {
335 if is_provenance(line) {
336 provenance.push(line.trim().to_string());
337 continue;
338 }
339 let mut t = line.split_whitespace();
340 match (t.next(), t.next(), t.next()) {
341 (Some(DEFERRED), Some(gate), None) => {
342 if !deferred.iter().any(|d| d == gate) {
343 deferred.push(gate.to_string());
344 }
345 }
346 _ => runs.extend(Run::parse(line)),
347 }
348 }
349 Note {
350 tokens: tokens.map(str::to_string).collect(),
351 deferred,
352 runs,
353 provenance,
354 }
355 }
356
357 pub fn render(&self) -> String {
360 let mut body = format!("{FORMAT} {}", self.tokens.join(" "));
361 for gate in &self.deferred {
362 body.push('\n');
363 body.push_str(&format!("{DEFERRED} {gate}"));
364 }
365 for run in &self.runs {
366 body.push('\n');
367 body.push_str(&run.render());
368 }
369 for line in &self.provenance {
370 body.push('\n');
371 body.push_str(line);
372 }
373 body
374 }
375
376 fn add_tokens(&mut self, tokens: &[String]) {
377 for t in tokens {
378 if !self.tokens.iter().any(|have| have == t) {
379 self.tokens.push(t.clone());
380 }
381 }
382 }
383
384 fn add_runs(&mut self, runs: &[Run]) {
386 self.runs.extend(runs.iter().cloned());
387 if self.runs.len() > MAX_RUNS {
388 self.runs.drain(..self.runs.len() - MAX_RUNS);
389 }
390 }
391}
392
393pub fn is_provenance(line: &str) -> bool {
396 line.split_whitespace().next() == Some(PROVENANCE)
397}
398
399fn note_at(key: &str) -> Note {
403 note_in(NOTES_REF, key)
404}
405
406fn note_in(notes_ref: &str, key: &str) -> Note {
407 crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
408 .map(|body| Note::parse(&body))
409 .unwrap_or_default()
410}
411
412fn input_tokens(tree: &str) -> Vec<String> {
421 let Some(spec) = crate::attest_inputs::spec_at(tree) else {
422 return canon_tokens(tree);
423 };
424 let mut out: Vec<String> = Vec::new();
425 for (gate, _) in &spec.gates {
426 if !manifest_is_an_input(tree, &spec, gate) {
427 continue;
428 }
429 let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
430 continue;
431 };
432 let Some(key) = crate::attest_inputs::input_key(gate, &fp) else {
433 continue;
434 };
435 for t in note_in(INPUTS_REF, &key).tokens {
436 if crate::gate_identity::base(&t) == gate.as_str() && !out.contains(&t) {
437 out.push(t);
438 }
439 }
440 }
441 out
442}
443
444fn canon_tokens(tree: &str) -> Vec<String> {
451 canon_key_of(tree)
452 .map(|key| note_in(INPUTS_REF, &key).tokens)
453 .unwrap_or_default()
454}
455
456fn canon_key_of(tree: &str) -> Option<String> {
458 let canon = crate::attest_inputs::canonical_route(tree)?;
459 crate::attest_inputs::canon_gate_key(&canon)
460}
461
462fn file_canon(tree: &str, tokens: &[String]) {
466 let Some(key) = canon_key_of(tree) else {
467 return;
468 };
469 let mut note = note_in(INPUTS_REF, &key);
470 note.add_tokens(tokens);
471 let _ = write_note_in(INPUTS_REF, &key, ¬e);
472}
473
474fn file_inputs(tree: &str, tokens: &[String]) {
479 if tokens.is_empty() {
480 return;
481 }
482 let Some(spec) = crate::attest_inputs::spec_at(tree) else {
483 file_canon(tree, tokens);
484 return;
485 };
486 for (gate, _) in &spec.gates {
487 let mine: Vec<String> = tokens
488 .iter()
489 .filter(|t| crate::gate_identity::base(t) == gate.as_str())
490 .cloned()
491 .collect();
492 if mine.is_empty() || !manifest_is_an_input(tree, &spec, gate) {
493 continue;
494 }
495 let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
496 continue;
497 };
498 let Some(key) = crate::attest_inputs::input_key(gate, &fp) else {
499 continue;
500 };
501 let mut note = note_in(INPUTS_REF, &key);
502 note.add_tokens(&mine);
503 let _ = write_note_in(INPUTS_REF, &key, ¬e);
504 }
505}
506
507fn manifest_is_an_input(tree: &str, spec: &crate::attest_inputs::Spec, gate: &str) -> bool {
513 let tracked = [crate::manifest::MANIFEST, crate::names::old::MANIFEST]
515 .into_iter()
516 .find(|name| crate::git::succeeds(&["cat-file", "-e", &format!("{tree}:{name}")]));
517 tracked.map_or(true, |name| {
518 crate::attest_inputs::declares(spec, gate, name)
519 })
520}
521
522fn inputs_ref_exists() -> bool {
526 crate::git::succeeds(&["rev-parse", "-q", "--verify", INPUTS_FULL_REF])
527}
528
529pub fn tree_tokens(tree: &str) -> Vec<String> {
533 let mut tokens = note_at(tree).tokens;
534 if inputs_ref_exists() {
535 for t in input_tokens(tree) {
536 if !tokens.contains(&t) {
537 tokens.push(t);
538 }
539 }
540 }
541 tokens
542}
543
544pub fn stamp_tree(tree: &str, tokens: &[String]) -> bool {
548 let mut note = note_at(tree);
549 note.add_tokens(tokens);
550 let ok = write_note(tree, ¬e);
551 file_inputs(tree, tokens);
552 ok
553}
554
555fn write_note(key: &str, note: &Note) -> bool {
557 write_note_in(NOTES_REF, key, note)
558}
559
560fn write_note_in(notes_ref: &str, key: &str, note: &Note) -> bool {
561 let body = note.render();
562 crate::git::succeeds(&["notes", "--ref", notes_ref, "add", "-f", "-m", &body, key])
563}
564
565pub fn record_runs(key: &str, runs: &[Run]) {
576 let runs: Vec<Run> = runs
581 .iter()
582 .filter(|r| !r.gate.is_empty() && !r.gate.contains(char::is_whitespace))
583 .cloned()
584 .collect();
585 if runs.is_empty() {
586 return;
587 }
588 let mut note = note_at(key);
589 note.add_runs(&runs);
590 let _ = write_note(key, ¬e);
591}
592
593pub fn record_deferred(tree: &str, gates: &[String]) {
597 let gates: Vec<&String> = gates
598 .iter()
599 .filter(|g| !g.is_empty() && !g.contains(char::is_whitespace))
600 .collect();
601 if gates.is_empty() {
602 return;
603 }
604 let mut note = note_at(tree);
605 for g in gates {
606 if !note.deferred.contains(g) {
607 note.deferred.push(g.clone());
608 }
609 }
610 let _ = write_note(tree, ¬e); }
612
613pub fn deferred_on(tree: &str) -> Vec<String> {
616 note_at(tree).deferred
617}
618
619pub fn deferred_for(commits: &[String], gate: &str) -> HashSet<String> {
623 let mut out = HashSet::new();
624 if commits.is_empty() {
625 return out;
626 }
627 let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
628 args.extend(commits.iter().map(String::as_str));
629 let Some(list) = crate::git::stdout(&args) else {
630 return out;
631 };
632 for line in list.lines() {
633 let mut it = line.split_whitespace();
634 let (Some(commit), Some(tree)) = (it.next(), it.next()) else {
635 continue;
636 };
637 if [commit, tree]
638 .iter()
639 .any(|key| note_at(key).deferred.iter().any(|d| d == gate))
640 {
641 out.insert(commit.to_string());
642 }
643 }
644 out
645}
646
647fn marker_path() -> Option<PathBuf> {
651 let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
652 Some(std::path::Path::new(&dir).join(MARKER))
653}
654
655pub fn record(scripts: &[&str]) {
666 let Some(path) = marker_path() else { return };
667 if scripts.is_empty() {
668 let _ = std::fs::remove_file(&path);
669 return;
670 }
671 let Some(tree) = crate::git::stdout(&["write-tree"]) else {
675 crate::hooks::common::warn(
679 "git would not name the staged tree — this commit records no gate stamp",
680 );
681 let _ = std::fs::remove_file(&path);
682 return;
683 };
684 let mut body = format!("{FORMAT}\n{tree}\n");
685 for s in scripts {
686 body.push_str(s);
687 body.push('\n');
688 }
689 let _ = std::fs::write(&path, body);
690}
691
692pub fn vouched_for_staged_tree() -> HashSet<String> {
720 let mut out = HashSet::new();
721 let Some(tree) = crate::git::stdout(&["write-tree"]) else {
722 return out;
723 };
724 if let Some(path) = marker_path() {
725 if let Ok(body) = std::fs::read_to_string(&path) {
726 let mut lines = body.lines();
727 if lines.next() == Some(FORMAT) && lines.next() == Some(tree.as_str()) {
728 out.extend(
729 lines
730 .filter(|l| !l.trim().is_empty() && !is_provenance(l))
731 .map(str::to_string),
732 );
733 }
734 }
735 }
736 out.extend(note_at(&tree).tokens);
745 if inputs_ref_exists() {
751 out.extend(input_tokens(&tree));
752 }
753 out
754}
755
756pub fn bind_to_head() -> Vec<String> {
767 let Some(path) = marker_path() else {
768 return Vec::new();
769 };
770 let Ok(body) = std::fs::read_to_string(&path) else {
771 return Vec::new(); };
773 let _ = std::fs::remove_file(&path);
774 let mut lines = body.lines();
775 if lines.next() != Some(FORMAT) {
776 return Vec::new();
777 }
778 let Some(tree) = lines.next() else {
779 return Vec::new();
780 };
781 let scripts: Vec<&str> = lines
782 .filter(|l| !l.trim().is_empty() && !is_provenance(l))
783 .collect();
784 if scripts.is_empty() {
785 return Vec::new();
786 }
787 let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
788 crate::hooks::common::warn(
789 "git would not name this commit's tree — no gate stamp was written",
790 );
791 return Vec::new();
792 };
793 if head_tree != tree {
796 return Vec::new();
797 }
798 let scripts: Vec<String> = scripts.iter().map(|s| s.to_string()).collect();
799 let mut tree_note = note_at(&head_tree);
824 tree_note.add_tokens(&scripts);
825 let _ = write_note(&head_tree, &tree_note);
826 file_inputs(&head_tree, &scripts);
827 let mut head_note = note_at("HEAD");
828 head_note.add_tokens(&scripts);
829 if !write_note("HEAD", &head_note) {
830 crate::hooks::common::warn(
833 "git refused to write the gate stamp — these checks will run again at push",
834 );
835 return Vec::new();
836 }
837 scripts
840 .iter()
841 .map(|s| crate::gate_identity::base(s).to_string())
842 .collect()
843}
844
845pub fn stamp_push(commit: &str, tree: &str, gates: &[String]) -> bool {
854 if gates.is_empty() {
855 return false;
856 }
857 let mut written = false;
858 for key in [tree, commit] {
859 let mut note = note_at(key);
860 note.add_tokens(gates);
861 let ok = write_note(key, ¬e);
862 if key == commit {
863 written = ok;
864 }
865 }
866 file_inputs(tree, gates);
867 if !written {
868 crate::hooks::common::warn(
869 "git refused to write the push stamp — these gates will run again on the next push",
870 );
871 }
872 written
873}
874
875#[derive(Debug, Clone, Copy, PartialEq, Eq)]
878pub enum Completion {
879 Warned,
881 FailedUnderWarn,
884 Unavailable,
887}
888
889const UNAVAILABLE_FOR_SECS: u64 = 60 * 60;
891
892fn completion_word(how: Completion, token: &str, now: u64) -> String {
894 match how {
895 Completion::Warned => format!("warned:{token}"),
896 Completion::FailedUnderWarn => format!("failed-under-warn:{token}"),
897 Completion::Unavailable => format!("unavailable:{now}:{token}"),
898 }
899}
900
901fn completion_answers(word: &str, token: &str, severity: crate::check::Severity, now: u64) -> bool {
903 if word.strip_prefix("warned:") == Some(token) {
904 return true;
905 }
906 if word.strip_prefix("failed-under-warn:") == Some(token) {
907 return severity == crate::check::Severity::Warn;
908 }
909 word.strip_prefix("unavailable:")
910 .and_then(|rest| rest.split_once(':'))
911 .is_some_and(|(at, tok)| {
912 tok == token
913 && at
914 .parse::<u64>()
915 .is_ok_and(|at| now.saturating_sub(at) <= UNAVAILABLE_FOR_SECS)
916 })
917}
918
919fn now_secs() -> u64 {
920 std::time::SystemTime::now()
921 .duration_since(std::time::UNIX_EPOCH)
922 .map(|d| d.as_secs())
923 .unwrap_or(0)
924}
925
926pub fn record_done(tree: &str, tokens: &[String], how: Completion) -> Result<(), String> {
932 if tokens.is_empty() {
933 return Ok(());
934 }
935 let now = now_secs();
936 let mut note = note_in(DONE_REF, tree);
937 if how == Completion::Unavailable {
938 note.tokens.retain(|word| {
939 !word
940 .strip_prefix("unavailable:")
941 .and_then(|rest| rest.split_once(':'))
942 .is_some_and(|(_, token)| tokens.iter().any(|t| t == token))
943 });
944 }
945 let words: Vec<String> = tokens
946 .iter()
947 .map(|t| completion_word(how, t, now))
948 .collect();
949 note.add_tokens(&words);
950 if write_note_in(DONE_REF, tree, ¬e) {
951 Ok(())
952 } else {
953 Err(format!(
954 "git refused to record the completed gates on {tree}"
955 ))
956 }
957}
958
959pub fn done_on_every(commits: &[String], token: &str, severity: crate::check::Severity) -> bool {
964 let now = now_secs();
965 !commits.is_empty()
966 && commits.iter().all(|c| {
967 crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]).is_some_and(|tree| {
968 note_in(DONE_REF, &tree)
969 .tokens
970 .iter()
971 .any(|word| completion_answers(word, token, severity, now))
972 })
973 })
974}
975
976pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
982 let mut out = HashMap::new();
983 if commits.is_empty() {
984 return out;
985 }
986 let Some(list) = crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]) else {
987 crate::hooks::common::warn(
997 "git would not list the gate stamps — every gated check will run again",
998 );
999 return out;
1000 };
1001 let noted: HashSet<&str> = list
1002 .lines()
1003 .filter_map(|l| l.split_whitespace().nth(1))
1004 .collect();
1005 let mut trees: HashMap<String, String> = HashMap::new();
1009 {
1010 let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
1011 args.extend(commits.iter().map(String::as_str));
1012 if let Some(out) = crate::git::stdout(&args) {
1013 for line in out.lines() {
1014 let mut it = line.split_whitespace();
1015 if let (Some(c), Some(t)) = (it.next(), it.next()) {
1016 trees.insert(c.to_string(), t.to_string());
1017 }
1018 }
1019 }
1020 }
1024
1025 let by_inputs = inputs_ref_exists();
1031
1032 for commit in commits {
1033 let mut tokens: Vec<String> = Vec::new();
1052 let mut keys: Vec<&str> = Vec::new();
1053 if noted.contains(commit.as_str()) {
1054 keys.push(commit);
1055 }
1056 if let Some(tree) = trees.get(commit).filter(|t| noted.contains(t.as_str())) {
1057 keys.push(tree);
1058 }
1059 for key in keys {
1060 for t in note_at(key).tokens {
1061 if !tokens.contains(&t) {
1062 tokens.push(t);
1063 }
1064 }
1065 }
1066 if by_inputs {
1067 if let Some(tree) = trees.get(commit) {
1068 for t in input_tokens(tree) {
1069 if !tokens.contains(&t) {
1070 tokens.push(t);
1071 }
1072 }
1073 }
1074 }
1075 if tokens.is_empty() {
1076 continue;
1077 }
1078 out.insert(commit.clone(), tokens);
1079 }
1080 out
1081}
1082
1083pub fn forget() -> bool {
1088 let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
1089 let notes = crate::git::succeeds(&["update-ref", "-d", NOTES_FULL_REF]);
1090 let inputs = crate::git::succeeds(&["update-ref", "-d", INPUTS_FULL_REF]);
1091 let cluster = crate::git::succeeds(&["update-ref", "-d", CLUSTER_FULL_REF]);
1092 marker || notes || inputs || cluster
1093}
1094
1095pub(crate) fn cluster_tokens(tree: &str) -> Vec<String> {
1098 note_in(CLUSTER_REF, tree).tokens
1099}
1100
1101pub(crate) fn stamp_cluster(tree: &str, token: &str, provenance: &str) -> bool {
1104 let mut note = note_in(CLUSTER_REF, tree);
1105 note.add_tokens(&[token.to_string()]);
1106 let line = format!("{PROVENANCE} {token} {provenance}");
1107 note.provenance
1108 .retain(|l| l.split_whitespace().nth(1) != Some(token));
1109 note.provenance.push(line);
1110 write_note_in(CLUSTER_REF, tree, ¬e)
1111}
1112
1113pub(crate) fn cluster_stamps_for(commits: &[String]) -> HashMap<String, (String, Vec<String>)> {
1117 let mut out = HashMap::new();
1118 for commit in commits {
1119 let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")]) else {
1120 continue;
1121 };
1122 let tokens = cluster_tokens(&tree);
1123 if !tokens.is_empty() {
1124 out.insert(commit.clone(), (tree, tokens));
1125 }
1126 }
1127 out
1128}
1129
1130pub fn forget_in(repo: &std::path::Path) -> bool {
1132 let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
1133 .is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
1134 let notes = crate::git::succeeds_in(repo, &["update-ref", "-d", NOTES_FULL_REF]);
1135 let inputs = crate::git::succeeds_in(repo, &["update-ref", "-d", INPUTS_FULL_REF]);
1136 let cluster = crate::git::succeeds_in(repo, &["update-ref", "-d", CLUSTER_FULL_REF]);
1137 marker || notes || inputs || cluster
1138}
1139
1140#[cfg(test)]
1141mod tests {
1142 use super::*;
1143 use std::path::Path;
1144
1145 #[test]
1149 fn a_completion_answers_only_while_it_should() {
1150 use crate::check::Severity::{Block, Warn};
1151 let now = 1_700_000_000;
1152 let word = |how| completion_word(how, "gate-tok", now);
1153 assert!(completion_answers(
1154 &word(Completion::Warned),
1155 "gate-tok",
1156 Block,
1157 now
1158 ));
1159 assert!(completion_answers(
1160 &word(Completion::FailedUnderWarn),
1161 "gate-tok",
1162 Warn,
1163 now
1164 ));
1165 assert!(!completion_answers(
1166 &word(Completion::FailedUnderWarn),
1167 "gate-tok",
1168 Block,
1169 now
1170 ));
1171 let unavailable = word(Completion::Unavailable);
1172 assert!(completion_answers(
1173 &unavailable,
1174 "gate-tok",
1175 Block,
1176 now + 3600
1177 ));
1178 assert!(!completion_answers(
1179 &unavailable,
1180 "gate-tok",
1181 Block,
1182 now + 3601
1183 ));
1184 assert!(!completion_answers(
1185 &word(Completion::Warned),
1186 "other-tok",
1187 Warn,
1188 now
1189 ));
1190 }
1191
1192 fn repo(name: &str) -> PathBuf {
1195 let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
1196 let _ = std::fs::remove_dir_all(&dir);
1197 std::fs::create_dir_all(&dir).unwrap();
1198 git(&dir, &["init", "-q", "--template=", "."]);
1199 git(&dir, &["config", "user.email", "t@t.test"]);
1200 git(&dir, &["config", "user.name", "t"]);
1201 dir
1202 }
1203
1204 fn git(dir: &Path, args: &[&str]) -> String {
1213 let out = std::process::Command::new("git")
1214 .arg("-C")
1215 .arg(dir)
1216 .args(args)
1217 .output()
1218 .expect("git");
1219 assert!(
1220 out.status.success(),
1221 "fixture: git {args:?} in {} exited {:?}: {}",
1222 dir.display(),
1223 out.status.code(),
1224 String::from_utf8_lossy(&out.stderr).trim()
1225 );
1226 String::from_utf8_lossy(&out.stdout).trim().to_string()
1227 }
1228
1229 fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
1233 let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
1234 let prev = std::env::current_dir().unwrap();
1235 std::env::set_current_dir(dir).unwrap();
1236 let r = f();
1237 std::env::set_current_dir(prev).unwrap();
1238 r
1239 }
1240
1241 #[test]
1242 fn the_commit_note_does_not_hide_the_tree_notes_push_tokens() {
1243 let dir = repo("union");
1244 std::fs::write(dir.join("a.ts"), "x").unwrap();
1245 git(&dir, &["add", "a.ts"]);
1246 in_repo(&dir, || {
1247 record(&["test"]);
1248 git(&dir, &["commit", "-qm", "chore: a"]);
1249 bind_to_head();
1250 let head = git(&dir, &["rev-parse", "HEAD"]);
1251 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1252 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1255 assert_eq!(note_at(&head).tokens, vec!["test".to_string()]);
1256 let stamps = stamps_for(std::slice::from_ref(&head));
1257 assert_eq!(
1258 stamps.get(&head).map(Vec::as_slice),
1259 Some(&["test".to_string(), "pre-push-cargo-test".to_string()][..]),
1260 "both notes speak for the same tree"
1261 );
1262 });
1263 let _ = std::fs::remove_dir_all(&dir);
1264 }
1265
1266 #[test]
1270 fn an_unavailable_record_replaces_its_predecessor_only() {
1271 let dir = repo("done-unavailable");
1272 std::fs::write(dir.join("a.ts"), "x").unwrap();
1273 git(&dir, &["add", "a.ts"]);
1274 git(&dir, &["commit", "-qm", "chore: a"]);
1275 in_repo(&dir, || {
1276 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1277 let one = |t: &str| vec![t.to_string()];
1278 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("first");
1279 record_done(&tree, &one("lint@b"), Completion::Unavailable).expect("other gate");
1280 record_done(&tree, &one("lint@b"), Completion::Warned).expect("a warning");
1281 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("again");
1282 let words = note_in(DONE_REF, &tree).tokens;
1283 let unavailable_for = |token: &str| {
1284 words
1285 .iter()
1286 .filter(|w| w.starts_with("unavailable:") && w.ends_with(&format!(":{token}")))
1287 .count()
1288 };
1289 assert_eq!(unavailable_for("suite@a"), 1, "{words:?}");
1290 assert_eq!(unavailable_for("lint@b"), 1, "{words:?}");
1291 assert!(words.contains(&"warned:lint@b".to_string()), "{words:?}");
1292 });
1293 let _ = std::fs::remove_dir_all(&dir); }
1295
1296 #[test]
1297 fn a_commit_with_only_a_tree_note_still_reads_the_tree_tokens() {
1298 let dir = repo("tree-only");
1299 std::fs::write(dir.join("a.ts"), "x").unwrap();
1300 git(&dir, &["add", "a.ts"]);
1301 git(&dir, &["commit", "-qm", "chore: a"]);
1302 in_repo(&dir, || {
1303 let head = git(&dir, &["rev-parse", "HEAD"]);
1304 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1305 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1306 let stamps = stamps_for(std::slice::from_ref(&head));
1307 assert_eq!(
1308 stamps.get(&head).map(Vec::as_slice),
1309 Some(&["pre-push-cargo-test".to_string()][..])
1310 );
1311 });
1312 let _ = std::fs::remove_dir_all(&dir);
1313 }
1314
1315 #[test]
1316 fn a_commit_with_only_a_commit_note_still_reads_its_tokens() {
1317 let dir = repo("commit-only");
1318 std::fs::write(dir.join("a.ts"), "x").unwrap();
1319 git(&dir, &["add", "a.ts"]);
1320 git(&dir, &["commit", "-qm", "chore: a"]);
1321 in_repo(&dir, || {
1322 let head = git(&dir, &["rev-parse", "HEAD"]);
1323 let mut note = Note::default();
1324 note.add_tokens(&["typecheck".to_string()]);
1325 assert!(write_note(&head, ¬e));
1326 let stamps = stamps_for(std::slice::from_ref(&head));
1327 assert_eq!(
1328 stamps.get(&head).map(Vec::as_slice),
1329 Some(&["typecheck".to_string()][..])
1330 );
1331 });
1332 let _ = std::fs::remove_dir_all(&dir);
1333 }
1334
1335 #[test]
1336 fn a_token_on_both_notes_is_read_once() {
1337 let dir = repo("dedup");
1338 std::fs::write(dir.join("a.ts"), "x").unwrap();
1339 git(&dir, &["add", "a.ts"]);
1340 in_repo(&dir, || {
1341 record(&["test"]);
1342 git(&dir, &["commit", "-qm", "chore: a"]);
1343 bind_to_head(); let head = git(&dir, &["rev-parse", "HEAD"]);
1345 let stamps = stamps_for(std::slice::from_ref(&head));
1346 assert_eq!(
1347 stamps.get(&head).map(Vec::as_slice),
1348 Some(&["test".to_string()][..])
1349 );
1350 });
1351 let _ = std::fs::remove_dir_all(&dir);
1352 }
1353
1354 #[test]
1355 fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
1356 let dir = repo("roundtrip");
1357 std::fs::write(dir.join("a.ts"), "x").unwrap();
1358 git(&dir, &["add", "a.ts"]);
1359 in_repo(&dir, || {
1360 record(&["typecheck", "test"]);
1361 git(&dir, &["commit", "-qm", "chore: a"]);
1362 let stamped = bind_to_head();
1363 assert_eq!(
1364 stamped,
1365 vec!["typecheck".to_string(), "test".to_string()],
1366 "bind_to_head reports the scripts it stamped"
1367 );
1368 let head = git(&dir, &["rev-parse", "HEAD"]);
1369 let stamps = stamps_for(std::slice::from_ref(&head));
1370 assert_eq!(
1371 stamps.get(&head).map(Vec::as_slice),
1372 Some(&["typecheck".to_string(), "test".to_string()][..])
1373 );
1374 assert!(!dir.join(".git").join(MARKER).exists());
1381 });
1382 let _ = std::fs::remove_dir_all(&dir);
1383 }
1384
1385 #[test]
1386 fn a_marker_for_a_different_tree_stamps_nothing() {
1387 let dir = repo("stale");
1388 std::fs::write(dir.join("a.ts"), "x").unwrap();
1389 git(&dir, &["add", "a.ts"]);
1390 in_repo(&dir, || {
1391 record(&["typecheck"]);
1392 std::fs::write(dir.join("a.ts"), "y").unwrap();
1395 git(&dir, &["add", "a.ts"]);
1396 git(&dir, &["commit", "-qm", "chore: different"]);
1397 assert!(
1398 bind_to_head().is_empty(),
1399 "bind_to_head reports nothing when the tree moved"
1400 );
1401 let head = git(&dir, &["rev-parse", "HEAD"]);
1402 assert!(
1403 stamps_for(&[head]).is_empty(),
1404 "a stale marker must not vouch"
1405 );
1406 assert!(
1407 !dir.join(".git").join(MARKER).exists(),
1408 "consumed either way"
1409 );
1410 });
1411 let _ = std::fs::remove_dir_all(&dir);
1412 }
1413
1414 #[test]
1415 fn an_empty_record_clears_a_previous_marker() {
1416 let dir = repo("clears");
1417 std::fs::write(dir.join("a.ts"), "x").unwrap();
1418 git(&dir, &["add", "a.ts"]);
1419 in_repo(&dir, || {
1420 record(&["typecheck"]);
1421 assert!(dir.join(".git").join(MARKER).exists());
1422 record(&[]);
1423 assert!(!dir.join(".git").join(MARKER).exists());
1424 });
1425 let _ = std::fs::remove_dir_all(&dir);
1426 }
1427
1428 #[test]
1433 fn a_marker_in_an_unknown_format_stamps_nothing() {
1434 let dir = repo("wrongformat");
1435 std::fs::write(dir.join("a.ts"), "x").unwrap();
1436 git(&dir, &["add", "a.ts"]);
1437 in_repo(&dir, || {
1438 let tree = git(&dir, &["write-tree"]);
1439 let marker = dir.join(".git").join(MARKER);
1440 std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
1441 git(&dir, &["commit", "-qm", "chore: a"]);
1442 bind_to_head();
1443 let head = git(&dir, &["rev-parse", "HEAD"]);
1444 assert!(
1445 stamps_for(std::slice::from_ref(&head)).is_empty(),
1446 "an unknown format was trusted"
1447 );
1448 assert!(!marker.exists(), "consumed either way");
1449 });
1450 let _ = std::fs::remove_dir_all(&dir);
1451 }
1452
1453 #[test]
1457 fn a_foreign_note_is_not_a_stamp() {
1458 let dir = repo("foreignnote");
1459 std::fs::write(dir.join("a.ts"), "x").unwrap();
1460 git(&dir, &["add", "a.ts"]);
1461 in_repo(&dir, || {
1462 git(&dir, &["commit", "-qm", "chore: a"]);
1463 git(
1464 &dir,
1465 &[
1466 "notes",
1467 "--ref",
1468 NOTES_REF,
1469 "add",
1470 "-m",
1471 "typecheck test",
1472 "HEAD",
1473 ],
1474 );
1475 let head = git(&dir, &["rev-parse", "HEAD"]);
1476 assert!(
1477 stamps_for(std::slice::from_ref(&head)).is_empty(),
1478 "a note without the format token was trusted"
1479 );
1480 });
1481 let _ = std::fs::remove_dir_all(&dir);
1482 }
1483
1484 #[test]
1488 fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
1489 let dir = repo("no-stamps");
1490 std::fs::write(dir.join("a.ts"), "x").unwrap();
1491 git(&dir, &["add", "a.ts"]);
1492 git(&dir, &["commit", "-qm", "chore: a"]);
1493 in_repo(&dir, || {
1494 assert_eq!(
1495 crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
1496 Some(""),
1497 "an absent notes ref must be an ANSWER, not a failure — the \
1498 no-stamps path and the git-is-broken path are told apart by it"
1499 );
1500 let head = git(&dir, &["rev-parse", "HEAD"]);
1501 assert!(stamps_for(&[head]).is_empty());
1502 });
1503 let _ = std::fs::remove_dir_all(&dir);
1504 }
1505
1506 #[test]
1513 fn a_note_from_before_the_run_lines_parses_unchanged() {
1514 let note = Note::parse("amont-gate-v1 typecheck test");
1515 assert_eq!(note.tokens, vec!["typecheck", "test"]);
1516 assert!(note.runs.is_empty());
1517 assert_eq!(note.render(), "amont-gate-v1 typecheck test");
1520 }
1521
1522 #[test]
1524 fn run_lines_are_read_without_disturbing_the_tokens() {
1525 let body = "amont-gate-v1 pre-push-cargo-test\n\
1526 run 1726900000 pre-push-cargo-test pass 412391\n\
1527 run 1726903600 pre-push-audit-js fail 903\n";
1528 let note = Note::parse(body);
1529 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1530 assert_eq!(note.runs.len(), 2);
1531 assert_eq!(
1532 note.runs[0],
1533 Run {
1534 at: 1_726_900_000,
1535 gate: "pre-push-cargo-test".into(),
1536 outcome: RunOutcome::Passed,
1537 ms: 412_391,
1538 }
1539 );
1540 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1541 assert_eq!(note.render(), body.trim_end());
1542 }
1543
1544 #[test]
1548 fn an_unreadable_run_line_is_dropped_and_the_rest_survives() {
1549 let note = Note::parse(
1550 "amont-gate-v1 test\n\
1551 run 1726900000 pre-push-cargo-test pass 400\n\
1552 run tomorrow pre-push-cargo-test pass 400\n\
1553 run 1726900001 pre-push-cargo-test sideways 400\n\
1554 banana\n\
1555 run 1726900002 pre-push-cargo-test fail 500\n",
1556 );
1557 assert_eq!(note.tokens, vec!["test"]);
1558 assert_eq!(note.runs.len(), 2, "{:?}", note.runs);
1559 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1560 }
1561
1562 #[test]
1566 fn a_deferral_is_never_a_token_and_outlives_the_run_trim() {
1567 let mut note = Note::parse("amont-gate-v1 lint\ndeferred cargo-test\n");
1568 assert_eq!(note.tokens, vec!["lint"]);
1569 assert_eq!(note.deferred, vec!["cargo-test"]);
1570 let runs: Vec<Run> = (0..MAX_RUNS as u64 + 10)
1571 .map(|i| Run {
1572 at: 1_726_900_000 + i,
1573 gate: "pre-push-audit-js".into(),
1574 outcome: RunOutcome::Passed,
1575 ms: 1,
1576 })
1577 .collect();
1578 note.add_runs(&runs);
1579 let again = Note::parse(¬e.render());
1580 assert_eq!(again.runs.len(), MAX_RUNS);
1581 assert_eq!(again.deferred, vec!["cargo-test"]);
1582 assert_eq!(again.tokens, vec!["lint"]);
1583 }
1584
1585 #[test]
1588 fn a_foreign_note_yields_no_runs() {
1589 let note = Note::parse("hello\nrun 1726900000 pre-push-cargo-test pass 400\n");
1590 assert!(note.tokens.is_empty() && note.runs.is_empty());
1591 }
1592
1593 #[test]
1598 fn a_stamp_and_its_evidence_survive_each_other() {
1599 let dir = repo("evidence");
1600 std::fs::write(dir.join("a.ts"), "x").unwrap();
1601 git(&dir, &["add", "a.ts"]);
1602 in_repo(&dir, || {
1603 git(&dir, &["commit", "-qm", "chore: a"]);
1604 let head = git(&dir, &["rev-parse", "HEAD"]);
1605 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1606 record_runs(
1607 &tree,
1608 &[Run {
1609 at: 1_726_900_000,
1610 gate: "pre-push-cargo-test".into(),
1611 outcome: RunOutcome::Failed,
1612 ms: 412_391,
1613 }],
1614 );
1615 assert!(stamp_push(&head, &tree, &["pre-push-cargo-test".into()]));
1617 let note = note_at(&tree);
1618 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1619 assert_eq!(note.runs.len(), 1, "the evidence survived the stamp");
1620 let stamps = stamps_for(std::slice::from_ref(&head));
1622 assert_eq!(
1623 stamps.get(&head).map(Vec::as_slice),
1624 Some(&["pre-push-cargo-test".to_string()][..])
1625 );
1626 });
1627 let _ = std::fs::remove_dir_all(&dir);
1628 }
1629
1630 #[test]
1634 fn a_recorded_run_is_not_a_stamp() {
1635 let dir = repo("not-a-stamp");
1636 std::fs::write(dir.join("a.ts"), "x").unwrap();
1637 git(&dir, &["add", "a.ts"]);
1638 in_repo(&dir, || {
1639 git(&dir, &["commit", "-qm", "chore: a"]);
1640 let head = git(&dir, &["rev-parse", "HEAD"]);
1641 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1642 record_runs(
1643 &tree,
1644 &[Run {
1645 at: 1_726_900_000,
1646 gate: "pre-push-cargo-test".into(),
1647 outcome: RunOutcome::Passed,
1648 ms: 412_391,
1649 }],
1650 );
1651 assert!(
1652 stamps_for(std::slice::from_ref(&head)).is_empty(),
1653 "a run line vouched for a gate — evidence must never gate"
1654 );
1655 assert!(
1656 !vouched_for_staged_tree().contains("pre-push-cargo-test"),
1657 "a run line vouched at commit time"
1658 );
1659 let history = crate::gate_evidence::history_in(&dir);
1661 assert_eq!(history.runs.len(), 1);
1662 assert_eq!(history.runs[0].0, tree, "keyed by the content it ran on");
1663 });
1664 let _ = std::fs::remove_dir_all(&dir);
1665 }
1666
1667 #[test]
1668 fn forget_removes_the_stamps() {
1669 let dir = repo("forget");
1670 std::fs::write(dir.join("a.ts"), "x").unwrap();
1671 git(&dir, &["add", "a.ts"]);
1672 in_repo(&dir, || {
1673 record(&["typecheck"]);
1674 git(&dir, &["commit", "-qm", "chore: a"]);
1675 bind_to_head();
1676 let head = git(&dir, &["rev-parse", "HEAD"]);
1677 assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
1678 forget();
1679 assert!(stamps_for(&[head]).is_empty());
1680 });
1681 let _ = std::fs::remove_dir_all(&dir);
1682 }
1683
1684 #[test]
1698 fn a_stamp_survives_a_commit_being_rewritten_with_the_same_tree() {
1699 let dir = repo("squashed");
1700 std::fs::write(dir.join("a.ts"), "x").unwrap();
1701 git(&dir, &["add", "a.ts"]);
1702 in_repo(&dir, || {
1703 record(&["test"]);
1704 git(&dir, &["commit", "-qm", "feat: on a branch"]);
1705 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1706 let branch_tip = git(&dir, &["rev-parse", "HEAD"]);
1707
1708 git(
1712 &dir,
1713 &[
1714 "commit",
1715 "-q",
1716 "--amend",
1717 "-m",
1718 "feat: squashed by the forge",
1719 ],
1720 );
1721 let merged = git(&dir, &["rev-parse", "HEAD"]);
1722 assert_ne!(merged, branch_tip, "the fixture must produce a new commit");
1723 assert_eq!(
1724 git(&dir, &["rev-parse", "HEAD^{tree}"]),
1725 git(&dir, &["rev-parse", &format!("{branch_tip}^{{tree}}")]),
1726 "…carrying the same tree, which is the whole premise"
1727 );
1728
1729 let stamps = stamps_for(std::slice::from_ref(&merged));
1730 assert_eq!(
1731 stamps.get(&merged).map(Vec::as_slice),
1732 Some(&["test".to_string()][..]),
1733 "the stamp must follow the content, not the commit hash"
1734 );
1735 });
1736 let _ = std::fs::remove_dir_all(&dir);
1737 }
1738
1739 #[test]
1743 fn a_different_tree_gets_no_stamp_from_the_fallback() {
1744 let dir = repo("othertree");
1745 std::fs::write(dir.join("a.ts"), "x").unwrap();
1746 git(&dir, &["add", "a.ts"]);
1747 in_repo(&dir, || {
1748 record(&["test"]);
1749 git(&dir, &["commit", "-qm", "chore: stamped"]);
1750 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1751
1752 std::fs::write(dir.join("b.ts"), "y").unwrap();
1755 git(&dir, &["add", "b.ts"]);
1756 git(&dir, &["commit", "-qm", "chore: unjudged"]);
1757 let unstamped = git(&dir, &["rev-parse", "HEAD"]);
1758
1759 assert!(
1760 stamps_for(std::slice::from_ref(&unstamped)).is_empty(),
1761 "a tree nobody stamped must not inherit one"
1762 );
1763 });
1764 let _ = std::fs::remove_dir_all(&dir);
1765 }
1766
1767 fn declared(name: &str, spec: &str) -> PathBuf {
1773 let dir = repo(name);
1774 std::fs::create_dir_all(dir.join(".github")).unwrap();
1775 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
1776 std::fs::write(dir.join("a.ts"), "x").unwrap();
1777 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
1778 std::fs::write(dir.join(".github/attest-inputs"), spec).unwrap();
1779 git(&dir, &["add", "-A"]);
1780 in_repo(&dir, || {
1781 record(&["test@abc"]);
1782 git(&dir, &["commit", "-qm", "feat: judged"]);
1783 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1784 });
1785 dir
1786 }
1787
1788 fn plan_only_commit(dir: &Path) -> String {
1791 std::fs::write(dir.join("docs/plans/p.md"), "plan v2, closing").unwrap();
1792 git(dir, &["add", "docs/plans/p.md"]);
1793 git(dir, &["commit", "-qm", "docs(plan): done"]);
1794 git(dir, &["rev-parse", "HEAD"])
1795 }
1796
1797 #[test]
1798 fn a_plan_only_commit_reuses_the_stamp_of_a_declared_gate() {
1799 let dir = declared("plan-only", "test a.ts\n");
1800 in_repo(&dir, || {
1801 let head = plan_only_commit(&dir);
1802 let stamps = stamps_for(std::slice::from_ref(&head));
1803 assert_eq!(
1804 stamps.get(&head).map(Vec::as_slice),
1805 Some(&["test@abc".to_string()][..]),
1806 "the closing commit changed the tree and none of the declared inputs"
1807 );
1808 });
1809 let _ = std::fs::remove_dir_all(&dir);
1810 }
1811
1812 #[test]
1813 fn the_staged_tree_of_a_plan_only_commit_is_vouched_for() {
1814 let dir = declared("staged", "test a.ts\n");
1815 in_repo(&dir, || {
1816 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1817 git(&dir, &["add", "docs/plans/p.md"]);
1818 assert!(vouched_for_staged_tree().contains("test@abc"));
1819 });
1820 let _ = std::fs::remove_dir_all(&dir);
1821 }
1822
1823 #[test]
1824 fn partial_staging_is_judged_on_the_index_not_the_working_copy() {
1825 let dir = declared("partial", "test a.ts\n");
1826 in_repo(&dir, || {
1827 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1830 git(&dir, &["add", "docs/plans/p.md"]);
1831 std::fs::write(dir.join("a.ts"), "unstaged edit").unwrap();
1832 assert!(vouched_for_staged_tree().contains("test@abc"));
1833
1834 std::fs::write(dir.join("a.ts"), "staged edit").unwrap();
1837 git(&dir, &["add", "a.ts"]);
1838 std::fs::write(dir.join("a.ts"), "x").unwrap();
1839 assert!(!vouched_for_staged_tree().contains("test@abc"));
1840 });
1841 let _ = std::fs::remove_dir_all(&dir);
1842 }
1843
1844 #[test]
1845 fn a_changed_declared_input_misses() {
1846 let dir = declared("input-changed", "test a.ts\n");
1847 in_repo(&dir, || {
1848 std::fs::write(dir.join("a.ts"), "changed").unwrap();
1849 git(&dir, &["add", "a.ts"]);
1850 git(&dir, &["commit", "-qm", "feat: unjudged"]);
1851 let head = git(&dir, &["rev-parse", "HEAD"]);
1852 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1853 });
1854 let _ = std::fs::remove_dir_all(&dir);
1855 }
1856
1857 #[test]
1858 fn a_changed_declaration_misses() {
1859 let dir = declared("declaration-changed", "test a.ts\n");
1860 in_repo(&dir, || {
1861 std::fs::write(dir.join("b.ts"), "y").unwrap();
1864 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts b.ts\n").unwrap();
1865 git(&dir, &["add", "-A"]);
1866 git(&dir, &["commit", "-qm", "chore: widen the declaration"]);
1867 let head = git(&dir, &["rev-parse", "HEAD"]);
1868 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1869 });
1870 let _ = std::fs::remove_dir_all(&dir);
1871 }
1872
1873 #[test]
1874 fn a_declared_config_file_is_an_input_like_any_other() {
1875 let dir = declared("config", "test a.ts amont.conf\n");
1878 in_repo(&dir, || {
1879 assert!(!inputs_ref_exists());
1882
1883 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
1884 git(&dir, &["add", "amont.conf"]);
1885 record(&["test@abc"]);
1886 git(&dir, &["commit", "-qm", "chore: config"]);
1887 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1888
1889 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1890 git(&dir, &["add", "docs/plans/p.md"]);
1891 git(&dir, &["commit", "-qm", "docs(plan): done"]);
1892 let plan = git(&dir, &["rev-parse", "HEAD"]);
1893 assert!(stamps_for(std::slice::from_ref(&plan)).contains_key(&plan));
1894
1895 std::fs::write(dir.join("amont.conf"), "scope = lib\n").unwrap();
1896 git(&dir, &["add", "amont.conf"]);
1897 git(&dir, &["commit", "-qm", "chore: scope-only change"]);
1898 let scope = git(&dir, &["rev-parse", "HEAD"]);
1899 assert!(
1900 stamps_for(std::slice::from_ref(&scope)).is_empty(),
1901 "a scope-only change must miss"
1902 );
1903 });
1904 let _ = std::fs::remove_dir_all(&dir);
1905 }
1906
1907 #[test]
1908 fn a_declared_stamp_is_read_back_as_its_complete_token() {
1909 let dir = declared("identity", "test a.ts\n");
1915 in_repo(&dir, || {
1916 let head = plan_only_commit(&dir);
1917 let tokens = stamps_for(std::slice::from_ref(&head))
1918 .remove(&head)
1919 .unwrap_or_default();
1920 assert_eq!(tokens, vec!["test@abc".to_string()]);
1921
1922 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1923 assert!(stamp_tree(&tree, &["test@def".to_string()]));
1924 let tokens = tree_tokens(&tree);
1925 assert!(tokens.contains(&"test@abc".to_string()));
1926 assert!(tokens.contains(&"test@def".to_string()));
1927 assert!(!tokens.contains(&"test@zzz".to_string()));
1928 assert!(!tokens.contains(&"test".to_string()));
1929 });
1930 let _ = std::fs::remove_dir_all(&dir);
1931 }
1932
1933 #[test]
1934 fn a_gate_that_does_not_declare_the_manifest_is_not_offered_the_route() {
1935 let dir = repo("manifest-undeclared");
1939 std::fs::create_dir_all(dir.join(".github")).unwrap();
1940 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
1941 std::fs::write(dir.join("a.ts"), "x").unwrap();
1942 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
1943 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
1944 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
1945 git(&dir, &["add", "-A"]);
1946 in_repo(&dir, || {
1947 record(&["test@abc"]);
1948 git(&dir, &["commit", "-qm", "feat: judged"]);
1949 bind_to_head();
1950 assert!(!inputs_ref_exists(), "the route must not open");
1951 let head = plan_only_commit(&dir);
1952 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1953 });
1954 let _ = std::fs::remove_dir_all(&dir);
1955 }
1956
1957 #[test]
1958 fn a_gate_declaring_the_manifest_opens_the_route() {
1959 let dir = declared("manifest-declared", "test a.ts amont.conf\n");
1962 in_repo(&dir, || {
1963 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
1964 git(&dir, &["add", "amont.conf"]);
1965 record(&["test@abc"]);
1966 git(&dir, &["commit", "-qm", "chore: config"]);
1967 bind_to_head();
1968 assert!(inputs_ref_exists());
1969 });
1970 let _ = std::fs::remove_dir_all(&dir);
1971 }
1972
1973 #[test]
1974 fn an_undeclared_gate_keeps_whole_tree_behaviour() {
1975 let dir = declared("undeclared", "test a.ts\n");
1976 in_repo(&dir, || {
1977 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1980 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
1981 let head = plan_only_commit(&dir);
1982 let tokens = stamps_for(std::slice::from_ref(&head))
1983 .remove(&head)
1984 .unwrap_or_default();
1985 assert!(tokens.contains(&"test@abc".to_string()));
1986 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
1987 });
1988 let _ = std::fs::remove_dir_all(&dir);
1989 }
1990
1991 #[test]
1992 fn an_invalid_or_ambiguous_spec_falls_back_to_whole_tree_behaviour() {
1993 let dir = declared("invalid", "test src/*\n");
1995 in_repo(&dir, || {
1996 assert!(!inputs_ref_exists(), "no valid spec, nothing is filed");
1997 let head = plan_only_commit(&dir);
1998 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1999 });
2000 let _ = std::fs::remove_dir_all(&dir);
2001
2002 let dir = repo("ambiguous");
2004 std::fs::create_dir_all(dir.join(".github")).unwrap();
2005 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2006 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2007 std::fs::write(dir.join("a.ts"), "x").unwrap();
2008 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2009 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2010 std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
2011 git(&dir, &["add", "-A"]);
2012 in_repo(&dir, || {
2013 record(&["test@abc"]);
2014 git(&dir, &["commit", "-qm", "feat: judged"]);
2015 bind_to_head();
2016 assert!(!inputs_ref_exists());
2017 let head = plan_only_commit(&dir);
2018 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2019 });
2020 let _ = std::fs::remove_dir_all(&dir);
2021 }
2022
2023 #[test]
2024 fn a_gate_that_did_not_pass_leaves_no_declared_input_stamp() {
2025 let dir = repo("failed");
2026 std::fs::create_dir_all(dir.join(".github")).unwrap();
2027 std::fs::write(dir.join("a.ts"), "x").unwrap();
2028 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2029 git(&dir, &["add", "-A"]);
2030 in_repo(&dir, || {
2031 record(&[]);
2033 git(&dir, &["commit", "-qm", "feat: unjudged"]);
2034 assert!(bind_to_head().is_empty());
2035 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2036 let head = git(&dir, &["rev-parse", "HEAD"]);
2037 assert!(!stamp_push(&head, &tree, &[]));
2038 assert!(!inputs_ref_exists());
2039 });
2040 let _ = std::fs::remove_dir_all(&dir);
2041 }
2042
2043 #[test]
2044 fn stamp_tree_and_tree_tokens_use_the_inputs_ref() {
2045 let dir = declared("rehearsal", "test a.ts\n");
2046 in_repo(&dir, || {
2047 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2049 assert!(stamp_tree(&tree, &["test@rehearsed".to_string()]));
2050 plan_only_commit(&dir);
2052 let later = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2053 assert_ne!(later, tree);
2054 assert!(tree_tokens(&later).contains(&"test@rehearsed".to_string()));
2055 });
2056 let _ = std::fs::remove_dir_all(&dir);
2057 }
2058
2059 #[test]
2060 fn the_inputs_ref_is_keyed_the_way_attest_keys_its_own() {
2061 let dir = declared("key", "test a.ts\n");
2062 in_repo(&dir, || {
2063 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2064 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2065 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2066 let key = crate::attest_inputs::input_key("test", &fp).expect("key");
2067 let listed = git(&dir, &["notes", "--ref", INPUTS_REF, "list"]);
2068 assert!(
2069 listed
2070 .lines()
2071 .any(|l| l.split_whitespace().nth(1) == Some(key.as_str())),
2072 "{listed}"
2073 );
2074 });
2075 let _ = std::fs::remove_dir_all(&dir);
2076 }
2077
2078 #[test]
2079 fn a_foreign_token_in_the_inputs_ref_vouches_for_nothing() {
2080 let dir = declared("foreign", "test a.ts\n");
2081 in_repo(&dir, || {
2082 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2083 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2084 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2085 let key = crate::attest_inputs::input_key("test", &fp).expect("key");
2086 let mut note = note_in(INPUTS_REF, &key);
2088 note.add_tokens(&["publish@evil".to_string()]);
2089 assert!(write_note_in(INPUTS_REF, &key, ¬e));
2090 assert!(!tree_tokens(&tree).contains(&"publish@evil".to_string()));
2091 });
2092 let _ = std::fs::remove_dir_all(&dir);
2093 }
2094
2095 #[test]
2096 fn forget_removes_the_inputs_ref_too() {
2097 let dir = declared("forget-inputs", "test a.ts\n");
2098 in_repo(&dir, || {
2099 assert!(inputs_ref_exists());
2100 assert!(forget());
2101 assert!(!inputs_ref_exists());
2102 });
2103 let _ = std::fs::remove_dir_all(&dir);
2104 }
2105
2106 fn canonical(name: &str, conf: Option<&str>) -> PathBuf {
2109 let dir = repo(name);
2110 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2111 std::fs::write(dir.join("a.ts"), "x").unwrap();
2112 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
2113 if let Some(conf) = conf {
2114 std::fs::write(dir.join("amont.conf"), conf).unwrap();
2115 }
2116 git(&dir, &["add", "-A"]);
2117 in_repo(&dir, || {
2118 record(&["test@abc"]);
2119 git(&dir, &["commit", "-qm", "feat: judged"]);
2120 assert_eq!(bind_to_head(), vec!["test".to_string()]);
2121 });
2122 dir
2123 }
2124
2125 fn vouched(dir: &Path, commit: &str) -> Vec<String> {
2126 in_repo(dir, || {
2127 stamps_for(std::slice::from_ref(&commit.to_string()))
2128 .remove(commit)
2129 .unwrap_or_default()
2130 })
2131 }
2132
2133 #[test]
2134 fn with_no_spec_a_plans_only_commit_is_vouched_for_canonically() {
2135 let dir = canonical("canon-plan-edit", None);
2136 in_repo(&dir, || {
2137 assert!(inputs_ref_exists(), "the canonical stamp is filed");
2138 let head = plan_only_commit(&dir);
2139 assert_eq!(
2140 stamps_for(std::slice::from_ref(&head))
2141 .remove(&head)
2142 .unwrap_or_default(),
2143 vec!["test@abc".to_string()]
2144 );
2145 std::fs::write(dir.join("docs/plans/p.md"), "plan v3").unwrap();
2147 git(&dir, &["add", "docs/plans/p.md"]);
2148 assert!(vouched_for_staged_tree().contains("test@abc"));
2149 });
2150 let _ = std::fs::remove_dir_all(&dir);
2151 }
2152
2153 #[test]
2154 fn a_plan_added_deleted_or_renamed_is_not_vouched_for() {
2155 let dir = canonical("canon-plan-exists", None);
2156 std::fs::write(dir.join("docs/plans/q.md"), "second plan").unwrap();
2157 git(&dir, &["add", "docs/plans/q.md"]);
2158 git(&dir, &["commit", "-qm", "docs(plan): add"]);
2159 let added = git(&dir, &["rev-parse", "HEAD"]);
2160 assert!(vouched(&dir, &added).is_empty(), "a plan added");
2161 git(&dir, &["mv", "docs/plans/p.md", "docs/plans/r.md"]);
2162 git(&dir, &["commit", "-qm", "docs(plan): rename"]);
2163 let renamed = git(&dir, &["rev-parse", "HEAD"]);
2164 assert!(vouched(&dir, &renamed).is_empty(), "a plan renamed");
2165 let _ = std::fs::remove_dir_all(&dir);
2166 }
2167
2168 #[test]
2169 fn with_no_spec_any_other_change_is_not_vouched_for() {
2170 let dir = canonical("canon-code-edit", Some("gate test = make test\n"));
2171 std::fs::write(dir.join("a.ts"), "changed").unwrap();
2172 git(&dir, &["commit", "-qam", "feat: code"]);
2173 let code = git(&dir, &["rev-parse", "HEAD"]);
2174 assert!(vouched(&dir, &code).is_empty(), "a source edit");
2175 std::fs::write(dir.join("amont.conf"), "gate test = make other\n").unwrap();
2177 git(&dir, &["commit", "-qam", "chore: config"]);
2178 let conf = git(&dir, &["rev-parse", "HEAD"]);
2179 assert!(vouched(&dir, &conf).is_empty(), "a manifest edit");
2180 let _ = std::fs::remove_dir_all(&dir);
2181 }
2182
2183 #[test]
2184 fn plan_exempt_off_closes_the_canonical_route() {
2185 for (name, conf) in [
2186 ("off", "set planExempt off\n"),
2187 ("spelled", "SET PLANEXEMPT\tOff\r\n"),
2188 ("after", "set planExempt on\nset planExempt off\n"),
2189 ] {
2190 let dir = canonical(&format!("canon-off-{name}"), Some(conf));
2191 in_repo(&dir, || {
2192 assert!(!inputs_ref_exists(), "{name}: nothing is filed");
2193 let head = plan_only_commit(&dir);
2194 assert!(
2195 stamps_for(std::slice::from_ref(&head)).is_empty(),
2196 "{name}: a plans-only commit is a new tree"
2197 );
2198 });
2199 let _ = std::fs::remove_dir_all(&dir);
2200 }
2201 for (name, conf) in [
2203 ("on", "set planExempt on\n"),
2204 ("comment", "set planExempt off # no\n"),
2205 ("commented", "# set planExempt off\n"),
2206 ] {
2207 let dir = canonical(&format!("canon-on-{name}"), Some(conf));
2208 let head = plan_only_commit(&dir);
2209 assert!(!vouched(&dir, &head).is_empty(), "{name}: still canonical");
2210 let _ = std::fs::remove_dir_all(&dir);
2211 }
2212 }
2213
2214 #[test]
2215 fn a_spec_that_cannot_be_used_means_no_canonical_stamps() {
2216 let dir = repo("canon-unreadable-spec");
2218 std::fs::create_dir_all(dir.join(".github/attest-inputs")).unwrap();
2219 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2220 std::fs::write(dir.join(".github/attest-inputs/x"), "x").unwrap();
2221 std::fs::write(dir.join("a.ts"), "x").unwrap();
2222 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2223 git(&dir, &["add", "-A"]);
2224 in_repo(&dir, || {
2225 record(&["test@abc"]);
2226 git(&dir, &["commit", "-qm", "feat: judged"]);
2227 bind_to_head();
2228 assert!(!inputs_ref_exists(), "an unreadable spec opens nothing");
2229 let head = plan_only_commit(&dir);
2230 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2231 });
2232 let _ = std::fs::remove_dir_all(&dir);
2233 }
2234
2235 #[test]
2236 fn two_specs_mean_no_canonical_stamps() {
2237 let dir = repo("canon-ambiguous");
2238 std::fs::create_dir_all(dir.join(".github")).unwrap();
2239 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2240 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2241 std::fs::write(dir.join("a.ts"), "x").unwrap();
2242 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2243 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2244 std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
2245 git(&dir, &["add", "-A"]);
2246 in_repo(&dir, || {
2247 record(&["test@abc"]);
2248 git(&dir, &["commit", "-qm", "feat: judged"]);
2249 bind_to_head();
2250 assert!(!inputs_ref_exists());
2251 let head = plan_only_commit(&dir);
2252 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2253 });
2254 let _ = std::fs::remove_dir_all(&dir);
2255 }
2256
2257 #[test]
2258 fn a_valid_spec_keeps_precedence_over_the_canonical_route() {
2259 let dir = declared("canon-precedence", "test a.ts\n");
2261 in_repo(&dir, || {
2262 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2263 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2264 let head = plan_only_commit(&dir);
2265 let tokens = stamps_for(std::slice::from_ref(&head))
2266 .remove(&head)
2267 .unwrap_or_default();
2268 assert!(tokens.contains(&"test@abc".to_string()));
2269 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2270 });
2271 let _ = std::fs::remove_dir_all(&dir);
2272 }
2273}