1use std::collections::{BTreeMap, BTreeSet};
4use std::path::{Path, PathBuf};
5
6use serde::Serialize;
7
8use crate::config::{Artifact, ArtifactName, ConfigError, Eval, Fingerprint, Profile, RepoConfig};
9
10mod argument;
11pub(crate) use argument::PATH_SLOT;
12pub use argument::{Argument, LogicalSuffix, LogicalTarget};
13
14mod human;
15pub(crate) use human::{builtin_args, resolve_human_argv};
16
17pub use artifactize_tools::scope::{ArtifactId, ScopeError, ScopedPath, scoped_path};
18pub(crate) use artifactize_tools::scope::{logical_path, open_child, open_scoped};
19
20#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
21pub struct Relation {
22 pub source: ArtifactName,
24 pub target: ArtifactName,
26 #[serde(flatten)]
27 pub kind: RelationKind,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
31#[serde(tag = "kind", rename_all = "lowercase")]
32pub enum RelationKind {
33 Part,
36 Instruction {
37 #[serde(rename = "evalId")]
38 eval_id: crate::config::EvalId,
39 name: crate::config::ReferenceName,
40 },
41 #[serde(rename = "argv")]
42 Argument {
43 #[serde(rename = "evalId")]
44 eval_id: crate::config::EvalId,
45 index: usize,
46 name: crate::config::ReferenceName,
47 path: LogicalTarget,
48 },
49 Input {
51 #[serde(rename = "evalId")]
52 eval_id: crate::config::EvalId,
53 name: crate::config::ReferenceName,
54 },
55}
56
57#[derive(Debug, Clone)]
58pub struct Scope<'a> {
59 pub artifacts: BTreeMap<ArtifactName, &'a Artifact>,
60}
61
62impl Scope<'_> {
63 pub(crate) fn tool_scope(&self) -> artifactize_tools::scope::Scope {
65 artifactize_tools::scope::Scope {
66 artifacts: self
67 .artifacts
68 .iter()
69 .map(|(id, artifact)| (tool_id(id), artifact.tool_scope()))
70 .collect(),
71 }
72 }
73
74 pub fn resolve_path(
75 &self,
76 artifact_id: &ArtifactName,
77 path: &str,
78 ) -> Result<ScopedPath, ScopeError> {
79 self.tool_scope().resolve_path(&tool_id(artifact_id), path)
80 }
81
82 pub fn resolve_input(
83 &self,
84 root: &Path,
85 artifact_id: &ArtifactName,
86 path: &str,
87 ) -> Result<PathBuf, ScopeError> {
88 self.tool_scope()
89 .resolve_input(root, &tool_id(artifact_id), path)
90 }
91}
92
93pub(crate) fn tool_id(name: &ArtifactName) -> ArtifactId {
96 ArtifactId::new(name.as_str()).expect("configuration validates Artifact names")
97}
98
99pub(crate) fn validate_file_target(root: &Path, artifact: &Artifact) -> Result<(), ScopeError> {
101 if matches!(
102 artifact.kind(),
103 crate::config::ArtifactKind::Folder | crate::config::ArtifactKind::Aspect
104 ) {
105 let directory = scoped_path(root, artifact.folder())?;
106 let opened = crate::platform::open_directory(&directory).map_err(|error| {
107 ScopeError(format!(
108 "Artifact {} target {} must be a folder: {error}",
109 artifact.name, artifact.path
110 ))
111 })?;
112 if !opened
113 .metadata()
114 .map_err(|error| ScopeError(error.to_string()))?
115 .is_dir()
116 {
117 return Err(ScopeError(format!(
118 "Artifact {} target {} must be a folder.",
119 artifact.name, artifact.path
120 )));
121 }
122 for selected in artifact.select() {
123 let file = open_scoped(&directory, selected).map_err(|error| {
124 ScopeError(format!(
125 "Artifact {} selection {selected} is unavailable: {error}",
126 artifact.name
127 ))
128 })?;
129 let metadata = file
130 .metadata()
131 .map_err(|error| ScopeError(error.to_string()))?;
132 if !metadata.is_file() && !metadata.is_dir() {
133 return Err(ScopeError(format!(
134 "Artifact {} selection {selected} must be a file or folder.",
135 artifact.name
136 )));
137 }
138 }
139 }
140 if artifact.file_name().is_some() {
141 artifact
142 .path
143 .local()
144 .expect("file target")
145 .to_str()
146 .ok_or_else(|| ScopeError("Artifact paths must be UTF-8.".into()))?;
147 let target = artifact.path.to_string();
148 let file = open_scoped(root, &target).map_err(|error| {
149 ScopeError(format!(
150 "File Artifact {} target {} is unavailable: {error}",
151 artifact.name, artifact.path
152 ))
153 })?;
154 if !file
155 .metadata()
156 .map_err(|error| ScopeError(error.to_string()))?
157 .is_file()
158 {
159 return Err(ScopeError(format!(
160 "File Artifact {} target {} must remain a regular file.",
161 artifact.name, artifact.path
162 )));
163 }
164 }
165 Ok(())
166}
167
168fn reference_path(config: &RepoConfig, id: &ArtifactName, path: &str) -> Result<(), ScopeError> {
169 if config.artifacts[id].file_name().is_some() && !path.is_empty() {
170 return Err(ScopeError(format!(
171 "File Artifact {{{id}}} cannot have a /path suffix."
172 )));
173 }
174 Ok(())
175}
176
177fn nested_path(
180 everything: &artifactize_tools::scope::Scope,
181 source: &ArtifactName,
182 path: &str,
183) -> Result<(), ScopeError> {
184 if everything.artifacts[&tool_id(source)].kind() == crate::config::ArtifactKind::Live {
185 return Ok(());
186 }
187 let resolved = everything.resolve_path(&tool_id(source), path)?;
188 if resolved.artifact_id.as_str() != source.as_str() {
189 return Err(ScopeError(format!(
190 "{{{source}}}/{path} is in Artifact {owner}; reference {{{owner}}}/{rest} instead.",
191 owner = resolved.artifact_id,
192 rest = resolved.path,
193 )));
194 }
195 Ok(())
196}
197
198pub fn artifact_scope<'a>(
202 config: &'a RepoConfig,
203 roots: &[&ArtifactName],
204) -> Result<Scope<'a>, ScopeError> {
205 let artifacts = roots
206 .iter()
207 .map(|&id| {
208 config
209 .artifacts
210 .get_key_value(id)
211 .map(|(id, artifact)| (id.clone(), artifact))
212 .ok_or_else(|| ScopeError(format!("Unknown Artifact: {id}")))
213 })
214 .collect::<Result<_, _>>()?;
215 Ok(Scope { artifacts })
216}
217
218pub(crate) fn executable(
221 root: &Path,
222 scope: &Scope<'_>,
223 owner: &ArtifactName,
224 command: &str,
225) -> Result<std::ffi::OsString, String> {
226 let artifact = scope.artifacts[owner];
227 let cwd = scoped_path(root, artifact.folder()).map_err(|error| error.to_string())?;
228 let command = crate::platform::program_path(command).map_err(|error| error.to_string())?;
229 let relative = crate::platform::program::folder_relative(&command)?;
230 let program = if let Some(relative) = relative.as_deref() {
231 let physical = if artifact.file_name().is_some()
232 || artifact.kind() == crate::config::ArtifactKind::Live
233 {
234 artifactize_tools::scope::logical_path(relative).map_err(|error| error.to_string())?;
235 cwd.join(relative)
236 } else {
237 let resolved = scope
238 .resolve_path(owner, relative)
239 .map_err(|error| error.to_string())?;
240 root.join(scope.artifacts[resolved.artifact_id.as_str()].folder())
241 .join(resolved.path)
242 };
243 crate::platform::program::reject_link_ancestors(&physical)
245 .map_err(|error| error.to_string())?;
246 let resolve = |candidate: &Path| {
247 if artifact.file_name().is_some()
248 || artifact.kind() == crate::config::ArtifactKind::Live
249 {
250 scoped_path(&cwd, candidate).map_err(|error| error.to_string())
251 } else {
252 let logical = artifactize_tools::scope::logical_from_native(candidate)
253 .ok_or_else(|| "Executable path is not portable text.".to_owned())?;
254 scope
255 .resolve_input(root, owner, &logical)
256 .map_err(|error| error.to_string())
257 }
258 };
259 crate::platform::program::resolve_scoped(Path::new(relative), resolve)?
260 } else {
261 command
262 };
263 Ok(program.into_os_string())
264}
265
266pub fn eval_scope<'a>(config: &'a RepoConfig, eval: &Eval) -> Result<Scope<'a>, ScopeError> {
267 let roots: Vec<_> = std::iter::once(&eval.target)
268 .chain(eval.deps.iter())
269 .collect();
270 artifact_scope(config, &roots)
271}
272
273pub fn argv_scope<'a>(
275 config: &'a RepoConfig,
276 owner: &ArtifactName,
277 args: &[Argument],
278) -> Result<Scope<'a>, ScopeError> {
279 let mut roots = vec![owner];
280 for argument in args {
281 if let Argument::Reference { name, .. } = argument {
282 roots.push(reference_target(config, owner, name)?);
283 }
284 }
285 artifact_scope(config, &roots)
286}
287
288#[derive(Debug, Clone, PartialEq, Eq)]
289pub enum InstructionPart {
290 Text(String),
291 Artifact(ArtifactName),
292}
293
294pub(crate) fn artifact_instruction(eval: &Eval) -> Vec<InstructionPart> {
296 let Some(source) = eval.declaration.instruction() else {
297 return Vec::new();
298 };
299 let mut parts = Vec::new();
300 let mut start = 0;
301 for slot in eval.declaration.slots() {
302 let crate::config::Slot::Artf { artifact } = &slot.slot else {
303 continue;
304 };
305 if start < slot.range.start {
306 parts.push(InstructionPart::Text(
307 source[start..slot.range.start].into(),
308 ));
309 }
310 parts.push(InstructionPart::Artifact(artifact.clone()));
311 start = slot.range.end;
312 }
313 if start < source.len() {
314 parts.push(InstructionPart::Text(source[start..].into()));
315 }
316 parts
317}
318
319fn reference_target<'a>(
320 config: &'a RepoConfig,
321 owner: &ArtifactName,
322 name: &crate::config::ReferenceName,
323) -> Result<&'a ArtifactName, ScopeError> {
324 if !config.artifacts.contains_key(owner) {
325 return Err(ScopeError(format!("Unknown Artifact: {owner}")));
326 }
327 let target = config.artifacts.get_key_value(name.as_str());
328 target
329 .map(|(id, _)| id)
330 .ok_or_else(|| ScopeError(format!("Unknown Artifact in `@{{path {name}}}`.")))
331}
332
333#[derive(Debug, Clone, PartialEq, Eq)]
336pub(crate) enum ResolvedArgument {
337 Literal(String),
338 Path { prefix: String, path: PathBuf },
339}
340
341impl ResolvedArgument {
342 pub(crate) fn native(&self) -> String {
343 match self {
344 Self::Literal(text) => text.clone(),
345 Self::Path { prefix, path } => {
346 format!(
347 "{prefix}{}",
348 crate::platform::os_text(path.as_os_str()).expect("validated UTF-8 path")
349 )
350 }
351 }
352 }
353
354 pub(crate) fn shown(&self) -> String {
355 match self {
356 Self::Literal(text) => text.clone(),
357 Self::Path { prefix, path } => format!("{prefix}{}", crate::platform::path_text(path)),
358 }
359 }
360}
361
362pub fn resolve_argv(
365 config: &RepoConfig,
366 scope: &Scope<'_>,
367 owner: &ArtifactName,
368 args: &[Argument],
369) -> Result<Vec<String>, ScopeError> {
370 resolved_argv(config, scope, owner, args)
371 .map(|args| args.iter().map(ResolvedArgument::native).collect())
372}
373
374pub(crate) fn resolved_argv(
375 config: &RepoConfig,
376 scope: &Scope<'_>,
377 owner: &ArtifactName,
378 args: &[Argument],
379) -> Result<Vec<ResolvedArgument>, ScopeError> {
380 args.iter()
381 .map(|argument| {
382 let Argument::Reference { prefix, name, path } = argument else {
383 let literal = argument.literal().expect("a literal argument");
384 return Ok(ResolvedArgument::Literal(literal.to_owned()));
385 };
386 let id = reference_target(config, owner, name)?;
387 reference_path(config, id, path)?;
388 argument_value(config, scope, id, path, prefix)
389 })
390 .collect()
391}
392
393pub(crate) fn argument_value(
395 config: &RepoConfig,
396 scope: &Scope<'_>,
397 id: &ArtifactName,
398 path: &str,
399 prefix: &str,
400) -> Result<ResolvedArgument, ScopeError> {
401 let artifact = scope
402 .artifacts
403 .get(id)
404 .ok_or_else(|| ScopeError(format!("Artifact is outside this review: {id}")))?;
405 if let Some(uri) = artifact.path.uri() {
406 return Ok(ResolvedArgument::Literal(if path.is_empty() {
407 format!("{prefix}{uri}")
408 } else {
409 format!("{prefix}{uri}/{path}")
410 }));
411 }
412 let resolved = scope.resolve_input(&config.root, id, path)?;
413 if crate::platform::os_text(resolved.as_os_str()).is_none() {
414 return Err(ScopeError("Artifact paths must be UTF-8.".into()));
415 }
416 Ok(ResolvedArgument::Path {
417 prefix: prefix.into(),
418 path: resolved,
419 })
420}
421
422pub(crate) fn resolve_config(config: &mut RepoConfig) -> Result<(), ConfigError> {
424 let mut relations = Vec::new();
425 for (id, artifact) in &config.artifacts {
426 let error = |keys: &[&str], message: String| config.error_at(id, keys, message);
427 for (name, tool) in &artifact.views.agent_tools {
428 if let crate::config::AgentTool::Builtin(tool) = tool
429 && let Some(args) = &tool.args
430 {
431 let scope = artifact_scope(config, &[id]).map_err(|failure| {
432 error(&["views", "agent_tools", name, "args"], failure.to_string())
433 })?;
434 let owner = ArtifactId::new(id.as_str()).map_err(|failure| {
435 error(&["views", "agent_tools", name, "args"], failure.to_string())
436 })?;
437 artifactize_tools::builtin::validate_target(
438 tool.builtin,
439 args,
440 &config.root,
441 &scope.tool_scope(),
442 &owner,
443 )
444 .map_err(|failure| error(&["views", "agent_tools", name, "args"], failure))?;
445 }
446 if let crate::config::AgentTool::Command(tool) = tool
447 && tool.protocol == crate::config::ToolProtocol::Json
448 {
449 for argument in &tool.args {
450 if let Argument::Reference {
451 name: ref_name,
452 path,
453 ..
454 } = argument
455 {
456 let target = reference_target(config, id, ref_name).map_err(|failure| {
457 error(
458 &["views", "agent_tools", name, "args"],
459 format!("Agent tool {name}: {failure}"),
460 )
461 })?;
462 reference_path(config, target, path).map_err(|failure| {
463 error(
464 &["views", "agent_tools", name, "args"],
465 format!("Agent tool {name}: {failure}"),
466 )
467 })?;
468 }
469 }
470 }
471 }
472 if let Some(Fingerprint::Script { args, .. }) = &artifact.fingerprint {
473 for argument in args {
474 if let Argument::Reference {
475 name: ref_name,
476 path,
477 ..
478 } = argument
479 {
480 let target = reference_target(config, id, ref_name).map_err(|failure| {
481 error(
482 &["fingerprint", "script", "args"],
483 format!("fingerprint.script: {failure}"),
484 )
485 })?;
486 reference_path(config, target, path).map_err(|failure| {
487 error(
488 &["fingerprint", "script", "args"],
489 format!("fingerprint.script: {failure}"),
490 )
491 })?;
492 }
493 }
494 }
495 }
496 for (id, artifact) in &config.artifacts {
497 let Some(Fingerprint::Artifactsum { files: inputs, .. }) = &artifact.fingerprint else {
498 continue;
499 };
500 let error = |message: String| {
501 config.error_at(
502 id,
503 &["fingerprint", "files"],
504 format!("fingerprint.files: {message}"),
505 )
506 };
507 if artifact.covering_part.is_some() {
509 continue;
510 }
511 let scope = artifact_scope(config, &[id]).map_err(|failure| error(failure.0))?;
512 for input in inputs.iter().filter(|input| *input != ".") {
513 let location = scope
514 .resolve_path(id, input)
515 .map_err(|failure| error(failure.0))?;
516 if location.artifact_id.as_str() != id.as_str() {
517 return Err(error(format!(
518 "{input} belongs to Artifact {}; a fingerprint covers only its own Artifact's files.",
519 location.artifact_id
520 )));
521 }
522 }
523 }
524 let everything = everything(config);
525 let mut resolved = Vec::new();
526 for eval in &config.evals {
527 let mut found = eval_references(config, &everything, eval)?;
528 relations.append(&mut found.relations);
529 resolved.push(found);
530 }
531 for (eval, found) in config.evals.iter_mut().zip(resolved) {
532 eval.references = found.references;
533 eval.deps = found.deps;
534 }
535 for artifact in config.artifacts.values() {
536 for part in &artifact.parts {
537 let error = |message: String| config.error_at(&artifact.name, &["parts"], message);
538 match config.artifacts.get(part) {
539 None => return Err(error(format!("Unknown Artifact {part}."))),
540 Some(part) if part.kind() == crate::config::ArtifactKind::Graph => {
541 return Err(error(format!(
542 "The graph Artifact {} is a part of nothing.",
543 part.name
544 )));
545 }
546 Some(_) => relations.push(Relation {
547 source: part.clone(),
548 target: artifact.name.clone(),
549 kind: RelationKind::Part,
550 }),
551 }
552 }
553 }
554 parts_acyclic(config)?;
555 config.relations = relations;
556 human::validate_references(config)?;
557 crate::graph::Graph::new(config).map_err(|error| ConfigError::new(&config.root, error))?;
558 Ok(())
559}
560
561pub(crate) fn missing_eval_tools(
564 config: &RepoConfig,
565) -> impl Iterator<Item = (&Eval, &Artifact, &'static str)> {
566 config.evals.iter().flat_map(move |eval| {
567 std::iter::once(&eval.target)
568 .chain(&eval.deps)
569 .filter_map(move |id| {
570 let artifact = &config.artifacts[id];
571 let kind = match eval.declaration.profile() {
572 Profile::Agent { .. } if artifact.views.agent_tools.is_empty() => "Agent",
573 Profile::Human {} if artifact.views.human_tools.is_empty() => "Human",
574 _ => return None,
575 };
576 Some((eval, artifact, kind))
577 })
578 })
579}
580
581pub(crate) fn validate_eval_tools(config: &RepoConfig) -> Result<(), ConfigError> {
582 let Some((eval, artifact, kind)) = missing_eval_tools(config).next() else {
583 return Ok(());
584 };
585 let (article, audience) = if kind == "Agent" {
586 ("an", "agent")
587 } else {
588 ("a", "human")
589 };
590 let toolset_fix = if artifact.kind() == crate::config::ArtifactKind::Live {
591 String::new()
592 } else {
593 "; for a local file or folder, `: files` gives both".to_owned()
594 };
595 Err(config.error_at(
596 &eval.target,
597 &["evals", eval.declaration.id.as_ref()],
598 format!(
599 "Eval {} includes Artifact {} without {article} {kind} tool. Compose a toolset with `{audience}` tools on {}{toolset_fix}.",
600 eval.id, artifact.name, artifact.name
601 ),
602 ))
603}
604
605fn everything(config: &RepoConfig) -> artifactize_tools::scope::Scope {
607 Scope {
608 artifacts: config
609 .artifacts
610 .iter()
611 .map(|(id, artifact)| (id.clone(), artifact))
612 .collect(),
613 }
614 .tool_scope()
615}
616
617struct EvalReferences {
619 references: BTreeMap<crate::config::ReferenceName, ArtifactName>,
620 deps: Vec<ArtifactName>,
622 relations: Vec<Relation>,
624}
625
626fn eval_references(
627 config: &RepoConfig,
628 everything: &artifactize_tools::scope::Scope,
629 eval: &Eval,
630) -> Result<EvalReferences, ConfigError> {
631 let mut relations = Vec::new();
632 let error = |field: &[&str], failure: ScopeError| {
633 let mut keys = vec!["evals", eval.declaration.id.as_ref()];
634 keys.extend_from_slice(field);
635 config.error_at(&eval.target, &keys, format!("Eval {}: {failure}", eval.id))
636 };
637 let mut references = BTreeMap::new();
638 let mut deps = BTreeSet::new();
639 for slot in eval.declaration.slots() {
642 let source = slot.slot.artifact();
643 if let crate::config::Slot::Path { path, .. } = &slot.slot {
644 nested_path(everything, source, path)
645 .map_err(|failure| error(&["instruction"], failure))?;
646 }
647 let name = crate::config::ReferenceName::from(source);
648 if references.insert(name.clone(), source.clone()).is_some() || source == &eval.target {
649 continue;
650 }
651 deps.insert(source.clone());
652 relations.push(Relation {
653 source: source.clone(),
654 target: eval.target.clone(),
655 kind: RelationKind::Instruction {
656 eval_id: eval.id.clone(),
657 name,
658 },
659 });
660 }
661 for input in eval.declaration.inputs() {
662 if input == &eval.target {
663 return Err(error(
664 &["inputs"],
665 ScopeError(format!(
666 "{input} is the eval's own Artifact; list other Artifacts in inputs."
667 )),
668 ));
669 }
670 let name = crate::config::ReferenceName::from(input);
671 references.insert(name.clone(), input.clone());
672 if deps.insert(input.clone()) {
673 relations.push(Relation {
674 source: input.clone(),
675 target: eval.target.clone(),
676 kind: RelationKind::Input {
677 eval_id: eval.id.clone(),
678 name,
679 },
680 });
681 }
682 }
683 if let Profile::Runtime { args, .. } = eval.declaration.profile() {
684 for (index, argument) in args.iter().enumerate() {
685 let Argument::Reference {
686 name: ref_name,
687 path,
688 ..
689 } = argument
690 else {
691 continue;
692 };
693 let source = reference_target(config, &eval.target, ref_name)
694 .map_err(|failure| error(&["profile", "args"], failure))?;
695 reference_path(config, source, path)
696 .map_err(|failure| error(&["profile", "args"], failure))?;
697 nested_path(everything, source, path)
698 .map_err(|failure| error(&["profile", "args"], failure))?;
699 if source != &eval.target {
700 deps.insert(source.clone());
701 relations.push(Relation {
702 source: source.clone(),
703 target: eval.target.clone(),
704 kind: RelationKind::Argument {
705 eval_id: eval.id.clone(),
706 index,
707 name: ref_name.clone(),
708 path: path.clone(),
709 },
710 });
711 }
712 }
713 }
714 Ok(EvalReferences {
715 references,
716 deps: deps.into_iter().collect(),
717 relations,
718 })
719}
720
721fn parts_acyclic(config: &RepoConfig) -> Result<(), ConfigError> {
723 for artifact in config.artifacts.values() {
724 if config.descendants(&artifact.name).contains(&&artifact.name) {
725 return Err(config.error_at(
726 &artifact.name,
727 &["parts"],
728 format!("{} is a part of itself through its parts.", artifact.name),
729 ));
730 }
731 }
732 Ok(())
733}
734
735#[cfg(test)]
736mod tests;