artifactize 0.10.0

The AI-native collaboration layer for one-of-a-kind teammates and their agents: split a project into Artifacts with their own evals, and reuse every review while it still holds.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! Mounts, aliases, artifact references, and canonical scoped paths.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use serde::Serialize;

use crate::config::{Artifact, ArtifactName, ConfigError, Eval, Fingerprint, Profile, RepoConfig};

mod human;
mod instruction;
pub(crate) use human::{
    builtin_args, human_arguments, resolve_human_argv, validate_human_argument,
};
pub use instruction::instruction_references;

pub use artifactize_tools::scope::{ArtifactId, ScopeError, ScopedPath, scoped_path};
pub(crate) use artifactize_tools::scope::{logical_path, open_child, open_scoped};

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Relation {
    /// Input Artifact.
    pub source: ArtifactName,
    /// Consumer Artifact.
    pub target: ArtifactName,
    #[serde(flatten)]
    pub kind: RelationKind,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum RelationKind {
    Child {
        path: crate::config::ChildPrefix,
    },
    Mount {
        alias: crate::config::MountAlias,
    },
    Dependency {
        #[serde(rename = "evalId")]
        eval_id: crate::config::EvalId,
        name: crate::config::ReferenceName,
    },
    Instruction {
        #[serde(rename = "evalId")]
        eval_id: crate::config::EvalId,
        name: crate::config::ReferenceName,
    },
    #[serde(rename = "argv")]
    Argument {
        #[serde(rename = "evalId")]
        eval_id: crate::config::EvalId,
        index: usize,
        name: crate::config::ReferenceName,
        path: String,
    },
}

#[derive(Debug)]
pub struct Scope<'a> {
    pub artifacts: BTreeMap<ArtifactName, &'a Artifact>,
}

impl Scope<'_> {
    /// Snapshot only access data; composition and eval dependencies are decided here.
    pub(crate) fn tool_scope(&self) -> artifactize_tools::scope::Scope {
        artifactize_tools::scope::Scope {
            artifacts: self
                .artifacts
                .iter()
                .map(|(id, artifact)| (tool_id(id), artifact.tool_scope()))
                .collect(),
        }
    }

    pub fn resolve_path(&self, artifact_id: &str, path: &str) -> Result<ScopedPath, ScopeError> {
        self.tool_scope()
            .resolve_path(&ArtifactId::new(artifact_id)?, path)
    }

    pub fn resolve_input(
        &self,
        root: &Path,
        artifact_id: &str,
        path: &str,
    ) -> Result<PathBuf, ScopeError> {
        self.tool_scope()
            .resolve_input(root, &ArtifactId::new(artifact_id)?, path)
    }
}

/// The tool-side ID of a configured Artifact. Configuration validates every Artifact name,
/// mount target and child, so a name that fails here is a bug in that validation.
pub(crate) fn tool_id(name: &ArtifactName) -> ArtifactId {
    ArtifactId::new(name.as_str()).expect("configuration validates Artifact names")
}

/// Revalidate file targets at every preparation/read boundary, without following links.
pub(crate) fn validate_file_target(root: &Path, artifact: &Artifact) -> Result<(), ScopeError> {
    if artifact.file_name().is_some() {
        artifact
            .path
            .to_str()
            .ok_or_else(|| ScopeError("Artifact paths must be UTF-8.".into()))?;
        let target = crate::platform::path_text(&artifact.path);
        let file = open_scoped(root, &target).map_err(|error| {
            ScopeError(format!(
                "File Artifact {} target {} is unavailable: {error}",
                artifact.name,
                crate::platform::path_text(&artifact.path)
            ))
        })?;
        if !file
            .metadata()
            .map_err(|error| ScopeError(error.to_string()))?
            .is_file()
        {
            return Err(ScopeError(format!(
                "File Artifact {} target {} must remain a regular file.",
                artifact.name,
                crate::platform::path_text(&artifact.path)
            )));
        }
    }
    Ok(())
}

