artifactize 0.9.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
748
//! Mounts, aliases, artifact references, and canonical scoped paths.

use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File};
use std::io;
use std::path::{Component, Path, PathBuf};

use serde::Serialize;
use thiserror::Error;

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

mod human;
mod instruction;
pub(crate) use human::{resolve_human_argv, validate_human_args};
pub use instruction::instruction_references;

/// Bound logical tool paths in UTF-16 units, matching JSON Schema string limits
/// across supported clients without tying scoped paths to an OS-specific PATH_MAX.
pub(crate) const MAX_PATH_UNITS: usize = 4096;

#[derive(Debug, Error)]
#[error("{0}")]
pub struct ScopeError(pub String);

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

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

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopedPath {
    pub artifact_id: String,
    pub path: String,
}

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

impl Scope<'_> {
    /// Pure logical resolution. Each mount or child hop consumes path components.
    pub fn resolve_path(&self, artifact_id: &str, path: &str) -> Result<ScopedPath, ScopeError> {
        logical_path(path)?;
        let mut current = artifact_id;
        let mut remaining = path;
        loop {
            let artifact = self
                .artifacts
                .get(current)
                .ok_or_else(|| ScopeError(format!("Artifact is outside this review: {current}")))?;
            if remaining.is_empty() {
                break;
            }
            let (first, rest) = remaining.split_once('/').unwrap_or((remaining, ""));
            if let Some(target) = artifact.mounts.get(first) {
                current = target;
                remaining = rest;
                continue;
            }
            if let Some((prefix, target)) = artifact.children.iter().find(|(prefix, _)| {
                remaining == prefix.as_str()
                    || remaining
                        .strip_prefix(prefix.as_str())
                        .is_some_and(|rest| rest.starts_with('/'))
            }) {
                current = target;
                remaining = remaining[prefix.len()..].strip_prefix('/').unwrap_or("");
                continue;
            }
            break;
        }
        let artifact = self.artifacts[current];
        file_input(artifact, remaining)?;
        Ok(ScopedPath {
            artifact_id: current.to_owned(),
            path: remaining.to_owned(),
        })
    }

    /// Existing file or directory, without traversing links even inside the owner.
    pub fn resolve_input(
        &self,
        root: &Path,
        artifact_id: &str,
        path: &str,
    ) -> Result<PathBuf, ScopeError> {
        let location = self.resolve_path(artifact_id, path)?;
        let artifact = self.artifacts[location.artifact_id.as_str()];
        let owner = scoped_path(root, artifact.folder())?;
        let path = if location.path.is_empty() {
            artifact.file_name().unwrap_or("")
        } else {
            &location.path
        };
        let resolved = scoped_path(&owner, Path::new(path))?;
        if artifact.file_name().is_some() && !resolved.is_file() {
            return Err(ScopeError(
                "File Artifact target must remain a regular file.".into(),
            ));
        }
        Ok(resolved)
    }
}

/// 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() {
        let target = artifact
            .path
            .to_str()
            .ok_or_else(|| ScopeError("Artifact paths must be UTF-8.".into()))?;
        let file = open_scoped(root, target).map_err(|error| {
            ScopeError(format!(
                "File Artifact {} target {} is unavailable: {error}",
                artifact.name,
                artifact.path.display()
            ))
        })?;
        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,
                artifact.path.display()
            )));
        }
    }
    Ok(())
}

