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 read_indexed(
453 repo: &std::path::Path,
454 artifact: &crate::types::ArtifactName,
455 index: &crate::config::SiteIndex,
456 ) -> Result<Self, crate::config::ScopeReadError> {
457 let read = |index: &crate::config::SiteIndex| {
458 index.subset(
459 repo,
460 [artifact.clone()],
461 crate::config::Evals::None,
462 &crate::config::lang::process_environment,
463 )
464 };
465 let config = match read(index) {
466 Ok(config) => config,
467 Err(_) => {
468 let refreshed = crate::config::SiteIndex::read(repo)?;
469 if refreshed.site(artifact).is_none() {
470 return Err(crate::config::ScopeReadError::Moved {
471 name: artifact.clone(),
472 path: index
473 .site(artifact)
474 .map_or_else(|| repo.to_owned(), crate::config::Site::declaration_path),
475 });
476 }
477 read(&refreshed)?
478 }
479 };
480 Ok(Self {
481 config,
482 artifact: artifact.clone(),
483 })
484 }
485
486 pub fn tools(&self) -> Result<Vec<(Tool, Option<Resolved>)>, String> {
489 let registry = crate::tools::human::Registry::for_artifact(&self.config, &self.artifact)?;
490 let artifact = &self.config.artifacts[&self.artifact];
491 let mut tools: Vec<_> = artifact
492 .views
493 .human_tools
494 .iter()
495 .map(|(operation, declaration)| {
496 let name: ToolName = operation.published(self.artifact.as_str());
497 let command = registry.is_command(&name).then(|| registry.command(&name));
498 let tool = Tool {
499 name,
500 fqn: operation.clone(),
501 artifact: self.artifact.clone(),
502 kind: declaration.kind(),
503 description: declaration
504 .description()
505 .replace("{artifactName}", self.artifact.as_str()),
506 declared: Runs::declared(&self.config.artifacts, &self.artifact, declaration),
507 };
508 (tool, command)
509 })
510 .collect();
511 tools.sort_by(|(a, _), (b, _)| a.name.cmp(&b.name));
512 Ok(tools)
513 }
514
515 pub async fn run_tool(
519 &self,
520 checkout: &crate::monitor::live::Place,
521 tool: &ToolName,
522 cancel: CancellationToken,
523 run: log::Run,
524 ) -> Result<ToolResult, String> {
525 let artifact = &self.artifact;
526 let registry = match crate::tools::human::Registry::for_artifact(&self.config, artifact) {
527 Ok(registry) => registry,
528 Err(error) => {
529 run.end(log::End::Failed(error.clone()));
530 return Err(error);
531 }
532 };
533 if !registry
535 .list()
536 .any(|entry| &entry.name == tool && &entry.artifact_id == artifact)
537 {
538 let error = format!("{artifact} declares no Human tool {tool}.");
539 run.end(log::End::Failed(error.clone()));
540 return Err(error);
541 }
542 if let Err(error) = checkout.checked_workspace(self.config.root.clone()).await {
543 run.end(log::End::Failed(error.clone()));
544 return Err(error);
545 }
546 Ok(registry.call_logged(tool, cancel, run).await)
547 }
548}
549
550fn declared(
552 artifacts: &std::collections::BTreeMap<
553 crate::types::ArtifactName,
554 crate::store::definitions::Artifact,
555 >,
556) -> Vec<Tool> {
557 use crate::store::definitions::HumanTool;
558 let mut tools: Vec<_> = artifacts
559 .iter()
560 .flat_map(|(id, artifact)| {
561 artifact
562 .views
563 .value()
564 .and_then(|views| views.human_tools.value())
565 .into_iter()
566 .flatten()
567 .map(move |(operation, tool)| {
568 let (kind, description) = match tool {
569 HumanTool::Command(tool) => (tool.kind, &tool.description),
570 HumanTool::Builtin(tool) => (tool.kind, &tool.description),
571 HumanTool::Viewer(tool) => (HumanToolKind::Viewer, &tool.description),
572 };
573 Tool {
574 name: operation.published(id.as_str()),
575 fqn: operation.clone(),
576 artifact: id.clone(),
577 kind,
578 description: description.replace("{artifactName}", id.as_str()),
579 declared: Runs::parse(artifacts, id, tool),
580 }
581 })
582 })
583 .collect();
584 tools.sort_by(|a, b| a.name.cmp(&b.name));
585 tools
586}
587
588pub fn shell<'a>(words: impl IntoIterator<Item = &'a str>) -> String {
592 let quote = |word: &str| {
593 let plain = !word.is_empty()
594 && word
595 .chars()
596 .all(|c| c.is_ascii_alphanumeric() || "-_./=:,+@%{}".contains(c));
597 if plain {
598 word.to_owned()
599 } else {
600 format!("\"{}\"", word.replace('"', "\"\""))
601 }
602 };
603 words.into_iter().map(quote).collect::<Vec<_>>().join(" ")
604}
605
606#[cfg(test)]
607#[path = "review/tests/submission.rs"]
608mod submission_tests;
609
610#[cfg(test)]
611#[path = "review/tests/artifact_tool.rs"]
612mod artifact_tool_tests;