Skip to main content

artifactize_core/project/
verify.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    path::Path,
4    sync::Arc,
5};
6
7use tokio_util::sync::CancellationToken;
8
9use crate::{
10    broker::{self, now},
11    cache,
12    config::{self, ProfileKind, read_workspace_declarations_with},
13    graph::{EvalStatus, Evidence, Graph},
14    project::selection::Selection,
15    remote::Session,
16    store::{self, ExecutionOptions, Receipts, Request, Run, RunView},
17    workspace,
18};
19
20#[derive(Debug, Clone, Default)]
21pub struct VerifyOptions {
22    pub modes: crate::runs::RunModes,
23    /// Optional per-Run concurrency cap; absent admits every READY eval.
24    pub jobs: Option<usize>,
25    /// Fingerprints computed at once, in preparation and end-of-review rechecks; `None` uses
26    /// the available CPUs.
27    pub fingerprint_jobs: Option<usize>,
28    pub max_executions: Option<u64>,
29    /// Kinds whose evals only reuse a result, from the cache or the review store; one with
30    /// nothing to reuse is not executed, and the Run ends INCOMPLETE.
31    pub reuse_only: BTreeSet<ProfileKind>,
32    pub recursive: bool,
33    /// Force only explicitly selected Evals, never recursive dependencies.
34    pub force: bool,
35    /// What the requester is working on, shown with the Run; it changes nothing it does.
36    pub comment: Option<crate::types::RunComment>,
37    /// Override only declared profile matches for this Run. `None` selects the default branch.
38    pub profile_variables: BTreeMap<String, Option<String>>,
39}
40
41/// Submit to artifactize and observe settlement. Cancelling this future/token only stops watching.
42pub async fn verify(
43    repo: &Path,
44    state_dir: Option<&Path>,
45    selection: &Selection,
46    options: &VerifyOptions,
47    cancellation: CancellationToken,
48) -> Result<RunView, String> {
49    super::fingerprint_parallelism(options)?;
50    let context = crate::runs::Context::discover(repo, state_dir)?;
51    let observation = crate::runs::start(&context, selection, options, None).await?;
52    crate::runs::wait(&context, &observation.run, None, cancellation).await?;
53    crate::runs::view(&context, &observation.run).await
54}
55/// Validate declarations and reserve initial requests; fingerprints and remote I/O follow admission.
56pub(crate) async fn reserve(
57    repo: &Path,
58    state_dir: Option<&Path>,
59    selection: &Selection,
60    options: &VerifyOptions,
61    request_key: Option<&crate::types::RequestKey>,
62    request_args_hash: Option<&str>,
63    origin: &crate::runs::Origin,
64) -> Result<(crate::types::RunId, bool), String> {
65    if options.jobs == Some(0) {
66        return Err("jobs must be at least 1.".into());
67    }
68    let parallelism = super::fingerprint_parallelism(options)?;
69    let config =
70        read_workspace_declarations_with(repo, &|name| match options.profile_variables.get(name) {
71            Some(value) => value.clone(),
72            None => config::lang::process_environment(name),
73        })
74        .map_err(|e| e.to_string())?;
75    for (name, value) in &options.profile_variables {
76        if !config
77            .program
78            .as_ref()
79            .is_some_and(|program| program.environment.contains_key(name))
80        {
81            return Err(format!("No profile matches variable `{name}`."));
82        }
83        if value.as_ref().is_some_and(|value| value.trim().is_empty()) {
84            return Err(format!(
85                "Profile variable `{name}` needs a branch name or null."
86            ));
87        }
88    }
89    let graph = Graph::new(&config).map_err(|e| e.to_string())?;
90    let plan = selection.plan(&config, &graph, options.recursive)?;
91    let selected_ids: BTreeSet<_> = plan.selected.iter().map(|eval| &eval.id).collect();
92    let mut definitions = store::definitions::Definitions::from_view(&crate::query::scoped_graph(
93        &config,
94        selection,
95        &graph,
96        plan.required.iter().copied(),
97    ))
98    .map_err(|error| error.to_string())?;
99    // The Run keeps the code it read, so a reader shows its verdicts on that code later,
100    // whatever the files say by then. Its declarations alone decide its acceptance.
101    if let Some(program) = &config.program {
102        definitions.remember_sources(program);
103    }
104    if plan.required.len() < config.artifacts.len() {
105        definitions.remember_scope(crate::config::DeclarationScope::of(
106            &config,
107            plan.required.iter().copied(),
108        ));
109    }
110    let state = store::state_dir(state_dir)?;
111    let _limits = crate::limits::Limits::read(&state)?;
112    let receipts = Receipts::open(&state, &config.root).await?;
113    let result = async {
114        let runs = workspace::prepare_directory(&state.join("runs"), &config.root)
115            .map_err(|e| e.to_string())?;
116        let directory =
117            crate::platform::private_tempdir_in("run-", &runs).map_err(|e| e.to_string())?;
118        let id = directory
119            .path()
120            .file_name()
121            .unwrap()
122            .to_str()
123            .expect("generated run directory names are ASCII")
124            .to_owned();
125        directory.keep().map_err(|e| e.to_string())?;
126        let run = Run {
127            modes: options.modes.clone(),
128            control: Some(crate::runs::Control::starting()?),
129            request_key: request_key.cloned(),
130            request_args_hash: request_args_hash.map(str::to_owned),
131            origin: Some(origin.clone()),
132            comment: options.comment.clone(),
133            id: id.parse()?,
134            repo_path: config.root.clone(),
135            repository: crate::repository::identify(&config.root),
136            state_dir: state,
137            state: crate::store::RunState::Running,
138            created_at: now(),
139            selection: selection.clone(),
140            definitions,
141            jobs: options.jobs,
142            fingerprint_jobs: Some(parallelism.limit()),
143            max_executions: options.max_executions,
144            executions_started: 0,
145            wait_timeout_ms: None,
146            wait_timed_out: false,
147            reuse_only: options.reuse_only.clone(),
148            recursive: options.recursive,
149            force: options.force,
150            validation: Default::default(),
151            stopped_backends: Vec::new(),
152            evidence: BTreeMap::new(),
153        };
154        let requests: Vec<_> = plan
155            .included
156            .iter()
157            .enumerate()
158            .map(|(ordinal, eval)| Request {
159                state: crate::store::RequestState::pending(
160                    crate::types::RequestStatus::Queued,
161                    None,
162                )
163                .expect("queued state"),
164                id: format!("{}-{}", run.id, ordinal + 1)
165                    .parse()
166                    .expect("generated request id is a safe segment"),
167                run_id: run.id.clone(),
168                eval_id: eval.id.clone(),
169                target: eval.target.clone(),
170                title: eval.declaration.title.clone(),
171                profile: (eval.declaration.profile()).into(),
172                requested_profile: (eval.declaration.profile()).into(),
173                eval_def_hash: cache::eval_definition_hash(&eval.declaration),
174                options: ExecutionOptions {
175                    mutex: eval.declaration.mutex.clone(),
176                    ..ExecutionOptions::new(eval.declaration.profile())
177                },
178                execution_id: None,
179                provenance: None,
180                usage: None,
181                reused_usage: None,
182                joined: false,
183                producer: None,
184                reviewer: None,
185                origin: None,
186                session_id: None,
187                session: None,
188                review_notes: None,
189                human_definition: None,
190                payload: eval.declaration.payload().into(),
191                references: eval.references.clone(),
192                deps: eval.deps.clone(),
193                force: options.force && selected_ids.contains(&eval.id),
194                fingerprint: None,
195                key: None,
196                fingerprints: Default::default(),
197                created_at: run.created_at,
198                started_at: None,
199                cwd: config.root.join(config.artifacts[&eval.target].folder()),
200                run_dir: None,
201                argv: None,
202                child: None,
203                blocked_reason: None,
204                blocked_by: Vec::new(),
205            })
206            .collect();
207        let id = receipts.reserve(&run, &requests).await?;
208        let accepted = id == run.id;
209        if !accepted {
210            let _ = std::fs::remove_dir(run.state_dir.join("runs").join(run.id.as_str()));
211        }
212        Ok((id, accepted))
213    }
214    .await;
215    let closed = receipts.close().await;
216    result.and_then(|reserved| closed.map(|()| reserved))
217}
218/// Keep the failure kind typed through execution; prefixes belong only to display.
219#[derive(Debug, thiserror::Error)]
220pub(crate) enum Error {
221    #[error("INPUT_CHANGED: {0}")]
222    InputChanged(String),
223    #[error("{0}")]
224    Preparation(String),
225}
226impl Error {
227    pub(crate) fn code(&self) -> crate::types::FailureCode {
228        match self {
229            Self::InputChanged(_) => crate::types::FailureCode::InputChanged,
230            Self::Preparation(_) => crate::types::FailureCode::PreparationFailed,
231        }
232    }
233}
234impl From<String> for Error {
235    fn from(message: String) -> Self {
236        Self::Preparation(message)
237    }
238}
239impl From<&str> for Error {
240    fn from(message: &str) -> Self {
241        Self::Preparation(message.into())
242    }
243}
244
245/// Execute exactly the admitted Run. Never reserve a second Run or substitute changed declarations.
246pub(crate) async fn execute(
247    mut run: Run,
248    receipts: &Receipts,
249    cancellation: CancellationToken,
250) -> Result<(), Error> {
251    let selection = &run.selection.clone();
252    let options = &VerifyOptions {
253        modes: run.modes.clone(),
254        jobs: run.jobs,
255        fingerprint_jobs: run.fingerprint_jobs,
256        max_executions: run.max_executions,
257        reuse_only: run.reuse_only.clone(),
258        recursive: run.recursive,
259        force: run.force,
260        comment: run.comment.clone(),
261        ..VerifyOptions::default()
262    };
263    let repo = &run.repo_path;
264    let state_dir = Some(run.state_dir.as_path());
265    if options.jobs == Some(0) {
266        return Err("jobs must be at least 1.".into());
267    }
268    let parallelism = super::fingerprint_parallelism(options)?;
269    // The profiles read the environment the Run was submitted with, not this process's.
270    let accepted = Accepted::new(selection, std::mem::take(&mut run.definitions))?;
271    let state = store::state_dir(state_dir)?;
272    let limits = crate::limits::Limits::read(&state)?;
273    let runs =
274        workspace::prepare_directory(&state.join("runs"), repo).map_err(|e| e.to_string())?;
275    let inputs = {
276        let config = accepted.read(repo)?;
277        let graph = Graph::new(&config).map_err(|error| Error::InputChanged(error.to_string()))?;
278        let plan = accepted.plan(&config, &graph, options.recursive)?;
279        cache::Inputs::new(&config, &plan.evals)?
280    };
281    crate::platform::release_free_memory();
282    let prepared = inputs
283        .prepare(&runs, &parallelism, cancellation.clone())
284        .await?;
285    if cancellation.is_cancelled() {
286        return Err("Project preparation was cancelled.".into());
287    }
288    // The accepted declarations must still match at the execution boundary. The second
289    // expansion is also what the broker uses; no expanded graph was kept during fingerprinting.
290    let config = Arc::new(accepted.read(repo)?);
291    let graph = Graph::new(&config).map_err(|error| Error::InputChanged(error.to_string()))?;
292    let plan = accepted.plan(&config, &graph, options.recursive)?;
293    let required = &plan.required;
294    let fingerprints: BTreeMap<_, _> = prepared
295        .into_iter()
296        .map(|(id, value)| {
297            let (id, _) = config
298                .artifacts
299                .get_key_value(&id)
300                .expect("in accepted fingerprint scope");
301            (id, value)
302        })
303        .collect();
304    let keys: BTreeMap<_, _> = plan
305        .evals
306        .iter()
307        .filter_map(|eval| {
308            Some((
309                &eval.id,
310                cache::eval_key(&config, eval, &fingerprints).ok()?,
311            ))
312        })
313        .collect();
314    // The store is asked once for every key, and a record that completed after the local
315    // latest is mirrored into the local history before the Run claims anything. A forced Run
316    // reads nothing from the store, but publishes its results like any other.
317    let remote = Session::open(Some(&state), Some(&config.root))?;
318    // Results from a fake provider must never reach the shared review store.
319    if remote.is_some()
320        && let Some(variable) = crate::llm::active_test_endpoint()
321    {
322        return Err(format!(
323            "{variable} points Agent reviews at a local test endpoint; set ARTIFACTIZE_REMOTE=off so their results stay out of the review store."
324        ).into());
325    }
326    if let Some(remote) = &remote
327        && !options.force
328    {
329        remote
330            .refresh(
331                receipts,
332                keys.values().map(|key| key.value.clone()).collect(),
333            )
334            .await?;
335        // The store can take time: don't start an eval against a declaration changed since
336        // the execution-boundary read above.
337        accepted.recheck(repo)?;
338    }
339    let mut requests = store::read_run_requests_only(&state, &run.id).await?;
340    let included: BTreeMap<_, _> = plan.included.iter().map(|&eval| (&eval.id, eval)).collect();
341    for request in &mut requests {
342        request.fingerprint = fingerprints
343            .get(&request.target)
344            .map(|fingerprint| fingerprint.value.clone());
345        request.key = keys.get(&request.eval_id).map(|key| key.value.clone());
346        let eval = included.get(&request.eval_id)
347            .ok_or_else(|| {
348                format!(
349                    "Saved request {} in Run {} refers to Eval {}, which is missing from the workspace configuration.",
350                    request.id, request.run_id, request.eval_id
351                )
352            })?;
353        request.fingerprints = cache::dependencies(&config, eval)
354            .into_iter()
355            .filter_map(|name| {
356                fingerprints
357                    .get(name)
358                    .map(|fingerprint| (name.clone(), fingerprint.value.clone()))
359            })
360            .collect();
361        receipts.save_request(request).await?;
362    }
363    run.control.as_mut().expect("owned Run").activity = crate::runs::Activity::Executing;
364    receipts.save_run(&run).await?;
365    let mut evidence = match broker::schedule(
366        config.clone(),
367        &graph,
368        &plan.evals,
369        &fingerprints,
370        &keys,
371        &parallelism,
372        &limits,
373        &mut run,
374        &mut requests,
375        receipts,
376        remote.clone(),
377        cancellation.clone(),
378    )
379    .await
380    {
381        Ok(evidence) => evidence,
382        Err(error) => {
383            return Err(error.into());
384        }
385    };
386    let evaluation = graph.evaluate_for_run(&evidence, run.modes.gating());
387    // Freeze cancellation once at settlement so the Run and its requests agree.
388    let cancelled = cancellation.is_cancelled();
389    let at = now();
390    for request in &mut requests {
391        // A cancelled Run withdraws its waiting sign-offs too, deferred ones included.
392        let withdrawn = request.status().is_human_wait() && cancelled;
393        if !withdrawn
394            && (evidence.contains_key(request.eval_id.as_str()) || request.status().is_human_wait())
395        {
396            continue;
397        }
398        let eval = &evaluation.evals[request.eval_id.as_str()];
399        if request.status() == crate::types::RequestStatus::Blocked && !cancelled {
400            // A block saved mid-Run named the causes known then; the settled Run names all.
401            if eval.status == EvalStatus::Blocked {
402                request.blocked_by = eval.blocked_by.iter().copied().map(Into::into).collect();
403                request.blocked_reason = Some(gate_reason(eval));
404            }
405            continue;
406        }
407        if cancelled {
408            request.state = crate::store::RequestState::failed(
409                "Run was cancelled.".into(),
410                Some(crate::types::FailureCode::Cancelled),
411                at,
412            );
413            evidence.insert(request.eval_id.clone(), Evidence::OperationalError);
414        } else if request.status() == crate::types::RequestStatus::BudgetExhausted
415            && eval.can_execute()
416        {
417            continue;
418        } else {
419            request.state =
420                crate::store::RequestState::pending(status(eval.status), request.completed_at())
421                    .expect("non-executed request state");
422            request.blocked_reason = Some(gate_reason(eval));
423        }
424    }
425    let evaluation = graph.evaluate_for_run(&evidence, run.modes.gating());
426    let required_evals: Vec<_> = evaluation
427        .evals
428        .iter()
429        .filter(|(id, _)| required.contains(&graph.eval_target(id).unwrap()))
430        .collect();
431    let satisfied = required
432        .iter()
433        .all(|id| evaluation.artifacts[id.as_str()].satisfied());
434    let budget_exhausted = requests
435        .iter()
436        .any(|request| request.status() == crate::types::RequestStatus::BudgetExhausted);
437    // Only a --reuse-only eval that had nothing to reuse leaves stale evidence in a Run.
438    let not_reused = evidence
439        .values()
440        .filter(|evidence| matches!(evidence, Evidence::Stale))
441        .count();
442    run.state = terminal_state(
443        TerminalFacts {
444            required_evals: &required_evals,
445            satisfied,
446            required_have_review_basis: required.iter().all(|id| {
447                // A parent without evals of its own is reviewed through its parts.
448                let artifact = &graph.artifacts()[id.as_str()];
449                artifact.basis || !artifact.evals.is_empty() || !artifact.parts.is_empty()
450            }),
451            budget_error: budget_exhausted.then(|| broker::budget_reason(&run)),
452            not_reused,
453        },
454        at,
455        cancelled,
456    );
457    if cancelled {
458        run.control.as_mut().expect("owned Run").failure_code =
459            Some(crate::types::FailureCode::Cancelled);
460    }
461    use crate::config::Field;
462    run.validation = store::Validation(Some(store::ValidationSnapshot {
463        selection: Field::Value(store::definitions::SavedSelection {
464            known: run.selection.clone(),
465            extra: Default::default(),
466        }),
467        recursive: Field::Value(run.recursive),
468        force: Field::Value(run.force),
469        selected_eval_ids: Field::Value(plan.selected.iter().map(|eval| eval.id.clone()).collect()),
470        included_eval_ids: Field::Value(plan.included.iter().map(|eval| eval.id.clone()).collect()),
471        satisfied: Field::Value(satisfied && !cancelled),
472        obligations: Field::Value(
473            evaluation
474                .obligations
475                .iter()
476                .filter(|id| required.contains(*id))
477                .map(|id| (*id).clone())
478                .collect(),
479        ),
480        artifacts: Field::Value(
481            required
482                .iter()
483                .map(|id| {
484                    let artifact = &evaluation.artifacts[id.as_str()];
485                    let (fingerprint_kind, fingerprint) = fingerprints.get(id).map_or(
486                        (Field::Missing, Field::Missing),
487                        |fingerprint| {
488                            (
489                                config.artifacts[*id]
490                                    .fingerprint
491                                    .as_ref()
492                                    .map(crate::config::Fingerprint::kind)
493                                    .into(),
494                                Field::Value(fingerprint.value.clone()),
495                            )
496                        },
497                    );
498                    store::ArtifactValidation {
499                        id: (*id).clone(),
500                        status: Field::Value(artifact.status.into()),
501                        passed: Field::Value(artifact.passed as u64),
502                        total: Field::Value(artifact.total as u64),
503                        satisfied: Field::Value(artifact.satisfied()),
504                        fingerprint_kind,
505                        fingerprint,
506                        extra: Default::default(),
507                    }
508                })
509                .collect(),
510        ),
511        evals: Field::Value(
512            required_evals
513                .iter()
514                .map(|(id, eval)| store::EvalValidation {
515                    id: (*id).clone(),
516                    status: Field::Value(status(eval.status)),
517                    blocked_by: Field::Value(
518                        eval.blocked_by.iter().copied().map(Into::into).collect(),
519                    ),
520                    extra: Default::default(),
521                })
522                .collect(),
523        ),
524        extra: Default::default(),
525    }));
526    if cancelled {
527        receipts
528            .retire_worker(&run.id, crate::types::FailureCode::Cancelled)
529            .await?;
530    }
531    if run.modes.speculate
532        && let Some(remote) = remote
533    {
534        // A blocked result cannot be retracted from a team store. Publish survivors only
535        // after scheduling/withdrawal finishes, while the owned Run still owns failures.
536        let control = run.control.as_mut().expect("owned Run");
537        control.activity = crate::runs::Activity::Publishing;
538        control.only_signoffs = false;
539        let mut publishing = run.clone();
540        publishing.state = crate::store::RunState::Running;
541        receipts.save_run(&publishing).await?;
542        for request in &requests {
543            remote.publish_request(receipts, request).await?;
544        }
545    }
546    // The reuse history is collected once per Run, before it ends so that whoever waits for
547    // the end also sees a failure, which only warns.
548    if let Err(error) = store::history::collect(&run.state_dir).await {
549        use std::io::Write;
550        let _ = writeln!(std::io::stderr().lock(), "Cache GC failed: {error}");
551    }
552    receipts.finish(&run, &requests).await?;
553    // Saved Agent conversations past their size bound are collected; a failure only warns.
554    let state = run.state_dir.clone();
555    let bounds = limits.agent_sessions();
556    let collected = crate::task::joined(
557        tokio::task::spawn_blocking(move || crate::agent::session::collect(&state, bounds, false))
558            .await,
559    )
560    .map_err(|e| e.to_string())
561    .and_then(|collected| collected);
562    if let Err(error) = collected {
563        use std::io::Write;
564        let _ = writeln!(
565            std::io::stderr().lock(),
566            "Agent session collection failed: {error}"
567        );
568    }
569    Ok(())
570}
571
572struct TerminalFacts<'a, 'graph> {
573    required_evals: &'a [(
574        &'a crate::types::EvalId,
575        &'a crate::graph::EvalEvaluation<'graph>,
576    )],
577    satisfied: bool,
578    required_have_review_basis: bool,
579    budget_error: Option<String>,
580    not_reused: usize,
581}
582
583fn terminal_state(
584    facts: TerminalFacts<'_, '_>,
585    at: crate::types::Timestamp,
586    cancelled: bool,
587) -> store::RunState {
588    use store::RunState;
589    let TerminalFacts {
590        required_evals,
591        satisfied,
592        required_have_review_basis,
593        budget_error,
594        not_reused,
595    } = facts;
596    if cancelled {
597        RunState::Error {
598            at,
599            error: Some("Run was cancelled.".into()),
600        }
601    } else if let Some(error) = budget_error {
602        RunState::Incomplete {
603            at,
604            error: Some(error),
605        }
606    } else if not_reused > 0 {
607        RunState::Incomplete {
608            at,
609            error: Some(format!(
610                "{not_reused} eval{} had no result to reuse and {} not executed (--reuse-only).",
611                if not_reused == 1 { "" } else { "s" },
612                if not_reused == 1 { "was" } else { "were" }
613            )),
614        }
615    } else if required_evals
616        .iter()
617        .any(|(_, c)| c.status == EvalStatus::Error)
618    {
619        RunState::Error { at, error: None }
620    } else if required_evals
621        .iter()
622        .any(|(_, c)| c.status == EvalStatus::Red)
623    {
624        RunState::Red { at }
625    } else if required_evals
626        .iter()
627        .any(|(_, eval)| eval.status == EvalStatus::Deferred)
628        && required_evals
629            .iter()
630            .all(|(_, eval)| eval.status.passes_gate())
631        && required_have_review_basis
632    {
633        RunState::Yellow { at }
634    } else if satisfied {
635        RunState::Green { at }
636    } else {
637        RunState::Incomplete { at, error: None }
638    }
639}
640
641pub(crate) fn status(status: EvalStatus) -> crate::types::RequestStatus {
642    match status {
643        EvalStatus::Deferred => crate::types::RequestStatus::Deferred,
644        EvalStatus::Provisional => crate::types::RequestStatus::Provisional,
645        EvalStatus::Green => crate::types::RequestStatus::Green,
646        EvalStatus::Red => crate::types::RequestStatus::Red,
647        EvalStatus::Error => crate::types::RequestStatus::Error,
648        EvalStatus::Stale => crate::types::RequestStatus::Stale,
649        EvalStatus::Unreviewed => crate::types::RequestStatus::Unreviewed,
650        EvalStatus::Wait => crate::types::RequestStatus::WaitDependency,
651        EvalStatus::Blocked => crate::types::RequestStatus::Blocked,
652    }
653}
654
655/// The same gate explanation is saved during scheduling and at Run settlement.
656pub(crate) fn gate_reason(eval: &crate::graph::EvalEvaluation<'_>) -> String {
657    eval.blocked_reason().unwrap_or_else(|| {
658        format!(
659            "Waiting for current GREEN dependency evidence: {}",
660            eval.unmet_gates
661                .iter()
662                .map(ToString::to_string)
663                .collect::<Vec<_>>()
664                .join(", ")
665        )
666    })
667}
668
669/// A compact identity of the immutable admitted definitions. This lives only for the
670/// worker's lifetime; the published Run keeps the full definitions in its saved row.
671struct Accepted<'a> {
672    selection: &'a Selection,
673    environment: BTreeMap<String, Option<String>>,
674    scope: Option<crate::config::DeclarationScope>,
675    digest: [u8; 32],
676}
677
678impl<'a> Accepted<'a> {
679    fn new(
680        selection: &'a Selection,
681        mut saved: store::definitions::Definitions,
682    ) -> Result<Self, Error> {
683        let scope = saved.take_scope();
684        Ok(Self {
685            selection,
686            environment: saved.environment(),
687            scope,
688            digest: definitions_digest(&saved)?,
689        })
690    }
691
692    fn read(&self, repo: &Path) -> Result<crate::config::RepoConfig, Error> {
693        let environment = |name: &str| self.environment.get(name).cloned().flatten();
694        if let Some(scope) = &self.scope
695            && let Ok(mut config) = scope.read(repo, crate::config::Evals::All, &environment)
696        {
697            // Preserve the environment snapshot of the admitted Run, including variables
698            // belonging to profiles that the selected scope does not read.
699            if let Some(program) = &mut config.program {
700                Arc::make_mut(program)
701                    .environment
702                    .clone_from(&self.environment);
703            }
704            if let Ok(view) = crate::query::graph(&config, self.selection)
705                && self.check(&view).is_ok()
706            {
707                return Ok(config);
708            }
709        }
710        crate::config::read_workspace_declarations_with(repo, &environment)
711            .map_err(|error| Error::InputChanged(error.to_string()))
712    }
713
714    fn plan<'b>(
715        &self,
716        config: &'b crate::config::RepoConfig,
717        graph: &Graph<'b>,
718        recursive: bool,
719    ) -> Result<crate::project::selection::Plan<'b>, Error> {
720        let plan = self
721            .selection
722            .plan(config, graph, recursive)
723            .map_err(Error::InputChanged)?;
724        self.check(&crate::query::scoped_graph(
725            config,
726            self.selection,
727            graph,
728            plan.required.iter().copied(),
729        ))?;
730        Ok(plan)
731    }
732
733    fn recheck(&self, repo: &Path) -> Result<(), Error> {
734        let config = self.read(repo)?;
735        let view = crate::query::graph(&config, self.selection).map_err(Error::InputChanged)?;
736        self.check(&view)
737    }
738
739    fn check(&self, view: &crate::query::GraphView<'_>) -> Result<(), Error> {
740        let current = store::definitions::Definitions::from_view(view)
741            .map_err(|error| Error::InputChanged(error.to_string()))?;
742        if definitions_digest(&current)? != self.digest {
743            return Err(Error::InputChanged(
744                "declarations changed after acceptance.".into(),
745            ));
746        }
747        Ok(())
748    }
749}
750
751fn definitions_digest(definitions: &store::definitions::Definitions) -> Result<[u8; 32], Error> {
752    use sha2::{Digest, Sha256};
753    let graph = definitions
754        .graph()
755        .ok_or_else(|| Error::InputChanged("The Run has no saved declarations.".into()))?;
756    // Component numbers are positions in the caller's graph, not declarations. The
757    // Artifact parts, eval inputs and labeled relations already determine the components;
758    // a scope read and a workspace read may number the same component differently.
759    let identity = (
760        &graph.version,
761        &graph.repo_path,
762        &graph.selection,
763        &graph.artifacts,
764        &graph.evals,
765        &graph.relations,
766        &graph.extra,
767    );
768    let bytes =
769        serde_json::to_vec(&identity).map_err(|error| Error::InputChanged(error.to_string()))?;
770    Ok(Sha256::digest(bytes).into())
771}
772
773#[cfg(test)]
774mod tests;