/// Why a scoped open failed. A missing entry stays distinct, so a caller that knows the
/// logical path the user asked for can name it.
#[derive(Debug, Error)]
pub(crate) enum OpenError {
    #[error("No such file or directory.")]
    NotFound,
    #[error(transparent)]
    Refused(#[from] ScopeError),
}

/// Open each component relative to its pinned parent, so replacement cannot redirect a read
/// through a link.
pub(crate) fn open_input(root: &Path, artifact: &Artifact, path: &str) -> Result<File, OpenError> {
    if !root.is_absolute() || artifact.path.is_absolute() {
        return Err(
            ScopeError("Artifact roots must be absolute and owner paths relative.".into()).into(),
        );
    }
    file_input(artifact, path)?;
    let file = open_scoped(&root.join(artifact.folder()), path)?;
    if artifact.file_name().is_some()
        && !path.is_empty()
        && !file
            .metadata()
            .map_err(|e| ScopeError(e.to_string()))?
            .is_file()
    {
        return Err(ScopeError("File Artifact target must remain a regular file.".into()).into());
    }
    Ok(file)
}

/// A file Artifact exposes a virtual root containing only its target and mounts.
fn file_input(artifact: &Artifact, path: &str) -> Result<(), ScopeError> {
    if let Some(target) = artifact.file_name()
        && !path.is_empty()
        && path != target
    {
        return Err(ScopeError(format!(
            "File Artifact {} exposes only its target {target} and mounts.",
            artifact.name
        )));
    }
    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(())
}

/// Open a relative path below an absolute root without following any symlink components.
pub(crate) fn open_scoped(root: &Path, path: &str) -> Result<File, OpenError> {
    logical_path(path)?;
    if !root.is_absolute() {
        return Err(ScopeError("Scoped roots must be absolute.".into()).into());
    }
    let target = root.join(path);
    // `/`, or on Windows the volume or share root such as `C:\`.
    let filesystem_root = target.ancestors().last().unwrap_or(&target);
    let mut directory =
        platform::open_directory(filesystem_root).map_err(|e| ScopeError(e.to_string()))?;
    for component in target.components() {
        directory = match component {
            Component::Prefix(_) | Component::RootDir => continue,
            Component::Normal(name) => open_child(&directory, name)?,
            _ => {
                return Err(ScopeError(
                    "Artifact path must not traverse parent directories.".into(),
                )
                .into());
            }
        };
    }
    Ok(directory)
}

/// Open one entry of a pinned directory without following a symlink.
pub(crate) fn open_child(directory: &File, name: &std::ffi::OsStr) -> Result<File, OpenError> {
    let name = platform::EntryName::new(name)
        .ok_or_else(|| ScopeError("Invalid Artifact path.".into()))?;
    let file = platform::open_entry(directory, &name).map_err(|error| {
        if error.kind() == io::ErrorKind::NotFound {
            OpenError::NotFound
        } else if platform::is_link_refusal(&error) {
            ScopeError("Cannot open Artifact input without symlink traversal.".into()).into()
        } else {
            ScopeError(format!("Cannot open Artifact input: {error}")).into()
        }
    })?;
    let metadata = file.metadata().map_err(|e| ScopeError(e.to_string()))?;
    if !metadata.is_file() && !metadata.is_dir() {
        return Err(
            ScopeError("Artifact input must be a regular file or directory.".into()).into(),
        );
    }
    Ok(file)
}

/// 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.as_str(), artifact).is_some() {
            continue;
        }
        pending.extend(artifact.children.values().map(String::as_str));
        pending.extend(artifact.mounts.values().map(String::as_str));
    }
    Ok(Scope { artifacts })
}

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(String::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: &[String],
) -> Result<Scope<'a>, ScopeError> {
    let mut roots = vec![owner];
    for argument in args {
        if let Some(reference) = argument_reference(argument)? {
            roots.push(reference_target(config, owner, reference.name)?);
        }
    }
    artifact_scope(config, &roots)
}

fn logical_path(path: &str) -> Result<(), ScopeError> {
    if path.encode_utf16().count() > MAX_PATH_UNITS
        || path
            .bytes()
            .any(|byte| byte.is_ascii_control() || matches!(byte, b'\\' | b':'))
        || (!path.is_empty()
            && path
                .split('/')
                .any(|part| part.is_empty() || part == "." || part == ".."))
    {
        return Err(ScopeError(
            "Artifact path must be a safe relative logical path.".into(),
        ));
    }
    Ok(())
}

/// Resolve a physical input below a canonical root. No component may be a symlink.
pub fn scoped_path(root: &Path, path: &Path) -> Result<PathBuf, ScopeError> {
    let path = path
        .to_str()
        .ok_or_else(|| ScopeError("Artifact paths must be UTF-8.".into()))?;
    if path.contains(['\0', '\\'])
        || Path::new(path).is_absolute()
        || path.split('/').any(|part| part == "." || part == "..")
    {
        return Err(ScopeError(
            "Artifact path must be relative to its declared root.".into(),
        ));
    }
    let mut target = root.to_owned();
    for component in path.split('/').filter(|part| !part.is_empty()) {
        target.push(component);
        let metadata = fs::symlink_metadata(&target)
            .map_err(|error| ScopeError(format!("{}: {error}", target.display())))?;
        if metadata.is_symlink() {
            return Err(ScopeError("Artifact symlinks are not supported.".into()));
        }
    }
    let actual = platform::canonicalize(&target)
        .map_err(|error| ScopeError(format!("{}: {error}", target.display())))?;
    if !actual.starts_with(root) {
        return Err(ScopeError(
            "Artifact path escapes its declared root.".into(),
        ));
    }
    let metadata = fs::metadata(&actual)
        .map_err(|error| ScopeError(format!("{}: {error}", actual.display())))?;
    if !metadata.is_file() && !metadata.is_dir() {
        return Err(ScopeError(
            "Artifact input must be a file or directory.".into(),
        ));
    }
    Ok(actual)
}

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

/// Presentation tokens only: never expand content or mutate the authored payload.
pub fn parse_artifact_instruction(
    source: &str,
    scope: &Scope<'_>,
    references: &BTreeMap<String, String>,
) -> 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, String::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(id.into()));
        start = reference.end;
    }
    if start < source.len() {
        parts.push(InstructionPart::Text(source[start..].into()));
    }
    parts
}

struct ArgumentReference<'a> {
    name: &'a str,
    prefix: &'a str,
    path: &'a str,
}

