1use std::time::Duration;
18
19use crate::check::Stage;
20use crate::manifest::{External, Kind, Manifest};
21
22use super::{
23 key, last_line, log_line, machine_keys, run_label, sanitize_repo_dir, token_from, Call,
24 ClusterConfig, Fallback, Kube, CALL_SECS, SEQ,
25};
26use crate::json_read::Value;
27
28mod collect;
29mod pending;
30mod workflow;
31
32pub use collect::collect_command;
33pub(crate) use collect::{collect, settled_lines, status_lines, stop_pending};
34
35use pending::{Gate, GateState, Pending, PendingError, RecordPhase, Source, Store};
36
37const REHEARSE_CLUSTER: &str = "amont.rehearse.cluster";
39const PUSH_SECS: u64 = 60;
42const LS_REMOTE_SECS: u64 = 20;
43const LOCK_WAIT: Duration = Duration::from_secs(5);
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum Ask {
49 Flag,
51 Setting,
54}
55
56pub fn wanted(settings: &crate::config::Settings, ask: Ask) -> bool {
59 ask == Ask::Flag || crate::config::boolean_or(settings, REHEARSE_CLUSTER, false)
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Default)]
64pub struct Detached {
65 pub gates: Vec<String>,
66}
67
68#[cfg(feature = "test-hooks")]
71fn crash_point(at: &str) {
72 if std::env::var("AMONT_TEST_CRASH").is_ok_and(|v| v == at) {
73 std::process::exit(137);
74 }
75}
76
77#[cfg(not(feature = "test-hooks"))]
78fn crash_point(_at: &str) {}
79
80struct Machine {
82 base: ClusterConfig,
83 snapshot_remote: String,
84 snapshot_fetch: String,
85 mirror: Option<Mirror>,
86}
87
88struct Mirror {
91 remote: String,
92 fetch: String,
93}
94
95fn machine(settings: &crate::config::Settings) -> Result<Machine, Fallback> {
96 let base = super::cluster_config(settings)?;
97 let keys = machine_keys();
98 let need = |name: &'static str, shown: &'static str| {
99 key(&keys, name)
100 .map(str::to_string)
101 .ok_or(Fallback::Unconfigured(shown))
102 };
103 let snapshot_remote = need(
104 "amont.cluster.snapshotremote",
105 "amont.cluster.snapshotRemote is not set: `git config --global amont.cluster.snapshotRemote 'git@host:org/{repo}.git'`",
106 )?;
107 let snapshot_fetch = need(
108 "amont.cluster.snapshotfetch",
109 "amont.cluster.snapshotFetch is not set: `git config --global amont.cluster.snapshotFetch 'http://forgejo-http.forgejo.svc.cluster.local:3000/org/{repo}.git'`",
110 )?;
111 let mirror = match (
112 key(&keys, "amont.cluster.mirrorremote"),
113 key(&keys, "amont.cluster.mirror"),
114 ) {
115 (Some(remote), Some(fetch)) => Some(Mirror {
116 remote: remote.to_string(),
117 fetch: fetch.to_string(),
118 }),
119 _ => None,
120 };
121 Ok(Machine {
122 base,
123 snapshot_remote,
124 snapshot_fetch,
125 mirror,
126 })
127}
128
129fn repo_name() -> Result<String, String> {
132 let url = crate::git::stdout(&["remote", "get-url", "origin"])
133 .ok_or("the repository has no origin remote to name it by")?;
134 let last = url
135 .trim_end_matches('/')
136 .rsplit(['/', ':'])
137 .next()
138 .unwrap_or_default();
139 if last.is_empty() {
140 return Err(format!("cannot name the repository from {url:?}"));
141 }
142 Ok(sanitize_repo_dir(last))
143}
144
145fn expand(template: &str, repo: &str) -> String {
146 template.replace("{repo}", repo)
147}
148
149fn eligible<'a>(
153 settings: &crate::config::Settings,
154 manifest: &'a Manifest,
155 scoped: &[String],
156) -> Vec<&'a External> {
157 if !super::executor_is_cluster(settings) {
158 return Vec::new();
159 }
160 scoped
161 .iter()
162 .filter_map(|name| {
163 manifest
164 .externals
165 .iter()
166 .find(|e| e.stage == Stage::PrePush && e.id == *name)
167 })
168 .filter(|e| super::is_platform_any(e))
169 .collect()
170}
171
172fn known_for(tree: &str) -> (Vec<String>, Vec<String>) {
181 let Some(store) = Store::here() else {
182 return (Vec::new(), Vec::new());
183 };
184 let records = match store.read() {
185 Ok(records) => records,
186 Err(why) => {
187 log_line("detach", &format!("cluster-pending is unreadable: {why}"));
188 return (Vec::new(), Vec::new());
189 }
190 };
191 let ours = records.iter().filter(|r| r.tree == tree);
192 let waiting = ours
193 .clone()
194 .flat_map(|r| r.waiting().map(|g| g.id.clone()))
195 .collect();
196 let all = ours
197 .flat_map(|r| r.gates.iter().map(|g| g.id.clone()))
198 .collect();
199 (waiting, all)
200}
201
202pub fn detach(
211 settings: &crate::config::Settings,
212 manifest: &Manifest,
213 scoped: &[String],
214 ask: Ask,
215) -> Detached {
216 let Some(tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
217 return Detached::default();
218 };
219 let (waiting, known) = known_for(&tree);
220 let mut riding: Vec<String> = scoped
221 .iter()
222 .filter(|gate| waiting.contains(gate))
223 .cloned()
224 .collect();
225 if !wanted(settings, ask) {
226 return Detached { gates: riding };
227 }
228 let fresh: Vec<&External> = eligible(settings, manifest, scoped)
229 .into_iter()
230 .filter(|e| !known.contains(&e.id))
231 .collect();
232 if fresh.is_empty() {
233 if ask == Ask::Flag {
234 if riding.is_empty() {
235 eprintln!(
236 "no gate of this rehearsal can go to the cluster: it needs a trusted \
237 `platform=any` pre-push gate and `set executor cluster`"
238 );
239 } else {
240 eprintln!("already on the cluster: {}", riding.join(" "));
241 }
242 }
243 return Detached { gates: riding };
244 }
245 match submit(settings, &tree, &fresh) {
246 Ok(submitted) => {
247 eprintln!(
248 "submitted {} to the cluster: {} — the next commit or push collects the result",
249 submitted.name,
250 submitted.gates.join(" ")
251 );
252 riding.extend(submitted.gates);
253 }
254 Err(error) => {
255 let (line, spoken) = error.render();
256 for e in &fresh {
257 log_line(&e.id, &format!("detached: {line}"));
258 }
259 if ask == Ask::Flag {
260 crate::hooks::common::warn(&crate::ui::sanitize(&spoken));
261 }
262 }
263 }
264 Detached { gates: riding }
265}
266
267#[derive(Debug)]
269enum SubmitError {
270 NotSubmitted(Fallback),
272 Unconfirmed(String),
275}
276
277impl From<Fallback> for SubmitError {
278 fn from(f: Fallback) -> SubmitError {
279 SubmitError::NotSubmitted(f)
280 }
281}
282
283impl SubmitError {
284 fn render(&self) -> (String, String) {
286 match self {
287 SubmitError::NotSubmitted(Fallback::Misconfigured { why, fix }) => (
288 why.clone(),
289 format!("not submitted to the cluster, the gates run here: {why} — fix with {fix}"),
290 ),
291 SubmitError::NotSubmitted(f) => (
292 f.to_string(),
293 format!("not submitted to the cluster, the gates run here: {f}"),
294 ),
295 SubmitError::Unconfirmed(why) => (
296 format!("not confirmed: {why}"),
297 format!(
298 "submitted, not confirmed ({why}); the gates also run here, and the next \
299 commit or push collects the Workflow if it landed"
300 ),
301 ),
302 }
303 }
304}
305
306struct Submitted {
308 name: String,
309 gates: Vec<String>,
310}
311
312struct Origin {
314 source: Source,
315 url: String,
316}
317
318fn submit(
319 settings: &crate::config::Settings,
320 tree: &str,
321 gates: &[&External],
322) -> Result<Submitted, SubmitError> {
323 let machine = machine(settings)?;
324 let head = crate::git::stdout(&["rev-parse", "HEAD"])
325 .ok_or_else(|| Fallback::NotProved("git would not name HEAD".into()))?;
326 let repo = repo_name().map_err(Fallback::NotProved)?;
327 let label = run_label(SEQ.fetch_add(1, std::sync::atomic::Ordering::SeqCst));
328 let frozen = freeze(settings, &machine, gates)?;
329 let origin = choose_origin(&machine, &repo, &head, tree, &label)?;
330 let record = Pending {
331 name: workflow::workflow_name(&label),
332 uid: None,
333 label,
334 namespace: machine.base.namespace.clone(),
335 kubeconfig: machine.base.kubeconfig.clone(),
336 tree: tree.to_string(),
337 source: origin.source,
338 submitted: crate::gate_evidence::now(),
339 phase: RecordPhase::Submitting,
340 gates: frozen,
341 };
342 let store = Store::here()
343 .ok_or_else(|| Fallback::NotProved("git would not name the common directory".into()))?;
344 record_intent(&store, &record)?;
345 crash_point("before-create");
346 let plan = workflow::Plan {
347 config: &machine.base,
348 record: &record,
349 repo_dir: &super::repo_dir(),
350 url: &origin.url,
351 };
352 let kube = Kube::new(&machine.base);
353 let uid = create(&kube, &record, &workflow::workflow_json(&plan))?;
354 crash_point("after-create");
355 adopt(&store, &record.name, &uid)?;
356 Ok(Submitted {
357 name: record.name,
358 gates: record.gates.into_iter().map(|g| g.id).collect(),
359 })
360}
361
362fn freeze(
366 settings: &crate::config::Settings,
367 machine: &Machine,
368 gates: &[&External],
369) -> Result<Vec<Gate>, Fallback> {
370 let keys = machine_keys();
371 gates
372 .iter()
373 .enumerate()
374 .map(|(i, ext)| {
375 let Kind::Runnable {
376 program,
377 args,
378 scope,
379 ..
380 } = &ext.kind
381 else {
382 return Err(Fallback::NotProved(format!("{} is not runnable", ext.id)));
383 };
384 let token = token_from(&keys, settings, ext, &ext.id).ok_or_else(|| {
385 Fallback::NotProved(format!("git would not hash the identity of {}", ext.id))
386 })?;
387 let mut argv = vec![program.clone()];
388 argv.extend(args.iter().cloned());
389 Ok(Gate {
390 id: ext.id.clone(),
391 task: format!("g{i}"),
392 argv,
393 scope: format!("{scope:?}"),
394 prepare: machine.base.prepare.clone(),
395 digest: machine.base.digest.clone(),
396 contract: crate::gate_identity::CLUSTER_CONTRACT.to_string(),
397 token,
398 state: GateState::Waiting,
399 })
400 })
401 .collect()
402}
403
404fn choose_origin(
407 machine: &Machine,
408 repo: &str,
409 head: &str,
410 tree: &str,
411 label: &str,
412) -> Result<Origin, Fallback> {
413 if let Some(mirror) = &machine.mirror {
414 match advertised(&expand(&mirror.remote, repo)) {
415 Ok(oids) if oids.iter().any(|o| o == head) => {
416 return Ok(Origin {
417 source: Source {
418 snapshot_ref: None,
419 oid: head.to_string(),
420 },
421 url: expand(&mirror.fetch, repo),
422 })
423 }
424 Ok(_) => {}
425 Err(why) => log_line("detach", &format!("mirror not listed: {why}")),
426 }
427 }
428 let oid = snapshot_commit(head, tree, label)?;
429 let snapshot_ref = format!("refs/snapshots/{label}");
430 let remote = expand(&machine.snapshot_remote, repo);
431 push_snapshot(&remote, &oid, &snapshot_ref)?;
432 let seen = advertised_at(&remote, &snapshot_ref)
433 .map_err(|why| Fallback::NotProved(format!("the snapshot was not read back: {why}")))?;
434 if seen.as_deref() != Some(oid.as_str()) {
435 return Err(Fallback::NotProved(
436 "the snapshot was pushed but not read back from the remote".into(),
437 ));
438 }
439 Ok(Origin {
440 source: Source {
441 snapshot_ref: Some(snapshot_ref),
442 oid,
443 },
444 url: expand(&machine.snapshot_fetch, repo),
445 })
446}
447
448fn advertised(remote: &str) -> Result<Vec<String>, String> {
451 let (probe, out) = crate::git::probe_remote_stdout(
452 &["ls-remote", remote, "refs/heads/*", "refs/tags/*"],
453 LS_REMOTE_SECS,
454 );
455 match probe {
456 crate::git::Probe::Exit(0) => Ok(out
457 .lines()
458 .filter_map(|l| l.split_whitespace().next())
459 .map(str::to_string)
460 .collect()),
461 other => Err(format!("git ls-remote {remote}: {other:?}")),
462 }
463}
464
465fn advertised_at(remote: &str, ref_name: &str) -> Result<Option<String>, String> {
467 let (probe, out) =
468 crate::git::probe_remote_stdout(&["ls-remote", remote, ref_name], LS_REMOTE_SECS);
469 match probe {
470 crate::git::Probe::Exit(0) => Ok(out
471 .lines()
472 .filter_map(|l| l.split_once('\t'))
473 .find(|(_, name)| *name == ref_name)
474 .map(|(oid, _)| oid.trim().to_string())),
475 other => Err(format!("git ls-remote {remote}: {other:?}")),
476 }
477}
478
479fn snapshot_commit(head: &str, tree: &str, label: &str) -> Result<String, Fallback> {
483 let now = format!("@{} +0000", crate::gate_evidence::now());
484 let out = std::process::Command::new("git")
485 .args(["commit-tree", tree, "-p", head, "-m"])
486 .arg(format!("amont snapshot {label}"))
487 .env("GIT_AUTHOR_NAME", "amont")
488 .env("GIT_AUTHOR_EMAIL", "amont@localhost")
489 .env("GIT_COMMITTER_NAME", "amont")
490 .env("GIT_COMMITTER_EMAIL", "amont@localhost")
491 .env("GIT_AUTHOR_DATE", &now)
492 .env("GIT_COMMITTER_DATE", &now)
493 .stdin(std::process::Stdio::null())
494 .output()
495 .map_err(|e| Fallback::NotProved(format!("git commit-tree: {e}")))?;
496 let oid = String::from_utf8_lossy(&out.stdout).trim().to_string();
497 if out.status.success() && !oid.is_empty() {
498 Ok(oid)
499 } else {
500 Err(Fallback::NotProved("git commit-tree failed".into()))
501 }
502}
503
504fn push_snapshot(remote: &str, oid: &str, ref_name: &str) -> Result<(), Fallback> {
508 let (mut args, mut env) = crate::git::remote_env(crate::git::configured_ssh());
509 env.push((crate::attest::PUSH_GUARD, "1"));
510 let refspec = format!("{oid}:{ref_name}");
511 args.extend(["push", "-q", remote, &refspec]);
512 match crate::git::probe_env(&args, PUSH_SECS, &env) {
513 crate::git::Probe::Exit(0) => Ok(()),
514 other => Err(Fallback::NotProved(format!(
515 "git push of the snapshot to {remote}: {other:?}"
516 ))),
517 }
518}
519
520fn record_intent(store: &Store, record: &Pending) -> Result<(), Fallback> {
525 let not = |why: PendingError| Fallback::NotProved(format!("cluster-pending: {why}"));
526 let held = store.lock_within(LOCK_WAIT).ok_or_else(|| {
527 Fallback::NotProved("cluster-pending: busy, or no flock on this platform".into())
528 })?;
529 let mut records = store.read().map_err(not)?;
530 if let Some(taken) = holder_of(&records, record) {
531 return Err(Fallback::NotProved(format!(
532 "another submission of this tree already holds {taken}"
533 )));
534 }
535 records.push(record.clone());
536 store.write(&held, &records).map_err(not)
537}
538
539fn holder_of(records: &[Pending], record: &Pending) -> Option<String> {
541 records
542 .iter()
543 .filter(|other| other.tree == record.tree)
544 .flat_map(|other| other.gates.iter())
545 .find(|held| record.gates.iter().any(|g| g.id == held.id))
546 .map(|held| held.id.clone())
547}
548
549fn adopt(store: &Store, name: &str, uid: &str) -> Result<(), SubmitError> {
552 let not = |why: String| {
553 SubmitError::Unconfirmed(format!(
554 "the Workflow exists but its UID was not recorded: {why}"
555 ))
556 };
557 let held = store
558 .lock_within(LOCK_WAIT)
559 .ok_or_else(|| not("cluster-pending is busy".into()))?;
560 let records: Vec<Pending> = store
561 .read()
562 .map_err(|e| not(e.to_string()))?
563 .into_iter()
564 .map(|mut r| {
565 if r.name == name && r.uid.is_none() {
566 r.uid = Some(uid.to_string());
567 r.phase = RecordPhase::Pending;
568 }
569 r
570 })
571 .collect();
572 store.write(&held, &records).map_err(|e| not(e.to_string()))
573}
574
575#[derive(Debug, PartialEq, Eq)]
577enum Created {
578 Made(String),
580 Taken,
582 Rejected(String),
584 NotSent(String),
586 Unknown(String),
588}
589
590fn classify(call: Call) -> Created {
591 match call {
592 Call::Ok(uid) if !uid.trim().is_empty() => Created::Made(uid.trim().to_string()),
593 Call::Ok(_) => Created::Unknown("kubectl create printed no UID".into()),
594 Call::Refused(err) if err.contains("AlreadyExists") || err.contains("already exists") => {
595 Created::Taken
596 }
597 Call::Refused(err) if err.contains("Error from server") => {
600 Created::Rejected(last_line(&err))
601 }
602 Call::Refused(err) | Call::TimedOut(err) => Created::Unknown(last_line(&err)),
603 Call::NotStarted(err) => Created::NotSent(err),
604 }
605}
606
607#[derive(Debug, PartialEq, Eq)]
609enum Uncertain {
610 Taken,
612 Lost(String),
614}
615
616fn create(kube: &Kube, record: &Pending, json: &str) -> Result<String, SubmitError> {
620 let file = ManifestFile::write(&record.label, json)?;
621 let path = file.path.to_string_lossy().into_owned();
622 let args = ["create", "-f", &path, "-o", "jsonpath={.metadata.uid}"];
623 let outcome = classify(kube.capture(&args, CALL_SECS));
624 drop(file);
625 match outcome {
626 Created::Made(uid) => Ok(uid),
627 Created::Rejected(why) => {
628 forget(record);
629 Err(Fallback::NotProved(format!("the cluster refused it: {why}")).into())
630 }
631 Created::NotSent(why) => {
632 forget(record);
633 Err(Fallback::Unreachable(why).into())
634 }
635 Created::Taken => reconcile(kube, record, Uncertain::Taken),
636 Created::Unknown(why) => reconcile(kube, record, Uncertain::Lost(why)),
637 }
638}
639
640fn reconcile(kube: &Kube, record: &Pending, uncertain: Uncertain) -> Result<String, SubmitError> {
643 let said = match uncertain {
644 Uncertain::Lost(why) => why,
645 Uncertain::Taken => "the name was taken".to_string(),
646 };
647 match kube.capture(&["get", "workflow", &record.name, "-o", "json"], CALL_SECS) {
648 Call::Ok(json) => {
649 let wf = crate::json_read::parse(&json).ok_or_else(|| {
650 SubmitError::Unconfirmed("the Workflow found by name is not JSON".into())
651 })?;
652 let uid = wf
653 .get("metadata")
654 .and_then(|m| m.get("uid"))
655 .and_then(Value::as_str)
656 .ok_or_else(|| SubmitError::Unconfirmed("the Workflow found has no UID".into()))?;
657 match workflow::check_workflow(&wf, record) {
658 Ok(()) => Ok(uid.to_string()),
659 Err(why) => {
660 forget(record);
661 Err(Fallback::NotProved(format!(
662 "a Workflow named {} exists and is not the one submitted: {why}",
663 record.name
664 ))
665 .into())
666 }
667 }
668 }
669 Call::Refused(err) if err.contains("NotFound") => Err(SubmitError::Unconfirmed(format!(
673 "the cluster did not show the Workflow ({said}); the intent is kept"
674 ))),
675 Call::Refused(err) | Call::NotStarted(err) | Call::TimedOut(err) => {
676 Err(SubmitError::Unconfirmed(format!(
677 "the Workflow could not be looked up ({said}; {})",
678 last_line(&err)
679 )))
680 }
681 }
682}
683
684fn forget(record: &Pending) {
687 let Some(store) = Store::here() else { return };
688 let Some(held) = store.lock_within(LOCK_WAIT) else {
689 log_line(
690 "detach",
691 &format!("could not drop the intent of {}", record.name),
692 );
693 return;
694 };
695 let kept: Result<Vec<Pending>, PendingError> = store
696 .read()
697 .map(|rs| rs.into_iter().filter(|r| r.name != record.name).collect());
698 let written = kept.and_then(|rs| store.write(&held, &rs));
699 if let Err(why) = written {
700 log_line(
701 "detach",
702 &format!("could not drop the intent of {}: {why}", record.name),
703 );
704 }
705}
706
707struct ManifestFile {
713 path: std::path::PathBuf,
714}
715
716impl ManifestFile {
717 fn write(label: &str, json: &str) -> Result<ManifestFile, Fallback> {
718 let path = std::env::temp_dir().join(format!("amont-workflow-{label}.json"));
719 let mut options = std::fs::OpenOptions::new();
720 options.write(true).create_new(true);
721 #[cfg(unix)]
722 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
723 options
724 .open(&path)
725 .and_then(|mut f| std::io::Write::write_all(&mut f, json.as_bytes()))
726 .map_err(|e| Fallback::NotProved(format!("manifest file: {e}")))?;
727 super::track_temp_file(&path);
728 Ok(ManifestFile { path })
729 }
730}
731
732impl Drop for ManifestFile {
733 fn drop(&mut self) {
734 super::untrack_temp_file(&self.path);
735 if let Err(e) = std::fs::remove_file(&self.path) {
736 crate::hooks::common::warn(&format!("could not remove {}: {e}", self.path.display()));
737 }
738 }
739}
740
741#[cfg(test)]
742mod tests {
743 use super::*;
744
745 #[test]
746 fn a_repository_is_named_by_its_origin() {
747 for (url, name) in [
749 ("git@git.example:org/relais.git", "relais"),
750 (
751 "https://github.com/o/duro-design-system",
752 "duro-design-system",
753 ),
754 ("/tmp/x/remote.git/", "remote"),
755 ] {
756 let last = url
757 .trim_end_matches('/')
758 .rsplit(['/', ':'])
759 .next()
760 .unwrap_or_default();
761 assert_eq!(sanitize_repo_dir(last), name, "{url}");
762 }
763 assert_eq!(
764 expand("git@h:amont-snapshots/{repo}.git", "relais"),
765 "git@h:amont-snapshots/relais.git"
766 );
767 }
768
769 #[test]
770 fn a_create_is_only_repeated_never() {
771 let made = classify(Call::Ok("uid-1\n".into()));
772 assert_eq!(made, Created::Made("uid-1".into()));
773 assert_eq!(
774 classify(Call::Refused(
775 "Error from server (AlreadyExists): workflows.argoproj.io \"x\" already exists"
776 .into()
777 )),
778 Created::Taken
779 );
780 assert!(matches!(
782 classify(Call::Refused(
783 "Error from server (Forbidden): workflows is forbidden".into()
784 )),
785 Created::Rejected(_)
786 ));
787 assert!(matches!(
789 classify(Call::Refused("error: unexpected EOF".into())),
790 Created::Unknown(_)
791 ));
792 assert!(matches!(
793 classify(Call::TimedOut("kubectl timed out".into())),
794 Created::Unknown(_)
795 ));
796 assert!(matches!(
797 classify(Call::Ok(String::new())),
798 Created::Unknown(_)
799 ));
800 assert!(matches!(
801 classify(Call::NotStarted("kubectl: not found".into())),
802 Created::NotSent(_)
803 ));
804 }
805
806 #[test]
807 fn a_second_submission_of_a_tree_cannot_take_a_gate_already_held() {
808 let held = super::pending::tests::sample("wf-1");
809 let mut other = super::pending::tests::sample("wf-2");
810 assert_eq!(
811 holder_of(std::slice::from_ref(&held), &other),
812 Some("pre-push-lint".to_string())
813 );
814 other.tree = "0".repeat(40);
815 assert_eq!(holder_of(&[held], &other), None, "another tree");
816 }
817
818 #[cfg(unix)]
821 #[test]
822 fn record_intent_refuses_a_gate_a_record_of_the_tree_holds() {
823 let dir = std::env::temp_dir().join(format!("amont-intent-{}", std::process::id()));
824 std::fs::create_dir_all(&dir).expect("mkdir");
825 let store = Store::in_dir(&dir);
826 let first = super::pending::tests::sample("wf-1");
827 assert!(record_intent(&store, &first).is_ok());
828 let second = super::pending::tests::sample("wf-2");
829 let refused = record_intent(&store, &second).expect_err("held");
830 assert!(
831 refused.to_string().contains("already holds pre-push-lint"),
832 "{refused}"
833 );
834 assert_eq!(store.read().expect("read").len(), 1);
835 std::fs::remove_dir_all(&dir).expect("clean");
836 }
837}