fn reference_path(config: &RepoConfig, id: &str, path: &str) -> Result<(), ScopeError> {
    if config.artifacts[id].file_name().is_some() && !path.is_empty() {
        return Err(ScopeError(format!(
            "File Artifact {{{id}}} cannot have a /path suffix."
        )));
    }
    Ok(())
}

/// Composition grants access; a referenced Artifact's Eval instructions do not.
pub fn artifact_scope<'a>(config: &'a RepoConfig, roots: &[&str]) -> Result<Scope<'a>, ScopeError> {
    let mut artifacts = BTreeMap::new();
    let mut pending = roots.to_vec();
    while let Some(id) = pending.pop() {
        let (id, artifact) = config
            .artifacts
            .get_key_value(id)
            .ok_or_else(|| ScopeError(format!("Unknown Artifact: {id}")))?;
        if artifacts.insert(id.clone(), artifact).is_some() {
            continue;
        }
        pending.extend(artifact.children.values().map(ArtifactName::as_str));
        pending.extend(artifact.mounts.values().map(ArtifactName::as_str));
    }
    Ok(Scope { artifacts })
}

/// Validate scope-relative command paths before process lookup. Bare names and absolute
/// paths stay literal here; preflight and both launchers use the shared PATH/PATHEXT rule.
pub(crate) fn executable(
    root: &Path,
    scope: &Scope<'_>,
    owner: &str,
    command: &str,
) -> Result<std::ffi::OsString, String> {
    let artifact = scope.artifacts[owner];
    let cwd = scoped_path(root, artifact.folder()).map_err(|error| error.to_string())?;
    let program = if let Some(relative) = crate::platform::program::folder_relative(command) {
        let mounted = artifact
            .mounts
            .contains_key(relative.split('/').next().unwrap_or(""));
        let physical = if artifact.file_name().is_some() && !mounted {
            artifactize_tools::scope::logical_path(relative).map_err(|error| error.to_string())?;
            cwd.join(relative)
        } else {
            let resolved = scope
                .resolve_path(owner, relative)
                .map_err(|error| error.to_string())?;
            root.join(scope.artifacts[resolved.artifact_id.as_str()].folder())
                .join(resolved.path)
        };
        // Even an extensionless declaration must not hide a link behind PATHEXT.
        crate::platform::program::reject_link_ancestors(&physical)?;
        let mut failure = None;
        crate::platform::program::candidates(Path::new(relative))
            .into_iter()
            .find_map(|candidate| {
                // A suffix the lookup added is matched to the entry's actual spelling.
                let candidate = if candidate.as_path() != Path::new(relative) {
                    executable_spelling(root, scope, owner, &cwd, &candidate, mounted)?
                } else {
                    candidate
                };
                let resolved = if artifact.file_name().is_some() && !mounted {
                    scoped_path(&cwd, &candidate)
                } else {
                    scope.resolve_input(
                        root,
                        owner,
                        &artifactize_tools::scope::logical_from_native(&candidate)?,
                    )
                };
                match resolved {
                    Ok(program) if program.is_file() => Some(program),
                    Ok(_) => None,
                    Err(error) => {
                        failure.get_or_insert_with(|| error.to_string());
                        None
                    }
                }
            })
            .ok_or_else(|| {
                failure.unwrap_or_else(|| "Executable path is unavailable or outside scope.".into())
            })?
    } else {
        PathBuf::from(command)
    };
    Ok(program.into_os_string())
}

/// PATHEXT supplies a suffix, not a model-authored name: use its actual directory-entry
/// spelling before strict scoped validation. Parent components retain their input spelling.
fn executable_spelling(
    root: &Path,
    scope: &Scope<'_>,
    owner: &str,
    cwd: &Path,
    candidate: &Path,
    mounted: bool,
) -> Option<PathBuf> {
    let parent = candidate.parent().unwrap_or(Path::new(""));
    let directory = if scope.artifacts[owner].file_name().is_some() && !mounted {
        scoped_path(cwd, parent).ok()?
    } else {
        scope.resolve_input(root, owner, parent.to_str()?).ok()?
    };
    crate::platform::program::suffix_spelling(&directory, candidate)
}

