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::{self, 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 = 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 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
414pub 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
424pub type Resolved = Result<CommandLine, String>;
426
427pub struct ArtifactDeclarations {
431 config: crate::config::RepoConfig,
432 artifact: crate::types::ArtifactName,
433}
434
435impl ArtifactDeclarations {
436 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 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 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 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
514fn 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
552pub 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;