Skip to main content

artifactize_core/
graph_structure.rs

1//! Name-based project structure shared by the graph fingerprint and both graph tools.
2//! Paths locate declarations, never identify graph entities. Extraction is flat, so Artifact
3//! cycles need no recursive traversal and the graph Artifact includes itself without recursion.
4use std::{collections::BTreeMap, fmt::Write, path::Path};
5
6use serde::Serialize;
7use serde_json::{Map, Value};
8use sha2::{Digest, Sha256};
9
10use crate::{
11    config::{ArtifactKind, EvalPayload, Fingerprint, Profile, RepoConfig},
12    scope::{Argument, RelationKind},
13    types::{ArtifactName, EvalId},
14};
15
16/// Domain separation: changing the extraction contract invalidates old graph fingerprints.
17const FORMAT: &[u8] = b"artifactize-graph-v1\n";
18
19#[derive(Debug, Serialize)]
20#[serde(rename_all = "camelCase")]
21pub struct Structure {
22    pub artifacts: BTreeMap<ArtifactName, Artifact>,
23    pub evals: BTreeMap<EvalId, Eval>,
24    pub relations: Vec<Relation>,
25}
26
27#[derive(Debug, Serialize)]
28pub struct Artifact {
29    pub kind: ArtifactKind,
30    /// The scoped declarations view carries a type, including null for Custom. Omit it
31    /// from the workspace-wide extraction, whose bytes define the graph fingerprint.
32    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
33    pub type_name: Option<Option<crate::config::ArtifactType>>,
34    pub basis: Option<bool>,
35    pub fingerprint: Coverage,
36    /// An aspect's boundary; absent for other kinds, so their extraction is unchanged.
37    #[serde(skip_serializing_if = "Vec::is_empty")]
38    pub select: Vec<crate::config::LogicalPath>,
39}
40
41#[derive(Debug, Serialize)]
42#[serde(tag = "kind", rename_all = "lowercase")]
43pub enum Coverage {
44    Graph,
45    Disabled,
46    Artifactsum {
47        files: Vec<crate::config::LogicalPath>,
48        ignore: Vec<String>,
49    },
50    Script {
51        command: String,
52        args: Vec<Argument>,
53        files: Vec<crate::config::LogicalPath>,
54    },
55}
56
57#[derive(Debug, Serialize)]
58#[serde(rename_all = "camelCase")]
59pub struct Eval {
60    pub target: ArtifactName,
61    pub title: String,
62    pub criteria: Criteria,
63    pub payload: Option<EvalPayload>,
64    pub pass_schema: Option<Map<String, Value>>,
65    pub fail_schema: Option<Map<String, Value>>,
66    /// Artifactize Viewer names external inputs without importing their definitions.
67    #[serde(skip_serializing_if = "Vec::is_empty")]
68    pub reads: Vec<ArtifactName>,
69}
70
71/// One explicit extraction per profile: execution options never enter this type.
72#[derive(Debug, Serialize)]
73#[serde(tag = "kind", rename_all = "lowercase")]
74pub enum Criteria {
75    Agent {
76        #[serde(rename = "redAt", skip_serializing_if = "Option::is_none")]
77        red_at: Option<crate::config::Priority>,
78    },
79    Human,
80    Runtime {
81        command: String,
82        args: Vec<Argument>,
83    },
84}
85
86#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
87pub struct Relation {
88    pub source: ArtifactName,
89    pub target: ArtifactName,
90    #[serde(flatten)]
91    pub kind: Edge,
92}
93
94#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
95#[serde(tag = "kind", rename_all = "lowercase")]
96pub enum Edge {
97    Part,
98    Instruction {
99        eval_id: EvalId,
100        name: crate::config::ReferenceName,
101    },
102    Argv {
103        eval_id: EvalId,
104        index: usize,
105        name: crate::config::ReferenceName,
106        path: crate::scope::LogicalTarget,
107    },
108}
109
110pub fn extract(config: &RepoConfig) -> Structure {
111    extract_where(config, |_, _| true)
112}
113
114fn extract_where(
115    config: &RepoConfig,
116    include: impl Fn(&ArtifactName, &crate::config::Artifact) -> bool,
117) -> Structure {
118    let artifacts: BTreeMap<_, _> = config
119        .artifacts
120        .iter()
121        .filter(|(name, artifact)| include(name, artifact))
122        .map(|(name, artifact)| {
123            let fingerprint = match &artifact.fingerprint {
124                Some(Fingerprint::Graph) => Coverage::Graph,
125                None => Coverage::Disabled,
126                Some(Fingerprint::Artifactsum { files, ignore }) => Coverage::Artifactsum {
127                    files: files.clone(),
128                    ignore: ignore.patterns().to_vec(),
129                },
130                Some(Fingerprint::Script {
131                    command,
132                    args,
133                    files,
134                    ..
135                }) => Coverage::Script {
136                    command: crate::platform::program_text(command),
137                    args: args.clone(),
138                    files: files.clone(),
139                },
140            };
141            (
142                name.clone(),
143                Artifact {
144                    kind: artifact.kind(),
145                    type_name: None,
146                    basis: artifact.basis,
147                    fingerprint,
148                    select: artifact.select().to_vec(),
149                },
150            )
151        })
152        .collect();
153    let evals = config
154        .evals
155        .iter()
156        .filter(|eval| artifacts.contains_key(&eval.target))
157        .map(|eval| {
158            let declaration = &eval.declaration;
159            let criteria = match declaration.profile() {
160                Profile::Agent { .. } => Criteria::Agent {
161                    red_at: declaration.red_at(),
162                },
163                Profile::Human {} => Criteria::Human,
164                Profile::Runtime { command, args, .. } => Criteria::Runtime {
165                    command: crate::platform::program_text(command),
166                    args: args.clone(),
167                },
168            };
169            (
170                eval.id.clone(),
171                Eval {
172                    target: eval.target.clone(),
173                    title: declaration.title.clone(),
174                    criteria,
175                    payload: declaration.payload().cloned(),
176                    pass_schema: declaration.pass_schema().cloned(),
177                    fail_schema: declaration.fail_schema().cloned(),
178                    reads: Vec::new(),
179                },
180            )
181        })
182        .collect();
183    let mut relations: Vec<_> = config
184        .relations
185        .iter()
186        .filter(|relation| {
187            artifacts.contains_key(&relation.source) && artifacts.contains_key(&relation.target)
188        })
189        .map(|relation| Relation {
190            source: relation.source.clone(),
191            target: relation.target.clone(),
192            kind: match &relation.kind {
193                RelationKind::Part => Edge::Part,
194                RelationKind::Instruction { eval_id, name } => Edge::Instruction {
195                    eval_id: eval_id.clone(),
196                    name: name.clone(),
197                },
198                RelationKind::Argument {
199                    eval_id,
200                    index,
201                    name,
202                    path,
203                } => Edge::Argv {
204                    eval_id: eval_id.clone(),
205                    index: *index,
206                    name: name.clone(),
207                    path: path.clone(),
208                },
209            },
210        })
211        .collect();
212    relations.sort();
213    Structure {
214        artifacts,
215        evals,
216        relations,
217    }
218}
219
220/// Reload declarations, not file contents: tools and end-of-review rechecks see current state.
221pub fn read(repo: &Path) -> Result<Structure, String> {
222    crate::config::read_workspace_declarations(repo)
223        .map(|config| extract(&config))
224        .map_err(|error| error.to_string())
225}
226
227/// Read only nodes with declarations in the owner's target, and edges between those nodes.
228pub fn read_scoped(repo: &Path, owner: &crate::config::Artifact) -> Result<Structure, String> {
229    let Some(target) = owner
230        .path
231        .local()
232        .filter(|path| path.starts_with(".artifactize"))
233    else {
234        return Err("The scoped declarations tool must target .artifactize/.".into());
235    };
236    let config =
237        crate::config::read_workspace_declarations(repo).map_err(|error| error.to_string())?;
238    let mut structure = extract_where(&config, |_, artifact| {
239        let definition = artifact.declaration_path();
240        if owner.kind() == ArtifactKind::File {
241            return definition == target;
242        }
243        definition.strip_prefix(target).is_ok_and(|path| {
244            owner.select().is_empty()
245                || owner
246                    .select()
247                    .iter()
248                    .any(|selection| path.starts_with(Path::new(selection.as_str())))
249        })
250    });
251    for (name, node) in &mut structure.artifacts {
252        node.type_name = Some(config.artifacts[name].type_name.clone());
253    }
254    for eval in &config.evals {
255        if let Some(scoped) = structure.evals.get_mut(&eval.id) {
256            scoped.reads.clone_from(&eval.deps);
257        }
258    }
259    Ok(structure)
260}
261
262impl Structure {
263    pub fn fingerprint(&self) -> crate::types::Fingerprint {
264        let mut value = serde_json::to_value(self).expect("graph structure is JSON");
265        value.sort_all_objects();
266        let mut digest = Sha256::new();
267        digest.update(FORMAT);
268        digest.update(serde_json::to_vec(&value).expect("graph structure is JSON"));
269        let hex: String = digest
270            .finalize()
271            .iter()
272            .map(|byte| format!("{byte:02x}"))
273            .collect();
274        format!("graph:{hex}")
275            .parse()
276            .expect("graph fingerprint is nonblank")
277    }
278
279    /// A flat, cycle-safe entity tree; arrows always run from input to consumer.
280    /// The criteria JSON exposes exactly the data hashed, not a separate graph projection.
281    pub fn tree(&self) -> String {
282        let mut text = format!("Artifact graph {}\n", self.fingerprint());
283        for (name, artifact) in &self.artifacts {
284            writeln!(text, "{name} [{:?}]", artifact.kind).expect("write to String");
285            writeln!(
286                text,
287                "  definition: {}",
288                serde_json::to_string(artifact).expect("Artifact is JSON")
289            )
290            .expect("write to String");
291            for (id, eval) in self.evals.iter().filter(|(_, eval)| &eval.target == name) {
292                writeln!(text, "  ├─ {id}: {}", eval.title).expect("write to String");
293                writeln!(
294                    text,
295                    "  │  criteria: {}",
296                    serde_json::to_string(eval).expect("Eval is JSON")
297                )
298                .expect("write to String");
299            }
300        }
301        for relation in &self.relations {
302            writeln!(
303                text,
304                "{} → {} {}",
305                relation.source,
306                relation.target,
307                serde_json::to_string(&relation.kind).expect("relation is JSON")
308            )
309            .expect("write to String");
310        }
311        text
312    }
313}
314
315/// The existing desktop application's detached launch path, with a current-project graph
316/// screen rather than a historical Run. No shell or second renderer is involved.
317/// Open the graph viewer on `repo`; its output reaches `run`'s Tool log until it exits. A
318/// failure hands the run back to be ended.
319pub(crate) fn launch(
320    repo: &Path,
321    run: crate::tools::human::log::Run,
322) -> Result<(), (String, crate::tools::human::log::Run)> {
323    // Validate the same structure before handing it to the desktop viewer.
324    if let Err(error) = read(repo) {
325        return Err((error, run));
326    }
327    let program = match crate::platform::program::resolve(Path::new("artifactize-desktop"), repo) {
328        Ok(program) => program,
329        Err(error) => return Err((format!("Cannot find artifactize-desktop: {error}"), run)),
330    };
331    crate::process::launch_watched(
332        program.as_os_str(),
333        &[
334            std::ffi::OsStr::new("graph"),
335            std::ffi::OsStr::new("--repo"),
336            repo.as_os_str(),
337        ],
338        repo,
339        run,
340    )
341    .map_err(|(error, run)| (error.to_string(), run))
342}
343
344#[cfg(test)]
345mod tests;