Skip to main content

artifactize_core/
human.rs

1//! Human waiting, claim locks, tools, and submission.
2
3use std::path::{Path, PathBuf};
4
5use serde_json::{Map, Value};
6use tokio_util::sync::CancellationToken;
7
8use crate::{
9    agent::verdict::{ValidatedResult, check_result},
10    cache,
11    config::{Eval, RepoConfig, read_workspace_config},
12    remote::Session,
13    scope,
14    store::{self, HumanClaim, Receipts, Request},
15    tools::human::{CommandLine, Registry, ToolResult},
16};
17
18/// Bound owner fields and serialized Human results consistently across CLI, editor
19/// and submission so untrusted JSON cannot grow the review audit without limit.
20pub const MAX_RESULT_BYTES: usize = 256_000;
21/// Read one sentinel byte beyond the bound to detect oversized files without loading them.
22pub const FIELDS_READ_BYTES: u64 = MAX_RESULT_BYTES as u64 + 1;
23
24pub fn default_reviewer() -> Result<crate::types::ReviewerId, String> {
25    crate::platform::user_name()
26        .ok_or("Provide an explicit reviewer id; no default reviewer is available.")?
27        .parse()
28}
29
30/// The saved request's Run repository and its receipts, where its Human actions are recorded.
31pub async fn open(
32    state: &Path,
33    request: &crate::types::RequestId,
34) -> Result<(Receipts, PathBuf), String> {
35    let repo = store::read_request_repo_by_id(state, request.clone()).await?;
36    Ok((Receipts::open(state, &repo).await?, repo))
37}
38
39pub async fn claim(
40    receipts: &Receipts,
41    request: &crate::types::RequestId,
42    reviewer: &crate::types::ReviewerId,
43) -> Result<HumanClaim, String> {
44    claim_acquisition(receipts, request, reviewer)
45        .await
46        .map(|(claim, _)| claim)
47}
48
49/// The saved claim and whether this action created it, rather than finding an existing claim.
50pub async fn claim_acquisition(
51    receipts: &Receipts,
52    request: &crate::types::RequestId,
53    reviewer: &crate::types::ReviewerId,
54) -> Result<(HumanClaim, bool), String> {
55    receipts.claim_human(request, reviewer).await
56}
57
58/// Release this particular claim, returning false if it is gone or has been replaced.
59pub async fn release_exact_claim(state: &Path, claim: &HumanClaim) -> Result<bool, String> {
60    let (receipts, _) = open(state, &claim.request_id).await?;
61    let result = receipts.release_exact_claim(claim.clone()).await;
62    let closed = receipts.close().await;
63    result.and_then(|released| closed.map(|()| released))
64}
65
66/// Release the reviewer lock without a verdict, so another reviewer can claim the request.
67pub async fn unclaim(
68    receipts: &Receipts,
69    request: &crate::types::RequestId,
70    reviewer: &crate::types::ReviewerId,
71) -> Result<HumanClaim, String> {
72    receipts.release_human(request, reviewer).await
73}
74
75/// Run `tool` for the reviewer who holds the claim, its output reaching `run`'s Tool log. A
76/// refusal before it starts ends the run with the refusal.
77pub async fn run_human_tool(
78    receipts: &Receipts,
79    request: &crate::types::RequestId,
80    reviewer: &crate::types::ReviewerId,
81    tool: &crate::config::ToolName,
82    cancellation: CancellationToken,
83    run: crate::tools::human::log::Run,
84) -> Result<ToolResult, String> {
85    let ready = async {
86        let (mut request, _) = receipts.human_request(request, reviewer).await?;
87        let config = reconnect(receipts, &request).await?;
88        let registry = Registry::new(&config, &request.eval_id)?;
89        if !registry.list().any(|entry| &entry.name == tool) {
90            return Err::<_, String>("Unknown registered Human tool.".into());
91        }
92        recheck(
93            receipts,
94            &mut request,
95            reviewer,
96            &config,
97            cancellation.clone(),
98        )
99        .await?;
100        receipts.human_request(&request.id, reviewer).await?;
101        Ok((config, request.eval_id))
102    };
103    let (config, eval) = match ready.await {
104        Ok(ready) => ready,
105        Err(error) => {
106            run.end(crate::tools::human::log::End::Failed(error.clone()));
107            return Err(error);
108        }
109    };
110    let registry = Registry::new(&config, &eval).expect("the registry was just built");
111    Ok(registry.call_logged(tool, cancellation, run).await)
112}
113
114/// What every registered Human tool of a waiting request would run, by tool name; needs no
115/// claim and runs nothing. A tool that cannot be resolved carries its error. A request whose
116/// declarations changed ends here as it does before a tool run or a submission.
117pub async fn tool_commands(
118    receipts: &Receipts,
119    request: &crate::types::RequestId,
120) -> Result<std::collections::BTreeMap<crate::config::ToolName, Result<CommandLine, String>>, String>
121{
122    let request = receipts.waiting_human(request).await?;
123    let config = reconnect(receipts, &request).await?;
124    commands_for(&config, &request.eval_id)
125}
126
127/// Resolve display-only command lines without retiring a request or changing its claim.
128pub async fn preview_tool_commands(
129    request: std::sync::Arc<Request>,
130) -> Result<std::collections::BTreeMap<crate::config::ToolName, Result<CommandLine, String>>, String>
131{
132    crate::task::blocking(move || {
133        let config = declarations(&request).map_err(|mismatch| match mismatch {
134            Mismatch::Unreadable(error) => error,
135            Mismatch::Changed(reason) => reason.into(),
136        })?;
137        commands_for(&config, &request.eval_id)
138    })
139    .await?
140}
141
142fn commands_for(
143    config: &RepoConfig,
144    eval: &crate::types::EvalId,
145) -> Result<std::collections::BTreeMap<crate::config::ToolName, Result<CommandLine, String>>, String>
146{
147    let registry = Registry::new(config, eval)?;
148    Ok(registry
149        .list()
150        .filter(|tool| registry.is_command(&tool.name))
151        .map(|tool| (tool.name.clone(), registry.command(&tool.name)))
152        .collect())
153}
154
155/// A Human answer parsed at the caller's input boundary. The request's owner schema is
156/// checked against these fields only once the saved request has been loaded.
157#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
158pub struct Submission {
159    verdict: crate::runtime::Verdict,
160    #[serde(flatten)]
161    fields: Map<String, Value>,
162}
163
164impl TryFrom<Value> for Submission {
165    type Error = String;
166
167    fn try_from(value: Value) -> Result<Self, Self::Error> {
168        serde_json::from_value(value).map_err(|error| error.to_string())
169    }
170}
171
172impl Submission {
173    pub fn new(
174        verdict: crate::runtime::Verdict,
175        fields: Map<String, Value>,
176    ) -> Result<Self, String> {
177        if fields.contains_key("verdict") {
178            return Err("Owner fields must not contain a verdict.".into());
179        }
180        Ok(Self { verdict, fields })
181    }
182
183    pub fn verdict(&self) -> crate::runtime::Verdict {
184        self.verdict
185    }
186
187    pub fn to_json(&self) -> Value {
188        serde_json::to_value(self).expect("Human submission is JSON")
189    }
190
191    fn validate(&self, eval: &crate::config::EvalDeclaration) -> Result<ValidatedResult, String> {
192        let value = self.to_json();
193        if serde_json::to_vec(&value).map_err(|e| e.to_string())?.len() > MAX_RESULT_BYTES {
194            return Err(format!("Human result exceeds {MAX_RESULT_BYTES} bytes."));
195        }
196        check_result(eval, &value)?;
197        Ok(ValidatedResult {
198            verdict: self.verdict,
199            fields: self.fields.clone(),
200        })
201    }
202}
203
204/// Invalid results remain correctable; only a valid submission performs the final fingerprint
205/// check.
206pub async fn submit(
207    receipts: &Receipts,
208    request: &crate::types::RequestId,
209    reviewer: &crate::types::ReviewerId,
210    submission: &Submission,
211    cancellation: CancellationToken,
212) -> Result<Request, String> {
213    submit_answer(
214        receipts,
215        request,
216        reviewer,
217        SubmittedAnswer::Explicit(submission),
218        cancellation,
219    )
220    .await
221}
222
223enum SubmittedAnswer<'a> {
224    Explicit(&'a Submission),
225    PreparedExplicit(&'a Submission),
226    SavedDraft,
227    PreparedDraft(crate::review::Draft),
228}
229
230async fn submit_answer(
231    receipts: &Receipts,
232    request: &crate::types::RequestId,
233    reviewer: &crate::types::ReviewerId,
234    answer: SubmittedAnswer<'_>,
235    cancellation: CancellationToken,
236) -> Result<Request, String> {
237    let (mut request, _) = receipts.human_request(request, reviewer).await?;
238    let config = reconnect(receipts, &request).await?;
239    let eval = config
240        .evals
241        .iter()
242        .find(|eval| eval.id == request.eval_id)
243        .expect("reconnected eval");
244    let (answer, expected) = match answer {
245        SubmittedAnswer::Explicit(submission) => (submission.validate(&eval.declaration)?, None),
246        SubmittedAnswer::PreparedExplicit(submission) => (
247            submission.validate(&eval.declaration)?,
248            Some(crate::review::Draft::default()),
249        ),
250        other => {
251            let draft = match other {
252                SubmittedAnswer::SavedDraft => receipts
253                    .read_review_draft(&request.id, reviewer)
254                    .await?
255                    .unwrap_or_default(),
256                SubmittedAnswer::PreparedDraft(draft) => draft,
257                SubmittedAnswer::Explicit(_) | SubmittedAnswer::PreparedExplicit(_) => {
258                    unreachable!()
259                }
260            };
261            (
262                draft.submission(&request)?.validate(&eval.declaration)?,
263                Some(draft),
264            )
265        }
266    };
267    recheck(receipts, &mut request, reviewer, &config, cancellation).await?;
268    request.state = crate::store::RequestState::completed(answer.into(), crate::broker::now());
269    receipts
270        .settle_human_if_draft(&request, reviewer, expected)
271        .await
272}
273
274/// `submit`, then publish the settled result to the configured remote review store.
275pub async fn submit_and_publish(
276    state: &Path,
277    request: &crate::types::RequestId,
278    reviewer: &crate::types::ReviewerId,
279    submission: &Submission,
280    cancellation: CancellationToken,
281) -> Result<Request, String> {
282    publish_answer(
283        state,
284        request,
285        reviewer,
286        SubmittedAnswer::Explicit(submission),
287        cancellation,
288    )
289    .await
290}
291
292pub(crate) async fn publish_explicit_without_draft(
293    state: &Path,
294    request: &crate::types::RequestId,
295    reviewer: &crate::types::ReviewerId,
296    submission: &Submission,
297    cancellation: CancellationToken,
298) -> Result<Request, String> {
299    publish_answer(
300        state,
301        request,
302        reviewer,
303        SubmittedAnswer::PreparedExplicit(submission),
304        cancellation,
305    )
306    .await
307}
308
309/// Submit the saved answer, refusing to settle if another surface changes its verdict or
310/// form while its inputs are checked. Notes are read at settlement in either case.
311pub(crate) async fn publish_saved_draft(
312    state: &Path,
313    request: &crate::types::RequestId,
314    reviewer: &crate::types::ReviewerId,
315    draft: Option<crate::review::Draft>,
316    cancellation: CancellationToken,
317) -> Result<Request, String> {
318    let answer = draft.map_or(SubmittedAnswer::SavedDraft, SubmittedAnswer::PreparedDraft);
319    publish_answer(state, request, reviewer, answer, cancellation).await
320}
321
322async fn publish_answer(
323    state: &Path,
324    request: &crate::types::RequestId,
325    reviewer: &crate::types::ReviewerId,
326    answer: SubmittedAnswer<'_>,
327    cancellation: CancellationToken,
328) -> Result<Request, String> {
329    let (receipts, repo) = open(state, request).await?;
330    let result = async {
331        let remote = Session::open(Some(state), Some(&repo))?;
332        let request = submit_answer(&receipts, request, reviewer, answer, cancellation).await?;
333        if let Some(remote) = remote {
334            remote
335                .publish_request(&receipts, &request)
336                .await
337                .map_err(|error| {
338                    format!("The Human result is saved locally, but publishing it failed: {error}")
339                })?;
340        }
341        Ok(request)
342    }
343    .await;
344    let closed = receipts.close().await;
345    result.and_then(|request| closed.map(|()| request))
346}
347
348pub(crate) fn definition(
349    config: &RepoConfig,
350    eval: &Eval,
351) -> Result<crate::store::HumanDefinition, String> {
352    let scope = scope::eval_scope(config, eval).map_err(|e| e.to_string())?;
353    Ok(crate::store::HumanDefinition::authored(
354        &config.root,
355        eval,
356        &scope,
357    ))
358}
359
360/// Why the live declarations cannot serve a waiting request.
361enum Mismatch {
362    /// They could not be read: the request keeps waiting until they load again.
363    Unreadable(String),
364    /// They differ from those the request recorded, so it can no longer be answered as recorded.
365    Changed(&'static str),
366}
367
368/// The live declarations of the request's eval. When they no longer match those it recorded,
369/// the request ends ERROR (INPUT_CHANGED) with the requests joined to it, whoever holds it, as
370/// a changed fingerprint ends it: the next verify asks again with the new declarations.
371async fn reconnect(receipts: &Receipts, request: &Request) -> Result<RepoConfig, String> {
372    match declarations(request) {
373        Ok(config) => Ok(config),
374        Err(Mismatch::Unreadable(error)) => Err(error),
375        Err(Mismatch::Changed(error)) => {
376            receipts
377                .retire_human(&request.id, crate::types::FailureCode::InputChanged, error)
378                .await?;
379            Err(error.into())
380        }
381    }
382}
383
384/// The live declarations of the request's eval, compared with those it was recorded with. Only
385/// the declarations of the eval's scope are read, however large the workspace is; the whole
386/// workspace only when the scope alone cannot answer, as when an Artifact of it moved.
387fn declarations(request: &Request) -> Result<RepoConfig, Mismatch> {
388    let repo = &request
389        .provenance
390        .as_ref()
391        .ok_or_else(|| Mismatch::Unreadable("Human request has no provenance.".into()))?
392        .repo_path;
393    let sites = request
394        .human_definition
395        .as_ref()
396        .and_then(|definition| definition.artifacts.value())
397        .and_then(|artifacts| {
398            artifacts
399                .iter()
400                .map(|(name, artifact)| {
401                    Some((
402                        name.clone(),
403                        crate::config::Site {
404                            path: artifact.path.value()?.clone(),
405                            definition: artifact.definition.value()?.clone(),
406                        },
407                    ))
408                })
409                .collect::<Option<std::collections::BTreeMap<_, _>>>()
410        });
411    let scoped = sites.and_then(|sites| {
412        crate::config::read_eval_scope(repo, &request.eval_id, &sites)
413            .ok()
414            .flatten()
415    });
416    let config = match scoped {
417        Some(config) => config,
418        None => read_workspace_config(repo).map_err(|e| Mismatch::Unreadable(e.to_string()))?,
419    };
420    let eval = config
421        .evals
422        .iter()
423        .find(|eval| eval.id == request.eval_id)
424        .ok_or(Mismatch::Changed("Recorded Human eval no longer exists."))?;
425    if Some(definition(&config, eval).map_err(Mismatch::Unreadable)?) != request.human_definition {
426        return Err(Mismatch::Changed(
427            "Human Artifact scope or eval declarations changed since the request was recorded.",
428        ));
429    }
430    Ok(config)
431}
432
433async fn recheck(
434    receipts: &Receipts,
435    request: &mut Request,
436    reviewer: &crate::types::ReviewerId,
437    config: &RepoConfig,
438    cancellation: CancellationToken,
439) -> Result<(), String> {
440    if cancellation.is_cancelled() {
441        return Err("Human action was cancelled.".into());
442    }
443    let eval = config
444        .evals
445        .iter()
446        .find(|eval| eval.id == request.eval_id)
447        .ok_or("Recorded Human eval no longer exists.")?;
448    if request.key.is_none() && cache::live_input(config, eval).is_none() {
449        return Ok(());
450    }
451    let output = request
452        .run_dir
453        .as_deref()
454        .ok_or("Human request has no output directory.")?;
455    let parallelism = cache::Parallelism::new(cache::Parallelism::available())?;
456    let (code, error) = match if let Some(expected) = &request.key {
457        cache::recheck(config, eval, output, &parallelism, cancellation.clone())
458            .await
459            .map(|actual| actual.as_ref() == Some(expected))
460    } else {
461        cache::recheck_observations(
462            config,
463            &request.fingerprints,
464            output,
465            &parallelism,
466            cancellation.clone(),
467        )
468        .await
469    } {
470        Ok(true) => return Ok(()),
471        Ok(false) => (
472            crate::types::FailureCode::InputChanged,
473            "Fingerprint changed during review.".into(),
474        ),
475        Err(error) if cancellation.is_cancelled() => return Err(error),
476        Err(error) => (crate::types::FailureCode::FingerprintRecheckFailed, error),
477    };
478    request.state =
479        crate::store::RequestState::failed(error.clone(), Some(code), crate::broker::now());
480    receipts.settle_human(request, reviewer).await?;
481    Err(error)
482}