use crate::{
config::{ArtifactKind, Profile, ProfileKind, RepoConfig},
monitor::model::{self, Card, Status, Tone},
project::{
ArtifactCondition, EvalCondition, EvalState, StatusView, VerifyAction, VerifyOptions,
selection::Selection,
},
store::{Claim, Execution, ExecutionResult},
types::{ArtifactName, EvalId},
};
use std::{
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
sync::Arc,
};
use time::OffsetDateTime;
use tokio_util::sync::CancellationToken;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Plan {
Run,
Check,
Unchecked,
Blocked,
Wait,
Reuse,
}
impl Plan {
pub fn word(self) -> &'static str {
match self {
Self::Run => "would run",
Self::Check => "checking",
Self::Unchecked => "not checked",
Self::Blocked => "blocked",
Self::Wait => "waiting",
Self::Reuse => "reused",
}
}
pub fn glyph(self) -> &'static str {
match self {
Self::Run => "○",
Self::Check => "…",
Self::Unchecked => "–",
Self::Blocked => Status::Blocked.glyph(),
Self::Wait => Status::Wait.glyph(),
Self::Reuse => "↻",
}
}
pub fn tone(self) -> Tone {
match self {
Self::Run => Tone::Running,
Self::Check | Self::Unchecked => Tone::Muted,
Self::Blocked => Tone::Blocked,
Self::Wait => Tone::Queued,
Self::Reuse => Tone::Green,
}
}
}
impl CurrentArtifact {
pub fn tally(&self) -> Option<model::Tally> {
(!self.evals.is_empty() && !matches!(self.plan, Plan::Check | Plan::Unchecked)).then(|| {
model::Tally {
passed: self
.evals
.iter()
.filter(|eval| eval.plan == Plan::Reuse)
.count(),
of: self.evals.len(),
}
})
}
pub fn text(&self) -> String {
match (self.plan, self.runs) {
(Plan::Run, 1) => "would run (1 eval)".into(),
(plan, 0) => plan.word().into(),
(Plan::Run, runs) => format!("would run ({runs} evals)"),
(plan, _) => plan.word().into(),
}
}
}
impl From<VerifyAction> for Plan {
fn from(action: VerifyAction) -> Self {
match action {
VerifyAction::Execute => Self::Run,
VerifyAction::Blocked => Self::Blocked,
VerifyAction::Wait => Self::Wait,
VerifyAction::Reuse => Self::Reuse,
}
}
}
const UNCHECKED: &str = "Status has not been requested.";
#[derive(Debug, Clone)]
pub struct CurrentEval {
pub id: EvalId,
pub name: String,
pub title: String,
pub kind: ProfileKind,
pub plan: Plan,
pub state: EvalCondition,
pub reason: String,
pub card: Card,
pub facts: Vec<(&'static str, String)>,
observed_at: Option<OffsetDateTime>,
}
#[derive(Debug, Clone)]
pub struct CurrentArtifact {
pub definition: PathBuf,
pub binding: Option<crate::config::Binding>,
pub tools: Option<String>,
pub target_missing: bool,
pub name: ArtifactName,
pub kind: ArtifactKind,
pub plan: Plan,
pub runs: usize,
pub path: crate::config::Target,
pub written_path: String,
pub state: ArtifactCondition,
pub reason: String,
pub evals: Vec<CurrentEval>,
pub parts: Vec<ArtifactName>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurrentEdge {
pub from: ArtifactName,
pub to: ArtifactName,
pub plan: Plan,
}
#[derive(Debug, Clone)]
pub struct Current {
pub scanned_at: Option<OffsetDateTime>,
pub artifacts: Vec<CurrentArtifact>,
pub edges: Vec<CurrentEdge>,
pub sites: Arc<crate::config::SiteIndex>,
pub parents: Arc<BTreeMap<ArtifactName, Vec<ArtifactName>>>,
incoming: Arc<BTreeMap<ArtifactName, Vec<usize>>>,
}
impl Current {
pub fn from_shape(
mut artifacts: Vec<CurrentArtifact>,
mut edges: Vec<CurrentEdge>,
sites: Arc<crate::config::SiteIndex>,
) -> Self {
artifacts.sort_by(|one, other| one.name.cmp(&other.name));
edges.sort_by(|one, other| (&one.from, &one.to).cmp(&(&other.from, &other.to)));
let mut parents: BTreeMap<_, Vec<_>> = BTreeMap::new();
for whole in &artifacts {
for part in &whole.parts {
parents
.entry(part.clone())
.or_default()
.push(whole.name.clone());
}
}
let mut incoming: BTreeMap<_, Vec<_>> = BTreeMap::new();
for (index, edge) in edges.iter().enumerate() {
incoming.entry(edge.to.clone()).or_default().push(index);
}
Self {
scanned_at: None,
artifacts,
edges,
sites,
parents: Arc::new(parents),
incoming: Arc::new(incoming),
}
}
pub fn adjacent(&self, name: &ArtifactName) -> (Vec<&CurrentEdge>, Vec<&CurrentEdge>) {
let incoming = self
.incoming
.get(name)
.into_iter()
.flatten()
.map(|&at| &self.edges[at])
.collect();
let start = self.edges.partition_point(|edge| &edge.from < name);
let outgoing = self.edges[start..]
.iter()
.take_while(|edge| &edge.from == name)
.collect();
(incoming, outgoing)
}
pub fn copies(&self, name: &ArtifactName) -> u32 {
fn count<'a>(
current: &'a Current,
name: &'a ArtifactName,
memo: &mut BTreeMap<&'a ArtifactName, u32>,
) -> u32 {
if let Some(copies) = memo.get(name) {
return *copies;
}
let copies = current.parents.get(name).map_or(1, |parents| {
parents.iter().fold(0u32, |total, parent| {
total.saturating_add(count(current, parent, memo))
})
});
memo.insert(name, copies);
copies
}
count(self, name, &mut BTreeMap::new())
}
pub fn same_shape(&self, other: &Self) -> bool {
self.artifacts
.iter()
.map(|artifact| (&artifact.name, &artifact.parts))
.eq(other
.artifacts
.iter()
.map(|artifact| (&artifact.name, &artifact.parts)))
&& self
.edges
.iter()
.map(|edge| (&edge.from, &edge.to))
.eq(other.edges.iter().map(|edge| (&edge.from, &edge.to)))
}
}
pub fn outline(repo: &Path) -> Result<Current, String> {
let outline = crate::config::read_workspace_declarations(repo)
.map(|config| declared(&config))
.map_err(|error| error.to_string());
crate::platform::release_free_memory();
outline
}
pub async fn scan(
repo: &Path,
state: &Path,
cancellation: CancellationToken,
mut publish: impl FnMut(Current) + Send,
) -> Result<Current, String> {
let result = async {
let config = read_config(repo, &Selection::All, None).await?;
let mut current = declared(&config);
for artifact in &mut current.artifacts {
artifact.plan = Plan::Check;
artifact.reason = "Waiting for the requested status check.".into();
for eval in &mut artifact.evals {
eval.plan = Plan::Check;
eval.reason.clone_from(&artifact.reason);
}
}
for edge in &mut current.edges {
edge.plan = Plan::Check;
}
publish(current.clone());
let current = scan_config(
config,
current,
state,
&Selection::All,
cancellation,
|_| {},
)
.await?;
publish(current.clone());
Ok(current)
}
.await;
crate::platform::release_free_memory();
result
}
pub async fn scan_scope(
repo: &Path,
state: &Path,
selection: &Selection,
sites: Option<Arc<crate::config::SiteIndex>>,
cancellation: CancellationToken,
progress: impl FnMut(usize) + Send,
) -> Result<Current, String> {
let result = async {
let config = read_config(repo, selection, sites).await?;
let current = declared(&config);
scan_config(config, current, state, selection, cancellation, progress).await
}
.await;
crate::platform::release_free_memory();
result
}
async fn read_config(
repo: &Path,
selection: &Selection,
sites: Option<Arc<crate::config::SiteIndex>>,
) -> Result<RepoConfig, String> {
let repo = repo.to_path_buf();
let indexed = sites.zip(selection.roots());
crate::task::blocking(move || {
let scoped = indexed.and_then(|(sites, names)| {
sites
.subset(
&repo,
names,
crate::config::Evals::All,
&crate::config::lang::process_environment,
)
.ok()
});
scoped.map_or_else(|| crate::config::read_workspace_declarations(&repo), Ok)
})
.await?
.map_err(|error| error.to_string())
}
async fn scan_config(
config: RepoConfig,
mut current: Current,
state: &Path,
selection: &Selection,
cancellation: CancellationToken,
mut progress: impl FnMut(usize) + Send,
) -> Result<Current, String> {
let (status, cached) = crate::project::scan(
config,
Some(state),
selection,
&VerifyOptions::default(),
cancellation,
Some(&mut progress),
)
.await?;
current.apply_status(&status, &cached);
Ok(current)
}
fn declared(config: &RepoConfig) -> Current {
let mut evals: BTreeMap<&ArtifactName, Vec<CurrentEval>> = BTreeMap::new();
let now = OffsetDateTime::now_utc();
for eval in &config.evals {
let profile = eval.declaration.profile();
evals.entry(&eval.target).or_default().push(CurrentEval {
id: eval.id.clone(),
name: crate::monitor::model::tree::local(&eval.id).into(),
title: eval.declaration.title.clone(),
kind: profile.kind(),
plan: Plan::Unchecked,
state: EvalCondition::Unreviewed,
reason: UNCHECKED.into(),
card: card(
eval.declaration.instruction().unwrap_or(""),
profile,
Plan::Unchecked,
None,
now,
),
facts: vec![("Profile", self::profile(profile))],
observed_at: None,
});
}
let artifacts = config
.artifacts
.values()
.map(|artifact| CurrentArtifact {
definition: artifact.definition.clone(),
binding: artifact.binding.clone(),
tools: artifact.tools.clone(),
target_missing: artifact.target_error.is_some(),
name: artifact.name.clone(),
kind: artifact.kind(),
plan: Plan::Unchecked,
runs: 0,
path: artifact.path.clone(),
written_path: artifact.written_path(),
state: ArtifactCondition::Unreviewed,
reason: UNCHECKED.into(),
evals: evals.remove(&artifact.name).unwrap_or_default(),
parts: artifact.parts.iter().cloned().collect(),
})
.collect();
let edges = config
.relations
.iter()
.filter(|rel| rel.source != rel.target && rel.kind != crate::scope::RelationKind::Part)
.map(|rel| (&rel.source, &rel.target))
.collect::<BTreeSet<_>>()
.into_iter()
.map(|(from, to)| CurrentEdge {
from: from.clone(),
to: to.clone(),
plan: Plan::Unchecked,
})
.collect();
Current::from_shape(
artifacts,
edges,
Arc::new(crate::config::SiteIndex::new(config)),
)
}
fn profile(profile: &Profile) -> String {
match profile {
Profile::Agent { backend, model, .. } => format!("agent · {} · {model}", backend.as_str()),
other => other.kind().name().to_owned(),
}
}
fn card(
instruction: &str,
profile: &Profile,
plan: Plan,
reused: Option<&Execution>,
now: OffsetDateTime,
) -> Card {
let result = reused.and_then(Execution::result);
Card {
instruction: instruction.to_owned(),
issues: result.map(ExecutionResult::issues),
raw: result.map(model::raw),
exit_code: result.and_then(ExecutionResult::exit_code),
error: None,
reused: plan == Plan::Reuse,
took: reused
.and_then(|execution| model::span(execution.started_at, execution.completed_at(), now)),
tokens: reused
.and_then(|execution| execution.usage.as_deref())
.and_then(model::attempt_tokens),
model: match profile {
Profile::Agent { model, .. } => Some(model.to_string()),
_ => None,
},
}
}
pub struct CurrentRun(Vec<crate::store::Request>);
pub async fn current_run(
state: &Path,
place: &super::Place,
run: &crate::types::RunId,
) -> Result<CurrentRun, String> {
let (repo, identity) = crate::store::run_checkout(state, run).await?;
if super::Place::for_checkout(&repo, &identity) != *place {
return Err("Run belongs to a different checkout.".into());
}
crate::store::read_run_requests_only(state, run)
.await
.map(CurrentRun)
}
impl Current {
pub fn artifact(&self, name: &ArtifactName) -> Option<&CurrentArtifact> {
let at = self
.artifacts
.binary_search_by(|node| node.name.cmp(name))
.ok()?;
Some(&self.artifacts[at])
}
fn artifact_mut(&mut self, name: &ArtifactName) -> Option<&mut CurrentArtifact> {
let at = self
.artifacts
.binary_search_by(|node| node.name.cmp(name))
.ok()?;
Some(&mut self.artifacts[at])
}
fn apply_status(&mut self, status: &StatusView, cached: &BTreeMap<EvalId, Claim>) {
let now = OffsetDateTime::now_utc();
for artifact in &status.artifacts {
if let Some(node) = self.artifact_mut(&artifact.id) {
node.target_missing = artifact.target_missing;
node.state = artifact.state;
node.reason.clone_from(&artifact.reason);
node.plan = Plan::Reuse;
}
}
for eval in &status.evals {
if let Some(node) = self.artifact_mut(&eval.target)
&& let Some(found) = node.evals.iter_mut().find(|item| item.id == eval.id)
{
forecast(found, eval, cached.get(&eval.id), now);
}
}
self.scanned_at = Some(now);
self.relight(
status
.artifacts
.iter()
.map(|artifact| artifact.id.clone())
.collect(),
);
}
pub fn merge_scope(&mut self, scoped: Current) {
let mut changed = BTreeSet::new();
for node in scoped
.artifacts
.into_iter()
.filter(|node| node.plan != Plan::Unchecked)
{
if let Some(old) = self.artifact_mut(&node.name)
&& old.parts == node.parts
&& old
.evals
.iter()
.map(|e| &e.id)
.eq(node.evals.iter().map(|e| &e.id))
{
changed.insert(node.name.clone());
*old = node;
}
}
self.relight(changed);
}
pub fn apply_run(&mut self, run: CurrentRun) -> bool {
use crate::types::RequestStatus;
let mut changed = BTreeSet::new();
for request in &run.0 {
let completed = if request.key.is_some() {
Plan::Reuse
} else {
Plan::Run
};
let (plan, state) = match request.status() {
RequestStatus::Green => (completed, EvalCondition::Pass),
RequestStatus::Red => (completed, EvalCondition::Red),
RequestStatus::Error => (Plan::Run, EvalCondition::Error),
RequestStatus::Deferred => (Plan::Wait, EvalCondition::Deferred),
RequestStatus::WaitingHuman => (Plan::Wait, EvalCondition::WaitingHuman),
RequestStatus::Blocked => (Plan::Blocked, EvalCondition::Blocked),
_ => continue,
};
let Some(node) = self.artifact_mut(&request.target) else {
continue;
};
let Some(eval) = node
.evals
.iter_mut()
.find(|eval| eval.id == request.eval_id)
else {
continue;
};
let observed = request.completed_at().unwrap_or(request.created_at).time();
if eval
.observed_at
.is_some_and(|previous| previous >= observed)
{
continue;
}
eval.observed_at = Some(observed);
eval.plan = plan;
eval.state = state;
eval.reason = format!(
"As recorded by {}. Check status for changes since that Run.",
request.run_id
);
eval.facts
.retain(|(name, _)| *name == "Profile" || *name == "Eval");
if let Some(key) = &request.key {
eval.facts.push(("Reuse key", key.to_string()));
}
if let Some(fingerprint) = &request.fingerprint {
eval.facts.push(("Fingerprint", fingerprint.to_string()));
}
eval.facts.push(("Last Run", request.run_id.to_string()));
let result = request.result();
eval.card.issues = result.map(ExecutionResult::issues);
eval.card.raw = result.map(model::raw);
eval.card.exit_code = result.and_then(ExecutionResult::exit_code);
eval.card.error = request.error().map(str::to_owned);
eval.card.took = None;
eval.card.tokens = None;
eval.card.reused = plan == Plan::Reuse;
node.reason.clone_from(&eval.reason);
changed.insert(request.target.clone());
}
let any = !changed.is_empty();
self.relight(changed);
any
}
fn relight(&mut self, mut affected: BTreeSet<ArtifactName>) {
let mut work: Vec<_> = affected.iter().cloned().collect();
while let Some(part) = work.pop() {
for whole in self.parents.get(&part).into_iter().flatten() {
if self
.artifact(whole)
.is_some_and(|node| node.evals.is_empty())
&& affected.insert(whole.clone())
{
work.push(whole.clone());
}
}
}
let mut plans = BTreeMap::new();
let mut pending = Vec::new();
for node in affected.iter().filter_map(|name| self.artifact(name)) {
pending.push((node, false));
while let Some((item, ready)) = pending.pop() {
if plans.contains_key(&item.name) {
continue;
}
let plan = if !item.evals.is_empty() {
item.evals
.iter()
.map(|eval| eval.plan)
.min()
.expect("nonempty evals")
} else if item.parts.is_empty() {
item.plan
} else if ready {
item.parts
.iter()
.filter_map(|part| {
plans
.get(part)
.copied()
.or_else(|| self.artifact(part).map(|part| part.plan))
})
.min()
.unwrap_or(item.plan)
} else {
pending.push((item, true));
pending.extend(
item.parts
.iter()
.filter(|part| affected.contains(*part))
.filter_map(|part| self.artifact(part))
.map(|part| (part, false)),
);
continue;
};
plans.insert(&item.name, plan);
}
}
let plans: BTreeMap<_, _> = plans
.into_iter()
.map(|(name, plan)| (name.clone(), plan))
.collect();
for (name, plan) in plans {
if let Some(node) = self.artifact_mut(&name) {
node.plan = plan;
node.runs = node
.evals
.iter()
.filter(|eval| eval.plan == Plan::Run)
.count();
}
let start = self.edges.partition_point(|edge| edge.from < name);
for edge in self.edges[start..]
.iter_mut()
.take_while(|edge| edge.from == name)
{
edge.plan = plan;
}
}
}
}
fn forecast(
found: &mut CurrentEval,
eval: &EvalState,
cached: Option<&Claim>,
now: OffsetDateTime,
) {
let plan = Plan::from(eval.action);
let reused = match cached {
Some(Claim::Reuse(execution)) => Some(&**execution),
_ => None,
};
let mut facts = vec![("Profile", profile(&eval.profile))];
facts.extend(
eval.fingerprint
.as_ref()
.map(|hash| ("Fingerprint", hash.to_string())),
);
facts.push(("Eval", eval.id.to_string()));
facts.push(("Verify would", eval.action.to_string()));
facts.push(("State", eval.state.to_string()));
facts.extend(eval.key.as_ref().map(|key| ("Reuse key", key.to_string())));
facts.push(("Definition hash", eval.eval_def_hash.to_string()));
facts.extend(
eval.last
.as_ref()
.map(|last| ("Last Run", format!("{} · {}", last.run_id, last.verdict))),
);
if let Some(changes) = &eval.changes {
facts.push(("Changes", changes.summary.clone()));
facts.extend(
changes
.files
.as_ref()
.map(|files| ("Changed files", files.join("\n"))),
);
facts.extend(
changes
.dependencies
.as_ref()
.map(|names| ("Changed dependencies", names.join("\n"))),
);
}
found.plan = plan;
found.observed_at = Some(now);
found.state = eval.state;
found.reason.clone_from(&eval.reason);
found.card = card(&found.card.instruction, &eval.profile, plan, reused, now);
found.facts = facts;
}
#[cfg(test)]
mod tests;