interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-proof / src / gate.rs

1453 lines · 52973 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Gate manifests: small declarative descriptions of what closes a gate.
17//!
18//! The evidence system never decides architectural policy. It evaluates a
19//! checked in manifest against stored receipts and reports exactly which
20//! prerequisite is responsible for PASS, FAIL, BLOCKED, or INCOMPLETE.
21
22use serde::{Deserialize, Serialize};
23use std::collections::BTreeSet;
24use std::path::Path;
25
26use crate::chain::tier_satisfies;
27use crate::evidence::{list_receipts, load_receipt, Tier, Verdict};
28
29/// Subdirectory of the proof store holding gate manifests.
30pub const GATE_DIR: &str = "gates";
31
32/// One prerequisite inside a gate manifest.
33#[derive(Debug, Clone, Serialize, Deserialize)]
34#[serde(deny_unknown_fields)]
35pub struct Requirement {
36 /// Human label used in status output, for example `SEED-0B-QEMU`.
37 pub name: String,
38 /// Receipt kind that satisfies this requirement, for example `m3`.
39 pub kind: String,
40 /// Optional nested gate requirement. When set, `kind` must be empty.
41 #[serde(default)]
42 pub gate_ref: Option<String>,
43 /// Exact physical resource required for hardware evidence and its hold.
44 #[serde(default)]
45 pub resource: Option<String>,
46 /// Exact repository identity when the prerequisite belongs to another repo.
47 #[serde(default)]
48 pub repo: Option<String>,
49 /// Exact machine/resource identity for non-hardware tiers.
50 #[serde(default)]
51 pub machine: Option<String>,
52 /// Required substring in the procedure identity, often carrying the test script version.
53 #[serde(default)]
54 pub procedure_contains: Option<String>,
55 /// Minimum count of input artifact digests required on the receipt.
56 #[serde(default)]
57 pub min_input_artifacts: usize,
58 /// Required receipt kinds reachable through this receipt's verified chain.
59 #[serde(default)]
60 pub dependency_kinds: Vec<String>,
61 /// Minimum qualification tier. A QEMU receipt never satisfies a
62 /// Machine 1 requirement.
63 #[serde(default = "default_tier")]
64 pub min_tier: Tier,
65 /// Assertion IDs that must exist and pass on the chosen receipt.
66 #[serde(default)]
67 pub assertions: Vec<String>,
68 /// Optional source constraints for assertions whose origin matters.
69 #[serde(default)]
70 pub assertion_sources: Vec<AssertionSource>,
71 /// Exact mutation class required from the receipt, when specified.
72 #[serde(default)]
73 pub mutation: Option<crate::evidence::Mutation>,
74 /// When true, the satisfying receipt must come from a clean tree.
75 #[serde(default)]
76 pub require_clean: bool,
77 /// Status used when no satisfying receipt, or a required assertion on
78 /// it, exists in the store.
79 #[serde(default)]
80 pub missing_as: MissingAs,
81 /// Named external condition behind a known BLOCKED prerequisite.
82 #[serde(default)]
83 pub missing_reason: Option<String>,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(deny_unknown_fields)]
88pub struct AssertionSource {
89 pub id: String,
90 pub source: String,
91}
92
93/// Status reported when required proof is absent from the store.
94/// BLOCKED names a known prerequisite that prevents the run from proceeding
95/// legally or procedurally, for example the owner trust chain.
96/// INCOMPLETE names proof that is simply absent so far.
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
98pub enum MissingAs {
99 #[serde(rename = "BLOCKED")]
100 #[default]
101 Blocked,
102 #[serde(rename = "INCOMPLETE")]
103 Incomplete,
104}
105
106impl MissingAs {
107 fn verdict(self) -> Verdict {
108 match self {
109 MissingAs::Blocked => Verdict::Blocked,
110 MissingAs::Incomplete => Verdict::Incomplete,
111 }
112 }
113}
114
115fn default_tier() -> Tier {
116 Tier::HostTest
117}
118
119/// A named gate: the set of prerequisites that close it.
120#[derive(Debug, Clone, Serialize, Deserialize)]
121#[serde(deny_unknown_fields)]
122pub struct Gate {
123 pub gate: String,
124 #[serde(default)]
125 pub description: String,
126 pub requires: Vec<Requirement>,
127}
128
129impl Gate {
130 /// Reject malformed manifests at load: unnamed or duplicated
131 /// requirements, requirements naming both or neither of gate and kind,
132 /// and source constraints on assertions the manifest never requires.
133 pub fn validate(&self) -> Result<(), String> {
134 if self.gate.trim().is_empty() {
135 return Err("gate manifest has no gate name".to_string());
136 }
137 let mut names = BTreeSet::new();
138 for req in &self.requires {
139 if req.name.trim().is_empty() {
140 return Err(format!("gate {} has an unnamed requirement", self.gate));
141 }
142 if req
143 .gate_ref
144 .as_ref()
145 .is_some_and(|name| name.trim().is_empty())
146 {
147 return Err(format!(
148 "gate {} requirement {:?} has an empty gate reference",
149 self.gate, req.name
150 ));
151 }
152 if !names.insert(req.name.clone()) {
153 return Err(format!(
154 "gate {} lists requirement {:?} twice",
155 self.gate, req.name
156 ));
157 }
158 match (&req.gate_ref, req.kind.trim().is_empty()) {
159 (Some(_), false) => {
160 return Err(format!(
161 "gate {} requirement {:?} names both a gate and a receipt kind",
162 self.gate, req.name
163 ));
164 }
165 (None, true) => {
166 return Err(format!(
167 "gate {} requirement {:?} names neither a gate nor a receipt kind",
168 self.gate, req.name
169 ));
170 }
171 _ => {}
172 }
173 for constrained in &req.assertion_sources {
174 if !req.assertions.iter().any(|a| a == &constrained.id) {
175 return Err(format!(
176 "gate {} requirement {:?} constrains source of assertion {:?} it never requires",
177 self.gate, req.name, constrained.id
178 ));
179 }
180 }
181 if req.gate_ref.is_some() && !req.dependency_kinds.is_empty() {
182 return Err(format!(
183 "gate {} nested gate requirement {:?} cannot declare receipt dependency kinds",
184 self.gate, req.name
185 ));
186 }
187 }
188 Ok(())
189 }
190}
191
192/// Per requirement outcome.
193#[derive(Debug, Clone)]
194pub struct GateLine {
195 pub name: String,
196 pub status: Verdict,
197 pub detail: String,
198}
199
200/// Whole gate outcome plus the responsible prerequisite lines.
201#[derive(Debug, Clone)]
202pub struct GateReport {
203 pub gate: String,
204 pub status: Verdict,
205 pub lines: Vec<GateLine>,
206}
207
208fn worse(a: Verdict, b: Verdict) -> Verdict {
209 fn rank(v: Verdict) -> u8 {
210 match v {
211 Verdict::Fail => 0,
212 Verdict::Blocked => 1,
213 Verdict::Incomplete => 2,
214 Verdict::Skipped => 3,
215 Verdict::Pass => 4,
216 }
217 }
218 if rank(a) <= rank(b) {
219 a
220 } else {
221 b
222 }
223}
224
225/// Pick the best stored receipt of `kind`: PASS first, then highest tier.
226pub fn best_candidate(store: &Path, kind: &str) -> Option<crate::evidence::Receipt> {
227 let mut best: Option<crate::evidence::Receipt> = None;
228 for id in list_receipts(store) {
229 let receipt = load_receipt(store, &id).ok()?;
230 if receipt.kind != kind {
231 continue;
232 }
233 let take = match &best {
234 None => true,
235 Some(current) => {
236 let rank = |r: &crate::evidence::Receipt| {
237 (r.result == Verdict::Pass, r.tier.rank(), r.timestamp)
238 };
239 rank(&receipt) > rank(current)
240 }
241 };
242 if take {
243 best = Some(receipt);
244 }
245 }
246 best
247}
248
249/// Evaluate one requirement against the store.
250fn eval_requirement(store: &Path, req: &Requirement, stack: &mut Vec<String>) -> GateLine {
251 if let Some(child_name) = &req.gate_ref {
252 if !req.kind.is_empty() {
253 return GateLine {
254 name: req.name.clone(),
255 status: Verdict::Fail,
256 detail: "manifest requirement cannot name both a gate and receipt kind".into(),
257 };
258 }
259 if stack.contains(child_name) {
260 return GateLine {
261 name: req.name.clone(),
262 status: Verdict::Fail,
263 detail: format!("gate dependency cycle through {child_name}"),
264 };
265 }
266 let child = match load_manifest(store, child_name, None) {
267 Ok(g) => g,
268 Err(e) => {
269 return GateLine {
270 name: req.name.clone(),
271 status: Verdict::Blocked,
272 detail: format!("BLOCKED {child_name}: {e}"),
273 }
274 }
275 };
276 stack.push(child_name.clone());
277 let report = evaluate_inner(&child, store, stack);
278 stack.pop();
279 let summary = report
280 .lines
281 .iter()
282 .filter(|l| l.status != Verdict::Pass)
283 .map(|l| format!("{}: {}", l.name, l.detail))
284 .collect::<Vec<_>>()
285 .join("; ");
286 let summary = if summary.is_empty() {
287 format!("all {} requirements PASS", report.lines.len())
288 } else {
289 summary
290 };
291 return GateLine {
292 name: req.name.clone(),
293 status: report.status,
294 detail: format!("{}: {} ({})", child_name, report.status.as_str(), summary),
295 };
296 }
297 if req.kind.is_empty() {
298 return GateLine {
299 name: req.name.clone(),
300 status: Verdict::Fail,
301 detail: "manifest requirement has neither gate_ref nor receipt kind".into(),
302 };
303 }
304 let receipt = match best_candidate(store, &req.kind) {
305 None => {
306 let detail = req.missing_reason.as_ref().map_or_else(
307 || format!("MISSING: no receipt of kind {:?} in store", req.kind),
308 |reason| format!("MISSING: {reason}"),
309 );
310 return GateLine {
311 name: req.name.clone(),
312 status: req.missing_as.verdict(),
313 detail,
314 };
315 }
316 Some(r) => r,
317 };
318 if receipt.result != Verdict::Pass {
319 return GateLine {
320 name: req.name.clone(),
321 status: receipt.result,
322 detail: format!(
323 "{}: receipt {} records {}",
324 req.kind,
325 &receipt.id[..16],
326 receipt.result.as_str()
327 ),
328 };
329 }
330 if !tier_satisfies(req.min_tier, receipt.tier) {
331 return GateLine {
332 name: req.name.clone(),
333 status: Verdict::Blocked,
334 detail: format!(
335 "{}: receipt tier {} cannot satisfy required {}",
336 req.kind,
337 receipt.tier.as_str(),
338 req.min_tier.as_str()
339 ),
340 };
341 }
342 if let Some(resource) = &req.resource {
343 if receipt.machine != *resource
344 || receipt
345 .lease
346 .as_ref()
347 .is_none_or(|lease| lease.resource != *resource)
348 {
349 return GateLine {
350 name: req.name.clone(),
351 status: Verdict::Incomplete,
352 detail: format!(
353 "{}: receipt and exclusive hold must bind resource {:?}",
354 req.kind, resource
355 ),
356 };
357 }
358 }
359 if req.repo.as_ref().is_some_and(|repo| receipt.repo != *repo) {
360 return GateLine {
361 name: req.name.clone(),
362 status: Verdict::Fail,
363 detail: format!(
364 "{}: repository identity does not match required {:?}",
365 req.kind,
366 req.repo.as_deref().unwrap_or_default()
367 ),
368 };
369 }
370 if req
371 .machine
372 .as_ref()
373 .is_some_and(|machine| receipt.machine != *machine)
374 {
375 return GateLine {
376 name: req.name.clone(),
377 status: Verdict::Fail,
378 detail: format!(
379 "{}: machine identity does not match required {:?}",
380 req.kind,
381 req.machine.as_deref().unwrap_or_default()
382 ),
383 };
384 }
385 if req
386 .procedure_contains
387 .as_ref()
388 .is_some_and(|needle| !receipt.procedure.contains(needle))
389 {
390 return GateLine {
391 name: req.name.clone(),
392 status: Verdict::Fail,
393 detail: format!(
394 "{}: procedure identity must include {:?}",
395 req.kind,
396 req.procedure_contains.as_deref().unwrap_or_default()
397 ),
398 };
399 }
400 if receipt.input_artifacts.len() < req.min_input_artifacts {
401 return GateLine {
402 name: req.name.clone(),
403 status: req.missing_as.verdict(),
404 detail: format!(
405 "{}: requires at least {} input artifact digests, receipt has {}",
406 req.kind,
407 req.min_input_artifacts,
408 receipt.input_artifacts.len()
409 ),
410 };
411 }
412 if req.require_clean && receipt.dirty {
413 return GateLine {
414 name: req.name.clone(),
415 status: Verdict::Blocked,
416 detail: format!(
417 "{}: gate requires a clean source tree but receipt {} is dirty",
418 req.kind,
419 &receipt.id[..16]
420 ),
421 };
422 }
423 let mut assertion_problems = Vec::new();
424 let mut assertion_status = Verdict::Pass;
425 for wanted in &req.assertions {
426 match receipt.assertions.iter().find(|a| &a.id == wanted) {
427 Some(a) if a.pass => {}
428 Some(_) => {
429 assertion_status = Verdict::Fail;
430 assertion_problems.push(format!("assertion {wanted:?} failed"));
431 }
432 None => {
433 if assertion_status != Verdict::Fail {
434 assertion_status = req.missing_as.verdict();
435 }
436 assertion_problems.push(format!("assertion {wanted:?} missing"));
437 }
438 }
439 }
440 for wanted in &req.assertion_sources {
441 match receipt.assertions.iter().find(|a| a.id == wanted.id) {
442 Some(a) if a.pass && a.source == wanted.source => {}
443 Some(a) if !a.pass => {
444 assertion_status = Verdict::Fail;
445 assertion_problems.push(format!("assertion {:?} failed", wanted.id));
446 }
447 Some(a) => {
448 assertion_status = Verdict::Fail;
449 assertion_problems.push(format!(
450 "assertion {:?} source {:?} does not match required {:?}",
451 wanted.id, a.source, wanted.source
452 ));
453 }
454 None => {
455 if assertion_status != Verdict::Fail {
456 assertion_status = req.missing_as.verdict();
457 }
458 assertion_problems.push(format!("assertion {:?} missing", wanted.id));
459 }
460 }
461 }
462 if !assertion_problems.is_empty() {
463 return GateLine {
464 name: req.name.clone(),
465 status: assertion_status,
466 detail: format!("{}: {}", req.kind, assertion_problems.join("; ")),
467 };
468 }
469 if let Some(mutation) = req.mutation {
470 if receipt.declared_mutation != mutation || receipt.observed_mutation != mutation {
471 return GateLine {
472 name: req.name.clone(),
473 status: Verdict::Fail,
474 detail: format!(
475 "{}: declared/observed mutation must both be {}",
476 req.kind,
477 mutation.as_str()
478 ),
479 };
480 }
481 }
482 if receipt.tier.is_hardware() {
483 match crate::lease::lease_status(&receipt, store) {
484 Some(r) if r.status != Verdict::Pass => {
485 return GateLine {
486 name: req.name.clone(),
487 status: if r.status == Verdict::Fail {
488 Verdict::Fail
489 } else {
490 Verdict::Blocked
491 },
492 detail: format!("{}: {}", req.kind, r.reasons.join("; ")),
493 };
494 }
495 _ => {}
496 }
497 }
498 let chain_path = store
499 .join(crate::evidence::RECEIPT_DIR)
500 .join(format!("{}.json", receipt.id));
501 match crate::chain::verify_chain(&chain_path, store) {
502 Ok(chain) if chain.status == Verdict::Pass => {}
503 Ok(chain) => {
504 return GateLine {
505 name: req.name.clone(),
506 status: chain.status,
507 detail: format!(
508 "{}: receipt dependency chain {}: {}",
509 req.kind,
510 chain.status.as_str(),
511 chain.reasons.join("; ")
512 ),
513 };
514 }
515 Err(e) => {
516 return GateLine {
517 name: req.name.clone(),
518 status: Verdict::Incomplete,
519 detail: format!("{}: cannot verify receipt dependency chain: {e}", req.kind),
520 };
521 }
522 }
523 if !req.dependency_kinds.is_empty() {
524 let chain = match crate::chain::verify_chain(&chain_path, store) {
525 Ok(chain) => chain,
526 Err(e) => {
527 return GateLine {
528 name: req.name.clone(),
529 status: Verdict::Incomplete,
530 detail: format!("{}: cannot resolve receipt dependencies: {e}", req.kind),
531 }
532 }
533 };
534 let missing: Vec<&str> = req
535 .dependency_kinds
536 .iter()
537 .filter(|kind| !chain.lines.iter().any(|line| &line.kind == *kind))
538 .map(String::as_str)
539 .collect();
540 if !missing.is_empty() {
541 return GateLine {
542 name: req.name.clone(),
543 status: req.missing_as.verdict(),
544 detail: format!(
545 "{}: required receipt dependency kinds missing from verified chain: {}",
546 req.kind,
547 missing.join(", ")
548 ),
549 };
550 }
551 }
552 GateLine {
553 name: req.name.clone(),
554 status: Verdict::Pass,
555 detail: format!(
556 "{}: receipt {} tier {}",
557 req.kind,
558 &receipt.id[..16],
559 receipt.tier.as_str()
560 ),
561 }
562}
563
564/// Evaluate a gate manifest against the store.
565pub fn evaluate(manifest: &Gate, store: &Path) -> GateReport {
566 evaluate_inner(manifest, store, &mut vec![manifest.gate.clone()])
567}
568
569fn evaluate_inner(manifest: &Gate, store: &Path, stack: &mut Vec<String>) -> GateReport {
570 let mut status = Verdict::Pass;
571 let mut lines = Vec::new();
572 for req in &manifest.requires {
573 let line = eval_requirement(store, req, stack);
574 status = worse(status, line.status);
575 lines.push(line);
576 }
577 // No requirements means nothing is proven.
578 if manifest.requires.is_empty() {
579 status = Verdict::Incomplete;
580 }
581 GateReport {
582 gate: manifest.gate.clone(),
583 status,
584 lines,
585 }
586}
587
588/// Load a manifest by gate name: explicit path first, then the store's
589/// gate directory.
590pub fn load_manifest(store: &Path, gate: &str, explicit: Option<&Path>) -> Result<Gate, String> {
591 if let Some(path) = explicit {
592 let text =
593 std::fs::read_to_string(path).map_err(|e| format!("cannot read gate file: {e}"))?;
594 let manifest: Gate =
595 serde_json::from_str(&text).map_err(|e| format!("gate manifest invalid: {e}"))?;
596 if manifest.gate != gate {
597 return Err(format!(
598 "gate manifest name {:?} does not match requested {gate:?}",
599 manifest.gate
600 ));
601 }
602 manifest.validate()?;
603 return Ok(manifest);
604 }
605 let text = if let Some(text) = embedded_manifest(gate) {
606 text.to_string()
607 } else {
608 let path = store.join(GATE_DIR).join(format!("{gate}.json"));
609 std::fs::read_to_string(&path)
610 .map_err(|_| format!("no manifest for gate {gate:?}: pass --gate <file>"))?
611 };
612 let manifest: Gate =
613 serde_json::from_str(&text).map_err(|e| format!("gate manifest invalid: {e}"))?;
614 if manifest.gate != gate {
615 return Err(format!(
616 "gate manifest name {:?} does not match requested {gate:?}",
617 manifest.gate
618 ));
619 }
620 manifest.validate()?;
621 Ok(manifest)
622}
623
624/// Built in example manifests. These are examples of the manifest shape,
625/// not claims that any gate has passed.
626pub const SEED_0B_EXAMPLE: &str = include_str!("../gates/SEED-0B.json");
627pub const SEED_0B_QEMU: &str = include_str!("../gates/SEED0B_QEMU.json");
628pub const STORE_V1_FORMAT_PR_MERGE: &str = include_str!("../gates/STORE_V1_FORMAT_PR_MERGE.json");
629pub const P3_STORE_QEMU: &str = include_str!("../gates/P3_STORE_QEMU.json");
630pub const P3_STORE_MACHINE1: &str = include_str!("../gates/P3_STORE_MACHINE1.json");
631pub const P3_DEVELOPMENT_QEMU_ENTRY: &str = include_str!("../gates/P3_DEVELOPMENT_QEMU_ENTRY.json");
632pub const P3_MACHINE1_WRITE_ENTRY: &str = include_str!("../gates/P3_MACHINE1_WRITE_ENTRY.json");
633pub const STORE_V1_FORMAT: &str = include_str!("../gates/STORE_V1_FORMAT.json");
634pub const STORE_V1_HOST: &str = include_str!("../gates/STORE_V1_HOST.json");
635pub const STORE_V1_QEMU: &str = include_str!("../gates/STORE_V1_QEMU.json");
636
637fn embedded_manifest(gate: &str) -> Option<&'static str> {
638 match gate {
639 "SEED-0B" => Some(SEED_0B_EXAMPLE),
640 "SEED0B_QEMU" => Some(SEED_0B_QEMU),
641 "STORE_V1_FORMAT_PR_MERGE" => Some(STORE_V1_FORMAT_PR_MERGE),
642 "P3_STORE_QEMU" => Some(P3_STORE_QEMU),
643 "P3_STORE_MACHINE1" => Some(P3_STORE_MACHINE1),
644 "P3_DEVELOPMENT_QEMU_ENTRY" => Some(P3_DEVELOPMENT_QEMU_ENTRY),
645 "P3_MACHINE1_WRITE_ENTRY" => Some(P3_MACHINE1_WRITE_ENTRY),
646 "STORE_V1_FORMAT" => Some(STORE_V1_FORMAT),
647 "STORE_V1_HOST" => Some(STORE_V1_HOST),
648 "STORE_V1_QEMU" => Some(STORE_V1_QEMU),
649 _ => None,
650 }
651}
652
653/// Materialize the example manifests into a directory.
654pub fn write_examples(dir: &Path) -> Result<Vec<std::path::PathBuf>, String> {
655 std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
656 let mut out = Vec::new();
657 for (name, text) in [
658 ("SEED-0B.json", SEED_0B_EXAMPLE),
659 ("SEED0B_QEMU.json", SEED_0B_QEMU),
660 ("STORE_V1_FORMAT_PR_MERGE.json", STORE_V1_FORMAT_PR_MERGE),
661 ("P3_STORE_QEMU.json", P3_STORE_QEMU),
662 ("P3_STORE_MACHINE1.json", P3_STORE_MACHINE1),
663 ("P3_DEVELOPMENT_QEMU_ENTRY.json", P3_DEVELOPMENT_QEMU_ENTRY),
664 ("P3_MACHINE1_WRITE_ENTRY.json", P3_MACHINE1_WRITE_ENTRY),
665 ("STORE_V1_FORMAT.json", STORE_V1_FORMAT),
666 ("STORE_V1_HOST.json", STORE_V1_HOST),
667 ("STORE_V1_QEMU.json", STORE_V1_QEMU),
668 ] {
669 // Validate the shipped shape before writing.
670 let manifest: Gate =
671 serde_json::from_str(text).map_err(|e| format!("built in manifest broken: {e}"))?;
672 manifest
673 .validate()
674 .map_err(|e| format!("built in manifest invalid: {e}"))?;
675 let path = dir.join(name);
676 std::fs::write(&path, text).map_err(|e| e.to_string())?;
677 out.push(path);
678 }
679 Ok(out)
680}
681
682#[cfg(test)]
683mod tests {
684 use super::*;
685 use crate::evidence::fixtures::{sample, sealed};
686 use crate::evidence::store_receipt;
687
688 fn store_qemu(store: &Path, kind: &str, assertions: Vec<&str>) {
689 let mut r = sample();
690 r.kind = kind.to_string();
691 let ids = if assertions.is_empty() {
692 vec!["recorded"]
693 } else {
694 assertions
695 };
696 r.assertions = ids
697 .into_iter()
698 .map(|id| crate::evidence::Assertion {
699 id: id.to_string(),
700 expected: "yes".to_string(),
701 observed: "yes".to_string(),
702 pass: true,
703 source: "example".to_string(),
704 note: String::new(),
705 })
706 .collect();
707 store_receipt(store, &sealed(r)).unwrap();
708 }
709
710 fn manifest() -> Gate {
711 Gate {
712 gate: "SEED-0B".to_string(),
713 description: "example".to_string(),
714 requires: vec![
715 Requirement {
716 name: "M3".to_string(),
717 kind: "m3".to_string(),
718 gate_ref: None,
719 resource: None,
720 repo: None,
721 machine: None,
722 procedure_contains: None,
723 min_input_artifacts: 0,
724 dependency_kinds: vec![],
725 min_tier: Tier::HostTest,
726 assertions: vec![],
727 assertion_sources: vec![],
728 mutation: None,
729 require_clean: false,
730 missing_as: MissingAs::Blocked,
731 missing_reason: None,
732 },
733 Requirement {
734 name: "SEED-0B-QEMU".to_string(),
735 kind: "seed-0b-qemu".to_string(),
736 gate_ref: None,
737 resource: None,
738 repo: None,
739 machine: None,
740 procedure_contains: None,
741 min_input_artifacts: 0,
742 dependency_kinds: vec![],
743 min_tier: Tier::Qemu,
744 assertions: vec!["artifact_signature_valid".to_string()],
745 assertion_sources: vec![],
746 mutation: None,
747 require_clean: true,
748 missing_as: MissingAs::Blocked,
749 missing_reason: None,
750 },
751 Requirement {
752 name: "SEED-0B-MACHINE1".to_string(),
753 kind: "seed-0b-machine1".to_string(),
754 gate_ref: None,
755 resource: None,
756 repo: None,
757 machine: None,
758 procedure_contains: None,
759 min_input_artifacts: 0,
760 dependency_kinds: vec![],
761 min_tier: Tier::Machine1Attended,
762 assertions: vec![],
763 assertion_sources: vec![],
764 mutation: None,
765 require_clean: true,
766 missing_as: MissingAs::Blocked,
767 missing_reason: None,
768 },
769 ],
770 }
771 }
772
773 #[test]
774 fn gate_reports_missing() {
775 let store = crate::testutil::temp_dir("gate-missing");
776 let report = evaluate(&manifest(), &store);
777 assert_eq!(report.status, Verdict::Blocked);
778 assert!(report.lines.iter().all(|l| l.status == Verdict::Blocked));
779 assert!(report.lines[0].detail.contains("MISSING"));
780 }
781
782 #[test]
783 fn qemu_receipt_cannot_satisfy_machine1_requirement() {
784 let store = crate::testutil::temp_dir("gate-tier");
785 store_qemu(&store, "m3", vec![]);
786 store_qemu(&store, "seed-0b-qemu", vec!["artifact_signature_valid"]);
787 // A QEMU tier receipt filed under the machine1 kind must not close
788 // the physical requirement.
789 let mut r = sample();
790 r.kind = "seed-0b-machine1".to_string();
791 store_receipt(&store, &sealed(r)).unwrap();
792 let report = evaluate(&manifest(), &store);
793 assert_eq!(report.status, Verdict::Blocked);
794 let line = report
795 .lines
796 .iter()
797 .find(|l| l.name == "SEED-0B-MACHINE1")
798 .unwrap();
799 assert!(line.detail.contains("cannot satisfy"));
800 }
801
802 #[test]
803 fn dirty_tree_fails_clean_requirement() {
804 let store = crate::testutil::temp_dir("gate-dirty");
805 let mut r = sample();
806 r.kind = "m3".to_string();
807 store_receipt(&store, &sealed(r)).unwrap();
808 let mut q = sample();
809 q.kind = "seed-0b-qemu".to_string();
810 q.dirty = true;
811 store_receipt(&store, &sealed(q)).unwrap();
812 let report = evaluate(&manifest(), &store);
813 let line = report
814 .lines
815 .iter()
816 .find(|l| l.name == "SEED-0B-QEMU")
817 .unwrap();
818 assert_eq!(line.status, Verdict::Blocked);
819 assert!(line.detail.contains("clean source tree"));
820 }
821
822 #[test]
823 fn failed_assertion_fails_gate() {
824 let store = crate::testutil::temp_dir("gate-assert");
825 store_qemu(&store, "m3", vec![]);
826 let mut q = sample();
827 q.kind = "seed-0b-qemu".to_string();
828 q.assertions[0].pass = false;
829 store_receipt(&store, &sealed(q)).unwrap();
830 let report = evaluate(&manifest(), &store);
831 let line = report
832 .lines
833 .iter()
834 .find(|l| l.name == "SEED-0B-QEMU")
835 .unwrap();
836 assert_eq!(line.status, Verdict::Fail);
837 }
838
839 #[test]
840 fn blocked_receipt_cannot_satisfy_a_gate() {
841 let store = crate::testutil::temp_dir("gate-blocked-receipt");
842 let mut r = sample();
843 r.kind = "seed-0b-qemu".to_string();
844 r.result = Verdict::Blocked;
845 store_receipt(&store, &sealed(r)).unwrap();
846 let report = evaluate(&manifest(), &store);
847 let line = report
848 .lines
849 .iter()
850 .find(|l| l.name == "SEED-0B-QEMU")
851 .unwrap();
852 assert_eq!(line.status, Verdict::Blocked);
853 }
854
855 #[test]
856 fn qemu_bootnext_mock_source_cannot_prove_firmware_variable_behavior() {
857 let store = crate::testutil::temp_dir("gate-bootnext-source");
858 let mut r = sample();
859 r.kind = "rollback".to_string();
860 r.assertions = vec![crate::evidence::Assertion {
861 id: "bootnext_consumed".into(),
862 expected: "unset".into(),
863 observed: "unset".into(),
864 pass: true,
865 source: "rollback_state_machine_mock".into(),
866 note: String::new(),
867 }];
868 store_receipt(&store, &sealed(r)).unwrap();
869 let gate = Gate {
870 gate: "rollback-source-test".into(),
871 description: String::new(),
872 requires: vec![Requirement {
873 name: "firmware BootNext".into(),
874 kind: "rollback".into(),
875 gate_ref: None,
876 resource: None,
877 repo: None,
878 machine: None,
879 procedure_contains: None,
880 min_input_artifacts: 0,
881 dependency_kinds: vec![],
882 min_tier: Tier::Qemu,
883 assertions: vec!["bootnext_consumed".into()],
884 assertion_sources: vec![AssertionSource {
885 id: "bootnext_consumed".into(),
886 source: "aavmf_variables".into(),
887 }],
888 mutation: None,
889 require_clean: true,
890 missing_as: MissingAs::Incomplete,
891 missing_reason: None,
892 }],
893 };
894 assert_eq!(evaluate(&gate, &store).status, Verdict::Fail);
895 }
896
897 #[test]
898 fn nested_gate_cycle_fails_closed() {
899 let store = crate::testutil::temp_dir("gate-cycle");
900 let dir = store.join(GATE_DIR);
901 std::fs::create_dir_all(&dir).unwrap();
902 std::fs::write(
903 dir.join("A.json"),
904 r#"{"gate":"A","requires":[{"name":"B","kind":"","gate_ref":"B"}]}"#,
905 )
906 .unwrap();
907 std::fs::write(
908 dir.join("B.json"),
909 r#"{"gate":"B","requires":[{"name":"A","kind":"","gate_ref":"A"}]}"#,
910 )
911 .unwrap();
912 let a = load_manifest(&store, "A", None).unwrap();
913 assert_eq!(evaluate(&a, &store).status, Verdict::Fail);
914 }
915
916 #[test]
917 fn p3_gates_preserve_qemu_and_machine1_distinction() {
918 let store = crate::testutil::temp_dir("gate-p3-split");
919 let qemu = load_manifest(&store, "P3_DEVELOPMENT_QEMU_ENTRY", None).unwrap();
920 let physical = load_manifest(&store, "P3_MACHINE1_WRITE_ENTRY", None).unwrap();
921 let qemu_report = evaluate(&qemu, &store);
922 let physical_report = evaluate(&physical, &store);
923 assert_eq!(qemu_report.status, Verdict::Incomplete);
924 assert_eq!(physical_report.status, Verdict::Blocked);
925 let trust = physical_report
926 .lines
927 .iter()
928 .find(|line| line.name == "OWNER_SECURE_BOOT_TRUST_CHAIN")
929 .unwrap();
930 assert_eq!(trust.status, Verdict::Blocked);
931 assert!(trust
932 .detail
933 .contains("HARDWARE_QUALIFICATION_BLOCKED_BY_TRUST_CHAIN"));
934 let bounded = physical_report
935 .lines
936 .iter()
937 .find(|line| line.name == "BOUNDED_MACHINE1_STORE_REGION")
938 .unwrap();
939 assert_eq!(bounded.status, Verdict::Incomplete);
940 assert_eq!(
941 physical.requires[0].gate_ref.as_deref(),
942 Some("P3_DEVELOPMENT_QEMU_ENTRY")
943 );
944 }
945
946 #[test]
947 fn checked_in_gate_cannot_be_substituted_by_store_copy() {
948 let store = crate::testutil::temp_dir("gate-no-substitution");
949 let dir = store.join(GATE_DIR);
950 std::fs::create_dir_all(&dir).unwrap();
951 std::fs::write(
952 dir.join("P3_DEVELOPMENT_QEMU_ENTRY.json"),
953 r#"{"gate":"P3_DEVELOPMENT_QEMU_ENTRY","requires":[]}"#,
954 )
955 .unwrap();
956 let manifest = load_manifest(&store, "P3_DEVELOPMENT_QEMU_ENTRY", None).unwrap();
957 assert_eq!(manifest.requires.len(), 4);
958 }
959
960 #[test]
961 fn narrow_store_format_merge_gate_does_not_require_seed_or_rollback() {
962 let store = crate::testutil::temp_dir("gate-format-merge");
963 store_assertion_receipt(
964 &store,
965 "adr0015-format",
966 Tier::HostTest,
967 "host",
968 "scripts/check_adr0015.sh",
969 pass_assertions(&["adr0015_accepted_frozen"], "adr0015"),
970 );
971 store_assertion_receipt(
972 &store,
973 "store-v1-format-golden-vectors",
974 Tier::HostTest,
975 "host",
976 "cargo test -p aien-system-store format_golden_vectors",
977 pass_assertions(
978 &["store_format_v1_valid", "store_golden_vectors_match"],
979 "store-format-tests",
980 ),
981 );
982 store_assertion_receipt(
983 &store,
984 "strict-main-verification",
985 Tier::HostTest,
986 "host",
987 "scripts/verify_all.sh",
988 pass_assertions(&["strict_main_pass"], "verify-all"),
989 );
990 let manifest = load_manifest(&store, "STORE_V1_FORMAT_PR_MERGE", None).unwrap();
991 assert_eq!(evaluate(&manifest, &store).status, Verdict::Pass);
992 assert!(manifest.requires.iter().all(|requirement| {
993 requirement.kind != "seed0b-qemu" && requirement.kind != "m0-native-rollback-qemu"
994 }));
995 }
996
997 #[test]
998 fn gate_rejects_receipt_with_missing_chain_dependency() {
999 let store = crate::testutil::temp_dir("gate-missing-chain");
1000 let mut r = sample();
1001 r.kind = "m3".to_string();
1002 r.dependencies = vec!["f".repeat(64)];
1003 store_receipt(&store, &sealed(r)).unwrap();
1004 let manifest = Gate {
1005 gate: "CHAIN-DEMO".to_string(),
1006 description: String::new(),
1007 requires: vec![req("M3", "m3", Tier::HostTest, vec![], MissingAs::Blocked)],
1008 };
1009 assert_eq!(evaluate(&manifest, &store).status, Verdict::Incomplete);
1010 }
1011
1012 #[test]
1013 fn mutation_class_mismatch_fails_gate() {
1014 use crate::evidence::Mutation;
1015 let store = crate::testutil::temp_dir("gate-mutation-mismatch");
1016 store_qemu(&store, "store-qemu", vec!["store_previous_or_new_only"]);
1017 let mut requirement = req(
1018 "Store QEMU",
1019 "store-qemu",
1020 Tier::Qemu,
1021 vec!["store_previous_or_new_only"],
1022 MissingAs::Incomplete,
1023 );
1024 requirement.mutation = Some(Mutation::BoundedTestRegionWrite);
1025 let report = evaluate(
1026 &Gate {
1027 gate: "MUTATION-DEMO".into(),
1028 description: String::new(),
1029 requires: vec![requirement],
1030 },
1031 &store,
1032 );
1033 assert_eq!(report.status, Verdict::Fail);
1034 assert!(report.lines[0]
1035 .detail
1036 .contains("declared/observed mutation"));
1037 }
1038
1039 #[test]
1040 fn hardware_gate_requires_the_machine1_hold() {
1041 let store = crate::testutil::temp_dir("gate-no-hold");
1042 store_assertion_receipt(
1043 &store,
1044 "machine-run",
1045 Tier::Machine1Attended,
1046 "machine-1",
1047 "scripts/qualify.sh",
1048 pass_assertions(&["operator_attended"], "operator"),
1049 );
1050 let mut requirement = req(
1051 "Machine 1 run",
1052 "machine-run",
1053 Tier::Machine1Attended,
1054 vec!["operator_attended"],
1055 MissingAs::Incomplete,
1056 );
1057 requirement.resource = Some("machine-1".into());
1058 let report = evaluate(
1059 &Gate {
1060 gate: "MACHINE-HOLD-DEMO".into(),
1061 description: String::new(),
1062 requires: vec![requirement],
1063 },
1064 &store,
1065 );
1066 assert_eq!(report.status, Verdict::Incomplete);
1067 assert!(report.lines[0].detail.contains("exclusive hold"));
1068 }
1069
1070 fn req(
1071 name: &str,
1072 kind: &str,
1073 min_tier: Tier,
1074 assertions: Vec<&str>,
1075 missing_as: MissingAs,
1076 ) -> Requirement {
1077 Requirement {
1078 name: name.to_string(),
1079 kind: kind.to_string(),
1080 gate_ref: None,
1081 resource: None,
1082 repo: None,
1083 machine: None,
1084 procedure_contains: None,
1085 min_input_artifacts: 0,
1086 dependency_kinds: vec![],
1087 min_tier,
1088 assertions: assertions.into_iter().map(str::to_string).collect(),
1089 assertion_sources: vec![],
1090 mutation: None,
1091 require_clean: false,
1092 missing_as,
1093 missing_reason: None,
1094 }
1095 }
1096
1097 fn assertion(id: &str, source: &str, pass: bool) -> crate::evidence::Assertion {
1098 crate::evidence::Assertion {
1099 id: id.to_string(),
1100 expected: "yes".to_string(),
1101 observed: "yes".to_string(),
1102 pass,
1103 source: source.to_string(),
1104 note: String::new(),
1105 }
1106 }
1107
1108 /// Materialize the embedded P3 manifests into a fresh store.
1109 fn p3_store(tag: &str) -> std::path::PathBuf {
1110 let store = crate::testutil::temp_dir(tag);
1111 write_examples(&store.join(GATE_DIR)).unwrap();
1112 store
1113 }
1114
1115 #[test]
1116 fn machine1_gate_names_its_blockers_on_an_empty_store() {
1117 let store = p3_store("gate-m1-empty");
1118 let manifest = load_manifest(&store, "P3_MACHINE1_WRITE_ENTRY", None).unwrap();
1119 let report = evaluate(&manifest, &store);
1120 assert_eq!(report.status, Verdict::Blocked);
1121 let trust = report
1122 .lines
1123 .iter()
1124 .find(|l| l.name == "OWNER_SECURE_BOOT_TRUST_CHAIN")
1125 .unwrap();
1126 assert_eq!(trust.status, Verdict::Blocked);
1127 assert!(trust
1128 .detail
1129 .contains("HARDWARE_QUALIFICATION_BLOCKED_BY_TRUST_CHAIN"));
1130 let rollback = report
1131 .lines
1132 .iter()
1133 .find(|l| l.name == "M0_NATIVE_ROLLBACK_MACHINE1")
1134 .unwrap();
1135 assert_eq!(rollback.status, Verdict::Blocked);
1136 // The bounded region is proof simply absent so far, not a known
1137 // procedural block.
1138 let region = report
1139 .lines
1140 .iter()
1141 .find(|l| l.name == "BOUNDED_MACHINE1_STORE_REGION")
1142 .unwrap();
1143 assert_eq!(region.status, Verdict::Incomplete);
1144 }
1145
1146 fn store_assertion_receipt(
1147 store: &Path,
1148 kind: &str,
1149 tier: Tier,
1150 machine: &str,
1151 procedure: &str,
1152 assertions: Vec<crate::evidence::Assertion>,
1153 ) {
1154 let mut r = sample();
1155 r.kind = kind.to_string();
1156 r.tier = tier;
1157 r.env_class = tier.as_str().to_string();
1158 r.machine = machine.to_string();
1159 r.procedure = procedure.to_string();
1160 r.input_artifacts = vec![
1161 "blake3:".to_string() + &"b".repeat(64),
1162 "sha256:".to_string() + &"c".repeat(64),
1163 ];
1164 r.assertions = assertions;
1165 store_receipt(store, &sealed(r)).unwrap();
1166 }
1167
1168 const ROLLBACK_BRANCHES: &[&str] = &[
1169 "rollback_harness_version_recorded",
1170 "qemu_aavmf_environment_recorded",
1171 "rollback_normal_pass",
1172 "rollback_fault_pass",
1173 "rollback_timeout_pass",
1174 "rollback_rejected_pass",
1175 "rollback_absent_pass",
1176 "rollback_repeat_boot_pass",
1177 "m0_native_rollback_qemu_pass",
1178 ];
1179
1180 const ROLLBACK_MACHINE: &str = "qemu-aarch64-aavmf";
1181 const ROLLBACK_PROCEDURE: &str = "scripts/qemu_native_rollback_test.sh@0.9.1";
1182
1183 fn pass_assertions(ids: &[&str], source: &str) -> Vec<crate::evidence::Assertion> {
1184 ids.iter().map(|id| assertion(id, source, true)).collect()
1185 }
1186
1187 /// Satisfy the QEMU development gate with real stored receipts, then
1188 /// prove the Machine 1 gate still reports BLOCKED for the trust chain.
1189 /// This is the done condition distinction in one test.
1190 #[test]
1191 fn qemu_gate_passes_while_machine1_gate_stays_blocked() {
1192 let store = p3_store("gate-qemu-vs-m1");
1193 store_assertion_receipt(
1194 &store,
1195 "m0-native-rollback-qemu",
1196 Tier::Qemu,
1197 ROLLBACK_MACHINE,
1198 ROLLBACK_PROCEDURE,
1199 [
1200 pass_assertions(ROLLBACK_BRANCHES, "rollback-verify"),
1201 vec![
1202 assertion("bootnext_consumed", "aavmf_variables", true),
1203 assertion("default_boot_unchanged", "aavmf_variables", true),
1204 ],
1205 ]
1206 .concat(),
1207 );
1208 store_assertion_receipt(
1209 &store,
1210 "seed0b-qemu",
1211 Tier::Qemu,
1212 "qemu-virt-aarch64",
1213 "scripts/qemu_seed0b.sh",
1214 pass_assertions(
1215 &[
1216 "seed0b_signature_valid",
1217 "granted_subset_requested",
1218 "unauthorized_write_denied",
1219 "forged_handle_denied",
1220 "all_task_frames_reclaimed",
1221 ],
1222 "seed0b-qemu",
1223 ),
1224 );
1225 store_assertion_receipt(
1226 &store,
1227 "adr0015-format",
1228 Tier::HostTest,
1229 "host",
1230 "scripts/check_adr0015.sh",
1231 pass_assertions(&["adr0015_accepted_frozen"], "adr0015"),
1232 );
1233 store_assertion_receipt(
1234 &store,
1235 "strict-main-verification",
1236 Tier::HostTest,
1237 "host",
1238 "scripts/verify_all.sh",
1239 pass_assertions(&["strict_main_pass"], "verify-all"),
1240 );
1241 let qemu = load_manifest(&store, "P3_DEVELOPMENT_QEMU_ENTRY", None).unwrap();
1242 let qemu_report = evaluate(&qemu, &store);
1243 assert_eq!(qemu_report.status, Verdict::Pass, "{qemu_report:?}");
1244 let m1 = load_manifest(&store, "P3_MACHINE1_WRITE_ENTRY", None).unwrap();
1245 let m1_report = evaluate(&m1, &store);
1246 assert_eq!(m1_report.status, Verdict::Blocked);
1247 let sub = m1_report
1248 .lines
1249 .iter()
1250 .find(|l| l.name == "P3_DEVELOPMENT_QEMU_ENTRY")
1251 .unwrap();
1252 assert_eq!(sub.status, Verdict::Pass);
1253 let trust = m1_report
1254 .lines
1255 .iter()
1256 .find(|l| l.name == "OWNER_SECURE_BOOT_TRUST_CHAIN")
1257 .unwrap();
1258 assert_eq!(trust.status, Verdict::Blocked);
1259 }
1260
1261 #[test]
1262 fn mock_source_cannot_prove_firmware_bootnext() {
1263 let store = p3_store("gate-mock");
1264 store_assertion_receipt(
1265 &store,
1266 "m0-native-rollback-qemu",
1267 Tier::Qemu,
1268 ROLLBACK_MACHINE,
1269 ROLLBACK_PROCEDURE,
1270 [
1271 pass_assertions(ROLLBACK_BRANCHES, "rollback-verify"),
1272 vec![
1273 assertion("bootnext_consumed", "state-machine-mock", true),
1274 assertion("default_boot_unchanged", "aavmf_variables", true),
1275 ],
1276 ]
1277 .concat(),
1278 );
1279 let manifest = load_manifest(&store, "P3_DEVELOPMENT_QEMU_ENTRY", None).unwrap();
1280 let report = evaluate(&manifest, &store);
1281 let line = report
1282 .lines
1283 .iter()
1284 .find(|l| l.name == "M0_NATIVE_ROLLBACK_QEMU")
1285 .unwrap();
1286 assert_eq!(line.status, Verdict::Fail);
1287 assert!(line.detail.contains("aavmf_variables"));
1288 }
1289
1290 #[test]
1291 fn blocked_receipt_cannot_satisfy_a_requirement() {
1292 let store = crate::testutil::temp_dir("gate-blocked");
1293 let mut r = sample();
1294 r.kind = "m3".to_string();
1295 r.result = Verdict::Blocked;
1296 r.assertions = vec![assertion("recorded", "example", true)];
1297 let r = sealed(r);
1298 // BLOCKED receipts carry no chain burden here; store then evaluate.
1299 store_receipt(&store, &r).unwrap();
1300 let manifest = Gate {
1301 gate: "BLOCKED-DEMO".to_string(),
1302 description: String::new(),
1303 requires: vec![req("M3", "m3", Tier::HostTest, vec![], MissingAs::Blocked)],
1304 };
1305 let report = evaluate(&manifest, &store);
1306 assert_eq!(report.status, Verdict::Blocked);
1307 assert!(report.lines[0].detail.contains("records BLOCKED"));
1308 }
1309
1310 #[test]
1311 fn qemu_receipt_cannot_pose_as_machine1_rollback() {
1312 let store = p3_store("gate-rollback-tier");
1313 store_assertion_receipt(
1314 &store,
1315 "m0-native-rollback-machine1",
1316 Tier::Qemu,
1317 "machine-1",
1318 "scripts/rollback_machine1.sh",
1319 pass_assertions(&["secure_boot_unchanged"], "rollback-verify"),
1320 );
1321 let manifest = load_manifest(&store, "P3_MACHINE1_WRITE_ENTRY", None).unwrap();
1322 let report = evaluate(&manifest, &store);
1323 let line = report
1324 .lines
1325 .iter()
1326 .find(|l| l.name == "M0_NATIVE_ROLLBACK_MACHINE1")
1327 .unwrap();
1328 assert_eq!(line.status, Verdict::Blocked);
1329 assert!(line.detail.contains("cannot satisfy"));
1330 }
1331
1332 #[test]
1333 fn manifest_cycles_fail_closed() {
1334 let store = crate::testutil::temp_dir("gate-cycle");
1335 let dir = store.join(GATE_DIR);
1336 std::fs::create_dir_all(&dir).unwrap();
1337 for (name, child) in [("GATE-A", "GATE-B"), ("GATE-B", "GATE-A")] {
1338 let manifest = Gate {
1339 gate: name.to_string(),
1340 description: String::new(),
1341 requires: vec![Requirement {
1342 name: format!("child {child}"),
1343 kind: String::new(),
1344 gate_ref: Some(child.to_string()),
1345 resource: None,
1346 repo: None,
1347 machine: None,
1348 procedure_contains: None,
1349 min_input_artifacts: 0,
1350 dependency_kinds: vec![],
1351 min_tier: Tier::HostTest,
1352 assertions: vec![],
1353 assertion_sources: vec![],
1354 mutation: None,
1355 require_clean: false,
1356 missing_as: MissingAs::Blocked,
1357 missing_reason: None,
1358 }],
1359 };
1360 std::fs::write(
1361 dir.join(format!("{name}.json")),
1362 serde_json::to_string_pretty(&manifest).unwrap(),
1363 )
1364 .unwrap();
1365 }
1366 let manifest = load_manifest(&store, "GATE-A", None).unwrap();
1367 let report = evaluate(&manifest, &store);
1368 assert_eq!(report.status, Verdict::Fail);
1369 assert!(report.lines[0].detail.contains("cycle"));
1370 }
1371
1372 #[test]
1373 fn malformed_manifests_rejected_at_load() {
1374 let both = Gate {
1375 gate: "BAD".to_string(),
1376 description: String::new(),
1377 requires: vec![Requirement {
1378 name: "x".to_string(),
1379 kind: "m3".to_string(),
1380 gate_ref: Some("OTHER".to_string()),
1381 resource: None,
1382 repo: None,
1383 machine: None,
1384 procedure_contains: None,
1385 min_input_artifacts: 0,
1386 dependency_kinds: vec![],
1387 min_tier: Tier::HostTest,
1388 assertions: vec![],
1389 assertion_sources: vec![],
1390 mutation: None,
1391 require_clean: false,
1392 missing_as: MissingAs::Blocked,
1393 missing_reason: None,
1394 }],
1395 };
1396 assert!(both.validate().is_err());
1397 let stray_source = Gate {
1398 gate: "BAD".to_string(),
1399 description: String::new(),
1400 requires: vec![Requirement {
1401 name: "x".to_string(),
1402 kind: "m3".to_string(),
1403 gate_ref: None,
1404 resource: None,
1405 repo: None,
1406 machine: None,
1407 procedure_contains: None,
1408 min_input_artifacts: 0,
1409 dependency_kinds: vec![],
1410 min_tier: Tier::HostTest,
1411 assertions: vec!["a".to_string()],
1412 assertion_sources: vec![AssertionSource {
1413 id: "b".to_string(),
1414 source: "mock".to_string(),
1415 }],
1416 mutation: None,
1417 require_clean: false,
1418 missing_as: MissingAs::Blocked,
1419 missing_reason: None,
1420 }],
1421 };
1422 assert!(stray_source.validate().is_err());
1423 }
1424
1425 #[test]
1426 fn shipped_examples_parse() {
1427 let seed: Gate = serde_json::from_str(SEED_0B_EXAMPLE).unwrap();
1428 assert_eq!(seed.gate, "SEED-0B");
1429 assert!(!seed.requires.is_empty());
1430 let seed_qemu: Gate = serde_json::from_str(SEED_0B_QEMU).unwrap();
1431 assert_eq!(seed_qemu.gate, "SEED0B_QEMU");
1432 let format: Gate = serde_json::from_str(STORE_V1_FORMAT_PR_MERGE).unwrap();
1433 assert_eq!(format.gate, "STORE_V1_FORMAT_PR_MERGE");
1434 let p3_qemu: Gate = serde_json::from_str(P3_STORE_QEMU).unwrap();
1435 assert_eq!(p3_qemu.gate, "P3_STORE_QEMU");
1436 let p3_machine: Gate = serde_json::from_str(P3_STORE_MACHINE1).unwrap();
1437 assert_eq!(p3_machine.gate, "P3_STORE_MACHINE1");
1438 let p3: Gate = serde_json::from_str(P3_DEVELOPMENT_QEMU_ENTRY).unwrap();
1439 assert_eq!(p3.gate, "P3_DEVELOPMENT_QEMU_ENTRY");
1440 assert!(!p3.requires.is_empty());
1441 let physical: Gate = serde_json::from_str(P3_MACHINE1_WRITE_ENTRY).unwrap();
1442 assert_eq!(physical.gate, "P3_MACHINE1_WRITE_ENTRY");
1443 let store_format: Gate = serde_json::from_str(STORE_V1_FORMAT).unwrap();
1444 assert_eq!(store_format.gate, "STORE_V1_FORMAT");
1445 store_format.validate().unwrap();
1446 let store_host: Gate = serde_json::from_str(STORE_V1_HOST).unwrap();
1447 assert_eq!(store_host.gate, "STORE_V1_HOST");
1448 store_host.validate().unwrap();
1449 let store_qemu: Gate = serde_json::from_str(STORE_V1_QEMU).unwrap();
1450 assert_eq!(store_qemu.gate, "STORE_V1_QEMU");
1451 store_qemu.validate().unwrap();
1452 }
1453}