use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct GateNames {
pub format: &'static str,
pub notes_ref: &'static str,
pub inputs_ref: &'static str,
pub cluster_ref: &'static str,
pub done_ref: &'static str,
pub canon_domain: &'static str,
pub attest: greensummit::format::Names,
}
pub(crate) const GREEN: GateNames = GateNames {
format: "greengate-gate-v1",
notes_ref: "greengate-gate",
inputs_ref: "greengate-gate-inputs",
cluster_ref: "greengate-gate-cluster",
done_ref: "greengate-gate-done",
canon_domain: "greengate-gate-canon",
attest: greensummit::format::SUMMIT,
};
pub(crate) const WRITE: GateNames = GREEN;
pub const FORMAT: &str = WRITE.format;
pub const NOTES_REF: &str = WRITE.notes_ref;
pub const NOTES_FULL_REF: &str = "refs/notes/greengate-gate";
pub const INPUTS_REF: &str = WRITE.inputs_ref;
pub const CLUSTER_REF: &str = WRITE.cluster_ref;
pub const CLUSTER_FULL_REF: &str = "refs/notes/greengate-gate-cluster";
pub const DONE_REF: &str = WRITE.done_ref;
pub const DONE_FULL_REF: &str = "refs/notes/greengate-gate-done";
pub const PROVENANCE: &str = "provenance";
pub const INPUTS_FULL_REF: &str = "refs/notes/greengate-gate-inputs";
const MARKER: &str = crate::names::GATE_MARKER;
const PUSH_STAMPS: &str = "greengate.pushStamps";
pub fn push_stamps_enabled(settings: &crate::config::Settings) -> bool {
crate::config::boolean_or(settings, PUSH_STAMPS, true)
}
const COMMIT_STAMPS: &str = "greengate.commitStamps";
pub fn commit_stamps_enabled(settings: &crate::config::Settings) -> bool {
crate::config::boolean_or(settings, COMMIT_STAMPS, true)
}
const RUN: &str = "run";
const MAX_RUNS: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunOutcome {
Passed,
Failed,
Warned,
Fixed,
Unavailable,
Inert,
Cold,
Busy,
Skew,
Withheld,
Cancelled,
Slow,
Deferred,
}
impl RunOutcome {
pub fn as_str(self) -> &'static str {
match self {
RunOutcome::Passed => "pass",
RunOutcome::Failed => "fail",
RunOutcome::Warned => "warn",
RunOutcome::Fixed => "fixed",
RunOutcome::Unavailable => "unavailable",
RunOutcome::Inert => "inert",
RunOutcome::Cold => "cold",
RunOutcome::Busy => "busy",
RunOutcome::Skew => "skew",
RunOutcome::Withheld => "withheld",
RunOutcome::Cancelled => "cancelled",
RunOutcome::Slow => "slow",
RunOutcome::Deferred => "deferred",
}
}
pub fn parse(s: &str) -> Option<RunOutcome> {
Some(match s {
"pass" => RunOutcome::Passed,
"fail" => RunOutcome::Failed,
"warn" => RunOutcome::Warned,
"fixed" => RunOutcome::Fixed,
"unavailable" => RunOutcome::Unavailable,
"inert" => RunOutcome::Inert,
"cold" => RunOutcome::Cold,
"busy" => RunOutcome::Busy,
"skew" => RunOutcome::Skew,
"withheld" => RunOutcome::Withheld,
"cancelled" => RunOutcome::Cancelled,
"slow" => RunOutcome::Slow,
"deferred" => RunOutcome::Deferred,
_ => return None,
})
}
pub fn is_verdict(self) -> bool {
matches!(self, RunOutcome::Passed | RunOutcome::Failed)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Run {
pub at: u64,
pub gate: String,
pub outcome: RunOutcome,
pub ms: u64,
}
impl Run {
fn render(&self) -> String {
format!(
"{RUN} {} {} {} {}",
self.at,
self.gate,
self.outcome.as_str(),
self.ms
)
}
fn parse(line: &str) -> Option<Run> {
let mut t = line.split_whitespace();
if t.next() != Some(RUN) {
return None;
}
let at = t.next()?.parse().ok()?;
let gate = t.next()?.to_string();
let outcome = RunOutcome::parse(t.next()?)?;
let ms = t.next()?.parse().ok()?;
Some(Run {
at,
gate,
outcome,
ms,
})
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Note {
pub tokens: Vec<String>,
pub deferred: Vec<String>,
pub runs: Vec<Run>,
pub provenance: Vec<String>,
}
const DEFERRED: &str = "deferred";
impl Note {
pub fn parse(body: &str) -> Note {
Note::parse_as(body, FORMAT)
}
pub(crate) fn parse_as(body: &str, format: &str) -> Note {
let mut lines = body.lines();
let Some(first) = lines.next() else {
return Note::default();
};
let mut tokens = first.split_whitespace();
if tokens.next() != Some(format) {
return Note::default();
}
let mut deferred = Vec::new();
let mut runs = Vec::new();
let mut provenance = Vec::new();
for line in lines {
if is_provenance(line) {
provenance.push(line.trim().to_string());
continue;
}
let mut t = line.split_whitespace();
match (t.next(), t.next(), t.next()) {
(Some(DEFERRED), Some(gate), None) => {
if !deferred.iter().any(|d| d == gate) {
deferred.push(gate.to_string());
}
}
_ => runs.extend(Run::parse(line)),
}
}
Note {
tokens: tokens.map(str::to_string).collect(),
deferred,
runs,
provenance,
}
}
pub fn render(&self) -> String {
let mut body = format!("{FORMAT} {}", self.tokens.join(" "));
for gate in &self.deferred {
body.push('\n');
body.push_str(&format!("{DEFERRED} {gate}"));
}
for run in &self.runs {
body.push('\n');
body.push_str(&run.render());
}
for line in &self.provenance {
body.push('\n');
body.push_str(line);
}
body
}
fn add_tokens(&mut self, tokens: &[String]) {
for t in tokens {
if !self.tokens.iter().any(|have| have == t) {
self.tokens.push(t.clone());
}
}
}
fn add_runs(&mut self, runs: &[Run]) {
self.runs.extend(runs.iter().cloned());
if self.runs.len() > MAX_RUNS {
self.runs.drain(..self.runs.len() - MAX_RUNS);
}
}
}
pub fn is_provenance(line: &str) -> bool {
line.split_whitespace().next() == Some(PROVENANCE)
}
fn note_at(key: &str) -> Note {
note_in(NOTES_REF, key)
}
fn note_in(notes_ref: &str, key: &str) -> Note {
crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
.map(|body| Note::parse(&body))
.unwrap_or_default()
}
fn stamp_in(which: fn(&GateNames) -> &'static str, key: &str) -> Note {
read_in(&WRITE, which(&WRITE), key).unwrap_or_default()
}
fn read_in(set: &GateNames, notes_ref: &str, key: &str) -> Option<Note> {
crate::git::stdout(&["notes", "--ref", notes_ref, "show", key])
.map(|body| Note::parse_as(&body, set.format))
}
fn stamp_at(key: &str) -> Note {
stamp_in(|s| s.notes_ref, key)
}
fn input_tokens(tree: &str) -> Vec<String> {
let Some(spec) = crate::attest_inputs::spec_at(tree) else {
return canon_tokens(tree);
};
let mut out: Vec<String> = Vec::new();
for (gate, _) in &spec.gates {
if !manifest_is_an_input(tree, &spec, gate) {
continue;
}
let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
continue;
};
let note = crate::attest_inputs::input_key(&WRITE.attest, gate, &fp)
.and_then(|key| read_in(&WRITE, WRITE.inputs_ref, &key));
for t in note.unwrap_or_default().tokens {
if crate::gate_identity::base(&t) == gate.as_str() && !out.contains(&t) {
out.push(t);
}
}
}
out
}
fn canon_tokens(tree: &str) -> Vec<String> {
let Some(canon) = crate::attest_inputs::canonical_route(tree) else {
return Vec::new();
};
crate::attest_inputs::canon_gate_key(WRITE.canon_domain, &canon)
.and_then(|key| read_in(&WRITE, WRITE.inputs_ref, &key))
.map(|note| note.tokens)
.unwrap_or_default()
}
fn canon_key_of(tree: &str) -> Option<String> {
let canon = crate::attest_inputs::canonical_route(tree)?;
crate::attest_inputs::canon_gate_key(WRITE.canon_domain, &canon)
}
fn file_canon(tree: &str, tokens: &[String]) {
let Some(key) = canon_key_of(tree) else {
return;
};
let mut note = note_in(INPUTS_REF, &key);
note.add_tokens(tokens);
let _ = write_note_in(INPUTS_REF, &key, ¬e);
}
fn file_inputs(tree: &str, tokens: &[String]) {
if tokens.is_empty() {
return;
}
let Some(spec) = crate::attest_inputs::spec_at(tree) else {
file_canon(tree, tokens);
return;
};
for (gate, _) in &spec.gates {
let mine: Vec<String> = tokens
.iter()
.filter(|t| crate::gate_identity::base(t) == gate.as_str())
.cloned()
.collect();
if mine.is_empty() || !manifest_is_an_input(tree, &spec, gate) {
continue;
}
let Some(fp) = crate::attest_inputs::fingerprint(tree, &spec, gate) else {
continue;
};
let Some(key) = crate::attest_inputs::input_key(&WRITE.attest, gate, &fp) else {
continue;
};
let mut note = note_in(INPUTS_REF, &key);
note.add_tokens(&mine);
let _ = write_note_in(INPUTS_REF, &key, ¬e);
}
}
fn manifest_is_an_input(tree: &str, spec: &crate::attest_inputs::Spec, gate: &str) -> bool {
let tracked = [crate::manifest::MANIFEST, crate::names::old::MANIFEST]
.into_iter()
.find(|name| crate::git::succeeds(&["cat-file", "-e", &format!("{tree}:{name}")]));
tracked.map_or(true, |name| {
crate::attest_inputs::declares(spec, gate, name)
})
}
fn inputs_ref_exists() -> bool {
crate::git::succeeds(&[
"rev-parse",
"-q",
"--verify",
&format!("refs/notes/{}", WRITE.inputs_ref),
])
}
pub fn tree_tokens(tree: &str) -> Vec<String> {
let mut tokens = stamp_at(tree).tokens;
if inputs_ref_exists() {
for t in input_tokens(tree) {
if !tokens.contains(&t) {
tokens.push(t);
}
}
}
tokens
}
pub fn stamp_tree(tree: &str, tokens: &[String]) -> bool {
let mut note = note_at(tree);
note.add_tokens(tokens);
let ok = write_note(tree, ¬e);
file_inputs(tree, tokens);
ok
}
fn write_note(key: &str, note: &Note) -> bool {
write_note_in(NOTES_REF, key, note)
}
fn write_note_in(notes_ref: &str, key: &str, note: &Note) -> bool {
let body = note.render();
crate::git::succeeds(&["notes", "--ref", notes_ref, "add", "-f", "-m", &body, key])
}
pub fn record_runs(key: &str, runs: &[Run]) {
let runs: Vec<Run> = runs
.iter()
.filter(|r| !r.gate.is_empty() && !r.gate.contains(char::is_whitespace))
.cloned()
.collect();
if runs.is_empty() {
return;
}
let mut note = note_at(key);
note.add_runs(&runs);
let _ = write_note(key, ¬e);
}
pub fn record_deferred(tree: &str, gates: &[String]) {
let gates: Vec<&String> = gates
.iter()
.filter(|g| !g.is_empty() && !g.contains(char::is_whitespace))
.collect();
if gates.is_empty() {
return;
}
let mut note = note_at(tree);
for g in gates {
if !note.deferred.contains(g) {
note.deferred.push(g.clone());
}
}
let _ = write_note(tree, ¬e); }
pub fn deferred_on(tree: &str) -> Vec<String> {
stamp_at(tree).deferred
}
pub fn deferred_for(commits: &[String], gate: &str) -> HashSet<String> {
let mut out = HashSet::new();
if commits.is_empty() {
return out;
}
let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
args.extend(commits.iter().map(String::as_str));
let Some(list) = crate::git::stdout(&args) else {
return out;
};
for line in list.lines() {
let mut it = line.split_whitespace();
let (Some(commit), Some(tree)) = (it.next(), it.next()) else {
continue;
};
if [commit, tree]
.iter()
.any(|key| stamp_at(key).deferred.iter().any(|d| d == gate))
{
out.insert(commit.to_string());
}
}
out
}
fn marker_path() -> Option<PathBuf> {
let dir = crate::git::stdout(&["rev-parse", "--git-dir"])?;
Some(std::path::Path::new(&dir).join(MARKER))
}
pub fn record(scripts: &[&str]) {
let Some(path) = marker_path() else { return };
if scripts.is_empty() {
let _ = std::fs::remove_file(&path);
return;
}
let Some(tree) = crate::git::stdout(&["write-tree"]) else {
crate::hooks::common::warn(
"git would not name the staged tree — this commit records no gate stamp",
);
let _ = std::fs::remove_file(&path);
return;
};
let mut body = format!("{FORMAT}\n{tree}\n");
for s in scripts {
body.push_str(s);
body.push('\n');
}
let _ = std::fs::write(&path, body);
}
pub fn vouched_for_staged_tree() -> HashSet<String> {
let mut out = HashSet::new();
let Some(tree) = crate::git::stdout(&["write-tree"]) else {
return out;
};
if let Some(path) = marker_path() {
if let Ok(body) = std::fs::read_to_string(&path) {
let mut lines = body.lines();
if lines.next() == Some(FORMAT) && lines.next() == Some(tree.as_str()) {
out.extend(
lines
.filter(|l| !l.trim().is_empty() && !is_provenance(l))
.map(str::to_string),
);
}
}
}
out.extend(stamp_at(&tree).tokens);
if inputs_ref_exists() {
out.extend(input_tokens(&tree));
}
out
}
pub fn bind_to_head() -> Vec<String> {
let Some(path) = marker_path() else {
return Vec::new();
};
let Ok(body) = std::fs::read_to_string(&path) else {
return Vec::new(); };
let _ = std::fs::remove_file(&path);
let mut lines = body.lines();
if lines.next() != Some(FORMAT) {
return Vec::new();
}
let Some(tree) = lines.next() else {
return Vec::new();
};
let scripts: Vec<&str> = lines
.filter(|l| !l.trim().is_empty() && !is_provenance(l))
.collect();
if scripts.is_empty() {
return Vec::new();
}
let Some(head_tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
crate::hooks::common::warn(
"git would not name this commit's tree — no gate stamp was written",
);
return Vec::new();
};
if head_tree != tree {
return Vec::new();
}
let scripts: Vec<String> = scripts.iter().map(|s| s.to_string()).collect();
let mut tree_note = note_at(&head_tree);
tree_note.add_tokens(&scripts);
let _ = write_note(&head_tree, &tree_note);
file_inputs(&head_tree, &scripts);
let mut head_note = note_at("HEAD");
head_note.add_tokens(&scripts);
if !write_note("HEAD", &head_note) {
crate::hooks::common::warn(
"git refused to write the gate stamp — these checks will run again at push",
);
return Vec::new();
}
scripts
.iter()
.map(|s| crate::gate_identity::base(s).to_string())
.collect()
}
pub fn stamp_push(commit: &str, tree: &str, gates: &[String]) -> bool {
if gates.is_empty() {
return false;
}
let mut written = false;
for key in [tree, commit] {
let mut note = note_at(key);
note.add_tokens(gates);
let ok = write_note(key, ¬e);
if key == commit {
written = ok;
}
}
file_inputs(tree, gates);
if !written {
crate::hooks::common::warn(
"git refused to write the push stamp — these gates will run again on the next push",
);
}
written
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Completion {
Warned,
FailedUnderWarn,
Unavailable,
}
const UNAVAILABLE_FOR_SECS: u64 = 60 * 60;
fn completion_word(how: Completion, token: &str, now: u64) -> String {
match how {
Completion::Warned => format!("warned:{token}"),
Completion::FailedUnderWarn => format!("failed-under-warn:{token}"),
Completion::Unavailable => format!("unavailable:{now}:{token}"),
}
}
fn completion_answers(word: &str, token: &str, severity: crate::check::Severity, now: u64) -> bool {
if word.strip_prefix("warned:") == Some(token) {
return true;
}
if word.strip_prefix("failed-under-warn:") == Some(token) {
return severity == crate::check::Severity::Warn;
}
word.strip_prefix("unavailable:")
.and_then(|rest| rest.split_once(':'))
.is_some_and(|(at, tok)| {
tok == token
&& at
.parse::<u64>()
.is_ok_and(|at| now.saturating_sub(at) <= UNAVAILABLE_FOR_SECS)
})
}
fn now_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
pub fn record_done(tree: &str, tokens: &[String], how: Completion) -> Result<(), String> {
if tokens.is_empty() {
return Ok(());
}
let now = now_secs();
let mut note = note_in(DONE_REF, tree);
if how == Completion::Unavailable {
note.tokens.retain(|word| {
!word
.strip_prefix("unavailable:")
.and_then(|rest| rest.split_once(':'))
.is_some_and(|(_, token)| tokens.iter().any(|t| t == token))
});
}
let words: Vec<String> = tokens
.iter()
.map(|t| completion_word(how, t, now))
.collect();
note.add_tokens(&words);
if write_note_in(DONE_REF, tree, ¬e) {
Ok(())
} else {
Err(format!(
"git refused to record the completed gates on {tree}"
))
}
}
pub fn done_on_every(commits: &[String], token: &str, severity: crate::check::Severity) -> bool {
let now = now_secs();
!commits.is_empty()
&& commits.iter().all(|c| {
crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]).is_some_and(|tree| {
stamp_in(|s| s.done_ref, &tree)
.tokens
.iter()
.any(|word| completion_answers(word, token, severity, now))
})
})
}
pub fn stamps_for(commits: &[String]) -> HashMap<String, Vec<String>> {
let mut out = HashMap::new();
if commits.is_empty() {
return out;
}
let Some(list) = crate::git::stdout(&["notes", "--ref", WRITE.notes_ref, "list"]) else {
crate::hooks::common::warn(
"git would not list the gate stamps — every gated check will run again",
);
return out;
};
let noted: HashSet<&str> = list
.lines()
.filter_map(|l| l.split_whitespace().nth(1))
.collect();
let mut trees: HashMap<String, String> = HashMap::new();
{
let mut args: Vec<&str> = vec!["log", "--no-walk", "--format=%H %T"];
args.extend(commits.iter().map(String::as_str));
if let Some(out) = crate::git::stdout(&args) {
for line in out.lines() {
let mut it = line.split_whitespace();
if let (Some(c), Some(t)) = (it.next(), it.next()) {
trees.insert(c.to_string(), t.to_string());
}
}
}
}
let by_inputs = inputs_ref_exists();
for commit in commits {
let mut tokens: Vec<String> = Vec::new();
let mut keys: Vec<&str> = Vec::new();
if noted.contains(commit.as_str()) {
keys.push(commit);
}
if let Some(tree) = trees.get(commit).filter(|t| noted.contains(t.as_str())) {
keys.push(tree);
}
for key in keys {
for t in stamp_at(key).tokens {
if !tokens.contains(&t) {
tokens.push(t);
}
}
}
if by_inputs {
if let Some(tree) = trees.get(commit) {
for t in input_tokens(tree) {
if !tokens.contains(&t) {
tokens.push(t);
}
}
}
}
if tokens.is_empty() {
continue;
}
out.insert(commit.clone(), tokens);
}
out
}
pub fn forget() -> bool {
let marker = marker_path().is_some_and(|path| std::fs::remove_file(&path).is_ok());
let mut deleted = false;
for r in full_refs(&WRITE) {
deleted |= crate::git::succeeds(&["update-ref", "-d", &r]);
}
marker || deleted
}
fn full_refs(set: &GateNames) -> [String; 4] {
[set.notes_ref, set.inputs_ref, set.cluster_ref, set.done_ref]
.map(|short| format!("refs/notes/{short}"))
}
pub(crate) fn cluster_tokens(tree: &str) -> Vec<String> {
stamp_in(|s| s.cluster_ref, tree).tokens
}
pub(crate) fn stamp_cluster(tree: &str, token: &str, provenance: &str) -> bool {
let mut note = note_in(CLUSTER_REF, tree);
note.add_tokens(&[token.to_string()]);
let line = format!("{PROVENANCE} {token} {provenance}");
note.provenance
.retain(|l| l.split_whitespace().nth(1) != Some(token));
note.provenance.push(line);
write_note_in(CLUSTER_REF, tree, ¬e)
}
pub(crate) fn cluster_stamps_for(commits: &[String]) -> HashMap<String, (String, Vec<String>)> {
let mut out = HashMap::new();
for commit in commits {
let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")]) else {
continue;
};
let tokens = cluster_tokens(&tree);
if !tokens.is_empty() {
out.insert(commit.clone(), (tree, tokens));
}
}
out
}
pub fn forget_in(repo: &std::path::Path) -> bool {
let marker = crate::git::stdout_in(repo, &["rev-parse", "--absolute-git-dir"])
.is_some_and(|dir| std::fs::remove_file(std::path::Path::new(&dir).join(MARKER)).is_ok());
let mut deleted = false;
for r in full_refs(&WRITE) {
deleted |= crate::git::succeeds_in(repo, &["update-ref", "-d", &r]);
}
marker || deleted
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
#[test]
fn a_completion_answers_only_while_it_should() {
use crate::check::Severity::{Block, Warn};
let now = 1_700_000_000;
let word = |how| completion_word(how, "gate-tok", now);
assert!(completion_answers(
&word(Completion::Warned),
"gate-tok",
Block,
now
));
assert!(completion_answers(
&word(Completion::FailedUnderWarn),
"gate-tok",
Warn,
now
));
assert!(!completion_answers(
&word(Completion::FailedUnderWarn),
"gate-tok",
Block,
now
));
let unavailable = word(Completion::Unavailable);
assert!(completion_answers(
&unavailable,
"gate-tok",
Block,
now + 3600
));
assert!(!completion_answers(
&unavailable,
"gate-tok",
Block,
now + 3601
));
assert!(!completion_answers(
&word(Completion::Warned),
"other-tok",
Warn,
now
));
}
fn repo(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("gate-stamp-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
git(&dir, &["init", "-q", "--template=", "."]);
git(&dir, &["config", "user.email", "t@t.test"]);
git(&dir, &["config", "user.name", "t"]);
dir
}
fn git(dir: &Path, args: &[&str]) -> String {
let out = std::process::Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.expect("git");
assert!(
out.status.success(),
"fixture: git {args:?} in {} exited {:?}: {}",
dir.display(),
out.status.code(),
String::from_utf8_lossy(&out.stderr).trim()
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
let prev = std::env::current_dir().unwrap();
std::env::set_current_dir(dir).unwrap();
let r = f();
std::env::set_current_dir(prev).unwrap();
r
}
#[test]
fn the_commit_note_does_not_hide_the_tree_notes_push_tokens() {
let dir = repo("union");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
record(&["test"]);
git(&dir, &["commit", "-qm", "chore: a"]);
bind_to_head();
let head = git(&dir, &["rev-parse", "HEAD"]);
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
assert_eq!(note_at(&head).tokens, vec!["test".to_string()]);
let stamps = stamps_for(std::slice::from_ref(&head));
assert_eq!(
stamps.get(&head).map(Vec::as_slice),
Some(&["test".to_string(), "pre-push-cargo-test".to_string()][..]),
"both notes speak for the same tree"
);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_unavailable_record_replaces_its_predecessor_only() {
let dir = repo("done-unavailable");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
git(&dir, &["commit", "-qm", "chore: a"]);
in_repo(&dir, || {
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
let one = |t: &str| vec![t.to_string()];
record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("first");
record_done(&tree, &one("lint@b"), Completion::Unavailable).expect("other gate");
record_done(&tree, &one("lint@b"), Completion::Warned).expect("a warning");
record_done(&tree, &one("suite@a"), Completion::Unavailable).expect("again");
let words = note_in(DONE_REF, &tree).tokens;
let unavailable_for = |token: &str| {
words
.iter()
.filter(|w| w.starts_with("unavailable:") && w.ends_with(&format!(":{token}")))
.count()
};
assert_eq!(unavailable_for("suite@a"), 1, "{words:?}");
assert_eq!(unavailable_for("lint@b"), 1, "{words:?}");
assert!(words.contains(&"warned:lint@b".to_string()), "{words:?}");
});
let _ = std::fs::remove_dir_all(&dir); }
#[test]
fn a_commit_with_only_a_tree_note_still_reads_the_tree_tokens() {
let dir = repo("tree-only");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
git(&dir, &["commit", "-qm", "chore: a"]);
in_repo(&dir, || {
let head = git(&dir, &["rev-parse", "HEAD"]);
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
assert!(stamp_tree(&tree, &["pre-push-cargo-test".to_string()]));
let stamps = stamps_for(std::slice::from_ref(&head));
assert_eq!(
stamps.get(&head).map(Vec::as_slice),
Some(&["pre-push-cargo-test".to_string()][..])
);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_commit_with_only_a_commit_note_still_reads_its_tokens() {
let dir = repo("commit-only");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
git(&dir, &["commit", "-qm", "chore: a"]);
in_repo(&dir, || {
let head = git(&dir, &["rev-parse", "HEAD"]);
let mut note = Note::default();
note.add_tokens(&["typecheck".to_string()]);
assert!(write_note(&head, ¬e));
let stamps = stamps_for(std::slice::from_ref(&head));
assert_eq!(
stamps.get(&head).map(Vec::as_slice),
Some(&["typecheck".to_string()][..])
);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_token_on_both_notes_is_read_once() {
let dir = repo("dedup");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
record(&["test"]);
git(&dir, &["commit", "-qm", "chore: a"]);
bind_to_head(); let head = git(&dir, &["rev-parse", "HEAD"]);
let stamps = stamps_for(std::slice::from_ref(&head));
assert_eq!(
stamps.get(&head).map(Vec::as_slice),
Some(&["test".to_string()][..])
);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_recorded_marker_becomes_a_stamp_on_the_matching_commit() {
let dir = repo("roundtrip");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
record(&["typecheck", "test"]);
git(&dir, &["commit", "-qm", "chore: a"]);
let stamped = bind_to_head();
assert_eq!(
stamped,
vec!["typecheck".to_string(), "test".to_string()],
"bind_to_head reports the scripts it stamped"
);
let head = git(&dir, &["rev-parse", "HEAD"]);
let stamps = stamps_for(std::slice::from_ref(&head));
assert_eq!(
stamps.get(&head).map(Vec::as_slice),
Some(&["typecheck".to_string(), "test".to_string()][..])
);
assert!(!dir.join(".git").join(MARKER).exists());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_marker_for_a_different_tree_stamps_nothing() {
let dir = repo("stale");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
record(&["typecheck"]);
std::fs::write(dir.join("a.ts"), "y").unwrap();
git(&dir, &["add", "a.ts"]);
git(&dir, &["commit", "-qm", "chore: different"]);
assert!(
bind_to_head().is_empty(),
"bind_to_head reports nothing when the tree moved"
);
let head = git(&dir, &["rev-parse", "HEAD"]);
assert!(
stamps_for(&[head]).is_empty(),
"a stale marker must not vouch"
);
assert!(
!dir.join(".git").join(MARKER).exists(),
"consumed either way"
);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_empty_record_clears_a_previous_marker() {
let dir = repo("clears");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
record(&["typecheck"]);
assert!(dir.join(".git").join(MARKER).exists());
record(&[]);
assert!(!dir.join(".git").join(MARKER).exists());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_marker_in_an_unknown_format_stamps_nothing() {
let dir = repo("wrongformat");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
let tree = git(&dir, &["write-tree"]);
let marker = dir.join(".git").join(MARKER);
std::fs::write(&marker, format!("amont-gate-v99\n{tree}\ntypecheck\n")).unwrap();
git(&dir, &["commit", "-qm", "chore: a"]);
bind_to_head();
let head = git(&dir, &["rev-parse", "HEAD"]);
assert!(
stamps_for(std::slice::from_ref(&head)).is_empty(),
"an unknown format was trusted"
);
assert!(!marker.exists(), "consumed either way");
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_foreign_note_is_not_a_stamp() {
let dir = repo("foreignnote");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
git(&dir, &["commit", "-qm", "chore: a"]);
git(
&dir,
&[
"notes",
"--ref",
NOTES_REF,
"add",
"-m",
"typecheck test",
"HEAD",
],
);
let head = git(&dir, &["rev-parse", "HEAD"]);
assert!(
stamps_for(std::slice::from_ref(&head)).is_empty(),
"a note without the format token was trusted"
);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_repo_with_no_stamps_answers_emptily_rather_than_failing() {
let dir = repo("no-stamps");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
git(&dir, &["commit", "-qm", "chore: a"]);
in_repo(&dir, || {
assert_eq!(
crate::git::stdout(&["notes", "--ref", NOTES_REF, "list"]).as_deref(),
Some(""),
"an absent notes ref must be an ANSWER, not a failure — the \
no-stamps path and the git-is-broken path are told apart by it"
);
let head = git(&dir, &["rev-parse", "HEAD"]);
assert!(stamps_for(&[head]).is_empty());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_note_from_before_the_run_lines_parses_unchanged() {
let note = Note::parse("greengate-gate-v1 typecheck test");
assert_eq!(note.tokens, vec!["typecheck", "test"]);
assert!(note.runs.is_empty());
assert_eq!(note.render(), "greengate-gate-v1 typecheck test");
}
#[test]
fn run_lines_are_read_without_disturbing_the_tokens() {
let body = "greengate-gate-v1 pre-push-cargo-test\n\
run 1726900000 pre-push-cargo-test pass 412391\n\
run 1726903600 pre-push-audit-js fail 903\n";
let note = Note::parse(body);
assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
assert_eq!(note.runs.len(), 2);
assert_eq!(
note.runs[0],
Run {
at: 1_726_900_000,
gate: "pre-push-cargo-test".into(),
outcome: RunOutcome::Passed,
ms: 412_391,
}
);
assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
assert_eq!(note.render(), body.trim_end());
}
#[test]
fn an_unreadable_run_line_is_dropped_and_the_rest_survives() {
let note = Note::parse(
"greengate-gate-v1 test\n\
run 1726900000 pre-push-cargo-test pass 400\n\
run tomorrow pre-push-cargo-test pass 400\n\
run 1726900001 pre-push-cargo-test sideways 400\n\
banana\n\
run 1726900002 pre-push-cargo-test fail 500\n",
);
assert_eq!(note.tokens, vec!["test"]);
assert_eq!(note.runs.len(), 2, "{:?}", note.runs);
assert_eq!(note.runs[1].outcome, RunOutcome::Failed);
}
#[test]
fn a_deferral_is_never_a_token_and_outlives_the_run_trim() {
let mut note = Note::parse("greengate-gate-v1 lint\ndeferred cargo-test\n");
assert_eq!(note.tokens, vec!["lint"]);
assert_eq!(note.deferred, vec!["cargo-test"]);
let runs: Vec<Run> = (0..MAX_RUNS as u64 + 10)
.map(|i| Run {
at: 1_726_900_000 + i,
gate: "pre-push-audit-js".into(),
outcome: RunOutcome::Passed,
ms: 1,
})
.collect();
note.add_runs(&runs);
let again = Note::parse(¬e.render());
assert_eq!(again.runs.len(), MAX_RUNS);
assert_eq!(again.deferred, vec!["cargo-test"]);
assert_eq!(again.tokens, vec!["lint"]);
}
#[test]
fn a_foreign_note_yields_no_runs() {
let note = Note::parse("hello\nrun 1726900000 pre-push-cargo-test pass 400\n");
assert!(note.tokens.is_empty() && note.runs.is_empty());
}
#[test]
fn a_stamp_and_its_evidence_survive_each_other() {
let dir = repo("evidence");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
git(&dir, &["commit", "-qm", "chore: a"]);
let head = git(&dir, &["rev-parse", "HEAD"]);
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
record_runs(
&tree,
&[Run {
at: 1_726_900_000,
gate: "pre-push-cargo-test".into(),
outcome: RunOutcome::Failed,
ms: 412_391,
}],
);
assert!(stamp_push(&head, &tree, &["pre-push-cargo-test".into()]));
let note = note_at(&tree);
assert_eq!(note.tokens, vec!["pre-push-cargo-test"]);
assert_eq!(note.runs.len(), 1, "the evidence survived the stamp");
let stamps = stamps_for(std::slice::from_ref(&head));
assert_eq!(
stamps.get(&head).map(Vec::as_slice),
Some(&["pre-push-cargo-test".to_string()][..])
);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_recorded_run_is_not_a_stamp() {
let dir = repo("not-a-stamp");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
git(&dir, &["commit", "-qm", "chore: a"]);
let head = git(&dir, &["rev-parse", "HEAD"]);
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
record_runs(
&tree,
&[Run {
at: 1_726_900_000,
gate: "pre-push-cargo-test".into(),
outcome: RunOutcome::Passed,
ms: 412_391,
}],
);
assert!(
stamps_for(std::slice::from_ref(&head)).is_empty(),
"a run line vouched for a gate — evidence must never gate"
);
assert!(
!vouched_for_staged_tree().contains("pre-push-cargo-test"),
"a run line vouched at commit time"
);
let history = crate::gate_evidence::history_in(&dir);
assert_eq!(history.runs.len(), 1);
assert_eq!(history.runs[0].0, tree, "keyed by the content it ran on");
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn forget_removes_the_stamps() {
let dir = repo("forget");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
record(&["typecheck"]);
git(&dir, &["commit", "-qm", "chore: a"]);
bind_to_head();
let head = git(&dir, &["rev-parse", "HEAD"]);
assert!(!stamps_for(std::slice::from_ref(&head)).is_empty());
forget();
assert!(stamps_for(&[head]).is_empty());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_stamp_survives_a_commit_being_rewritten_with_the_same_tree() {
let dir = repo("squashed");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
record(&["test"]);
git(&dir, &["commit", "-qm", "feat: on a branch"]);
assert_eq!(bind_to_head(), vec!["test".to_string()]);
let branch_tip = git(&dir, &["rev-parse", "HEAD"]);
git(
&dir,
&[
"commit",
"-q",
"--amend",
"-m",
"feat: squashed by the forge",
],
);
let merged = git(&dir, &["rev-parse", "HEAD"]);
assert_ne!(merged, branch_tip, "the fixture must produce a new commit");
assert_eq!(
git(&dir, &["rev-parse", "HEAD^{tree}"]),
git(&dir, &["rev-parse", &format!("{branch_tip}^{{tree}}")]),
"…carrying the same tree, which is the whole premise"
);
let stamps = stamps_for(std::slice::from_ref(&merged));
assert_eq!(
stamps.get(&merged).map(Vec::as_slice),
Some(&["test".to_string()][..]),
"the stamp must follow the content, not the commit hash"
);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_different_tree_gets_no_stamp_from_the_fallback() {
let dir = repo("othertree");
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
in_repo(&dir, || {
record(&["test"]);
git(&dir, &["commit", "-qm", "chore: stamped"]);
assert_eq!(bind_to_head(), vec!["test".to_string()]);
std::fs::write(dir.join("b.ts"), "y").unwrap();
git(&dir, &["add", "b.ts"]);
git(&dir, &["commit", "-qm", "chore: unjudged"]);
let unstamped = git(&dir, &["rev-parse", "HEAD"]);
assert!(
stamps_for(std::slice::from_ref(&unstamped)).is_empty(),
"a tree nobody stamped must not inherit one"
);
});
let _ = std::fs::remove_dir_all(&dir);
}
fn declared(name: &str, spec: &str) -> PathBuf {
let dir = repo(name);
std::fs::create_dir_all(dir.join(".github")).unwrap();
std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
std::fs::write(dir.join("a.ts"), "x").unwrap();
std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
std::fs::write(dir.join(".github/greensummit-inputs"), spec).unwrap();
git(&dir, &["add", "-A"]);
in_repo(&dir, || {
record(&["test@abc"]);
git(&dir, &["commit", "-qm", "feat: judged"]);
assert_eq!(bind_to_head(), vec!["test".to_string()]);
});
dir
}
fn plan_only_commit(dir: &Path) -> String {
std::fs::write(dir.join("docs/plans/p.md"), "plan v2, closing").unwrap();
git(dir, &["add", "docs/plans/p.md"]);
git(dir, &["commit", "-qm", "docs(plan): done"]);
git(dir, &["rev-parse", "HEAD"])
}
#[test]
fn a_plan_only_commit_reuses_the_stamp_of_a_declared_gate() {
let dir = declared("plan-only", "test a.ts\n");
in_repo(&dir, || {
let head = plan_only_commit(&dir);
let stamps = stamps_for(std::slice::from_ref(&head));
assert_eq!(
stamps.get(&head).map(Vec::as_slice),
Some(&["test@abc".to_string()][..]),
"the closing commit changed the tree and none of the declared inputs"
);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_staged_tree_of_a_plan_only_commit_is_vouched_for() {
let dir = declared("staged", "test a.ts\n");
in_repo(&dir, || {
std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
git(&dir, &["add", "docs/plans/p.md"]);
assert!(vouched_for_staged_tree().contains("test@abc"));
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn partial_staging_is_judged_on_the_index_not_the_working_copy() {
let dir = declared("partial", "test a.ts\n");
in_repo(&dir, || {
std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
git(&dir, &["add", "docs/plans/p.md"]);
std::fs::write(dir.join("a.ts"), "unstaged edit").unwrap();
assert!(vouched_for_staged_tree().contains("test@abc"));
std::fs::write(dir.join("a.ts"), "staged edit").unwrap();
git(&dir, &["add", "a.ts"]);
std::fs::write(dir.join("a.ts"), "x").unwrap();
assert!(!vouched_for_staged_tree().contains("test@abc"));
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_changed_declared_input_misses() {
let dir = declared("input-changed", "test a.ts\n");
in_repo(&dir, || {
std::fs::write(dir.join("a.ts"), "changed").unwrap();
git(&dir, &["add", "a.ts"]);
git(&dir, &["commit", "-qm", "feat: unjudged"]);
let head = git(&dir, &["rev-parse", "HEAD"]);
assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_changed_declaration_misses() {
let dir = declared("declaration-changed", "test a.ts\n");
in_repo(&dir, || {
std::fs::write(dir.join("b.ts"), "y").unwrap();
std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts b.ts\n").unwrap();
git(&dir, &["add", "-A"]);
git(&dir, &["commit", "-qm", "chore: widen the declaration"]);
let head = git(&dir, &["rev-parse", "HEAD"]);
assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_declared_config_file_is_an_input_like_any_other() {
let dir = declared("config", "test a.ts amont.conf\n");
in_repo(&dir, || {
assert!(!inputs_ref_exists());
std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
git(&dir, &["add", "amont.conf"]);
record(&["test@abc"]);
git(&dir, &["commit", "-qm", "chore: config"]);
assert_eq!(bind_to_head(), vec!["test".to_string()]);
std::fs::write(dir.join("docs/plans/p.md"), "plan v2").unwrap();
git(&dir, &["add", "docs/plans/p.md"]);
git(&dir, &["commit", "-qm", "docs(plan): done"]);
let plan = git(&dir, &["rev-parse", "HEAD"]);
assert!(stamps_for(std::slice::from_ref(&plan)).contains_key(&plan));
std::fs::write(dir.join("amont.conf"), "scope = lib\n").unwrap();
git(&dir, &["add", "amont.conf"]);
git(&dir, &["commit", "-qm", "chore: scope-only change"]);
let scope = git(&dir, &["rev-parse", "HEAD"]);
assert!(
stamps_for(std::slice::from_ref(&scope)).is_empty(),
"a scope-only change must miss"
);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_declared_stamp_is_read_back_as_its_complete_token() {
let dir = declared("identity", "test a.ts\n");
in_repo(&dir, || {
let head = plan_only_commit(&dir);
let tokens = stamps_for(std::slice::from_ref(&head))
.remove(&head)
.unwrap_or_default();
assert_eq!(tokens, vec!["test@abc".to_string()]);
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
assert!(stamp_tree(&tree, &["test@def".to_string()]));
let tokens = tree_tokens(&tree);
assert!(tokens.contains(&"test@abc".to_string()));
assert!(tokens.contains(&"test@def".to_string()));
assert!(!tokens.contains(&"test@zzz".to_string()));
assert!(!tokens.contains(&"test".to_string()));
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_gate_that_does_not_declare_the_manifest_is_not_offered_the_route() {
let dir = repo("manifest-undeclared");
std::fs::create_dir_all(dir.join(".github")).unwrap();
std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
std::fs::write(dir.join("a.ts"), "x").unwrap();
std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
git(&dir, &["add", "-A"]);
in_repo(&dir, || {
record(&["test@abc"]);
git(&dir, &["commit", "-qm", "feat: judged"]);
bind_to_head();
assert!(!inputs_ref_exists(), "the route must not open");
let head = plan_only_commit(&dir);
assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_gate_declaring_the_manifest_opens_the_route() {
let dir = declared("manifest-declared", "test a.ts amont.conf\n");
in_repo(&dir, || {
std::fs::write(dir.join("amont.conf"), "scope = src\n").unwrap();
git(&dir, &["add", "amont.conf"]);
record(&["test@abc"]);
git(&dir, &["commit", "-qm", "chore: config"]);
bind_to_head();
assert!(inputs_ref_exists());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_undeclared_gate_keeps_whole_tree_behaviour() {
let dir = declared("undeclared", "test a.ts\n");
in_repo(&dir, || {
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
let head = plan_only_commit(&dir);
let tokens = stamps_for(std::slice::from_ref(&head))
.remove(&head)
.unwrap_or_default();
assert!(tokens.contains(&"test@abc".to_string()));
assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_invalid_or_ambiguous_spec_falls_back_to_whole_tree_behaviour() {
let dir = declared("invalid", "test src/*\n");
in_repo(&dir, || {
assert!(!inputs_ref_exists(), "no valid spec, nothing is filed");
let head = plan_only_commit(&dir);
assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
});
let _ = std::fs::remove_dir_all(&dir);
let dir = repo("ambiguous");
std::fs::create_dir_all(dir.join(".github")).unwrap();
std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
std::fs::write(dir.join("a.ts"), "x").unwrap();
std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
std::fs::write(dir.join(".forgejo/greensummit-inputs"), "test a.ts\n").unwrap();
git(&dir, &["add", "-A"]);
in_repo(&dir, || {
record(&["test@abc"]);
git(&dir, &["commit", "-qm", "feat: judged"]);
bind_to_head();
assert!(!inputs_ref_exists());
let head = plan_only_commit(&dir);
assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_gate_that_did_not_pass_leaves_no_declared_input_stamp() {
let dir = repo("failed");
std::fs::create_dir_all(dir.join(".github")).unwrap();
std::fs::write(dir.join("a.ts"), "x").unwrap();
std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
git(&dir, &["add", "-A"]);
in_repo(&dir, || {
record(&[]);
git(&dir, &["commit", "-qm", "feat: unjudged"]);
assert!(bind_to_head().is_empty());
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
let head = git(&dir, &["rev-parse", "HEAD"]);
assert!(!stamp_push(&head, &tree, &[]));
assert!(!inputs_ref_exists());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn stamp_tree_and_tree_tokens_use_the_inputs_ref() {
let dir = declared("rehearsal", "test a.ts\n");
in_repo(&dir, || {
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
assert!(stamp_tree(&tree, &["test@rehearsed".to_string()]));
plan_only_commit(&dir);
let later = git(&dir, &["rev-parse", "HEAD^{tree}"]);
assert_ne!(later, tree);
assert!(tree_tokens(&later).contains(&"test@rehearsed".to_string()));
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_inputs_ref_is_keyed_the_way_attest_keys_its_own() {
let dir = declared("key", "test a.ts\n");
in_repo(&dir, || {
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
let listed = git(&dir, &["notes", "--ref", INPUTS_REF, "list"]);
assert!(
listed
.lines()
.any(|l| l.split_whitespace().nth(1) == Some(key.as_str())),
"{listed}"
);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_foreign_token_in_the_inputs_ref_vouches_for_nothing() {
let dir = declared("foreign", "test a.ts\n");
in_repo(&dir, || {
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
let fp = crate::attest_inputs::fingerprint(&tree, &spec, &spec.gates[0].0).expect("fp");
let key = crate::attest_inputs::input_key(&WRITE.attest, "test", &fp).expect("key");
let mut note = note_in(INPUTS_REF, &key);
note.add_tokens(&["publish@evil".to_string()]);
assert!(write_note_in(INPUTS_REF, &key, ¬e));
assert!(!tree_tokens(&tree).contains(&"publish@evil".to_string()));
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn forget_removes_the_inputs_ref_too() {
let dir = declared("forget-inputs", "test a.ts\n");
in_repo(&dir, || {
assert!(inputs_ref_exists());
assert!(forget());
assert!(!inputs_ref_exists());
});
let _ = std::fs::remove_dir_all(&dir);
}
fn canonical(name: &str, conf: Option<&str>) -> PathBuf {
let dir = repo(name);
std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
std::fs::write(dir.join("a.ts"), "x").unwrap();
std::fs::write(dir.join("docs/plans/p.md"), "plan v1").unwrap();
if let Some(conf) = conf {
std::fs::write(dir.join("amont.conf"), conf).unwrap();
}
git(&dir, &["add", "-A"]);
in_repo(&dir, || {
record(&["test@abc"]);
git(&dir, &["commit", "-qm", "feat: judged"]);
assert_eq!(bind_to_head(), vec!["test".to_string()]);
});
dir
}
fn vouched(dir: &Path, commit: &str) -> Vec<String> {
in_repo(dir, || {
stamps_for(std::slice::from_ref(&commit.to_string()))
.remove(commit)
.unwrap_or_default()
})
}
#[test]
fn with_no_spec_a_plans_only_commit_is_vouched_for_canonically() {
let dir = canonical("canon-plan-edit", None);
in_repo(&dir, || {
assert!(inputs_ref_exists(), "the canonical stamp is filed");
let head = plan_only_commit(&dir);
assert_eq!(
stamps_for(std::slice::from_ref(&head))
.remove(&head)
.unwrap_or_default(),
vec!["test@abc".to_string()]
);
std::fs::write(dir.join("docs/plans/p.md"), "plan v3").unwrap();
git(&dir, &["add", "docs/plans/p.md"]);
assert!(vouched_for_staged_tree().contains("test@abc"));
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_plan_added_deleted_or_renamed_is_not_vouched_for() {
let dir = canonical("canon-plan-exists", None);
std::fs::write(dir.join("docs/plans/q.md"), "second plan").unwrap();
git(&dir, &["add", "docs/plans/q.md"]);
git(&dir, &["commit", "-qm", "docs(plan): add"]);
let added = git(&dir, &["rev-parse", "HEAD"]);
assert!(vouched(&dir, &added).is_empty(), "a plan added");
git(&dir, &["mv", "docs/plans/p.md", "docs/plans/r.md"]);
git(&dir, &["commit", "-qm", "docs(plan): rename"]);
let renamed = git(&dir, &["rev-parse", "HEAD"]);
assert!(vouched(&dir, &renamed).is_empty(), "a plan renamed");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn with_no_spec_any_other_change_is_not_vouched_for() {
let dir = canonical("canon-code-edit", Some("gate test = make test\n"));
std::fs::write(dir.join("a.ts"), "changed").unwrap();
git(&dir, &["commit", "-qam", "feat: code"]);
let code = git(&dir, &["rev-parse", "HEAD"]);
assert!(vouched(&dir, &code).is_empty(), "a source edit");
std::fs::write(dir.join("amont.conf"), "gate test = make other\n").unwrap();
git(&dir, &["commit", "-qam", "chore: config"]);
let conf = git(&dir, &["rev-parse", "HEAD"]);
assert!(vouched(&dir, &conf).is_empty(), "a manifest edit");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn plan_exempt_off_closes_the_canonical_route() {
for (name, conf) in [
("off", "set planExempt off\n"),
("spelled", "SET PLANEXEMPT\tOff\r\n"),
("after", "set planExempt on\nset planExempt off\n"),
] {
let dir = canonical(&format!("canon-off-{name}"), Some(conf));
in_repo(&dir, || {
assert!(!inputs_ref_exists(), "{name}: nothing is filed");
let head = plan_only_commit(&dir);
assert!(
stamps_for(std::slice::from_ref(&head)).is_empty(),
"{name}: a plans-only commit is a new tree"
);
});
let _ = std::fs::remove_dir_all(&dir);
}
for (name, conf) in [
("on", "set planExempt on\n"),
("comment", "set planExempt off # no\n"),
("commented", "# set planExempt off\n"),
] {
let dir = canonical(&format!("canon-on-{name}"), Some(conf));
let head = plan_only_commit(&dir);
assert!(!vouched(&dir, &head).is_empty(), "{name}: still canonical");
let _ = std::fs::remove_dir_all(&dir);
}
}
#[test]
fn a_spec_that_cannot_be_used_means_no_canonical_stamps() {
let dir = repo("canon-unreadable-spec");
std::fs::create_dir_all(dir.join(".github/greensummit-inputs")).unwrap();
std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
std::fs::write(dir.join(".github/greensummit-inputs/x"), "x").unwrap();
std::fs::write(dir.join("a.ts"), "x").unwrap();
std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
git(&dir, &["add", "-A"]);
in_repo(&dir, || {
record(&["test@abc"]);
git(&dir, &["commit", "-qm", "feat: judged"]);
bind_to_head();
assert!(!inputs_ref_exists(), "an unreadable spec opens nothing");
let head = plan_only_commit(&dir);
assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn two_specs_mean_no_canonical_stamps() {
let dir = repo("canon-ambiguous");
std::fs::create_dir_all(dir.join(".github")).unwrap();
std::fs::create_dir_all(dir.join(".forgejo")).unwrap();
std::fs::create_dir_all(dir.join("docs/plans")).unwrap();
std::fs::write(dir.join("a.ts"), "x").unwrap();
std::fs::write(dir.join("docs/plans/p.md"), "v1").unwrap();
std::fs::write(dir.join(".github/greensummit-inputs"), "test a.ts\n").unwrap();
std::fs::write(dir.join(".forgejo/greensummit-inputs"), "test a.ts\n").unwrap();
git(&dir, &["add", "-A"]);
in_repo(&dir, || {
record(&["test@abc"]);
git(&dir, &["commit", "-qm", "feat: judged"]);
bind_to_head();
assert!(!inputs_ref_exists());
let head = plan_only_commit(&dir);
assert!(stamps_for(std::slice::from_ref(&head)).is_empty());
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_valid_spec_keeps_precedence_over_the_canonical_route() {
let dir = declared("canon-precedence", "test a.ts\n");
in_repo(&dir, || {
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
assert!(stamp_tree(&tree, &["lint@zzz".to_string()]));
let head = plan_only_commit(&dir);
let tokens = stamps_for(std::slice::from_ref(&head))
.remove(&head)
.unwrap_or_default();
assert!(tokens.contains(&"test@abc".to_string()));
assert!(!tokens.iter().any(|t| t.starts_with("lint@")));
});
let _ = std::fs::remove_dir_all(&dir);
}
fn unstamped(name: &str) -> (PathBuf, String, String) {
let dir = repo(name);
std::fs::write(dir.join("a.ts"), "x").unwrap();
git(&dir, &["add", "a.ts"]);
git(&dir, &["commit", "-qm", "feat: a"]);
let head = git(&dir, &["rev-parse", "HEAD"]);
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
(dir, head, tree)
}
fn plant(dir: &Path, notes_ref: &str, key: &str, body: &str) {
git(
dir,
&["notes", "--ref", notes_ref, "add", "-f", "-m", body, key],
);
}
fn stamps_of(commit: &str) -> Vec<String> {
stamps_for(&[commit.to_string()])
.remove(commit)
.unwrap_or_default()
}
#[test]
fn a_pass_is_found_under_each_gate_ref() {
let set = &WRITE;
let (dir, head, tree) = unstamped("either-0");
plant(
&dir,
set.notes_ref,
&head,
&format!("{} test@c", set.format),
);
plant(
&dir,
set.notes_ref,
&tree,
&format!("{} test@t", set.format),
);
plant(
&dir,
set.cluster_ref,
&tree,
&format!("{} suite@k", set.format),
);
plant(
&dir,
set.done_ref,
&tree,
&format!("{} warned:lint@w", set.format),
);
in_repo(&dir, || {
let mut got = stamps_of(&head);
got.sort();
assert_eq!(got, ["test@c", "test@t"], "{}", set.notes_ref);
assert_eq!(tree_tokens(&tree), ["test@t"], "{}", set.notes_ref);
assert_eq!(cluster_tokens(&tree), ["suite@k"], "{}", set.cluster_ref);
assert!(
done_on_every(
std::slice::from_ref(&head),
"lint@w",
crate::check::Severity::Block
),
"{}",
set.done_ref
);
});
let _ = std::fs::remove_dir_all(&dir); }
const LEGACY: GateNames = GateNames {
format: "amont-gate-v1",
notes_ref: "amont-gate",
inputs_ref: "amont-gate-inputs",
cluster_ref: "amont-gate-cluster",
done_ref: "amont-gate-done",
canon_domain: "amont-gate-canon",
attest: greensummit::format::Names {
format: "amont-attest-v2",
notes_ref: "amont-attest",
inputs_ref: "amont-attest-inputs",
namespace: "amont-attest",
input_domain: "amont-attest-input",
canon_domain: "amont-attest-canon",
producer: "amont",
},
};
#[test]
fn a_stamp_under_the_old_names_is_not_read() {
let (dir, head, tree) = unstamped("old-refs");
for key in [&head, &tree] {
plant(
&dir,
LEGACY.notes_ref,
key,
&format!("{} test@old", LEGACY.format),
);
}
plant(
&dir,
LEGACY.cluster_ref,
&tree,
&format!("{} suite@old", LEGACY.format),
);
in_repo(&dir, || {
assert!(stamps_of(&head).is_empty());
assert!(tree_tokens(&tree).is_empty());
assert!(cluster_tokens(&tree).is_empty());
});
let _ = std::fs::remove_dir_all(&dir); }
#[test]
fn with_notes_under_both_refs_the_green_note_is_read() {
let (dir, head, tree) = unstamped("both-refs");
for key in [&head, &tree] {
plant(
&dir,
LEGACY.notes_ref,
key,
&format!("{} test@old", LEGACY.format),
);
plant(
&dir,
GREEN.notes_ref,
key,
&format!("{} test@new", GREEN.format),
);
}
plant(
&dir,
LEGACY.cluster_ref,
&tree,
&format!("{} suite@old", LEGACY.format),
);
plant(
&dir,
GREEN.cluster_ref,
&tree,
&format!("{} suite@new", GREEN.format),
);
in_repo(&dir, || {
assert_eq!(stamps_of(&head), ["test@new"]);
assert_eq!(tree_tokens(&tree), ["test@new"]);
assert_eq!(cluster_tokens(&tree), ["suite@new"]);
});
let _ = std::fs::remove_dir_all(&dir); }
#[test]
fn a_note_whose_header_is_the_other_sets_reads_as_unstamped() {
for (i, (sits_in, header_of)) in [(LEGACY, GREEN), (GREEN, LEGACY)].iter().enumerate() {
let (dir, head, tree) = unstamped(&format!("mixed-{i}"));
for key in [&head, &tree] {
plant(
&dir,
sits_in.notes_ref,
key,
&format!("{} test@x", header_of.format),
);
}
plant(
&dir,
sits_in.cluster_ref,
&tree,
&format!("{} suite@x", header_of.format),
);
in_repo(&dir, || {
assert!(stamps_of(&head).is_empty(), "{}", sits_in.notes_ref);
assert!(tree_tokens(&tree).is_empty(), "{}", sits_in.notes_ref);
assert!(cluster_tokens(&tree).is_empty(), "{}", sits_in.cluster_ref);
});
let _ = std::fs::remove_dir_all(&dir); }
}
#[test]
fn the_inputs_ref_is_read_under_its_own_key() {
let dir = declared("green-inputs", "test a.ts\n");
in_repo(&dir, || {
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
let spec = crate::attest_inputs::spec_at(&tree).expect("spec");
let fp = crate::attest_inputs::fingerprint(&tree, &spec, "test").expect("fp");
let green = crate::attest_inputs::input_key(&GREEN.attest, "test", &fp).expect("key");
let legacy = crate::attest_inputs::input_key(&LEGACY.attest, "test", &fp).expect("key");
assert_ne!(green, legacy, "each set keys with its own domain");
let head = plan_only_commit(&dir);
plant(
&dir,
GREEN.inputs_ref,
&legacy,
&format!("{} test@wrongkey", GREEN.format),
);
assert_eq!(stamps_of(&head), ["test@abc"]);
plant(
&dir,
GREEN.inputs_ref,
&green,
&format!("{} test@green", GREEN.format),
);
assert_eq!(stamps_of(&head), ["test@green"]);
});
let _ = std::fs::remove_dir_all(&dir); }
#[test]
fn a_green_canonical_note_is_read_under_the_green_domain() {
let dir = canonical("green-canon", None);
in_repo(&dir, || {
let tree = git(&dir, &["rev-parse", "HEAD^{tree}"]);
let canon = crate::attest_inputs::canonical_route(&tree).expect("canon");
let key =
crate::attest_inputs::canon_gate_key(GREEN.canon_domain, &canon).expect("key");
plant(
&dir,
GREEN.inputs_ref,
&key,
&format!("{} test@green", GREEN.format),
);
let head = plan_only_commit(&dir);
assert_eq!(stamps_of(&head), ["test@green"]);
});
let _ = std::fs::remove_dir_all(&dir); }
#[test]
fn history_reads_runs_under_the_written_names_only() {
let (dir, _head, tree) = unstamped("history-both");
let other = git(&dir, &["rev-parse", "HEAD"]);
plant(
&dir,
LEGACY.notes_ref,
&other,
&format!("{}\nrun 100 old-gate pass 7", LEGACY.format),
);
plant(
&dir,
GREEN.notes_ref,
&tree,
&format!("{}\nrun 200 new-gate pass 9", GREEN.format),
);
plant(
&dir,
GREEN.notes_ref,
&other,
&format!("{}\nrun 300 mixed-gate pass 1", LEGACY.format),
);
let history = crate::gate_evidence::history_in(&dir);
let mut got: Vec<(String, String)> = history
.runs
.iter()
.map(|(k, r)| (k.clone(), r.gate.clone()))
.collect();
got.sort();
assert_eq!(got, [(tree, "new-gate".to_string())]);
let _ = std::fs::remove_dir_all(&dir); }
#[test]
fn forget_removes_the_written_refs() {
let (dir, _head, tree) = unstamped("forget-written");
plant(
&dir,
GREEN.notes_ref,
&tree,
&format!("{} test@g", GREEN.format),
);
plant(&dir, WRITE.done_ref, &tree, "done");
in_repo(&dir, || {
assert_eq!(tree_tokens(&tree).len(), 1);
assert!(forget());
assert!(tree_tokens(&tree).is_empty(), "{:?}", tree_tokens(&tree));
});
for r in full_refs(&WRITE) {
let out = std::process::Command::new("git")
.args(["-C"])
.arg(&dir)
.args(["rev-parse", "--verify", "-q", &r])
.output()
.unwrap();
assert!(!out.status.success(), "{r} survived forget");
}
let _ = std::fs::remove_dir_all(&dir); }
#[test]
fn writes_go_under_the_green_names_and_each_full_ref_names_its_ref() {
assert_eq!(WRITE, GREEN);
assert_eq!(FORMAT, "greengate-gate-v1");
for (full, short) in [
(NOTES_FULL_REF, NOTES_REF),
(INPUTS_FULL_REF, INPUTS_REF),
(CLUSTER_FULL_REF, CLUSTER_REF),
(DONE_FULL_REF, DONE_REF),
] {
assert_eq!(full, format!("refs/notes/{short}"));
assert!(full.starts_with("refs/notes/greengate-gate"), "{full}");
}
let (dir, head, tree) = unstamped("write-green");
plant(
&dir,
LEGACY.notes_ref,
&tree,
&format!("{} test@old", LEGACY.format),
);
in_repo(&dir, || {
assert!(stamp_push(&head, &tree, &["suite@p".to_string()]));
let written = git(&dir, &["notes", "--ref", GREEN.notes_ref, "show", &tree]);
assert_eq!(written, format!("{} suite@p", GREEN.format));
let old = git(&dir, &["notes", "--ref", LEGACY.notes_ref, "show", &tree]);
assert_eq!(old, format!("{} test@old", LEGACY.format));
});
let _ = std::fs::remove_dir_all(&dir); }
}