pub fn eval_scope<'a>(config: &'a RepoConfig, eval: &Eval) -> Result<Scope<'a>, ScopeError> {
    let roots: Vec<_> = std::iter::once(eval.target.as_str())
        .chain(eval.deps.iter().map(ArtifactName::as_str))
        .collect();
    artifact_scope(config, &roots)
}

/// Admit an owner plus the explicit references in its argv, as an Eval's scope admits its deps.
pub fn argv_scope<'a>(
    config: &'a RepoConfig,
    owner: &str,
    args: &[Argument],
) -> Result<Scope<'a>, ScopeError> {
    let mut roots = vec![owner];
    for argument in args {
        if let Argument::Reference { name, .. } = argument {
            roots.push(reference_target(config, owner, name)?);
        }
    }
    artifact_scope(config, &roots)
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InstructionPart {
    Text(String),
    Artifact(ArtifactName),
}

/// Presentation tokens only: never expand content or mutate the authored payload.
/// Artifact tokens carry names already validated by configuration.
pub fn parse_artifact_instruction(
    source: &str,
    scope: &Scope<'_>,
    references: &BTreeMap<crate::config::ReferenceName, ArtifactName>,
) -> Vec<InstructionPart> {
    let mut parts = Vec::new();
    let mut start = 0;
    for reference in instruction::references(source) {
        let id = references
            .get(&reference.name)
            .map_or(reference.name.as_str(), ArtifactName::as_str);
        if !scope.artifacts.contains_key(id) {
            continue;
        }
        if start < reference.start {
            parts.push(InstructionPart::Text(source[start..reference.start].into()));
        }
        parts.push(InstructionPart::Artifact(scope.artifacts[id].name.clone()));
        start = reference.end;
    }
    if start < source.len() {
        parts.push(InstructionPart::Text(source[start..].into()));
    }
    parts
}

/// A declared argument, parsed once when its declaration loads: either a plain literal, or a
/// `{name}[/path]` / `--flag={name}[/path]` Artifact reference. Parsing here only checks shape
/// (a single well-formed reference, a valid path suffix); whether `name` names a real Artifact
/// is a separate, config-wide check ([`reference_target`]) run once every declaration is loaded.
/// [`std::fmt::Display`] reconstructs the exact original text, so round-tripping through the
/// saved `Vec<String>` forms (`StoredProfile`, Views) changes no byte and no reuse key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Argument {
    Literal(String),
    Reference {
        prefix: String,
        name: crate::config::ReferenceName,
        path: String,
    },
}

impl std::str::FromStr for Argument {
    type Err = ScopeError;
    fn from_str(argument: &str) -> Result<Self, Self::Err> {
        let references = instruction::references(argument);
        let Some(reference) = references.first() else {
            return Ok(Self::Literal(argument.to_owned()));
        };
        let prefix = &argument[..reference.start];
        let flag = prefix
            .strip_prefix("--")
            .and_then(|flag| flag.strip_suffix('='))
            .is_some_and(|flag| {
                !flag.is_empty()
                    && flag
                        .bytes()
                        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
            });
        if references.len() != 1 || (!prefix.is_empty() && !flag) {
            return Err(ScopeError(
                "Artifact arguments must be {name}[/path] or --flag={name}[/path].".into(),
            ));
        }
        let suffix = &argument[reference.end..];
        let path = if suffix.is_empty() {
            ""
        } else {
            suffix
                .strip_prefix('/')
                .filter(|path| !path.is_empty())
                .ok_or_else(|| {
                    ScopeError("Artifact argument suffix must be a nonempty /path.".into())
                })?
        };
        logical_path(path)?;
        Ok(Self::Reference {
            prefix: prefix.to_owned(),
            name: reference.name.clone(),
            path: path.to_owned(),
        })
    }
}

impl std::fmt::Display for Argument {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Literal(text) => f.write_str(text),
            Self::Reference { prefix, name, path } => {
                write!(f, "{prefix}{{{name}}}")?;
                if !path.is_empty() {
                    write!(f, "/{path}")?;
                }
                Ok(())
            }
        }
    }
}

