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 relative = crate::platform::program::folder_relative(command)?;
227 let program = if let Some(relative) = relative.as_deref() {
228 let physical = if artifact.file_name().is_some()
229 || artifact.kind() == crate::config::ArtifactKind::Live
230 {
231 artifactize_tools::scope::logical_path(relative).map_err(|error| error.to_string())?;
232 cwd.join(relative)
233 } else {
234 let resolved = scope
235 .resolve_path(owner, relative)
236 .map_err(|error| error.to_string())?;
237 root.join(scope.artifacts[resolved.artifact_id.as_str()].folder())
238 .join(resolved.path)
239 };
240 crate::platform::program::reject_link_ancestors(&physical)?;
242 let resolve = |candidate: &Path| {
243 if artifact.file_name().is_some()
244 || artifact.kind() == crate::config::ArtifactKind::Live
245 {
246 scoped_path(&cwd, candidate).map_err(|error| error.to_string())
247 } else {
248 let logical = artifactize_tools::scope::logical_from_native(candidate)
249 .ok_or_else(|| "Executable path is not portable text.".to_owned())?;
250 scope
251 .resolve_input(root, owner, &logical)
252 .map_err(|error| error.to_string())
253 }
254 };
255 crate::platform::program::resolve_scoped(Path::new(relative), resolve)?
256 } else {
257 PathBuf::from(command)
258 };
259 Ok(program.into_os_string())
260}
261
262pub fn eval_scope<'a>(config: &'a RepoConfig, eval: &Eval) -> Result<Scope<'a>, ScopeError> {
263 let roots: Vec<_> = std::iter::once(&eval.target)
264 .chain(eval.deps.iter())
265 .collect();
266 artifact_scope(config, &roots)
267}
268
269pub fn argv_scope<'a>(
271 config: &'a RepoConfig,
272 owner: &ArtifactName,
273 args: &[Argument],
274) -> Result<Scope<'a>, ScopeError> {
275 let mut roots = vec![owner];
276 for argument in args {
277 if let Argument::Reference { name, .. } = argument {
278 roots.push(reference_target(config, owner, name)?);
279 }
280 }
281 artifact_scope(config, &roots)
282}
283
284#[derive(Debug, Clone, PartialEq, Eq)]
285pub enum InstructionPart {
286 Text(String),
287 Artifact(ArtifactName),
288}
289
290#[derive(Debug)]
292pub(crate) struct InstructionReference {
293 span: std::ops::Range<usize>,
294 artifact: ArtifactName,
295}
296
297pub(crate) fn artifact_instruction(eval: &Eval) -> Vec<InstructionPart> {
299 let Some(payload) = eval.declaration.payload() else {
300 return Vec::new();
301 };
302 let source = &payload.instruction;
303 let mut parts = Vec::new();
304 let mut start = 0;
305 for reference in &eval.instruction_references {
306 if start < reference.span.start {
307 parts.push(InstructionPart::Text(
308 source[start..reference.span.start].into(),
309 ));
310 }
311 parts.push(InstructionPart::Artifact(reference.artifact.clone()));
312 start = reference.span.end;
313 }
314 if start < source.len() {
315 parts.push(InstructionPart::Text(source[start..].into()));
316 }
317 parts
318}
319
320fn reference_target<'a>(
321 config: &'a RepoConfig,
322 owner: &ArtifactName,
323 name: &crate::config::ReferenceName,
324) -> Result<&'a ArtifactName, ScopeError> {
325 if !config.artifacts.contains_key(owner) {
326 return Err(ScopeError(format!("Unknown Artifact: {owner}")));
327 }
328 let target = config.artifacts.get_key_value(name.as_str());
329 target.map(|(id, _)| id).ok_or_else(|| {
330 ScopeError(format!(
331 "Unknown Artifact reference {{{name}}}. Escape literal braces with a backslash."
332 ))
333 })
334}
335
336#[derive(Debug, Clone, PartialEq, Eq)]
339pub(crate) enum ResolvedArgument {
340 Literal(String),
341 Path { prefix: String, path: PathBuf },
342}
343
344impl ResolvedArgument {
345 pub(crate) fn native(&self) -> String {
346 match self {
347 Self::Literal(text) => text.clone(),
348 Self::Path { prefix, path } => {
349 format!("{prefix}{}", path.to_str().expect("validated UTF-8 path"))
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 return Ok(ResolvedArgument::Literal(argument.to_string()));
384 };
385 let id = reference_target(config, owner, name)?;
386 reference_path(config, id, path)?;
387 argument_value(config, scope, id, path, prefix)
388 })
389 .collect()
390}
391
392pub(crate) fn argument_value(
394 config: &RepoConfig,
395 scope: &Scope<'_>,
396 id: &ArtifactName,
397 path: &str,
398 prefix: &str,
399) -> Result<ResolvedArgument, ScopeError> {
400 let artifact = scope
401 .artifacts
402 .get(id)
403 .ok_or_else(|| ScopeError(format!("Artifact is outside this review: {id}")))?;
404 if let Some(uri) = artifact.path.uri() {
405 return Ok(ResolvedArgument::Literal(if path.is_empty() {
406 format!("{prefix}{uri}")
407 } else {
408 format!("{prefix}{uri}/{path}")
409 }));
410 }
411 let resolved = scope.resolve_input(&config.root, id, path)?;
412 if resolved.to_str().is_none() {
413 return Err(ScopeError("Artifact paths must be UTF-8.".into()));
414 }
415 Ok(ResolvedArgument::Path {
416 prefix: prefix.into(),
417 path: resolved,
418 })
419}
420
421pub(crate) fn validate_selections(config: &RepoConfig) -> Result<(), ConfigError> {
423 for (id, artifact) in &config.artifacts {
424 let scope = artifact_scope(config, &[id]).expect("a configured Artifact");
425 for selected in artifact.select() {
426 scope
427 .resolve_input(&config.root, id, selected)
428 .map_err(|failure| {
429 ConfigError::declaration(
430 config.root.join(artifact.declaration_path()),
431 &["select"],
432 format!("select: {selected}: {failure}"),
433 )
434 })?;
435 }
436 }
437 Ok(())
438}
439
440pub(crate) fn resolve_config(config: &mut RepoConfig) -> Result<(), ConfigError> {
442 let mut relations = Vec::new();
443 for (id, artifact) in &config.artifacts {
444 let error = |keys: &[&str], message: String| {
445 ConfigError::declaration(config.root.join(artifact.declaration_path()), keys, message)
446 };
447 for (name, tool) in &artifact.views.agent_tools {
448 if let crate::config::AgentTool::Builtin(tool) = tool
449 && let Some(args) = &tool.args
450 {
451 let scope = artifact_scope(config, &[id]).map_err(|failure| {
452 error(&["views", "agent_tools", name, "args"], failure.to_string())
453 })?;
454 let owner = ArtifactId::new(id.as_str()).map_err(|failure| {
455 error(&["views", "agent_tools", name, "args"], failure.to_string())
456 })?;
457 artifactize_tools::builtin::validate_target(
458 tool.builtin,
459 args,
460 &config.root,
461 &scope.tool_scope(),
462 &owner,
463 )
464 .map_err(|failure| error(&["views", "agent_tools", name, "args"], failure))?;
465 }
466 if let crate::config::AgentTool::Command(tool) = tool
467 && tool.protocol == crate::config::ToolProtocol::Json
468 {
469 for argument in &tool.args {
470 if let Argument::Reference {
471 name: ref_name,
472 path,
473 ..
474 } = argument
475 {
476 let target = reference_target(config, id, ref_name).map_err(|failure| {
477 error(
478 &["views", "agent_tools", name, "args"],
479 format!("Agent tool {name}: {failure}"),
480 )
481 })?;
482 reference_path(config, target, path).map_err(|failure| {
483 error(
484 &["views", "agent_tools", name, "args"],
485 format!("Agent tool {name}: {failure}"),
486 )
487 })?;
488 }
489 }
490 }
491 }
492 if let Some(Fingerprint::Script { args, .. }) = &artifact.fingerprint {
493 for argument in args {
494 if let Argument::Reference {
495 name: ref_name,
496 path,
497 ..
498 } = argument
499 {
500 let target = reference_target(config, id, ref_name).map_err(|failure| {
501 error(
502 &["fingerprint", "script", "args"],
503 format!("fingerprint.script: {failure}"),
504 )
505 })?;
506 reference_path(config, target, path).map_err(|failure| {
507 error(
508 &["fingerprint", "script", "args"],
509 format!("fingerprint.script: {failure}"),
510 )
511 })?;
512 }
513 }
514 }
515 }
516 for (id, artifact) in &config.artifacts {
517 let Some(Fingerprint::Artifactsum { files: inputs, .. }) = &artifact.fingerprint else {
518 continue;
519 };
520 let error = |message: String| {
521 ConfigError::declaration(
522 config.root.join(artifact.declaration_path()),
523 &["fingerprint", "files"],
524 format!("fingerprint.files: {message}"),
525 )
526 };
527 if artifact.covering_part.is_some() {
529 continue;
530 }
531 let scope = artifact_scope(config, &[id]).map_err(|failure| error(failure.0))?;
532 for input in inputs.iter().filter(|input| *input != ".") {
533 let location = scope
534 .resolve_path(id, input)
535 .map_err(|failure| error(failure.0))?;
536 if location.artifact_id.as_str() != id.as_str() {
537 return Err(error(format!(
538 "{input} belongs to Artifact {}; a fingerprint covers only its own Artifact's files.",
539 location.artifact_id
540 )));
541 }
542 }
543 }
544 let everything = everything(config);
545 let mut resolved = Vec::new();
546 for eval in &config.evals {
547 let mut found = eval_references(config, &everything, eval)?;
548 relations.append(&mut found.relations);
549 resolved.push(found);
550 }
551 for (eval, found) in config.evals.iter_mut().zip(resolved) {
552 eval.references = found.references;
553 eval.instruction_references = found.instruction_references;
554 eval.deps = found.deps;
555 }
556 for artifact in config.artifacts.values() {
557 for part in &artifact.parts {
558 let error = |message: String| {
559 ConfigError::declaration(
560 config.root.join(artifact.declaration_path()),
561 &["parts"],
562 message,
563 )
564 };
565 match config.artifacts.get(part) {
566 None => return Err(error(format!("Unknown Artifact {part}."))),
567 Some(part) if part.kind() == crate::config::ArtifactKind::Graph => {
568 return Err(error(format!(
569 "The graph Artifact {} is a part of nothing.",
570 part.name
571 )));
572 }
573 Some(_) => relations.push(Relation {
574 source: part.clone(),
575 target: artifact.name.clone(),
576 kind: RelationKind::Part,
577 }),
578 }
579 }
580 }
581 parts_acyclic(config)?;
582 config.relations = relations;
583 human::validate_references(config)?;
584 crate::graph::Graph::new(config).map_err(|error| ConfigError::new(&config.root, error))?;
585 Ok(())
586}
587
588fn everything(config: &RepoConfig) -> artifactize_tools::scope::Scope {
590 Scope {
591 artifacts: config
592 .artifacts
593 .iter()
594 .map(|(id, artifact)| (id.clone(), artifact))
595 .collect(),
596 }
597 .tool_scope()
598}
599
600struct EvalReferences {
602 instruction_references: Vec<InstructionReference>,
603 references: BTreeMap<crate::config::ReferenceName, ArtifactName>,
604 deps: Vec<ArtifactName>,
606 relations: Vec<Relation>,
608}
609
610fn eval_references(
611 config: &RepoConfig,
612 everything: &artifactize_tools::scope::Scope,
613 eval: &Eval,
614) -> Result<EvalReferences, ConfigError> {
615 let mut relations = Vec::new();
616 let error = |field: &[&str], failure: ScopeError| {
617 let mut keys = vec!["evals", eval.declaration.id.as_ref()];
618 keys.extend_from_slice(field);
619 ConfigError::declaration(
620 config
621 .root
622 .join(config.artifacts[&eval.target].declaration_path()),
623 &keys,
624 format!("Eval {}: {failure}", eval.id),
625 )
626 };
627 let mut references = BTreeMap::new();
628 let mut instruction_references = Vec::new();
629 let mut deps = BTreeSet::new();
630 let instruction = eval
631 .declaration
632 .payload()
633 .map_or("", |payload| payload.instruction.as_str());
634 for reference in instruction::references(instruction) {
635 let name = reference.name;
636 let source = reference_target(config, &eval.target, &name)
637 .map_err(|failure| error(&["payload", "instruction"], failure))?;
638 if instruction[reference.end..].starts_with('/') {
639 reference_path(config, source, "/")
640 .map_err(|failure| error(&["payload", "instruction"], failure))?;
641 }
642 instruction_references.push(InstructionReference {
643 span: reference.start..reference.end,
644 artifact: source.clone(),
645 });
646 if references.insert(name.clone(), source.clone()).is_some() {
647 continue;
648 }
649 if source != &eval.target {
650 deps.insert(source.clone());
651 relations.push(Relation {
652 source: source.clone(),
653 target: eval.target.clone(),
654 kind: RelationKind::Instruction {
655 eval_id: eval.id.clone(),
656 name,
657 },
658 });
659 }
660 }
661 if let Profile::Runtime { args, .. } = eval.declaration.profile() {
662 for (index, argument) in args.iter().enumerate() {
663 let Argument::Reference {
664 name: ref_name,
665 path,
666 ..
667 } = argument
668 else {
669 continue;
670 };
671 let source = reference_target(config, &eval.target, ref_name)
672 .map_err(|failure| error(&["profile", "args"], failure))?;
673 reference_path(config, source, path)
674 .map_err(|failure| error(&["profile", "args"], failure))?;
675 nested_path(everything, source, path)
676 .map_err(|failure| error(&["profile", "args"], failure))?;
677 if source != &eval.target {
678 deps.insert(source.clone());
679 relations.push(Relation {
680 source: source.clone(),
681 target: eval.target.clone(),
682 kind: RelationKind::Argument {
683 eval_id: eval.id.clone(),
684 index,
685 name: ref_name.clone(),
686 path: path.clone(),
687 },
688 });
689 }
690 }
691 }
692 Ok(EvalReferences {
693 instruction_references,
694 references,
695 deps: deps.into_iter().collect(),
696 relations,
697 })
698}
699
700fn parts_acyclic(config: &RepoConfig) -> Result<(), ConfigError> {
702 for artifact in config.artifacts.values() {
703 if config.descendants(&artifact.name).contains(&&artifact.name) {
704 return Err(ConfigError::declaration(
705 config.root.join(artifact.declaration_path()),
706 &["parts"],
707 format!("{} is a part of itself through its parts.", artifact.name),
708 ));
709 }
710 }
711 Ok(())
712}
713
714#[cfg(test)]
715mod tests;