1mod detail;
4mod draft;
5mod read;
6mod runs;
7pub mod search;
8
9pub 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::Request,
23 tools::human::{CommandLine, Content, ToolResult},
24 types::RequestId,
25};
26use std::path::PathBuf;
27use tokio_util::sync::CancellationToken;
28
29#[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
45pub const CLAIM_FIRST: &str = "Claim this request before reviewing it.";
47pub const NOT_CLAIMED: &str = "The request is not claimed.";
49
50pub 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
73pub 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
85pub 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#[derive(Debug, Clone, PartialEq)]
99pub enum Answer {
100 Explicit(Submission),
101 ExplicitWithoutDraft(Submission),
103 SavedDraft,
104 PreparedDraft(Draft),
106}
107
108#[derive(Debug, Clone, PartialEq)]
110pub enum Job {
111 Claim { id: RequestId },
113 Run {
115 id: RequestId,
116 tool: ToolName,
117 claim: bool,
118 },
119 Submit {
121 id: RequestId,
122 answer: Answer,
123 claim: bool,
124 },
125 Release { ids: Vec<RequestId>, quit: bool },
127}
128
129#[derive(Debug)]
130pub enum Outcome {
131 Claimed {
132 result: Result<(HumanClaim, bool), String>,
133 },
134 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 failed: Vec<(RequestId, String)>,
154 },
155}
156
157impl Outcome {
158 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#[derive(Debug, Clone, PartialEq, Eq)]
207pub struct Tool {
208 pub name: ToolName,
209 pub fqn: crate::config::ToolFqn,
211 pub artifact: crate::types::ArtifactName,
213 pub kind: HumanToolKind,
214 pub description: String,
215 pub declared: Runs,
216}
217
218impl Tool {
219 pub fn operation(&self) -> &str {
222 self.fqn.as_str()
223 }
224
225 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 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 let declared = request(&state, &id).await.ok().and_then(|view| {
279 tools(&view.request)
280 .into_iter()
281 .find(|declared| declared.name == tool)
282 });
283 let run = match &declared {
284 Some(declared) => {
285 log.start(&id, declared.operation(), declared.artifact.as_str())
286 }
287 None => log.start(&id, tool.as_str(), ""),
288 };
289 let result = async {
290 let (receipts, _) = match human::open(&state, &id).await {
291 Ok(opened) => opened,
292 Err(error) => {
293 run.end(log::End::Failed(error.clone()));
294 return Err(error);
295 }
296 };
297 let result = async {
298 if first {
299 match human::claim(&receipts, &id, &reviewer).await {
300 Ok(claim) => claimed = Some(claim),
301 Err(error) => {
302 run.end(log::End::Failed(error.clone()));
303 return Err(error);
304 }
305 }
306 }
307 human::run_human_tool(&receipts, &id, &reviewer, &tool, cancel, run).await
308 }
309 .await;
310 let closed = receipts.close().await;
311 result.and_then(|result| closed.map(|()| result))
312 }
313 .await;
314 Outcome::Ran {
315 tool,
316 claimed,
317 result,
318 }
319 }
320 Job::Submit {
321 id,
322 answer,
323 claim: first,
324 } => {
325 let mut claimed = None;
326 let result = async {
327 if first {
328 let (receipts, _) = human::open(&state, &id).await?;
329 let result = human::claim(&receipts, &id, &reviewer).await;
330 let closed = receipts.close().await;
331 claimed = Some(result.and_then(|claim| closed.map(|()| claim))?);
332 }
333 match answer {
334 Answer::Explicit(result) => {
335 human::submit_and_publish(&state, &id, &reviewer, &result, cancel).await
336 }
337 Answer::ExplicitWithoutDraft(result) => {
338 human::publish_explicit_without_draft(
339 &state, &id, &reviewer, &result, cancel,
340 )
341 .await
342 }
343 Answer::SavedDraft => {
344 human::publish_saved_draft(&state, &id, &reviewer, None, cancel).await
345 }
346 Answer::PreparedDraft(draft) => {
347 human::publish_saved_draft(&state, &id, &reviewer, Some(draft), cancel)
348 .await
349 }
350 }
351 .map(Box::new)
352 }
353 .await;
354 if let Err(error) = &result
355 && let Ok(view) = request(&state, &id).await
356 && matches!(
357 view.request.status(),
358 crate::types::RequestStatus::Green | crate::types::RequestStatus::Red
359 )
360 && view.execution.as_ref().is_some_and(|execution| {
361 execution.reviewer.as_deref() == Some(reviewer.as_str())
362 })
363 {
364 return Outcome::SavedLocally {
365 request: Box::new(std::sync::Arc::unwrap_or_clone(view.request)),
366 error: error.clone(),
367 };
368 }
369 Outcome::Submitted {
370 id,
371 claimed,
372 result,
373 }
374 }
375 Job::Release { ids, quit } => {
376 let mut failed = Vec::new();
377 for id in &ids {
378 let release = async {
379 let check = || {
380 if cancel.is_cancelled() {
381 Err("Review action cancelled.".to_owned())
382 } else {
383 Ok(())
384 }
385 };
386 check()?;
387 let view = request(&state, id).await?;
389 if view.claim.is_none_or(|claim| claim.reviewer != reviewer) {
390 return Ok(());
391 }
392 check()?;
393 let (receipts, _) = human::open(&state, id).await?;
394 let result = match check() {
395 Ok(()) => human::unclaim(&receipts, id, &reviewer).await.map(drop),
396 Err(error) => Err(error),
397 };
398 let closed = receipts.close().await;
399 result.and(closed)
400 };
401 if let Err(error) = release.await {
402 failed.push((id.clone(), error));
403 }
404 }
405 Outcome::Released { ids, quit, failed }
406 }
407 }
408 }
409}
410
411pub fn instruction(request: &Request) -> crate::scope::Instruction {
414 let recorded = request
415 .human_definition
416 .as_ref()
417 .and_then(|definition| definition.artifacts.value());
418 crate::scope::Instruction::saved(
419 request.payload.instruction(),
420 request.references.values(),
421 |name| {
422 recorded
423 .and_then(|artifacts| artifacts.get(name))
424 .and_then(crate::store::definitions::Artifact::shown_path)
425 },
426 )
427}
428
429pub fn tools(request: &Request) -> Vec<Tool> {
431 request
432 .human_definition
433 .as_ref()
434 .and_then(|definition| definition.artifacts.value())
435 .map(declared)
436 .unwrap_or_default()
437}
438
439pub type Resolved = Result<CommandLine, String>;
441
442pub struct ArtifactDeclarations {
446 config: crate::config::RepoConfig,
447 artifact: crate::types::ArtifactName,
448}
449
450impl ArtifactDeclarations {
451 pub fn read(
455 repo: &std::path::Path,
456 artifact: &crate::types::ArtifactName,
457 site: &crate::config::Site,
458 ) -> Result<Self, crate::config::ScopeReadError> {
459 Ok(Self {
460 config: crate::config::read_artifact_scope(repo, artifact, site)?,
461 artifact: artifact.clone(),
462 })
463 }
464
465 pub fn read_indexed(
468 repo: &std::path::Path,
469 artifact: &crate::types::ArtifactName,
470 index: &crate::config::SiteIndex,
471 ) -> Result<Self, crate::config::ScopeReadError> {
472 let read = |index: &crate::config::SiteIndex| {
473 index.subset(
474 repo,
475 [artifact.clone()],
476 crate::config::Evals::None,
477 &crate::config::lang::process_environment,
478 )
479 };
480 let config = match read(index) {
481 Ok(config) => config,
482 Err(_) => {
483 let refreshed = crate::config::SiteIndex::read(repo)?;
484 if refreshed.site(artifact).is_none() {
485 return Err(crate::config::ScopeReadError::Moved {
486 name: artifact.clone(),
487 path: index
488 .site(artifact)
489 .map_or_else(|| repo.to_owned(), crate::config::Site::declaration_path),
490 });
491 }
492 read(&refreshed)?
493 }
494 };
495 Ok(Self {
496 config,
497 artifact: artifact.clone(),
498 })
499 }
500
501 pub fn tools(&self) -> Result<Vec<(Tool, Option<Resolved>)>, String> {
504 let registry = crate::tools::human::Registry::for_artifact(&self.config, &self.artifact)?;
505 let artifact = &self.config.artifacts[&self.artifact];
506 let mut tools: Vec<_> = artifact
507 .views
508 .human_tools
509 .iter()
510 .map(|(operation, declaration)| {
511 let name: ToolName = operation.published(self.artifact.as_str());
512 let command = registry.is_command(&name).then(|| registry.command(&name));
513 let tool = Tool {
514 name,
515 fqn: operation.clone(),
516 artifact: self.artifact.clone(),
517 kind: declaration.kind(),
518 description: declaration
519 .description()
520 .replace("{artifactName}", self.artifact.as_str()),
521 declared: Runs::declared(&self.config.artifacts, &self.artifact, declaration),
522 };
523 (tool, command)
524 })
525 .collect();
526 tools.sort_by(|(a, _), (b, _)| a.name.cmp(&b.name));
527 Ok(tools)
528 }
529
530 pub async fn run_tool(
534 &self,
535 checkout: &crate::monitor::live::Place,
536 tool: &ToolName,
537 cancel: CancellationToken,
538 run: log::Run,
539 ) -> Result<ToolResult, String> {
540 let artifact = &self.artifact;
541 let registry = match crate::tools::human::Registry::for_artifact(&self.config, artifact) {
542 Ok(registry) => registry,
543 Err(error) => {
544 run.end(log::End::Failed(error.clone()));
545 return Err(error);
546 }
547 };
548 if !registry
550 .list()
551 .any(|entry| &entry.name == tool && &entry.artifact_id == artifact)
552 {
553 let error = format!("{artifact} declares no Human tool {tool}.");
554 run.end(log::End::Failed(error.clone()));
555 return Err(error);
556 }
557 if let Err(error) = checkout.checked_workspace(self.config.root.clone()).await {
558 run.end(log::End::Failed(error.clone()));
559 return Err(error);
560 }
561 Ok(registry.call_logged(tool, cancel, run).await)
562 }
563}
564
565fn declared(
567 artifacts: &std::collections::BTreeMap<
568 crate::types::ArtifactName,
569 crate::store::definitions::Artifact,
570 >,
571) -> Vec<Tool> {
572 use crate::store::definitions::HumanTool;
573 let mut tools: Vec<_> = artifacts
574 .iter()
575 .flat_map(|(id, artifact)| {
576 artifact
577 .views
578 .value()
579 .and_then(|views| views.human_tools.value())
580 .into_iter()
581 .flatten()
582 .map(move |(operation, tool)| {
583 let (kind, description) = match tool {
584 HumanTool::Command(tool) => (tool.kind, &tool.description),
585 HumanTool::Builtin(tool) => (tool.kind, &tool.description),
586 HumanTool::Viewer(tool) => (HumanToolKind::Viewer, &tool.description),
587 };
588 Tool {
589 name: operation.published(id.as_str()),
590 fqn: operation.clone(),
591 artifact: id.clone(),
592 kind,
593 description: description.replace("{artifactName}", id.as_str()),
594 declared: Runs::parse(artifacts, id, tool),
595 }
596 })
597 })
598 .collect();
599 tools.sort_by(|a, b| a.name.cmp(&b.name));
600 tools
601}
602
603pub fn shell<'a>(words: impl IntoIterator<Item = &'a str>) -> String {
607 let quote = |word: &str| {
608 let plain = !word.is_empty()
609 && word
610 .chars()
611 .all(|c| c.is_ascii_alphanumeric() || "-_./=:,+@%{}".contains(c));
612 if plain {
613 word.to_owned()
614 } else {
615 format!("\"{}\"", word.replace('"', "\"\""))
616 }
617 };
618 words.into_iter().map(quote).collect::<Vec<_>>().join(" ")
619}
620
621#[cfg(test)]
622#[path = "review/tests/submission.rs"]
623mod submission_tests;
624
625#[cfg(test)]
626#[path = "review/tests/artifact_tool.rs"]
627mod artifact_tool_tests;