1mod detail;
4mod draft;
5mod form;
6mod reasons;
7mod runs;
8pub mod search;
9
10pub use crate::{human::Submission, tools::human::log};
12pub use detail::{Stage, meta, outcome_text, shared, stage, technical};
13pub use draft::{
14 Draft, DraftEdit, DraftFields, EMPTY_REASON, FieldValue, Point, REASON_CHANGED, Readiness,
15 append_point, edit_draft, read_draft, remove_point, values_of,
16};
17pub use form::{Field, Form, Input, Key, Row, Specification};
18pub use runs::Runs;
19
20use crate::{
21 config::{HumanToolKind, ToolName},
22 human,
23 store::{self, HumanClaim, Request},
24 tools::human::{CommandLine, Content, ToolResult},
25 types::RequestId,
26};
27use std::path::PathBuf;
28use tokio_util::sync::CancellationToken;
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct Target {
33 pub run: crate::types::RunId,
34 pub node: crate::monitor::NodeId,
35}
36
37impl From<&Request> for Target {
38 fn from(request: &Request) -> Self {
39 Self {
40 run: request.run_id.clone(),
41 node: crate::monitor::NodeId::eval(request.eval_id.clone()),
42 }
43 }
44}
45
46pub const CLAIM_FIRST: &str = "Claim this request before reviewing it.";
48pub const NOT_CLAIMED: &str = "The request is not claimed.";
50
51pub fn actionable(
55 view: Option<&crate::store::RequestView>,
56 reviewer: &crate::types::ReviewerId,
57) -> Result<(RequestId, bool), String> {
58 let view = view.ok_or("The request is still loading.")?;
59 if !view.request.status().is_human_wait() {
60 return Err(format!(
61 "The request is {}; there is nothing to review.",
62 view.request.status()
63 ));
64 }
65 match &view.claim {
66 Some(claim) if &claim.reviewer != reviewer => Err(format!(
67 "Claimed by {}; read-only for {}.",
68 claim.reviewer, reviewer
69 )),
70 claim => Ok((view.request.id.clone(), claim.is_none())),
71 }
72}
73
74pub fn review_refusal(
77 view: Option<&crate::store::RequestView>,
78 reviewer: &crate::types::ReviewerId,
79) -> Option<String> {
80 match actionable(view, reviewer) {
81 Ok((_, false)) => None,
82 Ok((_, true)) | Err(_) => Some(CLAIM_FIRST.into()),
83 }
84}
85
86pub fn release_refusal(
88 view: Option<&crate::store::RequestView>,
89 reviewer: &crate::types::ReviewerId,
90) -> Option<String> {
91 match actionable(view, reviewer) {
92 Ok((_, false)) => None,
93 Ok((_, true)) => Some(NOT_CLAIMED.into()),
94 Err(error) => Some(error),
95 }
96}
97
98#[derive(Debug, Clone, PartialEq)]
100pub enum Answer {
101 Explicit(Submission),
102 ExplicitWithoutDraft(Submission),
104 SavedDraft,
105 PreparedDraft(Draft),
107}
108
109#[derive(Debug, Clone, PartialEq)]
111pub enum Job {
112 Claim { id: RequestId },
114 Run {
116 id: RequestId,
117 tool: ToolName,
118 claim: bool,
119 },
120 Submit {
122 id: RequestId,
123 answer: Answer,
124 claim: bool,
125 },
126 Release { ids: Vec<RequestId>, quit: bool },
128}
129
130#[derive(Debug)]
131pub enum Outcome {
132 Claimed {
133 result: Result<(HumanClaim, bool), String>,
134 },
135 SavedLocally {
137 request: Box<Request>,
138 error: String,
139 },
140 Ran {
141 tool: ToolName,
142 claimed: Option<HumanClaim>,
143 result: Result<ToolResult, String>,
144 },
145 Submitted {
146 id: RequestId,
147 claimed: Option<HumanClaim>,
148 result: Result<Box<Request>, String>,
149 },
150 Released {
151 ids: Vec<RequestId>,
152 quit: bool,
153 failed: Vec<(RequestId, String)>,
155 },
156}
157
158impl Outcome {
159 pub fn notice(&self) -> (String, bool) {
161 match self {
162 Self::SavedLocally { error, .. } => (error.clone(), true),
163 Self::Claimed { result: Ok(_) } => (
164 "Claimed. Fill GREEN or RED fields, then Submit.".into(),
165 false,
166 ),
167 Self::Claimed { result: Err(error) } => (error.clone(), true),
168 Self::Ran { tool, result, .. } => {
169 let launched = Content::Launch { launched: true };
170 match result {
171 Ok(result) if result.is_error() => (
172 format!("{tool} failed; a tool error is not a verdict."),
173 true,
174 ),
175 Ok(result) if result.content().contains(&launched) => {
176 (format!("{tool} launched."), false)
177 }
178 Ok(_) => (format!("{tool} finished."), false),
179 Err(_) => (format!("{tool} did not run."), true),
180 }
181 }
182 Self::Submitted {
183 result: Ok(request),
184 ..
185 } => (
186 format!(
187 "Submitted {} for {} ({}).",
188 request.status(),
189 request.eval_id,
190 request.id
191 ),
192 false,
193 ),
194 Self::Submitted {
195 result: Err(error), ..
196 } => (error.clone(), true),
197 Self::Released { failed, .. } if failed.is_empty() => ("Claim released.".into(), false),
198 Self::Released { failed, .. } => {
199 let lines = failed.iter().map(|(id, error)| format!("{id}: {error}"));
200 (lines.collect::<Vec<_>>().join("\n"), true)
201 }
202 }
203 }
204}
205
206#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct Tool {
209 pub name: ToolName,
210 pub artifact: crate::types::ArtifactName,
212 pub kind: HumanToolKind,
213 pub description: String,
214 pub declared: Runs,
215}
216
217impl Tool {
218 pub fn operation(&self) -> &str {
220 Self::operation_of(&self.name, &self.artifact)
221 }
222
223 pub fn operation_of<'a>(name: &'a ToolName, artifact: &crate::types::ArtifactName) -> &'a str {
225 name.as_str()
226 .strip_suffix(&format!("_{}", artifact))
227 .unwrap_or(name.as_str())
228 }
229
230 pub fn action(&self, resolved: Option<&Result<CommandLine, String>>) -> String {
233 match (&self.declared, resolved) {
234 (Runs::Command(_), Some(Ok(command))) => {
235 let program = crate::platform::path_text(std::path::Path::new(&command.program));
236 let words = std::iter::once(program).chain(command.shown_args.iter().cloned());
237 let words: Vec<_> = words.collect();
238 format!("$ {}", shell(words.iter().map(String::as_str)))
239 }
240 (declared, _) => declared.line(),
241 }
242 }
243}
244
245impl Job {
246 pub async fn run(
250 self,
251 state: PathBuf,
252 reviewer: crate::types::ReviewerId,
253 cancel: CancellationToken,
254 log: log::Sink,
255 ) -> Outcome {
256 match self {
257 Job::Claim { id } => {
258 let result = async {
259 let cancelled = || "Review action cancelled.".to_owned();
260 let (receipts, _) = tokio::select! {
261 biased;
262 () = cancel.cancelled() => return Err(cancelled()),
263 opened = human::open(&state, &id) => opened?,
264 };
265 let result = if cancel.is_cancelled() {
266 Err(cancelled())
267 } else {
268 human::claim_acquisition(&receipts, &id, &reviewer).await
269 };
270 let closed = receipts.close().await;
271 result.and_then(|claim| closed.map(|()| claim))
272 }
273 .await;
274 Outcome::Claimed { result }
275 }
276 Job::Run {
277 id,
278 tool,
279 claim: first,
280 } => {
281 let mut claimed = None;
282 let declared = store::read_request_id(&state, &id)
284 .await
285 .ok()
286 .and_then(|view| {
287 tools(&view.request)
288 .into_iter()
289 .find(|declared| declared.name == tool)
290 });
291 let run = match &declared {
292 Some(declared) => {
293 log.start(&id, declared.operation(), declared.artifact.as_str())
294 }
295 None => log.start(&id, tool.as_str(), ""),
296 };
297 let result = async {
298 let (receipts, _) = match human::open(&state, &id).await {
299 Ok(opened) => opened,
300 Err(error) => {
301 run.end(log::End::Failed(error.clone()));
302 return Err(error);
303 }
304 };
305 let result = async {
306 if first {
307 match human::claim(&receipts, &id, &reviewer).await {
308 Ok(claim) => claimed = Some(claim),
309 Err(error) => {
310 run.end(log::End::Failed(error.clone()));
311 return Err(error);
312 }
313 }
314 }
315 human::run_human_tool(&receipts, &id, &reviewer, &tool, cancel, run).await
316 }
317 .await;
318 let closed = receipts.close().await;
319 result.and_then(|result| closed.map(|()| result))
320 }
321 .await;
322 Outcome::Ran {
323 tool,
324 claimed,
325 result,
326 }
327 }
328 Job::Submit {
329 id,
330 answer,
331 claim: first,
332 } => {
333 let mut claimed = None;
334 let result = async {
335 if first {
336 let (receipts, _) = human::open(&state, &id).await?;
337 let result = human::claim(&receipts, &id, &reviewer).await;
338 let closed = receipts.close().await;
339 claimed = Some(result.and_then(|claim| closed.map(|()| claim))?);
340 }
341 match answer {
342 Answer::Explicit(result) => {
343 human::submit_and_publish(&state, &id, &reviewer, &result, cancel).await
344 }
345 Answer::ExplicitWithoutDraft(result) => {
346 human::publish_explicit_without_draft(
347 &state, &id, &reviewer, &result, cancel,
348 )
349 .await
350 }
351 Answer::SavedDraft => {
352 human::publish_saved_draft(&state, &id, &reviewer, None, cancel).await
353 }
354 Answer::PreparedDraft(draft) => {
355 human::publish_saved_draft(&state, &id, &reviewer, Some(draft), cancel)
356 .await
357 }
358 }
359 .map(Box::new)
360 }
361 .await;
362 if let Err(error) = &result
363 && let Ok(view) = store::read_request_id(&state, &id).await
364 && matches!(
365 view.request.status(),
366 crate::types::RequestStatus::Green | crate::types::RequestStatus::Red
367 )
368 && view.execution.as_ref().is_some_and(|execution| {
369 execution.reviewer.as_deref() == Some(reviewer.as_str())
370 })
371 {
372 return Outcome::SavedLocally {
373 request: Box::new(std::sync::Arc::unwrap_or_clone(view.request)),
374 error: error.clone(),
375 };
376 }
377 Outcome::Submitted {
378 id,
379 claimed,
380 result,
381 }
382 }
383 Job::Release { ids, quit } => {
384 let mut failed = Vec::new();
385 for id in &ids {
386 let release = async {
387 let check = || {
388 if cancel.is_cancelled() {
389 Err("Review action cancelled.".to_owned())
390 } else {
391 Ok(())
392 }
393 };
394 check()?;
395 let view = store::read_request_id(&state, id).await?;
397 if view.claim.is_none_or(|claim| claim.reviewer != reviewer) {
398 return Ok(());
399 }
400 check()?;
401 let (receipts, _) = human::open(&state, id).await?;
402 let result = match check() {
403 Ok(()) => human::unclaim(&receipts, id, &reviewer).await.map(drop),
404 Err(error) => Err(error),
405 };
406 let closed = receipts.close().await;
407 result.and(closed)
408 };
409 if let Err(error) = release.await {
410 failed.push((id.clone(), error));
411 }
412 }
413 Outcome::Released { ids, quit, failed }
414 }
415 }
416 }
417}
418
419pub fn tools(request: &Request) -> Vec<Tool> {
421 request
422 .human_definition
423 .as_ref()
424 .and_then(|definition| definition.artifacts.value())
425 .map(declared)
426 .unwrap_or_default()
427}
428
429pub type Resolved = Result<CommandLine, String>;
431
432pub struct ArtifactDeclarations {
436 config: crate::config::RepoConfig,
437 artifact: crate::types::ArtifactName,
438}
439
440impl ArtifactDeclarations {
441 pub fn read(
445 repo: &std::path::Path,
446 artifact: &crate::types::ArtifactName,
447 site: &crate::config::Site,
448 ) -> Result<Self, crate::config::ScopeReadError> {
449 Ok(Self {
450 config: crate::config::read_artifact_scope(repo, artifact, site)?,
451 artifact: artifact.clone(),
452 })
453 }
454
455 pub fn tools(&self) -> Result<Vec<(Tool, Option<Resolved>)>, String> {
458 let registry = crate::tools::human::Registry::for_artifact(&self.config, &self.artifact)?;
459 let artifact = &self.config.artifacts[&self.artifact];
460 let mut tools: Vec<_> = artifact
461 .views
462 .human_tools
463 .iter()
464 .map(|(operation, declaration)| {
465 let name: ToolName = format!("{operation}_{}", self.artifact)
466 .parse()
467 .expect("validated tool and Artifact names");
468 let command = registry.is_command(&name).then(|| registry.command(&name));
469 let tool = Tool {
470 name,
471 artifact: self.artifact.clone(),
472 kind: declaration.kind(),
473 description: declaration
474 .description()
475 .replace("{artifactName}", self.artifact.as_str()),
476 declared: Runs::declared(&self.config.artifacts, &self.artifact, declaration),
477 };
478 (tool, command)
479 })
480 .collect();
481 tools.sort_by(|(a, _), (b, _)| a.name.cmp(&b.name));
482 Ok(tools)
483 }
484
485 pub async fn run_tool(
489 &self,
490 checkout: &crate::monitor::live::Place,
491 tool: &ToolName,
492 cancel: CancellationToken,
493 run: log::Run,
494 ) -> Result<ToolResult, String> {
495 let artifact = &self.artifact;
496 let registry = match crate::tools::human::Registry::for_artifact(&self.config, artifact) {
497 Ok(registry) => registry,
498 Err(error) => {
499 run.end(log::End::Failed(error.clone()));
500 return Err(error);
501 }
502 };
503 if !registry
505 .list()
506 .any(|entry| &entry.name == tool && &entry.artifact_id == artifact)
507 {
508 let error = format!("{artifact} declares no Human tool {tool}.");
509 run.end(log::End::Failed(error.clone()));
510 return Err(error);
511 }
512 if let Err(error) = checkout.checked_workspace(self.config.root.clone()).await {
513 run.end(log::End::Failed(error.clone()));
514 return Err(error);
515 }
516 Ok(registry.call_logged(tool, cancel, run).await)
517 }
518}
519
520fn declared(
522 artifacts: &std::collections::BTreeMap<
523 crate::types::ArtifactName,
524 crate::store::definitions::Artifact,
525 >,
526) -> Vec<Tool> {
527 use crate::store::definitions::HumanTool;
528 let mut tools: Vec<_> = artifacts
529 .iter()
530 .flat_map(|(id, artifact)| {
531 artifact
532 .views
533 .value()
534 .and_then(|views| views.human_tools.value())
535 .into_iter()
536 .flatten()
537 .filter_map(move |(operation, tool)| {
540 let (kind, description) = match tool {
541 HumanTool::Command(tool) => (tool.kind, &tool.description),
542 HumanTool::Builtin(tool) => (tool.kind, &tool.description),
543 HumanTool::Viewer(tool) => (HumanToolKind::Viewer, &tool.description),
544 };
545 Some(Tool {
546 name: format!("{operation}_{}", id).parse().ok()?,
547 artifact: id.clone(),
548 kind,
549 description: description.replace("{artifactName}", id.as_str()),
550 declared: Runs::parse(artifacts, id, tool),
551 })
552 })
553 })
554 .collect();
555 tools.sort_by(|a, b| a.name.cmp(&b.name));
556 tools
557}
558
559pub fn form(request: &Request, verdict: crate::runtime::Verdict) -> Result<Form, String> {
561 let definition = request.human_definition.as_ref().ok_or(
562 "This request records no Human definition; open the original request its actions go to.",
563 )?;
564 definition.eval.form(verdict)
565}
566
567pub fn shell<'a>(words: impl IntoIterator<Item = &'a str>) -> String {
571 let quote = |word: &str| {
572 let plain = !word.is_empty()
573 && word
574 .chars()
575 .all(|c| c.is_ascii_alphanumeric() || "-_./=:,+@%{}".contains(c));
576 if plain {
577 word.to_owned()
578 } else {
579 format!("\"{}\"", word.replace('"', "\"\""))
580 }
581 };
582 words.into_iter().map(quote).collect::<Vec<_>>().join(" ")
583}
584
585#[cfg(test)]
586mod submission_tests {
587 use super::Submission;
588 use crate::runtime::Verdict;
589 use serde_json::json;
590
591 #[test]
592 fn submission_parses_one_verdict_and_keeps_its_owner_fields() {
593 for (value, verdict) in [
594 (json!({"verdict":"GREEN","approved":true}), Verdict::Green),
595 (json!({"verdict":"RED","reason":"needs work"}), Verdict::Red),
596 ] {
597 let submitted = Submission::try_from(value.clone()).unwrap();
598 assert_eq!(submitted.verdict(), verdict);
599 assert_eq!(submitted.to_json(), value);
600 }
601 assert!(Submission::try_from(json!({"approved":true})).is_err());
602 assert!(Submission::try_from(json!({"verdict":"ERROR"})).is_err());
603 }
604}
605
606#[cfg(test)]
607mod artifact_tool_tests {
608 use super::*;
609 use crate::monitor::live::Place;
610
611 #[tokio::test]
612 async fn a_detail_tool_refuses_to_run_after_the_worktree_switches_branches() {
613 let workspace = crate::test_os::tempdir();
614 let root = crate::test_os::canonical(workspace.path());
615 std::fs::create_dir(root.join(".artifactize")).unwrap();
616 std::fs::write(
617 root.join(".artifactize/app.artf"),
618 r#"
619path = "notes.md"
620[views.human_tools]
621notes = { builtin = "read", args = ["{artifactPath}"] }
622"#,
623 )
624 .unwrap();
625 std::fs::write(root.join("notes.md"), "# Notes").unwrap();
626 crate::test_os::git(&root, &["init", "--quiet", "--initial-branch=expected"]);
627 let checkout = Place::for_checkout(&root, &crate::repository::identify(&root));
628 let artifact = "app".parse().unwrap();
629 let sites = crate::config::read_sites(&root).unwrap();
630 let app = ArtifactDeclarations::read(&root, &artifact, &sites[&artifact]).unwrap();
631 let tool = "notes_app".parse().unwrap();
632 let run = || {
633 app.run_tool(
634 &checkout,
635 &tool,
636 CancellationToken::new(),
637 log::Run::unwatched(),
638 )
639 };
640 assert!(!run().await.unwrap().is_error());
641 crate::test_os::git(&root, &["symbolic-ref", "HEAD", "refs/heads/other"]);
642 assert_eq!(
643 run().await.unwrap_err(),
644 "This branch is no longer checked out in the worktree."
645 );
646 }
647}