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