Skip to main content

sail_api/
acceptance.rs

1//! Positive Verus authority checked directly over the public report records.
2//!
3//! These predicates never infer a complete request from its selected-result
4//! flags. The caller with the independently resolved request must additionally
5//! establish [`requested_coverage`](crate::acceptance::requested_coverage). Currentness remains an input property:
6//! a fresh failed verification can be Current without authorizing a repair.
7#![allow(
8    clippy::redundant_as_str,
9    reason = "The pinned stock Verus specifies str::as_bytes, not String::as_bytes."
10)]
11
12use sail_acceptance::authority::{
13    CompletionPolicy, RequestedTarget, argument_flag, copy_bytes, exact_bytes, owned_obligation,
14    unique_obligations,
15};
16use sail_acceptance::{sail_code, sail_method, sail_proof, sail_spec, sail_verified, sail_while};
17
18/// Builds untrusted order candidates and invokes the checked authority factory.
19pub use crate::acceptance_sort::{
20    complete_report, complete_selection, complete_target, complete_whole_report,
21};
22
23use crate::output::{
24    CrateReport, EngineEstablishment, EstablishmentName, FunctionReport, Report, SourceSummaryName,
25    VerdictName,
26};
27use crate::project::{Currentness, ProjectResult, TargetResult};
28
29#[cfg(sail_verus)]
30use vstd::prelude::*;
31#[cfg(sail_verus)]
32use vstd::string::StringSliceAdditionalSpecFns;
33
34sail_code! {
35    /// Checked immutable report authority, bound to the actual report borrow.
36    /// Its fields are private so deserialization and caller flags cannot mint it.
37    pub struct CompleteReport<'a> {
38        report: &'a Report,
39        policy: CompletionPolicy,
40    }
41
42    /// Untrusted candidate ordering for one report's actual obligations.
43    pub struct ReportOrder {
44        /// Proposed sorted actual-ID indices.
45        pub forward: Vec<usize>,
46        /// Proposed inverse index certificate.
47        pub inverse: Vec<usize>,
48    }
49
50    /// Positive authority for the selected targets supplied in this envelope.
51    /// This does not invent an independently resolved request after storage.
52    pub struct CompleteSelection<'a> {
53        project: &'a ProjectResult,
54    }
55
56    impl CompleteSelection<'_> {
57        sail_method! {
58            /// Exact immutable project whose selected reports were checked.
59            #[must_use]
60            pub fn project(&self) -> (out: &ProjectResult)
61                requires(true)
62                ensures(out == selection_project(self))
63            { self.project }
64        }
65    }
66
67    impl CompleteReport<'_> {
68        sail_method! {
69            /// The immutable actual report whose fields were checked.
70            #[must_use]
71            pub fn report(&self) -> (out: &Report)
72                requires(true)
73                ensures(out == authority_report(self))
74            { self.report }
75        }
76
77        sail_method! {
78            /// The receipt or repair contract that was checked.
79            #[must_use]
80            pub fn policy(&self) -> (out: CompletionPolicy)
81                requires(true)
82                ensures(out == authority_policy(self))
83            { self.policy }
84        }
85    }
86}
87
88sail_spec! {
89    broadcast use {vstd::seq_lib::group_seq_properties, vstd::seq::Seq::lemma_push_map_commute};
90    pub open spec fn string_bytes(s: &String) -> Seq<u8> { vstd::utf8::encode_utf8(s@) }
91
92    pub open spec fn focused_argument(bytes: Seq<u8>) -> bool {
93        sail_acceptance::authority::flag_matches(bytes, b"--verify-module"@)
94            || sail_acceptance::authority::flag_matches(bytes, b"--verify-only-module"@)
95            || sail_acceptance::authority::flag_matches(bytes, b"--verify-function"@)
96            || sail_acceptance::authority::flag_matches(bytes, b"--verify-root"@)
97    }
98
99    pub open spec fn partial_command(args: Seq<String>) -> bool {
100        exists |i: int, j: int| 0 <= i <= j < args.len()
101            && string_bytes(&args[i]) == b"--"@ && focused_argument(string_bytes(&args[j]))
102    }
103
104    pub open spec fn verification_disabled(args: Seq<String>) -> bool {
105        exists |i: int, j: int| 0 <= i < j < args.len()
106            && string_bytes(&args[i]) == b"--"@
107            && string_bytes(&args[j]) == b"--no-verify"@
108    }
109
110    pub open spec fn options_disable_verification(args: Seq<String>) -> bool {
111        exists |i: int| 0 <= i < args.len() && string_bytes(&args[i]) == b"--no-verify"@
112            && forall |j: int| 0 <= j < i ==> string_bytes(&args[j]) != b"--"@
113    }
114
115    pub open spec fn target_match(e: &RequestedTarget, t: &TargetResult) -> bool {
116        e.package@ == string_bytes(&t.package_id) && e.name@ == string_bytes(&t.target)
117            && exists |i: int| 0 <= i < t.kind@.len() && e.kind@ == string_bytes(&t.kind@[i])
118    }
119
120    pub open spec fn request_covered(e: &RequestedTarget, ts: Seq<TargetResult>) -> bool {
121        exists |i: int| 0 <= i < ts.len() && target_match(e, &ts[i]) && ts[i].requested
122            && forall |j: int| 0 <= j < ts.len() && target_match(e, &ts[j]) ==> j == i
123    }
124
125    pub open spec fn target_covered(t: &TargetResult, es: Seq<RequestedTarget>) -> bool {
126        exists |i: int| 0 <= i < es.len() && target_match(&es[i], t)
127            && forall |j: int| 0 <= j < es.len() && target_match(&es[j], t) ==> j == i
128    }
129
130    pub open spec fn exact_requested_coverage(es: Seq<RequestedTarget>, ts: Seq<TargetResult>) -> bool {
131        es.len() > 0
132            && (forall |i: int| 0 <= i < es.len() ==> request_covered(&es[i], ts))
133            && (forall |i: int| 0 <= i < ts.len() && ts[i].requested ==> target_covered(&ts[i], es))
134    }
135
136    pub open spec fn same_target_identity(a: &TargetResult, b: &TargetResult) -> bool {
137        string_bytes(&a.package_id) == string_bytes(&b.package_id)
138            && string_bytes(&a.target) == string_bytes(&b.target)
139            && a.kind@.len() == b.kind@.len()
140            && (forall |i: int| 0 <= i < a.kind@.len() ==> string_bytes(&a.kind@[i]) == string_bytes(&b.kind@[i]))
141    }
142
143    pub open spec fn supplied_selection_authorized(p: &ProjectResult) -> bool {
144        p.currentness is Current && p.exit_code == Some(0i32) && p.error.is_none()
145            && (exists |i: int| 0 <= i < p.targets@.len() && p.targets@[i].requested)
146            && (forall |i: int| 0 <= i < p.targets@.len() && p.targets@[i].requested ==>
147                p.targets@[i].complete && p.targets@[i].scope_reuse.is_none()
148                    && !partial_command(p.targets@[i].report.command@)
149                    && successful_report(&p.targets@[i].report, CompletionPolicy::Repair))
150            && (forall |i: int, j: int| 0 <= i < j < p.targets@.len()
151                && p.targets@[i].requested && p.targets@[j].requested ==>
152                    !same_target_identity(&p.targets@[i], &p.targets@[j]))
153    }
154
155    pub closed spec fn selection_project<'a>(a: &CompleteSelection<'a>) -> &'a ProjectResult { a.project }
156    pub closed spec fn selection_authority_valid(a: &CompleteSelection) -> bool {
157        supplied_selection_authorized(a.project)
158    }
159
160    pub open spec fn provenance_valid(f: &FunctionReport) -> bool {
161        let p = &f.provenance;
162        match p.source {
163            SourceSummaryName::Fresh => p.checks_solved > 0 && p.checks_served == 0 && p.checks_unrecorded == 0,
164            SourceSummaryName::Cache => p.checks_solved == 0 && p.checks_served > 0 && p.checks_unrecorded == 0,
165            SourceSummaryName::Mixed => p.checks_solved > 0 && p.checks_served > 0 && p.checks_unrecorded == 0,
166            SourceSummaryName::Unrecorded => p.checks_unrecorded > 0
167                || (p.checks_solved == 0 && p.checks_served == 0 && p.checks_unrecorded == 0),
168        }
169    }
170
171    pub open spec fn confirmed(f: &FunctionReport) -> bool {
172        f.verdict is Verified && f.establishment is Confirmed
173            && f.evidence_tier.is_some() && provenance_valid(f)
174    }
175
176    pub open spec fn crate_completed(c: &CrateReport, policy: CompletionPolicy) -> bool {
177        c.verus.errors == Some(0u64) && c.verus.encountered_vir_error != Some(true)
178            && match policy {
179                CompletionPolicy::Receipt => c.verus.success != Some(false),
180                CompletionPolicy::Whole | CompletionPolicy::Repair => c.verus.success == Some(true),
181            }
182    }
183
184    pub open spec fn function_count(cs: Seq<CrateReport>) -> nat
185        decreases cs.len()
186    {
187        if cs.len() == 0 { 0 } else { function_count(cs.drop_last()) + cs.last().functions@.len() }
188    }
189
190    pub open spec fn unstable_functions(fs: Seq<FunctionReport>) -> nat
191        decreases fs.len()
192    {
193        if fs.len() == 0 { 0 } else {
194            unstable_functions(fs.drop_last()) + if fs.last().unstable { 1nat } else { 0nat }
195        }
196    }
197
198    pub open spec fn unstable_count(cs: Seq<CrateReport>) -> nat
199        decreases cs.len()
200    {
201        if cs.len() == 0 { 0 } else {
202            unstable_count(cs.drop_last()) + unstable_functions(cs.last().functions@)
203        }
204    }
205
206    pub open spec fn obligation_ids(f: &FunctionReport) -> Seq<Seq<u8>> {
207        match f.obligations {
208            Some(os) => os@.map_values(|o: crate::output::ObligationReport| string_bytes(&o.id)),
209            None => Seq::empty(),
210        }
211    }
212
213    pub open spec fn function_ids(fs: Seq<FunctionReport>) -> Seq<Seq<u8>>
214        decreases fs.len()
215    {
216        if fs.len() == 0 { Seq::empty() } else {
217            function_ids(fs.drop_last()) + obligation_ids(&fs.last())
218        }
219    }
220
221    pub open spec fn report_ids(cs: Seq<CrateReport>) -> Seq<Seq<u8>>
222        decreases cs.len()
223    {
224        if cs.len() == 0 { Seq::empty() } else {
225            report_ids(cs.drop_last()) + function_ids(cs.last().functions@)
226        }
227    }
228
229    pub open spec fn owned_function_ids(f: &FunctionReport) -> bool {
230        forall |i: int| 0 <= i < obligation_ids(f).len() ==>
231            obligation_ids(f)[i].len() > string_bytes(&f.function).len()
232                && obligation_ids(f)[i][string_bytes(&f.function).len() as int] == 35u8
233                && forall |j: int| 0 <= j < string_bytes(&f.function).len() ==>
234                    obligation_ids(f)[i][j] == string_bytes(&f.function)[j]
235    }
236
237    pub open spec fn all_owned_ids(cs: Seq<CrateReport>) -> bool {
238        forall |i: int, j: int| 0 <= i < cs.len() && 0 <= j < cs[i].functions@.len() ==>
239            owned_function_ids(&cs[i].functions@[j])
240    }
241
242    pub open spec fn distinct_ids(ids: Seq<Seq<u8>>) -> bool {
243        forall |i: int, j: int| 0 <= i < j < ids.len() ==> ids[i] != ids[j]
244    }
245
246    pub open spec fn successful_records(r: &Report, policy: CompletionPolicy) -> bool {
247        r.schema_version == crate::output::SCHEMA_VERSION && r.exit_code == Some(0i32) && r.error.is_none()
248            && !verification_disabled(r.command@)
249            && r.crates@.len() > 0
250            && (forall |i: int| 0 <= i < r.crates@.len() ==> crate_completed(&r.crates@[i], policy))
251            && (forall |i: int, j: int| 0 <= i < r.crates@.len() && 0 <= j < r.crates@[i].functions@.len()
252                ==> confirmed(&r.crates@[i].functions@[j]))
253            && r.summary.functions == function_count(r.crates@)
254            && r.summary.verified == function_count(r.crates@)
255            && r.summary.failed == 0 && r.summary.unknown == 0 && r.summary.provisional == 0
256            && r.summary.unstable == unstable_count(r.crates@)
257            && (policy is Repair ==> match r.engine {
258                None => true,
259                Some(engine) => engine.established_by is Engine,
260            })
261    }
262
263    pub open spec fn successful_report(r: &Report, policy: CompletionPolicy) -> bool {
264        successful_records(r, policy) && all_owned_ids(r.crates@)
265            && distinct_ids(report_ids(r.crates@))
266    }
267
268    pub open spec fn small_positive_report(r: &Report, policy: CompletionPolicy) -> bool {
269        successful_records(r, policy) && all_owned_ids(r.crates@)
270            && r.crates@.len() == 1 && r.crates@[0].functions@.len() <= 1
271            && report_ids(r.crates@).len() == 0
272    }
273
274    pub closed spec fn authority_report<'a>(a: &CompleteReport<'a>) -> &'a Report { a.report }
275    pub closed spec fn authority_policy(a: &CompleteReport) -> CompletionPolicy { a.policy }
276
277    pub closed spec fn report_authority_valid(a: &CompleteReport) -> bool {
278        successful_report(a.report, a.policy)
279    }
280}
281
282sail_verified! {
283    /// Refuses compile-only options in a Cargo command's forwarded Verus arguments.
284    /// A successful zero-function document alone does not establish verification.
285    pub fn verification_enabled_command(args: &[String]) -> (out: bool)
286        requires(true)
287        ensures(out == !verification_disabled(args@))
288    {
289        let mut separator = false;
290        let mut i = 0usize;
291        sail_while! { (i < args.len())
292            invariant(i <= args.len(), !verification_disabled(args@.take(i as int)),
293                separator == (exists |j: int| 0 <= j < i && string_bytes(&args@[j]) == b"--"@))
294            decreases(args.len() - i)
295            {
296                let bytes = args[i].as_str().as_bytes();
297                if separator && exact_bytes(bytes, b"--no-verify") { return false; }
298                if exact_bytes(bytes, b"--") { separator = true; }
299                i += 1;
300            }
301        }
302        sail_proof! { assert(args@.take(i as int) =~= args@); }
303        true
304    }
305}
306
307sail_verified! {
308    /// Checks decoded effective Verus options before their Rust-argument separator.
309    pub fn verification_enabled_options(args: &[String]) -> (out: bool)
310        requires(true)
311        ensures(out == !options_disable_verification(args@))
312    {
313        let mut i = 0usize;
314        sail_while! { (i < args.len())
315            invariant(i <= args.len(),
316                forall |j: int| 0 <= j < i ==> string_bytes(&args@[j]) != b"--"@
317                    && string_bytes(&args@[j]) != b"--no-verify"@)
318            decreases(args.len() - i)
319            {
320                let bytes = args[i].as_str().as_bytes();
321                if exact_bytes(bytes, b"--") {
322                    sail_proof! {
323                        assert(string_bytes(&args@[i as int]) == b"--"@);
324                        reveal(options_disable_verification);
325                        if options_disable_verification(args@) {
326                            let k = choose |k: int| 0 <= k < args@.len()
327                                && string_bytes(&args@[k]) == b"--no-verify"@
328                                && forall |j: int| 0 <= j < k ==> string_bytes(&args@[j]) != b"--"@;
329                            if k < i { assert(string_bytes(&args@[k]) != b"--no-verify"@); }
330                            else if k > i { assert(string_bytes(&args@[i as int]) != b"--"@); }
331                            else { assert(string_bytes(&args@[k]).len() == 2); }
332                        }
333                        assert(!options_disable_verification(args@));
334                    }
335                    return true;
336                }
337                if exact_bytes(bytes, b"--no-verify") { return false; }
338                i += 1;
339            }
340        }
341        true
342    }
343}
344
345sail_verified! {
346    /// Compares every field of a stored Cargo target identity.
347    pub fn same_target(a: &TargetResult, b: &TargetResult) -> (out: bool)
348        requires(true)
349        ensures(out == same_target_identity(a, b))
350    {
351        if !exact_bytes(a.package_id.as_str().as_bytes(), b.package_id.as_str().as_bytes())
352            || !exact_bytes(a.target.as_str().as_bytes(), b.target.as_str().as_bytes())
353            || a.kind.len() != b.kind.len() { return false; }
354        let mut i = 0usize;
355        sail_while! { (i < a.kind.len())
356            invariant(i <= a.kind.len(), a.kind.len() == b.kind.len(),
357                string_bytes(&a.package_id) == string_bytes(&b.package_id),
358                string_bytes(&a.target) == string_bytes(&b.target),
359                forall |j: int| 0 <= j < i ==> string_bytes(&a.kind@[j]) == string_bytes(&b.kind@[j]))
360            decreases(a.kind.len() - i)
361            {
362                if !exact_bytes(a.kind[i].as_str().as_bytes(), b.kind[i].as_str().as_bytes()) { return false; }
363                i += 1;
364            }
365        }
366        sail_proof! {
367            assert(a.kind@.map_values(|s: String| string_bytes(&s)) =~=
368                b.kind@.map_values(|s: String| string_bytes(&s)));
369        }
370        true
371    }
372}
373
374sail_verified! {
375    /// Mints selected-target authority using actual reports and arbitrary index candidates.
376    pub fn complete_selection_ordered<'a>(project: &'a ProjectResult, orders: &[ReportOrder])
377        -> (out: Option<CompleteSelection<'a>>)
378        requires(true)
379        ensures(out.is_some() ==> supplied_selection_authorized(project),
380            out.is_some() ==> selection_project(&out.unwrap()) == project,
381            out.is_some() ==> selection_authority_valid(&out.unwrap()))
382    {
383        if !matches!(project.currentness, Currentness::Current) || project.exit_code != Some(0)
384            || project.error.is_some() || orders.len() != project.targets.len() { return None; }
385        let mut found = false;
386        let mut i = 0usize;
387        sail_while! { (i < project.targets.len())
388            invariant(i <= project.targets.len(), orders.len() == project.targets.len(),
389                found == (exists |j: int| 0 <= j < i && project.targets@[j].requested),
390                forall |j: int| 0 <= j < i && project.targets@[j].requested ==>
391                    project.targets@[j].complete && project.targets@[j].scope_reuse.is_none()
392                        && !partial_command(project.targets@[j].report.command@)
393                        && successful_report(&project.targets@[j].report, CompletionPolicy::Repair),
394                forall |j: int, k: int| 0 <= j < k < i
395                    && project.targets@[j].requested && project.targets@[k].requested ==>
396                        !same_target_identity(&project.targets@[j], &project.targets@[k]))
397            decreases(project.targets.len() - i)
398            {
399                let t = &project.targets[i];
400                if t.requested {
401                    if !t.complete || t.scope_reuse.is_some() || focused_command(&t.report.command)
402                        || complete_report_ordered(&t.report, CompletionPolicy::Repair,
403                            &orders[i].forward, &orders[i].inverse).is_none() { return None; }
404                    let mut j = 0usize;
405                    sail_while! { (j < i)
406                        invariant(j <= i, i < project.targets.len(),
407                            forall |k: int| 0 <= k < j && project.targets@[k].requested ==>
408                                !same_target_identity(&project.targets@[k], t))
409                        decreases(i - j)
410                        {
411                            if project.targets[j].requested && same_target(&project.targets[j], t) { return None; }
412                            j += 1;
413                        }
414                    }
415                    found = true;
416                }
417                i += 1;
418            }
419        }
420        if !found { return None; }
421        Some(CompleteSelection { project })
422    }
423}
424
425sail_verified! {
426    /// Revalidates a target's positive presentation against its actual whole report.
427    pub fn complete_target_ordered<'a>(target: &'a TargetResult, forward: &[usize], inverse: &[usize])
428        -> (out: Option<CompleteReport<'a>>)
429        requires(true)
430        ensures(out.is_some() ==> target.complete && target.scope_reuse.is_none(),
431            out.is_some() ==> successful_report(&target.report, CompletionPolicy::Whole),
432            out.is_some() ==> !partial_command(target.report.command@),
433            out.is_some() ==> authority_report(&out.unwrap()) == &target.report)
434    {
435        if !target.complete || target.scope_reuse.is_some() { return None; }
436        complete_whole_report_ordered(&target.report, forward, inverse)
437    }
438}
439
440sail_verified! {
441    /// Whole-target authority additionally checks actual forwarded scope arguments.
442    pub fn complete_whole_report_ordered<'a>(report: &'a Report, forward: &[usize], inverse: &[usize])
443        -> (out: Option<CompleteReport<'a>>)
444        requires(true)
445        ensures(out.is_some() ==> successful_report(report, CompletionPolicy::Whole),
446            out.is_some() ==> !partial_command(report.command@),
447            out.is_some() ==> authority_report(&out.unwrap()) == report)
448    {
449        if focused_command(&report.command) { return None; }
450        complete_report_ordered(report, CompletionPolicy::Whole, forward, inverse)
451    }
452}
453
454sail_verified! {
455    /// Preserves exact strings from the independently resolved Cargo selection.
456    pub fn requested_target(package: &str, name: &str, kind: &str) -> (out: RequestedTarget)
457        requires(true)
458        ensures(out.package@ == package.spec_bytes(), out.name@ == name.spec_bytes(),
459            out.kind@ == kind.spec_bytes())
460    {
461        RequestedTarget {
462            package: copy_bytes(package.as_bytes()),
463            name: copy_bytes(name.as_bytes()),
464            kind: copy_bytes(kind.as_bytes()),
465        }
466    }
467}
468
469sail_verified! {
470    /// Matches exact Cargo package/name/kind, preserving normalized-name collisions.
471    pub fn target_matches(e: &RequestedTarget, t: &TargetResult) -> (out: bool)
472        requires(true)
473        ensures(out == target_match(e, t))
474    {
475        if !exact_bytes(&e.package, t.package_id.as_str().as_bytes())
476            || !exact_bytes(&e.name, t.target.as_str().as_bytes()) { return false; }
477        let mut i = 0usize;
478        sail_while! { (i < t.kind.len())
479            invariant(i <= t.kind.len(), e.package@ == string_bytes(&t.package_id),
480                e.name@ == string_bytes(&t.target),
481                forall |j: int| 0 <= j < i ==> e.kind@ != string_bytes(&t.kind@[j]))
482            decreases(t.kind.len() - i)
483            {
484                if exact_bytes(&e.kind, t.kind[i].as_str().as_bytes()) {
485                    sail_proof! { assert(target_match(e, t)); }
486                    return true;
487                }
488                i += 1;
489            }
490        }
491        false
492    }
493}
494
495sail_verified! {
496    fn unique_observed(e: &RequestedTarget, ts: &[TargetResult]) -> (out: Option<usize>)
497        requires(true)
498        ensures(out.is_some() ==> request_covered(e, ts@))
499    {
500        let mut found: Option<usize> = None;
501        let mut i = 0usize;
502        sail_while! { (i < ts.len())
503            invariant(i <= ts.len(),
504                found.is_some() ==> found.unwrap() < i && target_match(e, &ts@[found.unwrap() as int])
505                    && ts@[found.unwrap() as int].requested,
506                forall |j: int| 0 <= j < i && target_match(e, &ts@[j]) ==>
507                    found.is_some() && j == found.unwrap())
508            decreases(ts.len() - i)
509            {
510                if target_matches(e, &ts[i]) {
511                    if found.is_some() || !ts[i].requested { return None; }
512                    found = Some(i);
513                }
514                i += 1;
515            }
516        }
517        sail_proof! { if found.is_some() { assert(request_covered(e, ts@)); } }
518        found
519    }
520}
521
522sail_verified! {
523    fn unique_requested(t: &TargetResult, es: &[RequestedTarget]) -> (out: Option<usize>)
524        requires(true)
525        ensures(out.is_some() ==> target_covered(t, es@))
526    {
527        let mut found: Option<usize> = None;
528        let mut i = 0usize;
529        sail_while! { (i < es.len())
530            invariant(i <= es.len(),
531                found.is_some() ==> found.unwrap() < i && target_match(&es@[found.unwrap() as int], t),
532                forall |j: int| 0 <= j < i && target_match(&es@[j], t) ==>
533                    found.is_some() && j == found.unwrap())
534            decreases(es.len() - i)
535            {
536                if target_matches(&es[i], t) {
537                    if found.is_some() { return None; }
538                    found = Some(i);
539                }
540                i += 1;
541            }
542        }
543        sail_proof! { if found.is_some() { assert(target_covered(t, es@)); } }
544        found
545    }
546}
547
548sail_verified! {
549    /// Establishes one-to-one coverage of the independently resolved request.
550    /// Failed targets without artifacts must still appear as observations.
551    pub fn requested_coverage(expected: &[RequestedTarget], targets: &[TargetResult]) -> (out: bool)
552        requires(true)
553        ensures(out ==> exact_requested_coverage(expected@, targets@))
554    {
555        if expected.is_empty() { return false; }
556        let mut i = 0usize;
557        sail_while! { (i < expected.len())
558            invariant(i <= expected.len(),
559                forall |j: int| 0 <= j < i ==> request_covered(&expected@[j], targets@))
560            decreases(expected.len() - i)
561            {
562                if unique_observed(&expected[i], targets).is_none() { return false; }
563                i += 1;
564            }
565        }
566        let mut j = 0usize;
567        sail_while! { (j < targets.len())
568            invariant(j <= targets.len(),
569                forall |k: int| 0 <= k < targets@.len() && k < j && targets@[k].requested
570                    ==> target_covered(&targets@[k], expected@),
571                forall |k: int| 0 <= k < expected@.len() ==> request_covered(&expected@[k], targets@))
572            decreases(targets.len() - j)
573            {
574                if targets[j].requested && unique_requested(&targets[j], expected).is_none() { return false; }
575                j += 1;
576            }
577        }
578        true
579    }
580}
581
582sail_verified! {
583    /// Recognizes the actual forwarded Verus selectors that make a run partial.
584    pub fn focused_command(args: &[String]) -> (out: bool)
585        requires(true)
586        ensures(out == partial_command(args@))
587    {
588        let mut separator = false;
589        let mut i = 0usize;
590        sail_while! { (i < args.len())
591            invariant(i <= args.len(), !partial_command(args@.take(i as int)),
592                separator == (exists |j: int| 0 <= j < i && string_bytes(&args@[j]) == b"--"@))
593            decreases(args.len() - i)
594            {
595                let bytes = args[i].as_str().as_bytes();
596                if exact_bytes(bytes, b"--") { separator = true; }
597                if separator && (argument_flag(bytes, b"--verify-module")
598                    || argument_flag(bytes, b"--verify-only-module")
599                    || argument_flag(bytes, b"--verify-function")
600                    || argument_flag(bytes, b"--verify-root")) { return true; }
601                i += 1;
602            }
603        }
604        sail_proof! { assert(args@.take(i as int) =~= args@); }
605        false
606    }
607}
608
609sail_verified! {
610    /// Checks arbitrary candidate index data before minting actual report authority.
611    /// Candidate production and sorting need no correctness assumption.
612    #[allow(clippy::question_mark, reason = "Keep the explicit checked refusal branch in the shared source.")]
613    pub fn complete_report_ordered<'a>(report: &'a Report, policy: CompletionPolicy,
614        forward: &[usize], inverse: &[usize]) -> (out: Option<CompleteReport<'a>>)
615        requires(true)
616        ensures(out.is_some() ==> successful_report(report, policy),
617            out.is_some() ==> authority_report(&out.unwrap()) == report,
618            out.is_some() ==> authority_policy(&out.unwrap()) == policy,
619            out.is_some() ==> report_authority_valid(&out.unwrap()),
620            small_positive_report(report, policy) && forward@.len() == 0 && inverse@.len() == 0
621                ==> out.is_some())
622    {
623        if !completed_report_records(report, policy) { return None; }
624        let Some(ids) = collect_report_ids(report) else { return None; };
625        if !unique_obligations(&ids, forward, inverse) { return None; }
626        Some(CompleteReport { report, policy })
627    }
628}
629
630sail_verified! {
631    /// Checks confirmed verdict, evidence tier and actual provenance counts.
632    pub fn confirmed_function(f: &FunctionReport) -> (out: bool)
633        requires(true)
634        ensures(out == confirmed(f))
635    {
636        let p = &f.provenance;
637        let provenance = match p.source {
638            SourceSummaryName::Fresh => p.checks_solved > 0 && p.checks_served == 0 && p.checks_unrecorded == 0,
639            SourceSummaryName::Cache => p.checks_solved == 0 && p.checks_served > 0 && p.checks_unrecorded == 0,
640            SourceSummaryName::Mixed => p.checks_solved > 0 && p.checks_served > 0 && p.checks_unrecorded == 0,
641            SourceSummaryName::Unrecorded => p.checks_unrecorded > 0
642                || (p.checks_solved == 0 && p.checks_served == 0 && p.checks_unrecorded == 0),
643        };
644        matches!(f.verdict, VerdictName::Verified)
645            && matches!(f.establishment, EstablishmentName::Confirmed)
646            && f.evidence_tier.is_some()
647            && provenance
648    }
649}
650
651sail_verified! {
652    /// Counts only independently checked confirmed functions.
653    fn confirmed_counts(c: &CrateReport) -> (out: Option<(u64, u64)>)
654        requires(true)
655        ensures(out.is_some() ==> out.unwrap().0 == c.functions@.len(),
656            out.is_some() ==> out.unwrap().1 == unstable_functions(c.functions@),
657            out.is_some() ==> forall |i: int| 0 <= i < c.functions@.len() ==> confirmed(&c.functions@[i]),
658            (c.functions@.len() <= 1 && forall |i: int| 0 <= i < c.functions@.len() ==> confirmed(&c.functions@[i]))
659                ==> out.is_some())
660    {
661        if c.functions.len() as u128 > u128::from(u64::MAX) { return None; }
662        let mut i = 0usize;
663        let mut unstable = 0u64;
664        sail_while! { (i < c.functions.len())
665            invariant(i <= c.functions.len(), c.functions.len() <= u64::MAX,
666                unstable <= i, unstable == unstable_functions(c.functions@.take(i as int)),
667                forall |j: int| 0 <= j < i ==> confirmed(&c.functions@[j]))
668            decreases(c.functions.len() - i)
669            {
670                if !confirmed_function(&c.functions[i]) { return None; }
671                if c.functions[i].unstable { unstable += 1; }
672                sail_proof! {
673                    assert(c.functions@.take(i as int + 1).drop_last() == c.functions@.take(i as int));
674                    assert(c.functions@.take(i as int + 1).last() == c.functions@[i as int]);
675                    reveal(unstable_functions);
676                }
677                i += 1;
678            }
679        }
680        sail_proof! { assert(c.functions@.take(i as int) =~= c.functions@); }
681        Some((c.functions.len() as u64, unstable))
682    }
683}
684
685sail_verified! {
686    /// Checks exact report fields and summaries; a zero-function crate is valid.
687    fn completed_report_records(report: &Report, policy: CompletionPolicy) -> (out: bool)
688        requires(true)
689        ensures(out ==> successful_records(report, policy),
690            (successful_records(report, policy) && report.crates@.len() == 1
691                && report.crates@[0].functions@.len() <= 1) ==> out)
692    {
693        if !verification_enabled_command(&report.command) { return false; }
694        if report.schema_version != crate::output::SCHEMA_VERSION || report.exit_code != Some(0) || report.error.is_some()
695            || report.crates.is_empty() { return false; }
696        let engine_allowed = match (policy, &report.engine) {
697            (CompletionPolicy::Repair, Some(engine)) => matches!(engine.established_by, EngineEstablishment::Engine),
698            _ => true,
699        };
700        if !engine_allowed { return false; }
701        let mut i = 0usize;
702        let mut functions = 0u64;
703        let mut unstable = 0u64;
704        sail_while! { (i < report.crates.len())
705            invariant(i <= report.crates.len(),
706                functions == function_count(report.crates@.take(i as int)),
707                unstable == unstable_count(report.crates@.take(i as int)),
708                forall |j: int| 0 <= j < i ==> crate_completed(&report.crates@[j], policy),
709                forall |j: int, k: int| 0 <= j < i && 0 <= k < report.crates@[j].functions@.len()
710                    ==> confirmed(&report.crates@[j].functions@[k]))
711            decreases(report.crates.len() - i)
712            {
713                let c = &report.crates[i];
714                if !completed_crate(c, policy) { return false; }
715                let Some(counts) = confirmed_counts(c) else { return false; };
716                if u64::MAX - functions < counts.0 || u64::MAX - unstable < counts.1 {
717                    return false;
718                }
719                functions += counts.0;
720                unstable += counts.1;
721                sail_proof! {
722                    assert(report.crates@.take(i as int + 1).drop_last() == report.crates@.take(i as int));
723                    assert(report.crates@.take(i as int + 1).last() == report.crates@[i as int]);
724                    reveal(function_count);
725                    reveal(unstable_count);
726                }
727                i += 1;
728            }
729        }
730        sail_proof! { assert(report.crates@.take(i as int) =~= report.crates@); }
731        report.summary.functions == functions && report.summary.verified == functions
732            && report.summary.failed == 0 && report.summary.unknown == 0 && report.summary.provisional == 0
733            && report.summary.unstable == unstable
734    }
735}
736
737sail_verified! {
738    /// Appends every actual obligation ID after checking its exact ownership.
739    fn append_obligations(f: &FunctionReport, seen: &mut Vec<Vec<u8>>) -> (out: bool)
740        requires(true)
741        ensures(out == owned_function_ids(f),
742            out ==> final(seen)@.map_values(|v: Vec<u8>| v@)
743                == old(seen)@.map_values(|v: Vec<u8>| v@) + obligation_ids(f))
744    {
745        if let Some(os) = &f.obligations {
746            let mut i = 0usize;
747            sail_while! { (i < os.len())
748                invariant(i <= os.len(),
749                    obligation_ids(f) == os@.map_values(|o: crate::output::ObligationReport| string_bytes(&o.id)),
750                    seen@.map_values(|v: Vec<u8>| v@) == old(seen)@.map_values(|v: Vec<u8>| v@) + obligation_ids(f).take(i as int),
751                    forall |j: int| 0 <= j < i ==> obligation_ids(f)[j].len() > string_bytes(&f.function).len()
752                        && obligation_ids(f)[j][string_bytes(&f.function).len() as int] == 35u8
753                        && forall |k: int| 0 <= k < string_bytes(&f.function).len() ==>
754                            obligation_ids(f)[j][k] == string_bytes(&f.function)[k])
755                decreases(os.len() - i)
756                {
757                    let id = os[i].id.as_str().as_bytes();
758                    let name = f.function.as_str().as_bytes();
759                    if !owned_obligation(name, id) {
760                        sail_proof! {
761                            assert(obligation_ids(f)[i as int] == id@);
762                            if owned_function_ids(f) {
763                                assert(obligation_ids(f)[i as int].len() > string_bytes(&f.function).len());
764                                assert(sail_acceptance::authority::owned_id(name, id));
765                            }
766                        }
767                        return false;
768                    }
769                    seen.push(copy_bytes(id));
770                    sail_proof! {
771                        assert(obligation_ids(f).take(i as int + 1)
772                            == obligation_ids(f).take(i as int).push(obligation_ids(f)[i as int]));
773                        assert(seen@.map_values(|v: Vec<u8>| v@) =~=
774                            old(seen)@.map_values(|v: Vec<u8>| v@) + obligation_ids(f).take(i as int + 1));
775                    }
776                    i += 1;
777                }
778            }
779        }
780        true
781    }
782}
783
784sail_verified! {
785    /// Collects every actual obligation, checking its exact owning function.
786    pub fn collect_report_ids(report: &Report) -> (out: Option<Vec<Vec<u8>>>)
787        requires(true)
788        ensures(out.is_some() == all_owned_ids(report.crates@),
789            out.is_some() ==> out.unwrap()@.map_values(|v: Vec<u8>| v@) == report_ids(report.crates@))
790    {
791        let mut seen: Vec<Vec<u8>> = Vec::new();
792        let mut i = 0usize;
793        sail_while! { (i < report.crates.len())
794            invariant(i <= report.crates.len(),
795                seen@.map_values(|v: Vec<u8>| v@) == report_ids(report.crates@.take(i as int)),
796                all_owned_ids(report.crates@.take(i as int)))
797            decreases(report.crates.len() - i)
798            {
799                let c = &report.crates[i];
800                let mut j = 0usize;
801                sail_while! { (j < c.functions.len())
802                    invariant(j <= c.functions.len(), i < report.crates.len(), c == &report.crates@[i as int],
803                        seen@.map_values(|v: Vec<u8>| v@)
804                            == report_ids(report.crates@.take(i as int)) + function_ids(c.functions@.take(j as int)),
805                                all_owned_ids(report.crates@.take(i as int)),
806                        forall |k: int| 0 <= k < j ==> owned_function_ids(&c.functions@[k]))
807                    decreases(c.functions.len() - j)
808                    {
809                        if !append_obligations(&c.functions[j], &mut seen) {
810                            sail_proof! {
811                                if all_owned_ids(report.crates@) {
812                                    assert(owned_function_ids(&report.crates@[i as int].functions@[j as int]));
813                                }
814                            }
815                            return None;
816                        }
817                        sail_proof! {
818                            assert(c.functions@.take(j as int + 1).drop_last() == c.functions@.take(j as int));
819                            assert(c.functions@.take(j as int + 1).last() == c.functions@[j as int]);
820                            reveal(function_ids);
821                        }
822                        j += 1;
823                    }
824                }
825                sail_proof! {
826                    assert(c.functions@.take(j as int) =~= c.functions@);
827                    assert(report.crates@.take(i as int + 1).drop_last() == report.crates@.take(i as int));
828                    assert(report.crates@.take(i as int + 1).last() == report.crates@[i as int]);
829                    reveal(report_ids);
830                }
831                i += 1;
832            }
833        }
834        sail_proof! { assert(report.crates@.take(i as int) =~= report.crates@); }
835        Some(seen)
836    }
837}
838
839sail_verified! {
840    /// Checks real crate summary records, preserving solver-free success.
841    pub fn completed_crate(c: &CrateReport, policy: CompletionPolicy) -> (out: bool)
842        requires(true)
843        ensures(out == crate_completed(c, policy))
844    {
845        c.verus.errors == Some(0) && c.verus.encountered_vir_error != Some(true)
846            && match policy {
847                CompletionPolicy::Receipt => c.verus.success != Some(false),
848                CompletionPolicy::Whole | CompletionPolicy::Repair => c.verus.success == Some(true),
849            }
850    }
851}