impl TryFrom<String> for Argument {
    type Error = ScopeError;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        value.parse()
    }
}

impl From<Argument> for String {
    fn from(argument: Argument) -> Self {
        argument.to_string()
    }
}

impl Serialize for Argument {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> serde::Deserialize<'de> for Argument {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::Error;
        String::deserialize(deserializer)?
            .parse()
            .map_err(|failure: ScopeError| D::Error::custom(failure.0))
    }
}

/// For fixtures: a trusted literal string, as declarations and test tables already spell it.
impl From<&str> for Argument {
    fn from(value: &str) -> Self {
        value.parse().expect("a valid declared argument")
    }
}

/// Equal iff `other`, spelled as a declared argument, is the same literal or reference: not a
/// mere prefix/suffix match, and never panics on a malformed `other` (it is just unequal).
impl PartialEq<str> for Argument {
    fn eq(&self, other: &str) -> bool {
        other.parse::<Self>().is_ok_and(|parsed| *self == parsed)
    }
}
impl PartialEq<&str> for Argument {
    fn eq(&self, other: &&str) -> bool {
        self == *other
    }
}
impl PartialEq<Argument> for str {
    fn eq(&self, other: &Argument) -> bool {
        other == self
    }
}
impl PartialEq<Argument> for String {
    fn eq(&self, other: &Argument) -> bool {
        other == self.as_str()
    }
}
impl PartialEq<String> for Argument {
    fn eq(&self, other: &String) -> bool {
        self == other.as_str()
    }
}

fn reference_target<'a>(
    config: &'a RepoConfig,
    owner: &str,
    name: &str,
) -> Result<&'a ArtifactName, ScopeError> {
    let artifact = config
        .artifacts
        .get(owner)
        .ok_or_else(|| ScopeError(format!("Unknown Artifact: {owner}")))?;
    let target = artifact.mounts.get(name).map_or(name, ArtifactName::as_str);
    config
        .artifacts
        .get_key_value(target)
        .map(|(id, _)| id)
        .ok_or_else(|| {
            ScopeError(format!(
                "Unknown Artifact reference {{{name}}}. Escape literal braces with a backslash."
            ))
        })
}

/// Resolve `{name}[/path]` and `--flag={name}[/path]` operands to existing scoped inputs.
/// Other arguments, including escaped braces, stay literal. Never interpolate the command.
/// Call at execution preparation, after static config validation; it opens input metadata.
pub fn resolve_argv(
    config: &RepoConfig,
    scope: &Scope<'_>,
    owner: &str,
    args: &[Argument],
) -> Result<Vec<String>, ScopeError> {
    args.iter()
        .map(|argument| {
            let Argument::Reference { prefix, name, path } = argument else {
                return Ok(argument.to_string());
            };
            let id = reference_target(config, owner, name)?;
            reference_path(config, id, path)?;
            let resolved = scope.resolve_input(&config.root, id, path)?;
            resolved
                .to_str()
                .ok_or_else(|| ScopeError("Artifact paths must be UTF-8.".into()))?;
            let resolved = crate::platform::path_text(&resolved);
            Ok(format!("{prefix}{resolved}"))
        })
        .collect()
}

