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