Skip to main content

artifactize_core/
diagnostics.rs

1//! Backend readiness and tool checks.
2
3mod doctor;
4pub use doctor::{CheckStatus, DoctorReport, doctor};
5
6use std::path::Path;
7
8use serde::Serialize;
9use serde_json::json;
10use tokio_util::sync::CancellationToken;
11
12use crate::{
13    config::{Profile, RepoConfig},
14    tools::{self, human},
15    workspace,
16};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, clap::ValueEnum)]
19#[serde(rename_all = "lowercase")]
20pub enum Audience {
21    Agent,
22    Human,
23}
24
25use crate::{
26    config::ToolName,
27    types::{ArtifactName, EvalId},
28};
29
30/// Named arguments supplied by the owner, validated against the selected tool's schema.
31#[derive(Debug, Clone)]
32pub struct ToolArguments(serde_json::Map<String, serde_json::Value>);
33
34impl std::str::FromStr for ToolArguments {
35    type Err = String;
36    fn from_str(text: &str) -> Result<Self, Self::Err> {
37        match serde_json::from_str(text).map_err(|error| format!("Invalid --args JSON: {error}"))? {
38            serde_json::Value::Object(object) => Ok(Self(object)),
39            _ => Err("--args must be a JSON object.".into()),
40        }
41    }
42}
43
44#[derive(Debug)]
45pub enum ToolCheckOptions {
46    Inspect {
47        scope: InspectionScope,
48        tool: Option<ToolName>,
49    },
50    Execute {
51        scope: ExecutionScope,
52        tool: ToolName,
53    },
54}
55
56#[derive(Debug)]
57pub enum InspectionScope {
58    Eval(EvalId),
59    Catalog {
60        artifact: Option<ArtifactName>,
61        audience: Option<Audience>,
62    },
63}
64
65#[derive(Debug)]
66pub enum ExecutionScope {
67    Eval {
68        id: EvalId,
69        args: Option<ToolArguments>,
70    },
71    Agent {
72        artifact: ArtifactName,
73        args: Option<ToolArguments>,
74    },
75    Human {
76        artifact: ArtifactName,
77    },
78}
79
80impl ToolCheckOptions {
81    /// Parse CLI or MCP flag combinations once, before reading project configuration.
82    pub fn from_flags(
83        eval: Option<EvalId>,
84        artifact: Option<ArtifactName>,
85        audience: Option<Audience>,
86        tool: Option<ToolName>,
87        execute: bool,
88        args: Option<ToolArguments>,
89    ) -> Result<Self, String> {
90        if eval.is_some() && (artifact.is_some() || audience.is_some()) {
91            return Err("An eval selector determines scope and audience; do not combine it with --artifact or --audience.".into());
92        }
93        if execute
94            && (tool.is_none() || (eval.is_none() && (artifact.is_none() || audience.is_none())))
95        {
96            return Err("--execute requires --tool, with an eval selector or with --artifact and --audience.".into());
97        }
98        if args.is_some() && (!execute || audience == Some(Audience::Human)) {
99            return Err(AGENT_ARGS.into());
100        }
101        Ok(if execute {
102            let tool = tool.expect("execution requires a tool");
103            let scope = if let Some(id) = eval {
104                ExecutionScope::Eval { id, args }
105            } else {
106                let artifact = artifact.expect("execution requires an eval or an Artifact");
107                match audience.expect("Artifact execution requires an audience") {
108                    Audience::Agent => ExecutionScope::Agent { artifact, args },
109                    Audience::Human => ExecutionScope::Human { artifact },
110                }
111            };
112            Self::Execute { scope, tool }
113        } else {
114            Self::Inspect {
115                scope: eval.map_or(
116                    InspectionScope::Catalog { artifact, audience },
117                    InspectionScope::Eval,
118                ),
119                tool,
120            }
121        })
122    }
123}
124
125const AGENT_ARGS: &str =
126    "--args requires Agent tool execution; Human tools take no free arguments.";
127
128#[derive(Debug, Serialize)]
129#[serde(rename_all = "camelCase")]
130pub struct ToolCheckReport {
131    pub ok: bool,
132    pub scopes: Vec<ToolCheckScope>,
133    pub checks: Vec<ToolCheck>,
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub result: Option<ToolCheckResult>,
136}
137
138#[derive(Debug, Serialize)]
139#[serde(rename_all = "camelCase")]
140pub struct ToolCheckScope {
141    pub eval_id: Option<crate::config::EvalId>,
142    pub artifact_id: Option<crate::config::ArtifactName>,
143    pub audience: Audience,
144    pub tools: Vec<tools::ToolDefinition>,
145}
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
147#[serde(rename_all = "lowercase")]
148pub enum ToolCheckStage {
149    Declarations,
150    Preflight,
151    Execute,
152}
153
154#[derive(Debug)]
155pub struct ToolCheck {
156    pub stage: ToolCheckStage,
157    pub tool: Option<crate::config::ToolName>,
158    pub result: Result<(), String>,
159}
160
161impl Serialize for ToolCheck {
162    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
163        use serde::ser::SerializeStruct;
164        let mut state = serializer.serialize_struct("ToolCheck", 4)?;
165        state.serialize_field("stage", &self.stage)?;
166        state.serialize_field("tool", &self.tool)?;
167        state.serialize_field("ok", &self.result.is_ok())?;
168        state.serialize_field("message", &self.result.as_ref().err())?;
169        state.end()
170    }
171}
172#[derive(Debug, Serialize)]
173#[serde(untagged)]
174pub enum ToolCheckResult {
175    Agent(tools::ToolResult),
176    Human(human::ToolResult),
177}
178
179impl ToolCheckReport {
180    fn check(
181        &mut self,
182        stage: ToolCheckStage,
183        name: Option<&crate::config::ToolName>,
184        result: Result<(), String>,
185    ) {
186        self.ok &= result.is_ok();
187        self.checks.push(ToolCheck {
188            stage,
189            tool: name.cloned(),
190            result,
191        });
192    }
193}
194
195enum Catalog<'a> {
196    Agent(tools::Registry<'a>),
197    Human(human::Registry<'a>),
198}
199
200impl Catalog<'_> {
201    fn definitions(&self) -> Vec<tools::ToolDefinition> {
202        match self {
203            Self::Agent(registry) => registry.list().cloned().collect(),
204            Self::Human(registry) => registry
205                .list()
206                .map(|tool| tools::ToolDefinition {
207                    name: tool.name.clone(),
208                    artifact_id: tool.artifact_id.clone(),
209                    description: tool.description.clone(),
210                    input_schema: json!({
211                        "type":"object",
212                        "properties":{},
213                        "additionalProperties":false,
214                    }),
215                })
216                .collect(),
217        }
218    }
219    fn preflight(&self, name: &crate::config::ToolName) -> Result<(), String> {
220        match self {
221            Self::Agent(r) => r.preflight(name),
222            Self::Human(r) => r.preflight(name),
223        }
224    }
225}
226
227pub async fn check_tools(
228    repo: &Path,
229    state: Option<&Path>,
230    options: &ToolCheckOptions,
231    cancellation: CancellationToken,
232) -> Result<ToolCheckReport, String> {
233    let mut report = ToolCheckReport {
234        ok: true,
235        scopes: Vec::new(),
236        checks: Vec::new(),
237        result: None,
238    };
239    let config = match crate::config::read_workspace_config(repo) {
240        Ok(config) => config,
241        Err(error) => {
242            report.check(ToolCheckStage::Declarations, None, Err(error.to_string()));
243            return Ok(report);
244        }
245    };
246    let (selected, artifact, audience, tool, executing) = match options {
247        ToolCheckOptions::Inspect { scope, tool } => match scope {
248            InspectionScope::Eval(id) => (Some(id), None, None, tool.as_ref(), None),
249            InspectionScope::Catalog { artifact, audience } => {
250                (None, artifact.as_ref(), *audience, tool.as_ref(), None)
251            }
252        },
253        ToolCheckOptions::Execute { scope, tool } => match scope {
254            ExecutionScope::Eval { id, args } => {
255                (Some(id), None, None, Some(tool), Some(args.as_ref()))
256            }
257            ExecutionScope::Agent { artifact, args } => (
258                None,
259                Some(artifact),
260                Some(Audience::Agent),
261                Some(tool),
262                Some(args.as_ref()),
263            ),
264            ExecutionScope::Human { artifact } => (
265                None,
266                Some(artifact),
267                Some(Audience::Human),
268                Some(tool),
269                Some(None),
270            ),
271        },
272    };
273    if let Some(id) = selected
274        && !config.evals.iter().any(|eval| {
275            &eval.id == id
276                && matches!(
277                    eval.declaration.profile(),
278                    Profile::Agent { .. } | Profile::Human {}
279                )
280        })
281    {
282        return Err("Select a declared Agent or Human eval.".into());
283    }
284    if executing.flatten().is_some()
285        && let Some(id) = selected
286        && config
287            .evals
288            .iter()
289            .any(|eval| &eval.id == id && matches!(eval.declaration.profile(), Profile::Human {}))
290    {
291        return Err(AGENT_ARGS.into());
292    }
293    if let Some(id) = artifact
294        && !config.artifacts.contains_key(id)
295    {
296        return Err(format!("Unknown Artifact: {id}"));
297    }
298    let mut catalogs = Vec::new();
299    // An eval selector keeps the eval's own scope, also for one selected tool.
300    if artifact.is_some() || audience.is_some() || (tool.is_some() && selected.is_none()) {
301        let artifacts: Vec<_> =
302            artifact.map_or_else(|| config.artifacts.keys().collect(), |id| vec![id]);
303        for artifact in artifacts {
304            for kind in [Audience::Agent, Audience::Human] {
305                if audience.is_some_and(|a| a != kind) {
306                    continue;
307                }
308                let catalog = match kind {
309                    Audience::Agent => {
310                        tools::Registry::for_artifact(&config, artifact).map(Catalog::Agent)
311                    }
312                    Audience::Human => {
313                        human::Registry::for_artifact(&config, artifact).map(Catalog::Human)
314                    }
315                };
316                catalogs.push((None, Some(artifact), kind, catalog));
317            }
318        }
319    } else {
320        for eval in &config.evals {
321            if selected.is_some_and(|id| id != &eval.id) {
322                continue;
323            }
324            let (audience, catalog) = match eval.declaration.profile() {
325                Profile::Agent { .. } => (
326                    Audience::Agent,
327                    tools::Registry::new(&config, &eval.id).map(Catalog::Agent),
328                ),
329                Profile::Human { .. } => (
330                    Audience::Human,
331                    human::Registry::new(&config, &eval.id).map(Catalog::Human),
332                ),
333                Profile::Runtime { .. } => continue,
334            };
335            catalogs.push((Some(&eval.id), None, audience, catalog));
336        }
337    }
338    for (eval, artifact, audience, catalog) in catalogs {
339        let catalog = match catalog {
340            Ok(catalog) => catalog,
341            Err(error) => {
342                report.check(ToolCheckStage::Preflight, None, Err(error));
343                continue;
344            }
345        };
346        let mut definitions = catalog.definitions();
347        if let Some(name) = tool {
348            let published = definitions.iter().any(|d| d.name == *name);
349            definitions.retain(|d| {
350                artifact.is_none_or(|id| &d.artifact_id == id)
351                    && (d.name == *name
352                        || (!published
353                            && artifact.is_some()
354                            && d.name == format!("{name}_{}", d.artifact_id)))
355            });
356            if definitions.is_empty() {
357                report.check(
358                    ToolCheckStage::Preflight,
359                    Some(name),
360                    Err(if eval.is_some() {
361                        "The selected tool is not published to this eval.".into()
362                    } else {
363                        "The selected tool is not registered for this Artifact and audience.".into()
364                    }),
365                );
366            }
367        }
368        for definition in &definitions {
369            report.check(
370                ToolCheckStage::Preflight,
371                Some(&definition.name),
372                catalog.preflight(&definition.name),
373            );
374        }
375        report.scopes.push(ToolCheckScope {
376            eval_id: eval.cloned(),
377            artifact_id: artifact.map(|id| config.artifacts[id].name.clone()),
378            audience,
379            tools: definitions.clone(),
380        });
381        if let Some(args) = executing
382            && report.ok
383            && definitions.len() == 1
384        {
385            let name = &definitions[0].name;
386            let result =
387                execute_tool(&config, state, &catalog, name, args, cancellation.clone()).await;
388            match result {
389                Ok(result) => {
390                    report.check(
391                        ToolCheckStage::Execute,
392                        Some(name),
393                        if result.is_error() {
394                            Err("The tool returned an error; no review result was created.".into())
395                        } else {
396                            Ok(())
397                        },
398                    );
399                    report.result = Some(result);
400                }
401                Err(error) => report.check(ToolCheckStage::Execute, Some(name), Err(error)),
402            }
403        }
404    }
405    Ok(report)
406}
407
408async fn execute_tool(
409    config: &RepoConfig,
410    state: Option<&Path>,
411    catalog: &Catalog<'_>,
412    name: &crate::config::ToolName,
413    args: Option<&ToolArguments>,
414    cancellation: CancellationToken,
415) -> Result<ToolCheckResult, String> {
416    match catalog {
417        Catalog::Human(registry) => Ok(ToolCheckResult::Human(
418            registry.call(name, cancellation).await,
419        )),
420        Catalog::Agent(registry) => {
421            let state = crate::store::state_dir(state)?;
422            let root =
423                workspace::prepare_directory(&state, &config.root).map_err(|e| e.to_string())?;
424            let directory = crate::platform::private_tempdir_in("tools-check-", &root)
425                .map_err(|e| e.to_string())?;
426            let args =
427                serde_json::Value::Object(args.map(|args| args.0.clone()).unwrap_or_default());
428            let sessions = registry.sessions(&state, Some(name), cancellation.clone());
429            let registry = registry.with_session_scope(&sessions)?;
430            let result = registry
431                .call(name, args, directory.path(), cancellation)
432                .await;
433            sessions.close().await?;
434            directory
435                .close()
436                .map_err(|_| "Tool-check cleanup failed.".to_owned())?;
437            Ok(ToolCheckResult::Agent(result))
438        }
439    }
440}
441
442impl ToolCheckResult {
443    fn is_error(&self) -> bool {
444        match self {
445            Self::Agent(result) => result.is_error(),
446            Self::Human(result) => result.is_error(),
447        }
448    }
449}