1use std::path::{Path, PathBuf};
4
5use serde_json::Value;
6use tokio_util::sync::CancellationToken;
7
8use crate::{
9 cache,
10 config::{Eval, RepoConfig, read_workspace_config},
11 remote::Session,
12 scope,
13 store::{self, HumanClaim, Receipts, Request},
14 tools::human::{CommandLine, Registry, ToolResult},
15};
16
17pub const MAX_RESULT_BYTES: usize = 256_000;
20pub const ISSUES_READ_BYTES: u64 = MAX_RESULT_BYTES as u64 + 1;
22
23pub fn default_reviewer() -> Result<crate::types::ReviewerId, String> {
24 crate::platform::user_name()
25 .ok_or("Provide an explicit reviewer id; no default reviewer is available.")?
26 .parse()
27}
28
29pub async fn open(
31 state: &Path,
32 request: &crate::types::RequestId,
33) -> Result<(Receipts, PathBuf), String> {
34 let repo = store::read_request_repo_by_id(state, request.clone()).await?;
35 Ok((Receipts::open(state, &repo).await?, repo))
36}
37
38async fn with_receipts<T>(
40 state: &Path,
41 request: &crate::types::RequestId,
42 action: impl AsyncFnOnce(&Receipts) -> Result<T, String>,
43) -> Result<T, String> {
44 let (receipts, _) = open(state, request).await?;
45 let result = action(&receipts).await;
46 let closed = receipts.close().await;
47 result.and_then(|value| closed.map(|()| value))
48}
49
50pub async fn claim_request(
52 state: &Path,
53 request: &crate::types::RequestId,
54 reviewer: &crate::types::ReviewerId,
55) -> Result<HumanClaim, String> {
56 with_receipts(state, request, async |receipts| {
57 claim(receipts, request, reviewer).await
58 })
59 .await
60}
61
62pub async fn unclaim_request(
64 state: &Path,
65 request: &crate::types::RequestId,
66 reviewer: &crate::types::ReviewerId,
67) -> Result<HumanClaim, String> {
68 with_receipts(state, request, async |receipts| {
69 unclaim(receipts, request, reviewer).await
70 })
71 .await
72}
73
74pub async fn run_request_tool(
76 state: &Path,
77 request: &crate::types::RequestId,
78 reviewer: &crate::types::ReviewerId,
79 tool: &crate::config::ToolName,
80 cancellation: CancellationToken,
81) -> Result<ToolResult, String> {
82 with_receipts(state, request, async |receipts| {
83 run_human_tool(
84 receipts,
85 request,
86 reviewer,
87 tool,
88 cancellation,
89 crate::tools::human::log::Run::unwatched(),
90 )
91 .await
92 })
93 .await
94}
95
96pub async fn claim(
97 receipts: &Receipts,
98 request: &crate::types::RequestId,
99 reviewer: &crate::types::ReviewerId,
100) -> Result<HumanClaim, String> {
101 claim_acquisition(receipts, request, reviewer)
102 .await
103 .map(|(claim, _)| claim)
104}
105
106pub async fn claim_acquisition(
108 receipts: &Receipts,
109 request: &crate::types::RequestId,
110 reviewer: &crate::types::ReviewerId,
111) -> Result<(HumanClaim, bool), String> {
112 receipts.claim_human(request, reviewer).await
113}
114
115pub async fn release_exact_claim(state: &Path, claim: &HumanClaim) -> Result<bool, String> {
117 with_receipts(state, &claim.request_id, async |receipts| {
118 receipts.release_exact_claim(claim.clone()).await
119 })
120 .await
121}
122
123pub async fn unclaim(
125 receipts: &Receipts,
126 request: &crate::types::RequestId,
127 reviewer: &crate::types::ReviewerId,
128) -> Result<HumanClaim, String> {
129 receipts.release_human(request, reviewer).await
130}
131
132pub async fn run_human_tool(
135 receipts: &Receipts,
136 request: &crate::types::RequestId,
137 reviewer: &crate::types::ReviewerId,
138 tool: &crate::config::ToolName,
139 cancellation: CancellationToken,
140 run: crate::tools::human::log::Run,
141) -> Result<ToolResult, String> {
142 let ready = async {
143 let (mut request, _) = receipts.human_request(request, reviewer).await?;
144 let config = reconnect(receipts, &request).await?;
145 let registry = Registry::new(&config, &request.eval_id)?;
146 if !registry.list().any(|entry| &entry.name == tool) {
147 return Err::<_, String>("Unknown registered Human tool.".into());
148 }
149 recheck(
150 receipts,
151 &mut request,
152 reviewer,
153 &config,
154 cancellation.clone(),
155 )
156 .await?;
157 receipts.human_request(&request.id, reviewer).await?;
158 Ok((config, request.eval_id))
159 };
160 let (config, eval) = match ready.await {
161 Ok(ready) => ready,
162 Err(error) => {
163 run.end(crate::tools::human::log::End::Failed(error.clone()));
164 return Err(error);
165 }
166 };
167 let registry = Registry::new(&config, &eval).expect("the registry was just built");
168 Ok(registry.call_logged(tool, cancellation, run).await)
169}
170
171pub async fn tool_commands(
175 receipts: &Receipts,
176 request: &crate::types::RequestId,
177) -> Result<std::collections::BTreeMap<crate::config::ToolName, Result<CommandLine, String>>, String>
178{
179 let request = receipts.waiting_human(request).await?;
180 let config = reconnect(receipts, &request).await?;
181 commands_for(&config, &request.eval_id)
182}
183
184pub async fn preview_tool_commands(
186 request: std::sync::Arc<Request>,
187) -> Result<std::collections::BTreeMap<crate::config::ToolName, Result<CommandLine, String>>, String>
188{
189 crate::task::blocking(move || {
190 let config = declarations(&request).map_err(|mismatch| match mismatch {
191 Mismatch::Unreadable(error) => error,
192 Mismatch::Changed(reason) => reason.into(),
193 })?;
194 commands_for(&config, &request.eval_id)
195 })
196 .await?
197}
198
199fn commands_for(
200 config: &RepoConfig,
201 eval: &crate::types::EvalId,
202) -> Result<std::collections::BTreeMap<crate::config::ToolName, Result<CommandLine, String>>, String>
203{
204 let registry = Registry::new(config, eval)?;
205 Ok(registry
206 .list()
207 .filter(|tool| registry.is_command(&tool.name))
208 .map(|tool| (tool.name.clone(), registry.command(&tool.name)))
209 .collect())
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
215pub struct Submission {
216 verdict: crate::runtime::Verdict,
217 issues: Vec<String>,
218}
219
220pub const GREEN_WITH_ISSUES: &str = "GREEN takes no issues: remove them, or submit RED with them.";
222pub const RED_WITHOUT_ISSUE: &str = "RED needs at least one issue.";
224
225impl<'de> serde::Deserialize<'de> for Submission {
226 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
227 #[derive(serde::Deserialize)]
228 #[serde(deny_unknown_fields)]
229 struct Wire {
230 verdict: crate::runtime::Verdict,
231 #[serde(default)]
232 issues: Vec<String>,
233 }
234 let wire = Wire::deserialize(deserializer)?;
235 Self::new(wire.verdict, wire.issues).map_err(serde::de::Error::custom)
236 }
237}
238
239impl TryFrom<Value> for Submission {
240 type Error = String;
241
242 fn try_from(value: Value) -> Result<Self, Self::Error> {
243 serde_json::from_value(value).map_err(|error| error.to_string())
244 }
245}
246
247impl Submission {
248 pub fn new(verdict: crate::runtime::Verdict, issues: Vec<String>) -> Result<Self, String> {
249 let issues: Vec<String> = issues
250 .into_iter()
251 .map(|issue| issue.trim().to_owned())
252 .collect();
253 if issues.iter().any(String::is_empty) {
254 return Err("An issue needs text.".into());
255 }
256 match verdict {
257 crate::runtime::Verdict::Green if !issues.is_empty() => {
258 return Err(GREEN_WITH_ISSUES.into());
259 }
260 crate::runtime::Verdict::Red if issues.is_empty() => {
261 return Err(RED_WITHOUT_ISSUE.into());
262 }
263 crate::runtime::Verdict::Green | crate::runtime::Verdict::Red => {}
264 }
265 let submission = Self { verdict, issues };
266 if serde_json::to_vec(&submission.to_json())
267 .expect("a submission is JSON")
268 .len()
269 > MAX_RESULT_BYTES
270 {
271 return Err(format!("Human result exceeds {MAX_RESULT_BYTES} bytes."));
272 }
273 Ok(submission)
274 }
275
276 pub fn verdict(&self) -> crate::runtime::Verdict {
277 self.verdict
278 }
279
280 pub fn issues(&self) -> &[String] {
281 &self.issues
282 }
283
284 pub fn to_json(&self) -> Value {
285 serde_json::to_value(self).expect("Human submission is JSON")
286 }
287
288 fn result(&self) -> store::ExecutionResult {
289 store::ExecutionResult::Human {
290 verdict: self.verdict,
291 issues: self
292 .issues
293 .iter()
294 .map(|reason| store::HumanIssue {
295 reason: reason.clone(),
296 })
297 .collect(),
298 }
299 }
300}
301
302pub async fn submit(
305 receipts: &Receipts,
306 request: &crate::types::RequestId,
307 reviewer: &crate::types::ReviewerId,
308 submission: &Submission,
309 cancellation: CancellationToken,
310) -> Result<Request, String> {
311 submit_answer(
312 receipts,
313 request,
314 reviewer,
315 SubmittedAnswer::Explicit(submission),
316 cancellation,
317 )
318 .await
319}
320
321enum SubmittedAnswer<'a> {
322 Explicit(&'a Submission),
323 PreparedExplicit(&'a Submission),
324 SavedDraft,
325 PreparedDraft(crate::review::Draft),
326}
327
328async fn submit_answer(
329 receipts: &Receipts,
330 request: &crate::types::RequestId,
331 reviewer: &crate::types::ReviewerId,
332 answer: SubmittedAnswer<'_>,
333 cancellation: CancellationToken,
334) -> Result<Request, String> {
335 let (mut request, _) = receipts.human_request(request, reviewer).await?;
336 let config = reconnect(receipts, &request).await?;
337 let (answer, expected) = match answer {
338 SubmittedAnswer::Explicit(submission) => (submission.result(), None),
339 SubmittedAnswer::PreparedExplicit(submission) => {
340 (submission.result(), Some(crate::review::Draft::default()))
341 }
342 other => {
343 let draft = match other {
344 SubmittedAnswer::SavedDraft => receipts
345 .read_review_draft(&request.id, reviewer)
346 .await?
347 .unwrap_or_default(),
348 SubmittedAnswer::PreparedDraft(draft) => draft,
349 SubmittedAnswer::Explicit(_) | SubmittedAnswer::PreparedExplicit(_) => {
350 unreachable!()
351 }
352 };
353 (draft.submission()?.result(), Some(draft))
354 }
355 };
356 recheck(receipts, &mut request, reviewer, &config, cancellation).await?;
357 request.state = crate::store::RequestState::completed(answer, crate::broker::now());
358 receipts
359 .settle_human_if_draft(&request, reviewer, expected)
360 .await
361}
362
363pub async fn submit_and_publish(
365 state: &Path,
366 request: &crate::types::RequestId,
367 reviewer: &crate::types::ReviewerId,
368 submission: &Submission,
369 cancellation: CancellationToken,
370) -> Result<Request, String> {
371 publish_answer(
372 state,
373 request,
374 reviewer,
375 SubmittedAnswer::Explicit(submission),
376 cancellation,
377 )
378 .await
379}
380
381pub(crate) async fn publish_explicit_without_draft(
382 state: &Path,
383 request: &crate::types::RequestId,
384 reviewer: &crate::types::ReviewerId,
385 submission: &Submission,
386 cancellation: CancellationToken,
387) -> Result<Request, String> {
388 publish_answer(
389 state,
390 request,
391 reviewer,
392 SubmittedAnswer::PreparedExplicit(submission),
393 cancellation,
394 )
395 .await
396}
397
398pub(crate) async fn publish_saved_draft(
401 state: &Path,
402 request: &crate::types::RequestId,
403 reviewer: &crate::types::ReviewerId,
404 draft: Option<crate::review::Draft>,
405 cancellation: CancellationToken,
406) -> Result<Request, String> {
407 let answer = draft.map_or(SubmittedAnswer::SavedDraft, SubmittedAnswer::PreparedDraft);
408 publish_answer(state, request, reviewer, answer, cancellation).await
409}
410
411async fn publish_answer(
412 state: &Path,
413 request: &crate::types::RequestId,
414 reviewer: &crate::types::ReviewerId,
415 answer: SubmittedAnswer<'_>,
416 cancellation: CancellationToken,
417) -> Result<Request, String> {
418 let (receipts, repo) = open(state, request).await?;
419 let result = async {
420 let remote = Session::open(Some(state), Some(&repo))?;
421 let request = submit_answer(&receipts, request, reviewer, answer, cancellation).await?;
422 if let Some(remote) = remote {
423 remote
424 .publish_request(&receipts, &request)
425 .await
426 .map_err(|error| {
427 format!("The Human result is saved locally, but publishing it failed: {error}")
428 })?;
429 }
430 Ok(request)
431 }
432 .await;
433 let closed = receipts.close().await;
434 result.and_then(|request| closed.map(|()| request))
435}
436
437pub(crate) fn definition(
438 config: &RepoConfig,
439 eval: &Eval,
440) -> Result<crate::store::HumanDefinition, String> {
441 let scope = scope::eval_scope(config, eval).map_err(|e| e.to_string())?;
442 Ok(crate::store::HumanDefinition::authored(
443 &config.root,
444 eval,
445 &scope,
446 ))
447}
448
449enum Mismatch {
451 Unreadable(String),
453 Changed(&'static str),
455}
456
457async fn reconnect(receipts: &Receipts, request: &Request) -> Result<RepoConfig, String> {
461 match declarations(request) {
462 Ok(config) => Ok(config),
463 Err(Mismatch::Unreadable(error)) => Err(error),
464 Err(Mismatch::Changed(error)) => {
465 receipts
466 .retire_human(&request.id, crate::types::FailureCode::InputChanged, error)
467 .await?;
468 Err(error.into())
469 }
470 }
471}
472
473fn declarations(request: &Request) -> Result<RepoConfig, Mismatch> {
477 let repo = &request
478 .provenance
479 .as_ref()
480 .ok_or_else(|| Mismatch::Unreadable("Human request has no provenance.".into()))?
481 .repo_path;
482 let sites = request
483 .human_definition
484 .as_ref()
485 .and_then(|definition| definition.artifacts.value())
486 .and_then(|artifacts| {
487 artifacts
488 .iter()
489 .map(|(name, artifact)| {
490 Some((
491 name.clone(),
492 crate::config::Site {
493 path: artifact.path.value()?.clone(),
494 definition: artifact.definition.value()?.clone(),
495 },
496 ))
497 })
498 .collect::<Option<std::collections::BTreeMap<_, _>>>()
499 });
500 let scoped = sites.and_then(|sites| {
501 crate::config::read_eval_scope(repo, &request.eval_id, &sites)
502 .ok()
503 .flatten()
504 });
505 let config = match scoped {
506 Some(config) => config,
507 None => read_workspace_config(repo).map_err(|e| Mismatch::Unreadable(e.to_string()))?,
508 };
509 let eval = config
510 .evals
511 .iter()
512 .find(|eval| eval.id == request.eval_id)
513 .ok_or(Mismatch::Changed("Recorded Human eval no longer exists."))?;
514 if Some(definition(&config, eval).map_err(Mismatch::Unreadable)?) != request.human_definition {
515 return Err(Mismatch::Changed(
516 "Human Artifact scope or eval declarations changed since the request was recorded.",
517 ));
518 }
519 Ok(config)
520}
521
522async fn recheck(
523 receipts: &Receipts,
524 request: &mut Request,
525 reviewer: &crate::types::ReviewerId,
526 config: &RepoConfig,
527 cancellation: CancellationToken,
528) -> Result<(), String> {
529 if cancellation.is_cancelled() {
530 return Err("Human action was cancelled.".into());
531 }
532 let eval = config
533 .evals
534 .iter()
535 .find(|eval| eval.id == request.eval_id)
536 .ok_or("Recorded Human eval no longer exists.")?;
537 if request.key.is_none() && cache::live_input(config, eval).is_none() {
538 return Ok(());
539 }
540 let output = request
541 .run_dir
542 .as_deref()
543 .ok_or("Human request has no output directory.")?;
544 let parallelism = cache::Parallelism::new(cache::Parallelism::available())?;
545 let (code, error) = match if let Some(expected) = &request.key {
546 cache::recheck(config, eval, output, ¶llelism, cancellation.clone())
547 .await
548 .map(|actual| actual.as_ref() == Some(expected))
549 } else {
550 cache::recheck_observations(
551 config,
552 &request.fingerprints,
553 output,
554 ¶llelism,
555 cancellation.clone(),
556 )
557 .await
558 } {
559 Ok(true) => return Ok(()),
560 Ok(false) => (
561 crate::types::FailureCode::InputChanged,
562 "Fingerprint changed during review.".into(),
563 ),
564 Err(error) if cancellation.is_cancelled() => return Err(error),
565 Err(error) => (crate::types::FailureCode::FingerprintRecheckFailed, error),
566 };
567 request.state =
568 crate::store::RequestState::failed(error.clone(), Some(code), crate::broker::now());
569 receipts.settle_human(request, reviewer).await?;
570 Err(error)
571}