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 = "amont-gate";
134
135const PUSH_STAMPS: &str = "amont.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 = "amont.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::git::succeeds(&[
514 "cat-file",
515 "-e",
516 &format!("{tree}:{}", crate::manifest::MANIFEST),
517 ]);
518 !tracked || crate::attest_inputs::declares(spec, gate, crate::manifest::MANIFEST)
519}
520
521fn inputs_ref_exists() -> bool {
525 crate::git::succeeds(&["rev-parse", "-q", "--verify", INPUTS_FULL_REF])
526}
527
528pub fn tree_tokens(tree: &str) -> Vec<String> {
532 let mut tokens = note_at(tree).tokens;
533 if inputs_ref_exists() {
534 for t in input_tokens(tree) {
535 if !tokens.contains(&t) {
536 tokens.push(t);
537 }
538 }
539 }
540 tokens
541}
542
543pub fn stamp_tree(tree: &str, tokens: &[String]) -> bool {
547 let mut note = note_at(tree);
548 note.add_tokens(tokens);
549 let ok = write_note(tree, ¬e);
550 file_inputs(tree, tokens);
551 ok
552}
553
554fn write_note(key: &str, note: &Note) -> bool {
556 write_note_in(NOTES_REF, key, note)
557}
558
559fn write_note_in(notes_ref: &str, key: &str, note: &Note) -> bool {
560 let body = note.render();
561 crate::git::succeeds(&["notes", "--ref", notes_ref, "add", "-f", "-m", &body, key])
562}
563
564pub fn record_runs(key: &str, runs: &[Run]) {
575 let runs: Vec<Run> = runs
580 .iter()
581 .filter(|r| !r.gate.is_empty() && !r.gate.contains(char::is_whitespace))
582 .cloned()
583 .collect();
584 if runs.is_empty() {
585 return;
586 }
587 let mut note = note_at(key);
588 note.add_runs(&runs);
589 let _ = write_note(key, ¬e);
590}
591
592pub fn record_deferred(tree: &str, gates: &[String]) {
596 let gates: Vec<&String> = gates
597 .iter()
598 .filter(|g| !g.is_empty() && !g.contains(char::is_whitespace))
599 .collect();
600 if gates.is_empty() {
601 return;
602 }
603 let mut note = note_at(tree);
604 for g in gates {
605 if !note.deferred.contains(g) {
606 note.deferred.push(g.clone());
607 }
608 }
609 let _ = write_note(tree, ¬e); }
611
612pub fn deferred_on(tree: &str) -> Vec<String> {
615 note_at(tree).deferred
616}
617
618pub fn deferred_for(commits: &[String], gate: &str) -> HashSet<String> {
622 let mut out = HashSet::new();
623 if commits.is_empty() {
624 return out;
625 }
626 let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
627 args.extend(commits.iter().map(String::as_str));
628 let Some(list) = crate::git::stdout(&args) else {
629 return out;
630 };
631 for line in list.lines() {
632 let mut it = line.split_whitespace();
633 let (Some(commit), Some(tree)) = (it.next(), it.next()) else {
634 continue;
635 };
636 if [commit, tree]
637 .iter()
638 .any(|key| note_at(key).deferred.iter().any(|d| d == gate))
639 {
640 out.insert(commit.to_string());
641 }
642 }
643 out
644}
645
646fn marker_path() -> Option<PathBuf> {
650 let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
651 Some(std::path::Path::new(&dir).join(MARKER))
652}
653
654pub fn record(scripts: &[&str]) {
665 let Some(path) = marker_path() else { return };
666 if scripts.is_empty() {
667 let _ = std::fs::remove_file(&path);
668 return;
669 }
670 let Some(tree) = crate::git::stdout(&["write-tree"]) else {
674 crate::hooks::common::warn(
678 "git would not name the staged tree — this commit records no gate stamp",
679 );
680 let _ = std::fs::remove_file(&path);
681 return;
682 };
683 let mut body = format!("{FORMAT}\n{tree}\n");
684 for s in scripts {
685 body.push_str(s);
686 body.push('\n');
687 }
688 let _ = std::fs::write(&path, body);
689}
690
691pub fn vouched_for_staged_tree() -> HashSet<String> {
719 let mut out = HashSet::new();
720 let Some(tree) = crate::git::stdout(&["write-tree"]) else {
721 return out;
722 };
723 if let Some(path) = marker_path() {
724 if let Ok(body) = std::fs::read_to_string(&path) {
725 let mut lines = body.lines();
726 if lines.next() == Some(FORMAT) && lines.next() == Some(tree.as_str()) {
727 out.extend(
728 lines
729 .filter(|l| !l.trim().is_empty() && !is_provenance(l))
730 .map(str::to_string),
731 );
732 }
733 }
734 }
735 out.extend(note_at(&tree).tokens);
744 if inputs_ref_exists() {
750 out.extend(input_tokens(&tree));
751 }
752 out
753}
754
755pub fn bind_to_head() -> Vec<String> {
766 let Some(path) = marker_path() else {
767 return Vec::new();
768 };
769 let Ok(body) = std::fs::read_to_string(&path) else {
770 return Vec::new(); };
772 let _ = std::fs::remove_file(&path);
773 let mut lines = body.lines();
774 if lines.next() != Some(FORMAT) {
775 return Vec::new();
776 }
777 let Some(tree) = lines.next() else {
778 return Vec::new();
779 };
780 let scripts: Vec<&str> = lines
781 .filter(|l| !l.trim().is_empty() && !is_provenance(l))
782 .collect();
783 if scripts.is_empty() {
784 return Vec::new();
785 }
786 let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
787 crate::hooks::common::warn(
788 "git would not name this commit's tree — no gate stamp was written",
789 );
790 return Vec::new();
791 };
792 if head_tree != tree {
795 return Vec::new();
796 }
797 let scripts: Vec<String> = scripts.iter().map(|s| s.to_string()).collect();
798 let mut tree_note = note_at(&head_tree);
823 tree_note.add_tokens(&scripts);
824 let _ = write_note(&head_tree, &tree_note);
825 file_inputs(&head_tree, &scripts);
826 let mut head_note = note_at("HEAD");
827 head_note.add_tokens(&scripts);
828 if !write_note("HEAD", &head_note) {
829 crate::hooks::common::warn(
832 "git refused to write the gate stamp — these checks will run again at push",
833 );
834 return Vec::new();
835 }
836 scripts
839 .iter()
840 .map(|s| crate::gate_identity::base(s).to_string())
841 .collect()
842}
843
844pub fn stamp_push(commit: &str, tree: &str, gates: &[String]) -> bool {
853 if gates.is_empty() {
854 return false;
855 }
856 let mut written = false;
857 for key in [tree, commit] {
858 let mut note = note_at(key);
859 note.add_tokens(gates);
860 let ok = write_note(key, ¬e);
861 if key == commit {
862 written = ok;
863 }
864 }
865 file_inputs(tree, gates);
866 if !written {
867 crate::hooks::common::warn(
868 "git refused to write the push stamp — these gates will run again on the next push",
869 );
870 }
871 written
872}
873
874#[derive(Debug, Clone, Copy, PartialEq, Eq)]
877pub enum Completion {
878 Warned,
880 FailedUnderWarn,
883 Unavailable,
886}
887
888const UNAVAILABLE_FOR_SECS: u64 = 60 * 60;
890
891fn completion_word(how: Completion, token: &str, now: u64) -> String {
893 match how {
894 Completion::Warned => format!("warned:{token}"),
895 Completion::FailedUnderWarn => format!("failed-under-warn:{token}"),
896 Completion::Unavailable => format!("unavailable:{now}:{token}"),
897 }
898}
899
900fn completion_answers(word: &str, token: &str, severity: crate::check::Severity, now: u64) -> bool {
902 if word.strip_prefix("warned:") == Some(token) {
903 return true;
904 }
905 if word.strip_prefix("failed-under-warn:") == Some(token) {
906 return severity == crate::check::Severity::Warn;
907 }
908 word.strip_prefix("unavailable:")
909 .and_then(|rest| rest.split_once(':'))
910 .is_some_and(|(at, tok)| {
911 tok == token
912 && at
913 .parse::<u64>()
914 .is_ok_and(|at| now.saturating_sub(at) <= UNAVAILABLE_FOR_SECS)
915 })
916}
917
918fn now_secs() -> u64 {
919 std::time::SystemTime::now()
920 .duration_since(std::time::UNIX_EPOCH)
921 .map(|d| d.as_secs())
922 .unwrap_or(0)
923}
924
925pub fn record_done(tree: &str, tokens: &[String], how: Completion) -> Result<(), String> {
931 if tokens.is_empty() {
932 return Ok(());
933 }
934 let now = now_secs();
935 let mut note = note_in(DONE_REF, tree);
936 if how == Completion::Unavailable {
937 note.tokens.retain(|word| {
938 !word
939 .strip_prefix("unavailable:")
940 .and_then(|rest| rest.split_once(':'))
941 .is_some_and(|(_, token)| tokens.iter().any(|t| t == token))
942 });
943 }
944 let words: Vec<String> = tokens
945 .iter()
946 .map(|t| completion_word(how, t, now))
947 .collect();
948 note.add_tokens(&words);
949 if write_note_in(DONE_REF, tree, ¬e) {
950 Ok(())
951 } else {
952 Err(format!(
953 "git refused to record the completed gates on {tree}"
954 ))
955 }
956}
957
958pub fn done_on_every(commits: &[String], token: &str, severity: crate::check::Severity) -> bool {
963 let now = now_secs();
964 !commits.is_empty()
965 && commits.iter().all(|c| {
966 crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]).is_some_and(|tree| {
967 note_in(DONE_REF, &tree)
968 .tokens
969 .iter()
970 .any(|word| completion_answers(word, token, severity, now))
971 })
972 })
973}
974
975pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
981 let mut out = HashMap::new();
982 if commits.is_empty() {
983 return out;
984 }
985 let Some(list) = crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]) else {
986 crate::hooks::common::warn(
996 "git would not list the gate stamps — every gated check will run again",
997 );
998 return out;
999 };
1000 let noted: HashSet<&str> = list
1001 .lines()
1002 .filter_map(|l| l.split_whitespace().nth(1))
1003 .collect();
1004 let mut trees: HashMap<String, String> = HashMap::new();
1008 {
1009 let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
1010 args.extend(commits.iter().map(String::as_str));
1011 if let Some(out) = crate::git::stdout(&args) {
1012 for line in out.lines() {
1013 let mut it = line.split_whitespace();
1014 if let (Some(c), Some(t)) = (it.next(), it.next()) {
1015 trees.insert(c.to_string(), t.to_string());
1016 }
1017 }
1018 }
1019 }
1023
1024 let by_inputs = inputs_ref_exists();
1030
1031 for commit in commits {
1032 let mut tokens: Vec<String> = Vec::new();
1051 let mut keys: Vec<&str> = Vec::new();
1052 if noted.contains(commit.as_str()) {
1053 keys.push(commit);
1054 }
1055 if let Some(tree) = trees.get(commit).filter(|t| noted.contains(t.as_str())) {
1056 keys.push(tree);
1057 }
1058 for key in keys {
1059 for t in note_at(key).tokens {
1060 if !tokens.contains(&t) {
1061 tokens.push(t);
1062 }
1063 }
1064 }
1065 if by_inputs {
1066 if let Some(tree) = trees.get(commit) {
1067 for t in input_tokens(tree) {
1068 if !tokens.contains(&t) {
1069 tokens.push(t);
1070 }
1071 }
1072 }
1073 }
1074 if tokens.is_empty() {
1075 continue;
1076 }
1077 out.insert(commit.clone(), tokens);
1078 }
1079 out
1080}
1081
1082pub fn forget() -> bool {
1087 let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
1088 let notes = crate::git::succeeds(&["update-ref", "-d", NOTES_FULL_REF]);
1089 let inputs = crate::git::succeeds(&["update-ref", "-d", INPUTS_FULL_REF]);
1090 let cluster = crate::git::succeeds(&["update-ref", "-d", CLUSTER_FULL_REF]);
1091 marker || notes || inputs || cluster
1092}
1093
1094pub(crate) fn cluster_tokens(tree: &str) -> Vec<String> {
1097 note_in(CLUSTER_REF, tree).tokens
1098}
1099
1100pub(crate) fn stamp_cluster(tree: &str, token: &str, provenance: &str) -> bool {
1103 let mut note = note_in(CLUSTER_REF, tree);
1104 note.add_tokens(&[token.to_string()]);
1105 let line = format!("{PROVENANCE} {token} {provenance}");
1106 note.provenance
1107 .retain(|l| l.split_whitespace().nth(1) != Some(token));
1108 note.provenance.push(line);
1109 write_note_in(CLUSTER_REF, tree, ¬e)
1110}
1111
1112pub(crate) fn cluster_stamps_for(commits: &[String]) -> HashMap<String, (String, Vec<String>)> {
1116 let mut out = HashMap::new();
1117 for commit in commits {
1118 let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")]) else {
1119 continue;
1120 };
1121 let tokens = cluster_tokens(&tree);
1122 if !tokens.is_empty() {
1123 out.insert(commit.clone(), (tree, tokens));
1124 }
1125 }
1126 out
1127}
1128
1129pub fn forget_in(repo: &std::path::Path) -> bool {
1131 let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
1132 .is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
1133 let notes = crate::git::succeeds_in(repo, &["update-ref", "-d", NOTES_FULL_REF]);
1134 let inputs = crate::git::succeeds_in(repo, &["update-ref", "-d", INPUTS_FULL_REF]);
1135 let cluster = crate::git::succeeds_in(repo, &["update-ref", "-d", CLUSTER_FULL_REF]);
1136 marker || notes || inputs || cluster
1137}
1138
1139#[cfg(test)]
1140mod tests {
1141 use super::*;
1142 use std::path::Path;
1143
1144 #[test]
1148 fn a_completion_answers_only_while_it_should() {
1149 use crate::check::Severity::{Block, Warn};
1150 let now = 1_700_000_000;
1151 let word = |how| completion_word(how, "gate-tok", now);
1152 assert!(completion_answers(
1153 &word(Completion::Warned),
1154 "gate-tok",
1155 Block,
1156 now
1157 ));
1158 assert!(completion_answers(
1159 &word(Completion::FailedUnderWarn),
1160 "gate-tok",
1161 Warn,
1162 now
1163 ));
1164 assert!(!completion_answers(
1165 &word(Completion::FailedUnderWarn),
1166 "gate-tok",
1167 Block,
1168 now
1169 ));
1170 let unavailable = word(Completion::Unavailable);
1171 assert!(completion_answers(
1172 &unavailable,
1173 "gate-tok",
1174 Block,
1175 now + 3600
1176 ));
1177 assert!(!completion_answers(
1178 &unavailable,
1179 "gate-tok",
1180 Block,
1181 now + 3601
1182 ));
1183 assert!(!completion_answers(
1184 &word(Completion::Warned),
1185 "other-tok",
1186 Warn,
1187 now
1188 ));
1189 }
1190
1191 fn repo(name: &str) -> PathBuf {
1194 let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
1195 let _ = std::fs::remove_dir_all(&dir);
1196 std::fs::create_dir_all(&dir).unwrap();
1197 git(&dir, &["init", "-q", "--template=", "."]);
1198 git(&dir, &["config", "user.email", "t@t.test"]);
1199 git(&dir, &["config", "user.name", "t"]);
1200 dir
1201 }
1202
1203 fn git(dir: &Path, args: &[&str]) -> String {
1212 let out = std::process::Command::new("git")
1213 .arg("-C")
1214 .arg(dir)
1215 .args(args)
1216 .output()
1217 .expect("git");
1218 assert!(
1219 out.status.success(),
1220 "fixture: git {args:?} in {} exited {:?}: {}",
1221 dir.display(),
1222 out.status.code(),
1223 String::from_utf8_lossy(&out.stderr).trim()
1224 );
1225 String::from_utf8_lossy(&out.stdout).trim().to_string()
1226 }
1227
1228 fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
1232 let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
1233 let prev = std::env::current_dir().unwrap();
1234 std::env::set_current_dir(dir).unwrap();
1235 let r = f();
1236 std::env::set_current_dir(prev).unwrap();
1237 r
1238 }
1239
1240 #[test]
1241 fn the_commit_note_does_not_hide_the_tree_notes_push_tokens() {
1242 let dir = repo("union");
1243 std::fs::write(dir.join("a.ts"), "x").unwrap();
1244 git(&dir, &["add", "a.ts"]);
1245 in_repo(&dir, || {
1246 record(&["test"]);
1247 git(&dir, &["commit", "-qm", "chore: a"]);
1248 bind_to_head();
1249 let head = git(&dir, &["rev-parse", "HEAD"]);
1250 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1251 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1254 assert_eq!(note_at(&head).tokens, vec!["test".to_string()]);
1255 let stamps = stamps_for(std::slice::from_ref(&head));
1256 assert_eq!(
1257 stamps.get(&head).map(Vec::as_slice),
1258 Some(&["test".to_string(), "pre-push-cargo-test".to_string()][..]),
1259 "both notes speak for the same tree"
1260 );
1261 });
1262 let _ = std::fs::remove_dir_all(&dir);
1263 }
1264
1265 #[test]
1269 fn an_unavailable_record_replaces_its_predecessor_only() {
1270 let dir = repo("done-unavailable");
1271 std::fs::write(dir.join("a.ts"), "x").unwrap();
1272 git(&dir, &["add", "a.ts"]);
1273 git(&dir, &["commit", "-qm", "chore: a"]);
1274 in_repo(&dir, || {
1275 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1276 let one = |t: &str| vec![t.to_string()];
1277 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("first");
1278 record_done(&tree, &one("lint@b"), Completion::Unavailable).expect("other gate");
1279 record_done(&tree, &one("lint@b"), Completion::Warned).expect("a warning");
1280 record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("again");
1281 let words = note_in(DONE_REF, &tree).tokens;
1282 let unavailable_for = |token: &str| {
1283 words
1284 .iter()
1285 .filter(|w| w.starts_with("unavailable:") && w.ends_with(&format!(":{token}")))
1286 .count()
1287 };
1288 assert_eq!(unavailable_for("suite@a"), 1, "{words:?}");
1289 assert_eq!(unavailable_for("lint@b"), 1, "{words:?}");
1290 assert!(words.contains(&"warned:lint@b".to_string()), "{words:?}");
1291 });
1292 let _ = std::fs::remove_dir_all(&dir); }
1294
1295 #[test]
1296 fn a_commit_with_only_a_tree_note_still_reads_the_tree_tokens() {
1297 let dir = repo("tree-only");
1298 std::fs::write(dir.join("a.ts"), "x").unwrap();
1299 git(&dir, &["add", "a.ts"]);
1300 git(&dir, &["commit", "-qm", "chore: a"]);
1301 in_repo(&dir, || {
1302 let head = git(&dir, &["rev-parse", "HEAD"]);
1303 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1304 assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
1305 let stamps = stamps_for(std::slice::from_ref(&head));
1306 assert_eq!(
1307 stamps.get(&head).map(Vec::as_slice),
1308 Some(&["pre-push-cargo-test".to_string()][..])
1309 );
1310 });
1311 let _ = std::fs::remove_dir_all(&dir);
1312 }
1313
1314 #[test]
1315 fn a_commit_with_only_a_commit_note_still_reads_its_tokens() {
1316 let dir = repo("commit-only");
1317 std::fs::write(dir.join("a.ts"), "x").unwrap();
1318 git(&dir, &["add", "a.ts"]);
1319 git(&dir, &["commit", "-qm", "chore: a"]);
1320 in_repo(&dir, || {
1321 let head = git(&dir, &["rev-parse", "HEAD"]);
1322 let mut note = Note::default();
1323 note.add_tokens(&["typecheck".to_string()]);
1324 assert!(write_note(&head, ¬e));
1325 let stamps = stamps_for(std::slice::from_ref(&head));
1326 assert_eq!(
1327 stamps.get(&head).map(Vec::as_slice),
1328 Some(&["typecheck".to_string()][..])
1329 );
1330 });
1331 let _ = std::fs::remove_dir_all(&dir);
1332 }
1333
1334 #[test]
1335 fn a_token_on_both_notes_is_read_once() {
1336 let dir = repo("dedup");
1337 std::fs::write(dir.join("a.ts"), "x").unwrap();
1338 git(&dir, &["add", "a.ts"]);
1339 in_repo(&dir, || {
1340 record(&["test"]);
1341 git(&dir, &["commit", "-qm", "chore: a"]);
1342 bind_to_head(); let head = git(&dir, &["rev-parse", "HEAD"]);
1344 let stamps = stamps_for(std::slice::from_ref(&head));
1345 assert_eq!(
1346 stamps.get(&head).map(Vec::as_slice),
1347 Some(&["test".to_string()][..])
1348 );
1349 });
1350 let _ = std::fs::remove_dir_all(&dir);
1351 }
1352
1353 #[test]
1354 fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
1355 let dir = repo("roundtrip");
1356 std::fs::write(dir.join("a.ts"), "x").unwrap();
1357 git(&dir, &["add", "a.ts"]);
1358 in_repo(&dir, || {
1359 record(&["typecheck", "test"]);
1360 git(&dir, &["commit", "-qm", "chore: a"]);
1361 let stamped = bind_to_head();
1362 assert_eq!(
1363 stamped,
1364 vec!["typecheck".to_string(), "test".to_string()],
1365 "bind_to_head reports the scripts it stamped"
1366 );
1367 let head = git(&dir, &["rev-parse", "HEAD"]);
1368 let stamps = stamps_for(std::slice::from_ref(&head));
1369 assert_eq!(
1370 stamps.get(&head).map(Vec::as_slice),
1371 Some(&["typecheck".to_string(), "test".to_string()][..])
1372 );
1373 assert!(!dir.join(".git").join(MARKER).exists());
1380 });
1381 let _ = std::fs::remove_dir_all(&dir);
1382 }
1383
1384 #[test]
1385 fn a_marker_for_a_different_tree_stamps_nothing() {
1386 let dir = repo("stale");
1387 std::fs::write(dir.join("a.ts"), "x").unwrap();
1388 git(&dir, &["add", "a.ts"]);
1389 in_repo(&dir, || {
1390 record(&["typecheck"]);
1391 std::fs::write(dir.join("a.ts"), "y").unwrap();
1394 git(&dir, &["add", "a.ts"]);
1395 git(&dir, &["commit", "-qm", "chore: different"]);
1396 assert!(
1397 bind_to_head().is_empty(),
1398 "bind_to_head reports nothing when the tree moved"
1399 );
1400 let head = git(&dir, &["rev-parse", "HEAD"]);
1401 assert!(
1402 stamps_for(&[head]).is_empty(),
1403 "a stale marker must not vouch"
1404 );
1405 assert!(
1406 !dir.join(".git").join(MARKER).exists(),
1407 "consumed either way"
1408 );
1409 });
1410 let _ = std::fs::remove_dir_all(&dir);
1411 }
1412
1413 #[test]
1414 fn an_empty_record_clears_a_previous_marker() {
1415 let dir = repo("clears");
1416 std::fs::write(dir.join("a.ts"), "x").unwrap();
1417 git(&dir, &["add", "a.ts"]);
1418 in_repo(&dir, || {
1419 record(&["typecheck"]);
1420 assert!(dir.join(".git").join(MARKER).exists());
1421 record(&[]);
1422 assert!(!dir.join(".git").join(MARKER).exists());
1423 });
1424 let _ = std::fs::remove_dir_all(&dir);
1425 }
1426
1427 #[test]
1432 fn a_marker_in_an_unknown_format_stamps_nothing() {
1433 let dir = repo("wrongformat");
1434 std::fs::write(dir.join("a.ts"), "x").unwrap();
1435 git(&dir, &["add", "a.ts"]);
1436 in_repo(&dir, || {
1437 let tree = git(&dir, &["write-tree"]);
1438 let marker = dir.join(".git").join(MARKER);
1439 std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
1440 git(&dir, &["commit", "-qm", "chore: a"]);
1441 bind_to_head();
1442 let head = git(&dir, &["rev-parse", "HEAD"]);
1443 assert!(
1444 stamps_for(std::slice::from_ref(&head)).is_empty(),
1445 "an unknown format was trusted"
1446 );
1447 assert!(!marker.exists(), "consumed either way");
1448 });
1449 let _ = std::fs::remove_dir_all(&dir);
1450 }
1451
1452 #[test]
1456 fn a_foreign_note_is_not_a_stamp() {
1457 let dir = repo("foreignnote");
1458 std::fs::write(dir.join("a.ts"), "x").unwrap();
1459 git(&dir, &["add", "a.ts"]);
1460 in_repo(&dir, || {
1461 git(&dir, &["commit", "-qm", "chore: a"]);
1462 git(
1463 &dir,
1464 &[
1465 "notes",
1466 "--ref",
1467 NOTES_REF,
1468 "add",
1469 "-m",
1470 "typecheck test",
1471 "HEAD",
1472 ],
1473 );
1474 let head = git(&dir, &["rev-parse", "HEAD"]);
1475 assert!(
1476 stamps_for(std::slice::from_ref(&head)).is_empty(),
1477 "a note without the format token was trusted"
1478 );
1479 });
1480 let _ = std::fs::remove_dir_all(&dir);
1481 }
1482
1483 #[test]
1487 fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
1488 let dir = repo("no-stamps");
1489 std::fs::write(dir.join("a.ts"), "x").unwrap();
1490 git(&dir, &["add", "a.ts"]);
1491 git(&dir, &["commit", "-qm", "chore: a"]);
1492 in_repo(&dir, || {
1493 assert_eq!(
1494 crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
1495 Some(""),
1496 "an absent notes ref must be an ANSWER, not a failure — the \
1497 no-stamps path and the git-is-broken path are told apart by it"
1498 );
1499 let head = git(&dir, &["rev-parse", "HEAD"]);
1500 assert!(stamps_for(&[head]).is_empty());
1501 });
1502 let _ = std::fs::remove_dir_all(&dir);
1503 }
1504
1505 #[test]
1512 fn a_note_from_before_the_run_lines_parses_unchanged() {
1513 let note = Note::parse("amont-gate-v1 typecheck test");
1514 assert_eq!(note.tokens, vec!["typecheck", "test"]);
1515 assert!(note.runs.is_empty());
1516 assert_eq!(note.render(), "amont-gate-v1 typecheck test");
1519 }
1520
1521 #[test]
1523 fn run_lines_are_read_without_disturbing_the_tokens() {
1524 let body = "amont-gate-v1 pre-push-cargo-test\n\
1525 run 1726900000 pre-push-cargo-test pass 412391\n\
1526 run 1726903600 pre-push-audit-js fail 903\n";
1527 let note = Note::parse(body);
1528 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1529 assert_eq!(note.runs.len(), 2);
1530 assert_eq!(
1531 note.runs[0],
1532 Run {
1533 at: 1_726_900_000,
1534 gate: "pre-push-cargo-test".into(),
1535 outcome: RunOutcome::Passed,
1536 ms: 412_391,
1537 }
1538 );
1539 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1540 assert_eq!(note.render(), body.trim_end());
1541 }
1542
1543 #[test]
1547 fn an_unreadable_run_line_is_dropped_and_the_rest_survives() {
1548 let note = Note::parse(
1549 "amont-gate-v1 test\n\
1550 run 1726900000 pre-push-cargo-test pass 400\n\
1551 run tomorrow pre-push-cargo-test pass 400\n\
1552 run 1726900001 pre-push-cargo-test sideways 400\n\
1553 banana\n\
1554 run 1726900002 pre-push-cargo-test fail 500\n",
1555 );
1556 assert_eq!(note.tokens, vec!["test"]);
1557 assert_eq!(note.runs.len(), 2, "{:?}", note.runs);
1558 assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
1559 }
1560
1561 #[test]
1565 fn a_deferral_is_never_a_token_and_outlives_the_run_trim() {
1566 let mut note = Note::parse("amont-gate-v1 lint\ndeferred cargo-test\n");
1567 assert_eq!(note.tokens, vec!["lint"]);
1568 assert_eq!(note.deferred, vec!["cargo-test"]);
1569 let runs: Vec<Run> = (0..MAX_RUNS as u64 + 10)
1570 .map(|i| Run {
1571 at: 1_726_900_000 + i,
1572 gate: "pre-push-audit-js".into(),
1573 outcome: RunOutcome::Passed,
1574 ms: 1,
1575 })
1576 .collect();
1577 note.add_runs(&runs);
1578 let again = Note::parse(¬e.render());
1579 assert_eq!(again.runs.len(), MAX_RUNS);
1580 assert_eq!(again.deferred, vec!["cargo-test"]);
1581 assert_eq!(again.tokens, vec!["lint"]);
1582 }
1583
1584 #[test]
1587 fn a_foreign_note_yields_no_runs() {
1588 let note = Note::parse("hello\nrun 1726900000 pre-push-cargo-test pass 400\n");
1589 assert!(note.tokens.is_empty() && note.runs.is_empty());
1590 }
1591
1592 #[test]
1597 fn a_stamp_and_its_evidence_survive_each_other() {
1598 let dir = repo("evidence");
1599 std::fs::write(dir.join("a.ts"), "x").unwrap();
1600 git(&dir, &["add", "a.ts"]);
1601 in_repo(&dir, || {
1602 git(&dir, &["commit", "-qm", "chore: a"]);
1603 let head = git(&dir, &["rev-parse", "HEAD"]);
1604 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1605 record_runs(
1606 &tree,
1607 &[Run {
1608 at: 1_726_900_000,
1609 gate: "pre-push-cargo-test".into(),
1610 outcome: RunOutcome::Failed,
1611 ms: 412_391,
1612 }],
1613 );
1614 assert!(stamp_push(&head, &tree, &["pre-push-cargo-test".into()]));
1616 let note = note_at(&tree);
1617 assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
1618 assert_eq!(note.runs.len(), 1, "the evidence survived the stamp");
1619 let stamps = stamps_for(std::slice::from_ref(&head));
1621 assert_eq!(
1622 stamps.get(&head).map(Vec::as_slice),
1623 Some(&["pre-push-cargo-test".to_string()][..])
1624 );
1625 });
1626 let _ = std::fs::remove_dir_all(&dir);
1627 }
1628
1629 #[test]
1633 fn a_recorded_run_is_not_a_stamp() {
1634 let dir = repo("not-a-stamp");
1635 std::fs::write(dir.join("a.ts"), "x").unwrap();
1636 git(&dir, &["add", "a.ts"]);
1637 in_repo(&dir, || {
1638 git(&dir, &["commit", "-qm", "chore: a"]);
1639 let head = git(&dir, &["rev-parse", "HEAD"]);
1640 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1641 record_runs(
1642 &tree,
1643 &[Run {
1644 at: 1_726_900_000,
1645 gate: "pre-push-cargo-test".into(),
1646 outcome: RunOutcome::Passed,
1647 ms: 412_391,
1648 }],
1649 );
1650 assert!(
1651 stamps_for(std::slice::from_ref(&head)).is_empty(),
1652 "a run line vouched for a gate — evidence must never gate"
1653 );
1654 assert!(
1655 !vouched_for_staged_tree().contains("pre-push-cargo-test"),
1656 "a run line vouched at commit time"
1657 );
1658 let history = crate::gate_evidence::history_in(&dir);
1660 assert_eq!(history.runs.len(), 1);
1661 assert_eq!(history.runs[0].0, tree, "keyed by the content it ran on");
1662 });
1663 let _ = std::fs::remove_dir_all(&dir);
1664 }
1665
1666 #[test]
1667 fn forget_removes_the_stamps() {
1668 let dir = repo("forget");
1669 std::fs::write(dir.join("a.ts"), "x").unwrap();
1670 git(&dir, &["add", "a.ts"]);
1671 in_repo(&dir, || {
1672 record(&["typecheck"]);
1673 git(&dir, &["commit", "-qm", "chore: a"]);
1674 bind_to_head();
1675 let head = git(&dir, &["rev-parse", "HEAD"]);
1676 assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
1677 forget();
1678 assert!(stamps_for(&[head]).is_empty());
1679 });
1680 let _ = std::fs::remove_dir_all(&dir);
1681 }
1682
1683 #[test]
1697 fn a_stamp_survives_a_commit_being_rewritten_with_the_same_tree() {
1698 let dir = repo("squashed");
1699 std::fs::write(dir.join("a.ts"), "x").unwrap();
1700 git(&dir, &["add", "a.ts"]);
1701 in_repo(&dir, || {
1702 record(&["test"]);
1703 git(&dir, &["commit", "-qm", "feat: on a branch"]);
1704 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1705 let branch_tip = git(&dir, &["rev-parse", "HEAD"]);
1706
1707 git(
1711 &dir,
1712 &[
1713 "commit",
1714 "-q",
1715 "--amend",
1716 "-m",
1717 "feat: squashed by the forge",
1718 ],
1719 );
1720 let merged = git(&dir, &["rev-parse", "HEAD"]);
1721 assert_ne!(merged, branch_tip, "the fixture must produce a new commit");
1722 assert_eq!(
1723 git(&dir, &["rev-parse", "HEAD^{tree}"]),
1724 git(&dir, &["rev-parse", &format!("{branch_tip}^{{tree}}")]),
1725 "…carrying the same tree, which is the whole premise"
1726 );
1727
1728 let stamps = stamps_for(std::slice::from_ref(&merged));
1729 assert_eq!(
1730 stamps.get(&merged).map(Vec::as_slice),
1731 Some(&["test".to_string()][..]),
1732 "the stamp must follow the content, not the commit hash"
1733 );
1734 });
1735 let _ = std::fs::remove_dir_all(&dir);
1736 }
1737
1738 #[test]
1742 fn a_different_tree_gets_no_stamp_from_the_fallback() {
1743 let dir = repo("othertree");
1744 std::fs::write(dir.join("a.ts"), "x").unwrap();
1745 git(&dir, &["add", "a.ts"]);
1746 in_repo(&dir, || {
1747 record(&["test"]);
1748 git(&dir, &["commit", "-qm", "chore: stamped"]);
1749 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1750
1751 std::fs::write(dir.join("b.ts"), "y").unwrap();
1754 git(&dir, &["add", "b.ts"]);
1755 git(&dir, &["commit", "-qm", "chore: unjudged"]);
1756 let unstamped = git(&dir, &["rev-parse", "HEAD"]);
1757
1758 assert!(
1759 stamps_for(std::slice::from_ref(&unstamped)).is_empty(),
1760 "a tree nobody stamped must not inherit one"
1761 );
1762 });
1763 let _ = std::fs::remove_dir_all(&dir);
1764 }
1765
1766 fn declared(name: &str, spec: &str) -> PathBuf {
1772 let dir = repo(name);
1773 std::fs::create_dir_all(dir.join(".github")).unwrap();
1774 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
1775 std::fs::write(dir.join("a.ts"), "x").unwrap();
1776 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
1777 std::fs::write(dir.join(".github/attest-inputs"), spec).unwrap();
1778 git(&dir, &["add", "-A"]);
1779 in_repo(&dir, || {
1780 record(&["test@abc"]);
1781 git(&dir, &["commit", "-qm", "feat: judged"]);
1782 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1783 });
1784 dir
1785 }
1786
1787 fn plan_only_commit(dir: &Path) -> String {
1790 std::fs::write(dir.join("docs/plans/p.md"), "plan v2, closing").unwrap();
1791 git(dir, &["add", "docs/plans/p.md"]);
1792 git(dir, &["commit", "-qm", "docs(plan): done"]);
1793 git(dir, &["rev-parse", "HEAD"])
1794 }
1795
1796 #[test]
1797 fn a_plan_only_commit_reuses_the_stamp_of_a_declared_gate() {
1798 let dir = declared("plan-only", "test a.ts\n");
1799 in_repo(&dir, || {
1800 let head = plan_only_commit(&dir);
1801 let stamps = stamps_for(std::slice::from_ref(&head));
1802 assert_eq!(
1803 stamps.get(&head).map(Vec::as_slice),
1804 Some(&["test@abc".to_string()][..]),
1805 "the closing commit changed the tree and none of the declared inputs"
1806 );
1807 });
1808 let _ = std::fs::remove_dir_all(&dir);
1809 }
1810
1811 #[test]
1812 fn the_staged_tree_of_a_plan_only_commit_is_vouched_for() {
1813 let dir = declared("staged", "test a.ts\n");
1814 in_repo(&dir, || {
1815 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1816 git(&dir, &["add", "docs/plans/p.md"]);
1817 assert!(vouched_for_staged_tree().contains("test@abc"));
1818 });
1819 let _ = std::fs::remove_dir_all(&dir);
1820 }
1821
1822 #[test]
1823 fn partial_staging_is_judged_on_the_index_not_the_working_copy() {
1824 let dir = declared("partial", "test a.ts\n");
1825 in_repo(&dir, || {
1826 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1829 git(&dir, &["add", "docs/plans/p.md"]);
1830 std::fs::write(dir.join("a.ts"), "unstaged edit").unwrap();
1831 assert!(vouched_for_staged_tree().contains("test@abc"));
1832
1833 std::fs::write(dir.join("a.ts"), "staged edit").unwrap();
1836 git(&dir, &["add", "a.ts"]);
1837 std::fs::write(dir.join("a.ts"), "x").unwrap();
1838 assert!(!vouched_for_staged_tree().contains("test@abc"));
1839 });
1840 let _ = std::fs::remove_dir_all(&dir);
1841 }
1842
1843 #[test]
1844 fn a_changed_declared_input_misses() {
1845 let dir = declared("input-changed", "test a.ts\n");
1846 in_repo(&dir, || {
1847 std::fs::write(dir.join("a.ts"), "changed").unwrap();
1848 git(&dir, &["add", "a.ts"]);
1849 git(&dir, &["commit", "-qm", "feat: unjudged"]);
1850 let head = git(&dir, &["rev-parse", "HEAD"]);
1851 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1852 });
1853 let _ = std::fs::remove_dir_all(&dir);
1854 }
1855
1856 #[test]
1857 fn a_changed_declaration_misses() {
1858 let dir = declared("declaration-changed", "test a.ts\n");
1859 in_repo(&dir, || {
1860 std::fs::write(dir.join("b.ts"), "y").unwrap();
1863 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts b.ts\n").unwrap();
1864 git(&dir, &["add", "-A"]);
1865 git(&dir, &["commit", "-qm", "chore: widen the declaration"]);
1866 let head = git(&dir, &["rev-parse", "HEAD"]);
1867 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1868 });
1869 let _ = std::fs::remove_dir_all(&dir);
1870 }
1871
1872 #[test]
1873 fn a_declared_config_file_is_an_input_like_any_other() {
1874 let dir = declared("config", "test a.ts amont.conf\n");
1877 in_repo(&dir, || {
1878 assert!(!inputs_ref_exists());
1881
1882 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
1883 git(&dir, &["add", "amont.conf"]);
1884 record(&["test@abc"]);
1885 git(&dir, &["commit", "-qm", "chore: config"]);
1886 assert_eq!(bind_to_head(), vec!["test".to_string()]);
1887
1888 std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
1889 git(&dir, &["add", "docs/plans/p.md"]);
1890 git(&dir, &["commit", "-qm", "docs(plan): done"]);
1891 let plan = git(&dir, &["rev-parse", "HEAD"]);
1892 assert!(stamps_for(std::slice::from_ref(&plan)).contains_key(&plan));
1893
1894 std::fs::write(dir.join("amont.conf"), "scope = lib\n").unwrap();
1895 git(&dir, &["add", "amont.conf"]);
1896 git(&dir, &["commit", "-qm", "chore: scope-only change"]);
1897 let scope = git(&dir, &["rev-parse", "HEAD"]);
1898 assert!(
1899 stamps_for(std::slice::from_ref(&scope)).is_empty(),
1900 "a scope-only change must miss"
1901 );
1902 });
1903 let _ = std::fs::remove_dir_all(&dir);
1904 }
1905
1906 #[test]
1907 fn a_declared_stamp_is_read_back_as_its_complete_token() {
1908 let dir = declared("identity", "test a.ts\n");
1914 in_repo(&dir, || {
1915 let head = plan_only_commit(&dir);
1916 let tokens = stamps_for(std::slice::from_ref(&head))
1917 .remove(&head)
1918 .unwrap_or_default();
1919 assert_eq!(tokens, vec!["test@abc".to_string()]);
1920
1921 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1922 assert!(stamp_tree(&tree, &["test@def".to_string()]));
1923 let tokens = tree_tokens(&tree);
1924 assert!(tokens.contains(&"test@abc".to_string()));
1925 assert!(tokens.contains(&"test@def".to_string()));
1926 assert!(!tokens.contains(&"test@zzz".to_string()));
1927 assert!(!tokens.contains(&"test".to_string()));
1928 });
1929 let _ = std::fs::remove_dir_all(&dir);
1930 }
1931
1932 #[test]
1933 fn a_gate_that_does_not_declare_the_manifest_is_not_offered_the_route() {
1934 let dir = repo("manifest-undeclared");
1938 std::fs::create_dir_all(dir.join(".github")).unwrap();
1939 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
1940 std::fs::write(dir.join("a.ts"), "x").unwrap();
1941 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
1942 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
1943 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
1944 git(&dir, &["add", "-A"]);
1945 in_repo(&dir, || {
1946 record(&["test@abc"]);
1947 git(&dir, &["commit", "-qm", "feat: judged"]);
1948 bind_to_head();
1949 assert!(!inputs_ref_exists(), "the route must not open");
1950 let head = plan_only_commit(&dir);
1951 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1952 });
1953 let _ = std::fs::remove_dir_all(&dir);
1954 }
1955
1956 #[test]
1957 fn a_gate_declaring_the_manifest_opens_the_route() {
1958 let dir = declared("manifest-declared", "test a.ts amont.conf\n");
1961 in_repo(&dir, || {
1962 std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
1963 git(&dir, &["add", "amont.conf"]);
1964 record(&["test@abc"]);
1965 git(&dir, &["commit", "-qm", "chore: config"]);
1966 bind_to_head();
1967 assert!(inputs_ref_exists());
1968 });
1969 let _ = std::fs::remove_dir_all(&dir);
1970 }
1971
1972 #[test]
1973 fn an_undeclared_gate_keeps_whole_tree_behaviour() {
1974 let dir = declared("undeclared", "test a.ts\n");
1975 in_repo(&dir, || {
1976 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
1979 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
1980 let head = plan_only_commit(&dir);
1981 let tokens = stamps_for(std::slice::from_ref(&head))
1982 .remove(&head)
1983 .unwrap_or_default();
1984 assert!(tokens.contains(&"test@abc".to_string()));
1985 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
1986 });
1987 let _ = std::fs::remove_dir_all(&dir);
1988 }
1989
1990 #[test]
1991 fn an_invalid_or_ambiguous_spec_falls_back_to_whole_tree_behaviour() {
1992 let dir = declared("invalid", "test src/*\n");
1994 in_repo(&dir, || {
1995 assert!(!inputs_ref_exists(), "no valid spec, nothing is filed");
1996 let head = plan_only_commit(&dir);
1997 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
1998 });
1999 let _ = std::fs::remove_dir_all(&dir);
2000
2001 let dir = repo("ambiguous");
2003 std::fs::create_dir_all(dir.join(".github")).unwrap();
2004 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2005 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2006 std::fs::write(dir.join("a.ts"), "x").unwrap();
2007 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2008 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2009 std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
2010 git(&dir, &["add", "-A"]);
2011 in_repo(&dir, || {
2012 record(&["test@abc"]);
2013 git(&dir, &["commit", "-qm", "feat: judged"]);
2014 bind_to_head();
2015 assert!(!inputs_ref_exists());
2016 let head = plan_only_commit(&dir);
2017 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2018 });
2019 let _ = std::fs::remove_dir_all(&dir);
2020 }
2021
2022 #[test]
2023 fn a_gate_that_did_not_pass_leaves_no_declared_input_stamp() {
2024 let dir = repo("failed");
2025 std::fs::create_dir_all(dir.join(".github")).unwrap();
2026 std::fs::write(dir.join("a.ts"), "x").unwrap();
2027 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2028 git(&dir, &["add", "-A"]);
2029 in_repo(&dir, || {
2030 record(&[]);
2032 git(&dir, &["commit", "-qm", "feat: unjudged"]);
2033 assert!(bind_to_head().is_empty());
2034 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2035 let head = git(&dir, &["rev-parse", "HEAD"]);
2036 assert!(!stamp_push(&head, &tree, &[]));
2037 assert!(!inputs_ref_exists());
2038 });
2039 let _ = std::fs::remove_dir_all(&dir);
2040 }
2041
2042 #[test]
2043 fn stamp_tree_and_tree_tokens_use_the_inputs_ref() {
2044 let dir = declared("rehearsal", "test a.ts\n");
2045 in_repo(&dir, || {
2046 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2048 assert!(stamp_tree(&tree, &["test@rehearsed".to_string()]));
2049 plan_only_commit(&dir);
2051 let later = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2052 assert_ne!(later, tree);
2053 assert!(tree_tokens(&later).contains(&"test@rehearsed".to_string()));
2054 });
2055 let _ = std::fs::remove_dir_all(&dir);
2056 }
2057
2058 #[test]
2059 fn the_inputs_ref_is_keyed_the_way_attest_keys_its_own() {
2060 let dir = declared("key", "test a.ts\n");
2061 in_repo(&dir, || {
2062 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2063 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2064 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2065 let key = crate::attest_inputs::input_key("test", &fp).expect("key");
2066 let listed = git(&dir, &["notes", "--ref", INPUTS_REF, "list"]);
2067 assert!(
2068 listed
2069 .lines()
2070 .any(|l| l.split_whitespace().nth(1) == Some(key.as_str())),
2071 "{listed}"
2072 );
2073 });
2074 let _ = std::fs::remove_dir_all(&dir);
2075 }
2076
2077 #[test]
2078 fn a_foreign_token_in_the_inputs_ref_vouches_for_nothing() {
2079 let dir = declared("foreign", "test a.ts\n");
2080 in_repo(&dir, || {
2081 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2082 let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
2083 let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
2084 let key = crate::attest_inputs::input_key("test", &fp).expect("key");
2085 let mut note = note_in(INPUTS_REF, &key);
2087 note.add_tokens(&["publish@evil".to_string()]);
2088 assert!(write_note_in(INPUTS_REF, &key, ¬e));
2089 assert!(!tree_tokens(&tree).contains(&"publish@evil".to_string()));
2090 });
2091 let _ = std::fs::remove_dir_all(&dir);
2092 }
2093
2094 #[test]
2095 fn forget_removes_the_inputs_ref_too() {
2096 let dir = declared("forget-inputs", "test a.ts\n");
2097 in_repo(&dir, || {
2098 assert!(inputs_ref_exists());
2099 assert!(forget());
2100 assert!(!inputs_ref_exists());
2101 });
2102 let _ = std::fs::remove_dir_all(&dir);
2103 }
2104
2105 fn canonical(name: &str, conf: Option<&str>) -> PathBuf {
2108 let dir = repo(name);
2109 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2110 std::fs::write(dir.join("a.ts"), "x").unwrap();
2111 std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
2112 if let Some(conf) = conf {
2113 std::fs::write(dir.join("amont.conf"), conf).unwrap();
2114 }
2115 git(&dir, &["add", "-A"]);
2116 in_repo(&dir, || {
2117 record(&["test@abc"]);
2118 git(&dir, &["commit", "-qm", "feat: judged"]);
2119 assert_eq!(bind_to_head(), vec!["test".to_string()]);
2120 });
2121 dir
2122 }
2123
2124 fn vouched(dir: &Path, commit: &str) -> Vec<String> {
2125 in_repo(dir, || {
2126 stamps_for(std::slice::from_ref(&commit.to_string()))
2127 .remove(commit)
2128 .unwrap_or_default()
2129 })
2130 }
2131
2132 #[test]
2133 fn with_no_spec_a_plans_only_commit_is_vouched_for_canonically() {
2134 let dir = canonical("canon-plan-edit", None);
2135 in_repo(&dir, || {
2136 assert!(inputs_ref_exists(), "the canonical stamp is filed");
2137 let head = plan_only_commit(&dir);
2138 assert_eq!(
2139 stamps_for(std::slice::from_ref(&head))
2140 .remove(&head)
2141 .unwrap_or_default(),
2142 vec!["test@abc".to_string()]
2143 );
2144 std::fs::write(dir.join("docs/plans/p.md"), "plan v3").unwrap();
2146 git(&dir, &["add", "docs/plans/p.md"]);
2147 assert!(vouched_for_staged_tree().contains("test@abc"));
2148 });
2149 let _ = std::fs::remove_dir_all(&dir);
2150 }
2151
2152 #[test]
2153 fn a_plan_added_deleted_or_renamed_is_not_vouched_for() {
2154 let dir = canonical("canon-plan-exists", None);
2155 std::fs::write(dir.join("docs/plans/q.md"), "second plan").unwrap();
2156 git(&dir, &["add", "docs/plans/q.md"]);
2157 git(&dir, &["commit", "-qm", "docs(plan): add"]);
2158 let added = git(&dir, &["rev-parse", "HEAD"]);
2159 assert!(vouched(&dir, &added).is_empty(), "a plan added");
2160 git(&dir, &["mv", "docs/plans/p.md", "docs/plans/r.md"]);
2161 git(&dir, &["commit", "-qm", "docs(plan): rename"]);
2162 let renamed = git(&dir, &["rev-parse", "HEAD"]);
2163 assert!(vouched(&dir, &renamed).is_empty(), "a plan renamed");
2164 let _ = std::fs::remove_dir_all(&dir);
2165 }
2166
2167 #[test]
2168 fn with_no_spec_any_other_change_is_not_vouched_for() {
2169 let dir = canonical("canon-code-edit", Some("gate test = make test\n"));
2170 std::fs::write(dir.join("a.ts"), "changed").unwrap();
2171 git(&dir, &["commit", "-qam", "feat: code"]);
2172 let code = git(&dir, &["rev-parse", "HEAD"]);
2173 assert!(vouched(&dir, &code).is_empty(), "a source edit");
2174 std::fs::write(dir.join("amont.conf"), "gate test = make other\n").unwrap();
2176 git(&dir, &["commit", "-qam", "chore: config"]);
2177 let conf = git(&dir, &["rev-parse", "HEAD"]);
2178 assert!(vouched(&dir, &conf).is_empty(), "a manifest edit");
2179 let _ = std::fs::remove_dir_all(&dir);
2180 }
2181
2182 #[test]
2183 fn plan_exempt_off_closes_the_canonical_route() {
2184 for (name, conf) in [
2185 ("off", "set planExempt off\n"),
2186 ("spelled", "SET PLANEXEMPT\tOff\r\n"),
2187 ("after", "set planExempt on\nset planExempt off\n"),
2188 ] {
2189 let dir = canonical(&format!("canon-off-{name}"), Some(conf));
2190 in_repo(&dir, || {
2191 assert!(!inputs_ref_exists(), "{name}: nothing is filed");
2192 let head = plan_only_commit(&dir);
2193 assert!(
2194 stamps_for(std::slice::from_ref(&head)).is_empty(),
2195 "{name}: a plans-only commit is a new tree"
2196 );
2197 });
2198 let _ = std::fs::remove_dir_all(&dir);
2199 }
2200 for (name, conf) in [
2202 ("on", "set planExempt on\n"),
2203 ("comment", "set planExempt off # no\n"),
2204 ("commented", "# set planExempt off\n"),
2205 ] {
2206 let dir = canonical(&format!("canon-on-{name}"), Some(conf));
2207 let head = plan_only_commit(&dir);
2208 assert!(!vouched(&dir, &head).is_empty(), "{name}: still canonical");
2209 let _ = std::fs::remove_dir_all(&dir);
2210 }
2211 }
2212
2213 #[test]
2214 fn a_spec_that_cannot_be_used_means_no_canonical_stamps() {
2215 let dir = repo("canon-unreadable-spec");
2217 std::fs::create_dir_all(dir.join(".github/attest-inputs")).unwrap();
2218 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2219 std::fs::write(dir.join(".github/attest-inputs/x"), "x").unwrap();
2220 std::fs::write(dir.join("a.ts"), "x").unwrap();
2221 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2222 git(&dir, &["add", "-A"]);
2223 in_repo(&dir, || {
2224 record(&["test@abc"]);
2225 git(&dir, &["commit", "-qm", "feat: judged"]);
2226 bind_to_head();
2227 assert!(!inputs_ref_exists(), "an unreadable spec opens nothing");
2228 let head = plan_only_commit(&dir);
2229 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2230 });
2231 let _ = std::fs::remove_dir_all(&dir);
2232 }
2233
2234 #[test]
2235 fn two_specs_mean_no_canonical_stamps() {
2236 let dir = repo("canon-ambiguous");
2237 std::fs::create_dir_all(dir.join(".github")).unwrap();
2238 std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
2239 std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
2240 std::fs::write(dir.join("a.ts"), "x").unwrap();
2241 std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
2242 std::fs::write(dir.join(".github/attest-inputs"), "test a.ts\n").unwrap();
2243 std::fs::write(dir.join(".forgejo/attest-inputs"), "test a.ts\n").unwrap();
2244 git(&dir, &["add", "-A"]);
2245 in_repo(&dir, || {
2246 record(&["test@abc"]);
2247 git(&dir, &["commit", "-qm", "feat: judged"]);
2248 bind_to_head();
2249 assert!(!inputs_ref_exists());
2250 let head = plan_only_commit(&dir);
2251 assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
2252 });
2253 let _ = std::fs::remove_dir_all(&dir);
2254 }
2255
2256 #[test]
2257 fn a_valid_spec_keeps_precedence_over_the_canonical_route() {
2258 let dir = declared("canon-precedence", "test a.ts\n");
2260 in_repo(&dir, || {
2261 let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
2262 assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
2263 let head = plan_only_commit(&dir);
2264 let tokens = stamps_for(std::slice::from_ref(&head))
2265 .remove(&head)
2266 .unwrap_or_default();
2267 assert!(tokens.contains(&"test@abc".to_string()));
2268 assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
2269 });
2270 let _ = std::fs::remove_dir_all(&dir);
2271 }
2272}