fn argument_reference(argument: &str) -> Result<Option<ArgumentReference<'_>>, ScopeError> {
    let references = instruction::references(argument);
    let Some(reference) = references.first() else {
        return Ok(None);
    };
    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(Some(ArgumentReference {
        name: reference.name,
        prefix,
        path,
    }))
}

fn reference_target<'a>(
    config: &'a RepoConfig,
    owner: &str,
    name: &str,
) -> Result<&'a str, ScopeError> {
    let artifact = config
        .artifacts
        .get(owner)
        .ok_or_else(|| ScopeError(format!("Unknown Artifact: {owner}")))?;
    let target = artifact.mounts.get(name).map_or(name, String::as_str);
    config
        .artifacts
        .get_key_value(target)
        .map(|(id, _)| id.as_str())
        .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: &[String],
) -> Result<Vec<String>, ScopeError> {
    args.iter()
        .map(|argument| {
            let Some(reference) = argument_reference(argument)? else {
                return Ok(argument.clone());
            };
            let id = reference_target(config, owner, reference.name)?;
            reference_path(config, id, reference.path)?;
            let path = scope.resolve_input(&config.root, id, reference.path)?;
            let path = path
                .to_str()
                .ok_or_else(|| ScopeError("Artifact paths must be UTF-8.".into()))?;
            Ok(format!("{}{path}", reference.prefix))
        })
        .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::Command(tool) = tool
                && tool.protocol == crate::config::ToolProtocol::Json
            {
                for argument in &tool.args {
                    if let Some(reference) = argument_reference(argument).map_err(|failure| {
                        error(
                            &["views", "agent_tools", name, "args"],
                            format!("Agent tool {name}: {failure}"),
                        )
                    })? {
                        let target =
                            reference_target(config, id, reference.name).map_err(|failure| {
                                error(
                                    &["views", "agent_tools", name, "args"],
                                    format!("Agent tool {name}: {failure}"),
                                )
                            })?;
                        reference_path(config, target, reference.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 Some(reference) = argument_reference(argument).map_err(|failure| {
                    error(
                        &["fingerprint", "script", "args"],
                        format!("fingerprint.script: {failure}"),
                    )
                })? {
                    let target =
                        reference_target(config, id, reference.name).map_err(|failure| {
                            error(
                                &["fingerprint", "script", "args"],
                                format!("fingerprint.script: {failure}"),
                            )
                        })?;
                    reference_path(config, target, reference.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) && alias != source {
                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 fs::symlink_metadata(config.root.join(artifact.folder()).join(alias)) {
                    Ok(_) => {
                        return Err(error(
                            &["mounts", alias],
                            format!("Mount {id}/{alias} conflicts with a physical entry."),
                        ));
                    }
                    Err(failure) if failure.kind() == std::io::ErrorKind::NotFound => {}
                    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")
                && !fs::symlink_metadata(config.root.join(artifact.folder()).join(input))
                    .is_ok_and(|metadata| metadata.is_dir())
            {
                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 != *id {
                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];
            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.to_owned()) {
                    return Err(error(
                        &["profile", "depends_on"],
                        ScopeError(
                            "Dependency profile depends_on must resolve to unique Artifacts."
                                .into(),
                        ),
                    ));
                }
                relations.push(Relation {
                    source: source.to_owned(),
                    target: eval.target.clone(),
                    kind: RelationKind::Dependency {
                        eval_id: eval.id.clone(),
                        name: name.clone(),
                    },
                });
            }
        }
        let instruction = eval
            .declaration
            .payload
            .as_ref()
            .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.to_owned(), source.to_owned())
                .is_some()
            {
                continue;
            }
            if source != eval.target {
                deps.insert(source.to_owned());
                relations.push(Relation {
                    source: source.to_owned(),
                    target: eval.target.clone(),
                    kind: RelationKind::Instruction {
                        eval_id: eval.id.clone(),
                        name: name.to_owned(),
                    },
                });
            }
        }
        if let Profile::Runtime { args, .. } = &eval.declaration.profile {
            for (index, argument) in args.iter().enumerate() {
                let Some(reference) = argument_reference(argument)
                    .map_err(|failure| error(&["profile", "args"], failure))?
                else {
                    continue;
                };
                let source = reference_target(config, &eval.target, reference.name)
                    .map_err(|failure| error(&["profile", "args"], failure))?;
                reference_path(config, source, reference.path)
                    .map_err(|failure| error(&["profile", "args"], failure))?;
                if source != eval.target {
                    deps.insert(source.to_owned());
                    relations.push(Relation {
                        source: source.to_owned(),
                        target: eval.target.clone(),
                        kind: RelationKind::Argument {
                            eval_id: eval.id.clone(),
                            index,
                            name: reference.name.to_owned(),
                            path: reference.path.to_owned(),
                        },
                    });
                }
            }
        }
        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;