/// Static relationships only; scheduling and dependency closure belong to graph.
pub(crate) fn resolve_config(config: &mut RepoConfig) -> Result<(), ConfigError> {
    let mut relations = Vec::new();
    for (id, artifact) in &config.artifacts {
        let error = |keys: &[&str], message: String| {
            ConfigError::declaration(config.root.join(artifact.declaration_path()), keys, message)
        };
        for (name, tool) in &artifact.views.agent_tools {
            if let crate::config::AgentTool::Builtin(tool) = tool
                && let Some(args) = &tool.args
            {
                let scope = artifact_scope(config, &[id.as_str()]).map_err(|failure| {
                    error(&["views", "agent_tools", name, "args"], failure.to_string())
                })?;
                let owner = ArtifactId::new(id.as_str()).map_err(|failure| {
                    error(&["views", "agent_tools", name, "args"], failure.to_string())
                })?;
                artifactize_tools::builtin::validate_target(
                    tool.builtin,
                    args,
                    &config.root,
                    &scope.tool_scope(),
                    &owner,
                )
                .map_err(|failure| error(&["views", "agent_tools", name, "args"], failure))?;
            }
            if let crate::config::AgentTool::Command(tool) = tool
                && tool.protocol == crate::config::ToolProtocol::Json
            {
                for argument in &tool.args {
                    if let Argument::Reference {
                        name: ref_name,
                        path,
                        ..
                    } = argument
                    {
                        let target = reference_target(config, id, ref_name).map_err(|failure| {
                            error(
                                &["views", "agent_tools", name, "args"],
                                format!("Agent tool {name}: {failure}"),
                            )
                        })?;
                        reference_path(config, target, path).map_err(|failure| {
                            error(
                                &["views", "agent_tools", name, "args"],
                                format!("Agent tool {name}: {failure}"),
                            )
                        })?;
                    }
                }
            }
        }
        if let Some(Fingerprint::Script { args, .. }) = &artifact.fingerprint {
            for argument in args {
                if let Argument::Reference {
                    name: ref_name,
                    path,
                    ..
                } = argument
                {
                    let target = reference_target(config, id, ref_name).map_err(|failure| {
                        error(
                            &["fingerprint", "script", "args"],
                            format!("fingerprint.script: {failure}"),
                        )
                    })?;
                    reference_path(config, target, path).map_err(|failure| {
                        error(
                            &["fingerprint", "script", "args"],
                            format!("fingerprint.script: {failure}"),
                        )
                    })?;
                }
            }
        }
        for (path, source) in &artifact.children {
            relations.push(Relation {
                source: source.clone(),
                target: id.clone(),
                kind: RelationKind::Child { path: path.clone() },
            });
        }
        for (alias, source) in &artifact.mounts {
            if !config.artifacts.contains_key(source) {
                return Err(error(
                    &["mounts", alias],
                    format!("Unknown mount target {source} in {id}."),
                ));
            }
            if config.artifacts.contains_key(alias.as_str()) && alias.as_str() != source.as_str() {
                return Err(error(
                    &["mounts", alias],
                    format!("Ambiguous mount alias {alias} in {id}."),
                ));
            }
            if artifact.file_name().is_some() {
                if artifact.file_name() == Some(alias.as_str()) {
                    return Err(error(
                        &["mounts", alias],
                        format!("Mount {id}/{alias} conflicts with the target file."),
                    ));
                }
            } else {
                match crate::platform::entry_exists(
                    &config.root.join(artifact.folder()).join(alias.as_str()),
                ) {
                    Ok(true) => {
                        return Err(error(
                            &["mounts", alias],
                            format!("Mount {id}/{alias} conflicts with a physical entry."),
                        ));
                    }
                    Ok(false) => {}
                    Err(failure) => return Err(error(&["mounts", alias], failure.to_string())),
                }
            }
            relations.push(Relation {
                source: source.clone(),
                target: id.clone(),
                kind: RelationKind::Mount {
                    alias: alias.clone(),
                },
            });
        }
    }
    for (id, artifact) in &config.artifacts {
        let Some(Fingerprint::Artifactsum { files: inputs, .. }) = &artifact.fingerprint else {
            continue;
        };
        let error = |message: String| {
            ConfigError::declaration(
                config.root.join(artifact.declaration_path()),
                &["fingerprint", "files"],
                format!("fingerprint.files: {message}"),
            )
        };
        let scope = artifact_scope(config, &[id]).map_err(|failure| error(failure.0))?;
        for input in inputs.iter().filter(|input| *input != ".") {
            if input.ends_with(".artf")
                && !crate::platform::path_kind(&config.root.join(artifact.folder()).join(input))
                    .is_ok_and(|kind| kind == crate::platform::FileKind::Directory)
            {
                return Err(error(
                    "Artifact declarations (*.artf) cannot be explicit artifactsum inputs; declarations are excluded from artifactsum."
                        .into(),
                ));
            }
            let location = scope
                .resolve_path(id, input)
                .map_err(|failure| error(failure.0))?;
            if location.artifact_id.as_str() != id.as_str() {
                return Err(error(format!(
                    "{input} belongs to Artifact {}; dependencies come from children, mounts and references.",
                    location.artifact_id
                )));
            }
        }
    }
    let mut resolved = Vec::new();
    for eval in &config.evals {
        let error = |field: &[&str], failure: ScopeError| {
            let mut keys = vec!["evals", eval.declaration.id.as_ref()];
            keys.extend_from_slice(field);
            ConfigError::declaration(
                config
                    .root
                    .join(config.artifacts[&eval.target].declaration_path()),
                &keys,
                format!("Eval {}: {failure}", eval.id),
            )
        };
        let mut references = BTreeMap::new();
        let mut deps = BTreeSet::new();
        if let Profile::Dependency { depends_on } = eval.declaration.profile() {
            for name in depends_on {
                let source = reference_target(config, &eval.target, name)
                    .map_err(|failure| error(&["profile", "depends_on"], failure))?;
                if source == &eval.target {
                    return Err(error(
                        &["profile", "depends_on"],
                        ScopeError("Dependency Evals cannot depend on their own Artifact.".into()),
                    ));
                }
                if !deps.insert(source.clone()) {
                    return Err(error(
                        &["profile", "depends_on"],
                        ScopeError(
                            "Dependency profile depends_on must resolve to unique Artifacts."
                                .into(),
                        ),
                    ));
                }
                relations.push(Relation {
                    source: source.clone(),
                    target: eval.target.clone(),
                    kind: RelationKind::Dependency {
                        eval_id: eval.id.clone(),
                        name: name.into(),
                    },
                });
            }
        }
        let instruction = eval
            .declaration
            .payload()
            .map_or("", |payload| payload.instruction.as_str());
        for reference in instruction::references(instruction) {
            let name = reference.name;
            let source = reference_target(config, &eval.target, &name)
                .map_err(|failure| error(&["payload", "instruction"], failure))?;
            if instruction[reference.end..].starts_with('/') {
                reference_path(config, source, "/")
                    .map_err(|failure| error(&["payload", "instruction"], failure))?;
            }
            if references.insert(name.clone(), source.clone()).is_some() {
                continue;
            }
            if source != &eval.target {
                deps.insert(source.clone());
                relations.push(Relation {
                    source: source.clone(),
                    target: eval.target.clone(),
                    kind: RelationKind::Instruction {
                        eval_id: eval.id.clone(),
                        name,
                    },
                });
            }
        }
        if let Profile::Runtime { args, .. } = eval.declaration.profile() {
            for (index, argument) in args.iter().enumerate() {
                let Argument::Reference {
                    name: ref_name,
                    path,
                    ..
                } = argument
                else {
                    continue;
                };
                let source = reference_target(config, &eval.target, ref_name)
                    .map_err(|failure| error(&["profile", "args"], failure))?;
                reference_path(config, source, path)
                    .map_err(|failure| error(&["profile", "args"], failure))?;
                if source != &eval.target {
                    deps.insert(source.clone());
                    relations.push(Relation {
                        source: source.clone(),
                        target: eval.target.clone(),
                        kind: RelationKind::Argument {
                            eval_id: eval.id.clone(),
                            index,
                            name: ref_name.clone(),
                            path: path.clone(),
                        },
                    });
                }
            }
        }
        resolved.push((references, deps.into_iter().collect()));
    }
    for (eval, (references, deps)) in config.evals.iter_mut().zip(resolved) {
        eval.references = references;
        eval.deps = deps;
    }
    config.relations = relations;
    human::validate_references(config)?;
    crate::graph::Graph::new(config).map_err(|error| ConfigError::new(&config.root, error))?;
    Ok(())
}

#[cfg(test)]
mod tests;