Skip to main content

artifactize_core/
review.rs

1//! Human review: the facts and lifecycle jobs every interface shares.
2
3mod detail;
4mod draft;
5mod read;
6mod runs;
7pub mod search;
8
9/// The Tool log every review interface shows; see [`log::Sink`].
10pub use crate::{human::Submission, store::HumanClaim, tools::human::log};
11pub use detail::{Stage, meta, outcome_text, shared, stage, technical};
12pub use draft::{
13    Draft, DraftEdit, EMPTY_ISSUE, ISSUE_CHANGED, Point, Readiness, append_point, edit_draft,
14    read_draft, remove_point,
15};
16pub use read::{Review, claim_is_current, read, request, resolve};
17pub use runs::Runs;
18
19use crate::{
20    config::{HumanToolKind, ToolName},
21    human,
22    store::{self, Request},
23    tools::human::{CommandLine, Content, ToolResult},
24    types::RequestId,
25};
26use std::path::PathBuf;
27use tokio_util::sync::CancellationToken;
28
29/// The exact Verify Run and eval node behind a review receipt.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Target {
32    pub run: crate::types::RunId,
33    pub node: crate::monitor::NodeId,
34}
35
36impl From<&Request> for Target {
37    fn from(request: &Request) -> Self {
38        Self {
39            run: request.run_id.clone(),
40            node: crate::monitor::NodeId::eval(request.eval_id.clone()),
41        }
42    }
43}
44
45/// The refusal for reviewing a request nobody claimed.
46pub const CLAIM_FIRST: &str = "Claim this request before reviewing it.";
47/// The refusal for releasing a claim that is not this reviewer's.
48pub const NOT_CLAIMED: &str = "The request is not claimed.";
49
50/// What `reviewer` may do with the request now: its id and whether nobody holds the claim
51/// yet, or why it is read-only (loading, settled, claimed by someone else). Every interface
52/// asks this, so they refuse alike.
53pub fn actionable(
54    view: Option<&crate::store::RequestView>,
55    reviewer: &crate::types::ReviewerId,
56) -> Result<(RequestId, bool), String> {
57    let view = view.ok_or("The request is still loading.")?;
58    if !view.request.status().is_human_wait() {
59        return Err(format!(
60            "The request is {}; there is nothing to review.",
61            view.request.status()
62        ));
63    }
64    match &view.claim {
65        Some(claim) if &claim.reviewer != reviewer => Err(format!(
66            "Claimed by {}; read-only for {}.",
67            claim.reviewer, reviewer
68        )),
69        claim => Ok((view.request.id.clone(), claim.is_none())),
70    }
71}
72
73/// The refusal for choosing a verdict, running a tool or submitting, as the reviewer sees it:
74/// only the claimant reviews, and a claim is always the explicit one.
75pub fn review_refusal(
76    view: Option<&crate::store::RequestView>,
77    reviewer: &crate::types::ReviewerId,
78) -> Option<String> {
79    match actionable(view, reviewer) {
80        Ok((_, false)) => None,
81        Ok((_, true)) | Err(_) => Some(CLAIM_FIRST.into()),
82    }
83}
84
85/// The refusal for releasing: only a claim of this reviewer is released.
86pub fn release_refusal(
87    view: Option<&crate::store::RequestView>,
88    reviewer: &crate::types::ReviewerId,
89) -> Option<String> {
90    match actionable(view, reviewer) {
91        Ok((_, false)) => None,
92        Ok((_, true)) => Some(NOT_CLAIMED.into()),
93        Err(error) => Some(error),
94    }
95}
96
97/// The answer a review submits: explicit fields or the shared draft at submission time.
98#[derive(Debug, Clone, PartialEq)]
99pub enum Answer {
100    Explicit(Submission),
101    /// Legacy input may settle only when no saved form would be discarded.
102    ExplicitWithoutDraft(Submission),
103    SavedDraft,
104    /// Captured after earlier edits reached storage; checked again atomically at settlement.
105    PreparedDraft(Draft),
106}
107
108/// Lifecycle work with owned inputs, so the screen keeps drawing while it runs.
109#[derive(Debug, Clone, PartialEq)]
110pub enum Job {
111    /// Explicit claim for an embedded single-request review.
112    Claim { id: RequestId },
113    /// Claim first when `claim`, then run the tool.
114    Run {
115        id: RequestId,
116        tool: ToolName,
117        claim: bool,
118    },
119    /// Claim first when `claim`, then submit and publish like `request submit`.
120    Submit {
121        id: RequestId,
122        answer: Answer,
123        claim: bool,
124    },
125    /// Release the reviewer's remaining claims; quit afterwards when `quit`.
126    Release { ids: Vec<RequestId>, quit: bool },
127}
128
129#[derive(Debug)]
130pub enum Outcome {
131    Claimed {
132        result: Result<(HumanClaim, bool), String>,
133    },
134    /// Publishing failed after settlement; never offer to submit the verdict twice.
135    SavedLocally {
136        request: Box<Request>,
137        error: String,
138    },
139    Ran {
140        tool: ToolName,
141        claimed: Option<HumanClaim>,
142        result: Result<ToolResult, String>,
143    },
144    Submitted {
145        id: RequestId,
146        claimed: Option<HumanClaim>,
147        result: Result<Box<Request>, String>,
148    },
149    Released {
150        ids: Vec<RequestId>,
151        quit: bool,
152        /// Request IDs whose release failed, with the error.
153        failed: Vec<(RequestId, String)>,
154    },
155}
156
157impl Outcome {
158    /// What the review tells the reviewer about the outcome, and whether it is an error.
159    pub fn notice(&self) -> (String, bool) {
160        match self {
161            Self::SavedLocally { error, .. } => (error.clone(), true),
162            Self::Claimed { result: Ok(_) } => (
163                "Claimed. Fill GREEN or RED fields, then Submit.".into(),
164                false,
165            ),
166            Self::Claimed { result: Err(error) } => (error.clone(), true),
167            Self::Ran { tool, result, .. } => {
168                let launched = Content::Launch { launched: true };
169                match result {
170                    Ok(result) if result.is_error() => (
171                        format!("{tool} failed; a tool error is not a verdict."),
172                        true,
173                    ),
174                    Ok(result) if result.content().contains(&launched) => {
175                        (format!("{tool} launched."), false)
176                    }
177                    Ok(_) => (format!("{tool} finished."), false),
178                    Err(_) => (format!("{tool} did not run."), true),
179                }
180            }
181            Self::Submitted {
182                result: Ok(request),
183                ..
184            } => (
185                format!(
186                    "Submitted {} for {} ({}).",
187                    request.status(),
188                    request.eval_id,
189                    request.id
190                ),
191                false,
192            ),
193            Self::Submitted {
194                result: Err(error), ..
195            } => (error.clone(), true),
196            Self::Released { failed, .. } if failed.is_empty() => ("Claim released.".into(), false),
197            Self::Released { failed, .. } => {
198                let lines = failed.iter().map(|(id, error)| format!("{id}: {error}"));
199                (lines.collect::<Vec<_>>().join("\n"), true)
200            }
201        }
202    }
203}
204
205/// A declared Human tool as the saved definition records it.
206#[derive(Debug, Clone, PartialEq, Eq)]
207pub struct Tool {
208    pub name: ToolName,
209    /// Its name as its toolset declares it: `release.notes`.
210    pub fqn: crate::config::ToolFqn,
211    /// The Artifact that declares the tool.
212    pub artifact: crate::types::ArtifactName,
213    pub kind: HumanToolKind,
214    pub description: String,
215    pub declared: Runs,
216}
217
218impl Tool {
219    /// Its name as a person reads it: the toolset's `release.notes`, whatever Artifact
220    /// composes it.
221    pub fn operation(&self) -> &str {
222        self.fqn.as_str()
223    }
224
225    /// What running the tool does, as the Tools pane shows it: a command's resolved line once
226    /// `resolved` is known, else its declaration; a builtin's action on its logical target.
227    pub fn action(&self, resolved: Option<&Result<CommandLine, String>>) -> String {
228        match (&self.declared, resolved) {
229            (Runs::Command(_), Some(Ok(command))) => {
230                let program = crate::platform::path_text(std::path::Path::new(&command.program));
231                let words = std::iter::once(program).chain(command.shown_args.iter().cloned());
232                let words: Vec<_> = words.collect();
233                format!("$ {}", shell(words.iter().map(String::as_str)))
234            }
235            (declared, _) => declared.line(),
236        }
237    }
238}
239
240impl Job {
241    /// Carry out the job through the `human` lifecycle API, as `request` does; every UI runs
242    /// its Human actions through here. A tool run logs to `log` from its start line to its end,
243    /// failures included; a launched program's output keeps arriving after the job returns.
244    pub async fn run(
245        self,
246        state: PathBuf,
247        reviewer: crate::types::ReviewerId,
248        cancel: CancellationToken,
249        log: log::Sink,
250    ) -> Outcome {
251        match self {
252            Job::Claim { id } => {
253                let result = async {
254                    let cancelled = || "Review action cancelled.".to_owned();
255                    let (receipts, _) = tokio::select! {
256                        biased;
257                        () = cancel.cancelled() => return Err(cancelled()),
258                        opened = human::open(&state, &id) => opened?,
259                    };
260                    let result = if cancel.is_cancelled() {
261                        Err(cancelled())
262                    } else {
263                        human::claim_acquisition(&receipts, &id, &reviewer).await
264                    };
265                    let closed = receipts.close().await;
266                    result.and_then(|claim| closed.map(|()| claim))
267                }
268                .await;
269                Outcome::Claimed { result }
270            }
271            Job::Run {
272                id,
273                tool,
274                claim: first,
275            } => {
276                let mut claimed = None;
277                // The entry names the tool as the saved request declares it.
278                let declared = store::read_request_id(&state, &id)
279                    .await
280                    .ok()
281                    .and_then(|view| {
282                        tools(&view.request)
283                            .into_iter()
284                            .find(|declared| declared.name == tool)
285                    });
286                let run = match &declared {
287                    Some(declared) => {
288                        log.start(&id, declared.operation(), declared.artifact.as_str())
289                    }
290                    None => log.start(&id, tool.as_str(), ""),
291                };
292                let result = async {
293                    let (receipts, _) = match human::open(&state, &id).await {
294                        Ok(opened) => opened,
295                        Err(error) => {
296                            run.end(log::End::Failed(error.clone()));
297                            return Err(error);
298                        }
299                    };
300                    let result = async {
301                        if first {
302                            match human::claim(&receipts, &id, &reviewer).await {
303                                Ok(claim) => claimed = Some(claim),
304                                Err(error) => {
305                                    run.end(log::End::Failed(error.clone()));
306                                    return Err(error);
307                                }
308                            }
309                        }
310                        human::run_human_tool(&receipts, &id, &reviewer, &tool, cancel, run).await
311                    }
312                    .await;
313                    let closed = receipts.close().await;
314                    result.and_then(|result| closed.map(|()| result))
315                }
316                .await;
317                Outcome::Ran {
318                    tool,
319                    claimed,
320                    result,
321                }
322            }
323            Job::Submit {
324                id,
325                answer,
326                claim: first,
327            } => {
328                let mut claimed = None;
329                let result = async {
330                    if first {
331                        let (receipts, _) = human::open(&state, &id).await?;
332                        let result = human::claim(&receipts, &id, &reviewer).await;
333                        let closed = receipts.close().await;
334                        claimed = Some(result.and_then(|claim| closed.map(|()| claim))?);
335                    }
336                    match answer {
337                        Answer::Explicit(result) => {
338                            human::submit_and_publish(&state, &id, &reviewer, &result, cancel).await
339                        }
340                        Answer::ExplicitWithoutDraft(result) => {
341                            human::publish_explicit_without_draft(
342                                &state, &id, &reviewer, &result, cancel,
343                            )
344                            .await
345                        }
346                        Answer::SavedDraft => {
347                            human::publish_saved_draft(&state, &id, &reviewer, None, cancel).await
348                        }
349                        Answer::PreparedDraft(draft) => {
350                            human::publish_saved_draft(&state, &id, &reviewer, Some(draft), cancel)
351                                .await
352                        }
353                    }
354                    .map(Box::new)
355                }
356                .await;
357                if let Err(error) = &result
358                    && let Ok(view) = store::read_request_id(&state, &id).await
359                    && matches!(
360                        view.request.status(),
361                        crate::types::RequestStatus::Green | crate::types::RequestStatus::Red
362                    )
363                    && view.execution.as_ref().is_some_and(|execution| {
364                        execution.reviewer.as_deref() == Some(reviewer.as_str())
365                    })
366                {
367                    return Outcome::SavedLocally {
368                        request: Box::new(std::sync::Arc::unwrap_or_clone(view.request)),
369                        error: error.clone(),
370                    };
371                }
372                Outcome::Submitted {
373                    id,
374                    claimed,
375                    result,
376                }
377            }
378            Job::Release { ids, quit } => {
379                let mut failed = Vec::new();
380                for id in &ids {
381                    let release = async {
382                        let check = || {
383                            if cancel.is_cancelled() {
384                                Err("Review action cancelled.".to_owned())
385                            } else {
386                                Ok(())
387                            }
388                        };
389                        check()?;
390                        // Settled requests and claims released elsewhere leave nothing to release.
391                        let view = store::read_request_id(&state, id).await?;
392                        if view.claim.is_none_or(|claim| claim.reviewer != reviewer) {
393                            return Ok(());
394                        }
395                        check()?;
396                        let (receipts, _) = human::open(&state, id).await?;
397                        let result = match check() {
398                            Ok(()) => human::unclaim(&receipts, id, &reviewer).await.map(drop),
399                            Err(error) => Err(error),
400                        };
401                        let closed = receipts.close().await;
402                        result.and(closed)
403                    };
404                    if let Err(error) = release.await {
405                        failed.push((id.clone(), error));
406                    }
407                }
408                Outcome::Released { ids, quit, failed }
409            }
410        }
411    }
412}
413
414/// Declared Human tools in the eval scope, named like the registry.
415pub fn tools(request: &Request) -> Vec<Tool> {
416    request
417        .human_definition
418        .as_ref()
419        .and_then(|definition| definition.artifacts.value())
420        .map(declared)
421        .unwrap_or_default()
422}
423
424/// The command line a tool would run, or why it cannot be resolved.
425pub type Resolved = Result<CommandLine, String>;
426
427/// One Artifact's declarations in a workspace as it is now: its own and those of the Artifacts
428/// it composes, and nothing else. Its own Human tools are listed and run from them, for no
429/// review: no request, claim or Run is involved.
430pub struct ArtifactDeclarations {
431    config: crate::config::RepoConfig,
432    artifact: crate::types::ArtifactName,
433}
434
435impl ArtifactDeclarations {
436    /// Read Artifact `artifact`'s declarations in the workspace at `repo`, where `site` (from
437    /// [`crate::config::read_sites`]) says it is declared. A site that no longer declares it
438    /// is [`crate::config::ScopeReadError::Moved`].
439    pub fn read(
440        repo: &std::path::Path,
441        artifact: &crate::types::ArtifactName,
442        site: &crate::config::Site,
443    ) -> Result<Self, crate::config::ScopeReadError> {
444        Ok(Self {
445            config: crate::config::read_artifact_scope(repo, artifact, site)?,
446            artifact: artifact.clone(),
447        })
448    }
449
450    /// The Human tools the Artifact itself declares, named like the registry, each with the
451    /// command line it would run (a builtin has none).
452    pub fn tools(&self) -> Result<Vec<(Tool, Option<Resolved>)>, String> {
453        let registry = crate::tools::human::Registry::for_artifact(&self.config, &self.artifact)?;
454        let artifact = &self.config.artifacts[&self.artifact];
455        let mut tools: Vec<_> = artifact
456            .views
457            .human_tools
458            .iter()
459            .map(|(operation, declaration)| {
460                let name: ToolName = operation.published(self.artifact.as_str());
461                let command = registry.is_command(&name).then(|| registry.command(&name));
462                let tool = Tool {
463                    name,
464                    fqn: operation.clone(),
465                    artifact: self.artifact.clone(),
466                    kind: declaration.kind(),
467                    description: declaration
468                        .description()
469                        .replace("{artifactName}", self.artifact.as_str()),
470                    declared: Runs::declared(&self.config.artifacts, &self.artifact, declaration),
471                };
472                (tool, command)
473            })
474            .collect();
475        tools.sort_by(|(a, _), (b, _)| a.name.cmp(&b.name));
476        Ok(tools)
477    }
478
479    /// Run tool `tool` of the Artifact at once. Its output reaches `run`'s Tool log; a
480    /// launched program's keeps arriving until it exits. Check the requested checkout after
481    /// resolving the tool. A refusal ends the run with it.
482    pub async fn run_tool(
483        &self,
484        checkout: &crate::monitor::live::Place,
485        tool: &ToolName,
486        cancel: CancellationToken,
487        run: log::Run,
488    ) -> Result<ToolResult, String> {
489        let artifact = &self.artifact;
490        let registry = match crate::tools::human::Registry::for_artifact(&self.config, artifact) {
491            Ok(registry) => registry,
492            Err(error) => {
493                run.end(log::End::Failed(error.clone()));
494                return Err(error);
495            }
496        };
497        // Only the Artifact's own tools: one of a child it includes belongs to that child's Detail.
498        if !registry
499            .list()
500            .any(|entry| &entry.name == tool && &entry.artifact_id == artifact)
501        {
502            let error = format!("{artifact} declares no Human tool {tool}.");
503            run.end(log::End::Failed(error.clone()));
504            return Err(error);
505        }
506        if let Err(error) = checkout.checked_workspace(self.config.root.clone()).await {
507            run.end(log::End::Failed(error.clone()));
508            return Err(error);
509        }
510        Ok(registry.call_logged(tool, cancel, run).await)
511    }
512}
513
514/// The Human tools `artifacts` declare, named like the registry, sorted by name.
515fn declared(
516    artifacts: &std::collections::BTreeMap<
517        crate::types::ArtifactName,
518        crate::store::definitions::Artifact,
519    >,
520) -> Vec<Tool> {
521    use crate::store::definitions::HumanTool;
522    let mut tools: Vec<_> = artifacts
523        .iter()
524        .flat_map(|(id, artifact)| {
525            artifact
526                .views
527                .value()
528                .and_then(|views| views.human_tools.value())
529                .into_iter()
530                .flatten()
531                .map(move |(operation, tool)| {
532                    let (kind, description) = match tool {
533                        HumanTool::Command(tool) => (tool.kind, &tool.description),
534                        HumanTool::Builtin(tool) => (tool.kind, &tool.description),
535                        HumanTool::Viewer(tool) => (HumanToolKind::Viewer, &tool.description),
536                    };
537                    Tool {
538                        name: operation.published(id.as_str()),
539                        fqn: operation.clone(),
540                        artifact: id.clone(),
541                        kind,
542                        description: description.replace("{artifactName}", id.as_str()),
543                        declared: Runs::parse(artifacts, id, tool),
544                    }
545                })
546        })
547        .collect();
548    tools.sort_by(|a, b| a.name.cmp(&b.name));
549    tools
550}
551
552/// Words joined for an on-screen preview, double-quoted when a word has whitespace or a
553/// quote of its own. This is a reading aid, not a shell command: it claims no single
554/// shell's escaping rules, which differ between Unix shells and Windows's.
555pub fn shell<'a>(words: impl IntoIterator<Item = &'a str>) -> String {
556    let quote = |word: &str| {
557        let plain = !word.is_empty()
558            && word
559                .chars()
560                .all(|c| c.is_ascii_alphanumeric() || "-_./=:,+@%{}".contains(c));
561        if plain {
562            word.to_owned()
563        } else {
564            format!("\"{}\"", word.replace('"', "\"\""))
565        }
566    };
567    words.into_iter().map(quote).collect::<Vec<_>>().join(" ")
568}
569
570#[cfg(test)]
571#[path = "review/tests/submission.rs"]
572mod submission_tests;
573
574#[cfg(test)]
575#[path = "review/tests/artifact_tool.rs"]
576mod artifact_tool_tests;