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    pub basis: Option<bool>,
31    pub fingerprint: Coverage,
32    /// An aspect's boundary; absent for other kinds, so their extraction is unchanged.
33    #[serde(skip_serializing_if = "Vec::is_empty")]
34    pub select: Vec<crate::config::LogicalPath>,
35}
36
37#[derive(Debug, Serialize)]
38#[serde(tag = "kind", rename_all = "lowercase")]
39pub enum Coverage {
40    Graph,
41    Disabled,
42    Artifactsum {
43        files: Vec<crate::config::LogicalPath>,
44        ignore: Vec<String>,
45    },
46    Script {
47        command: String,
48        args: Vec<Argument>,
49        files: Vec<crate::config::LogicalPath>,
50    },
51}
52
53#[derive(Debug, Serialize)]
54#[serde(rename_all = "camelCase")]
55pub struct Eval {
56    pub target: ArtifactName,
57    pub title: String,
58    pub criteria: Criteria,
59    pub payload: Option<EvalPayload>,
60    pub pass_schema: Option<Map<String, Value>>,
61    pub fail_schema: Option<Map<String, Value>>,
62}
63
64/// One explicit extraction per profile: execution options never enter this type.
65#[derive(Debug, Serialize)]
66#[serde(tag = "kind", rename_all = "lowercase")]
67pub enum Criteria {
68    Agent {
69        #[serde(rename = "redAt", skip_serializing_if = "Option::is_none")]
70        red_at: Option<crate::config::Priority>,
71    },
72    Human,
73    Runtime {
74        command: String,
75        args: Vec<Argument>,
76    },
77}
78
79#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
80pub struct Relation {
81    pub source: ArtifactName,
82    pub target: ArtifactName,
83    #[serde(flatten)]
84    pub kind: Edge,
85}
86
87#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
88#[serde(tag = "kind", rename_all = "lowercase")]
89pub enum Edge {
90    Part,
91    Instruction {
92        eval_id: EvalId,
93        name: crate::config::ReferenceName,
94    },
95    Argv {
96        eval_id: EvalId,
97        index: usize,
98        name: crate::config::ReferenceName,
99        path: crate::scope::LogicalTarget,
100    },
101}
102
103pub fn extract(config: &RepoConfig) -> Structure {
104    let artifacts = config
105        .artifacts
106        .iter()
107        .map(|(name, artifact)| {
108            let fingerprint = match &artifact.fingerprint {
109                Some(Fingerprint::Graph) => Coverage::Graph,
110                None => Coverage::Disabled,
111                Some(Fingerprint::Artifactsum { files, ignore }) => Coverage::Artifactsum {
112                    files: files.clone(),
113                    ignore: ignore.patterns().to_vec(),
114                },
115                Some(Fingerprint::Script {
116                    command,
117                    args,
118                    files,
119                    ..
120                }) => Coverage::Script {
121                    command: crate::platform::program_text(command),
122                    args: args.clone(),
123                    files: files.clone(),
124                },
125            };
126            (
127                name.clone(),
128                Artifact {
129                    kind: artifact.kind(),
130                    basis: artifact.basis,
131                    fingerprint,
132                    select: artifact.select().to_vec(),
133                },
134            )
135        })
136        .collect();
137    let evals = config
138        .evals
139        .iter()
140        .map(|eval| {
141            let declaration = &eval.declaration;
142            let criteria = match declaration.profile() {
143                Profile::Agent { .. } => Criteria::Agent {
144                    red_at: declaration.red_at(),
145                },
146                Profile::Human {} => Criteria::Human,
147                Profile::Runtime { command, args, .. } => Criteria::Runtime {
148                    command: crate::platform::program_text(command),
149                    args: args.clone(),
150                },
151            };
152            (
153                eval.id.clone(),
154                Eval {
155                    target: eval.target.clone(),
156                    title: declaration.title.clone(),
157                    criteria,
158                    payload: declaration.payload().cloned(),
159                    pass_schema: declaration.pass_schema().cloned(),
160                    fail_schema: declaration.fail_schema().cloned(),
161                },
162            )
163        })
164        .collect();
165    let mut relations: Vec<_> = config
166        .relations
167        .iter()
168        .map(|relation| Relation {
169            source: relation.source.clone(),
170            target: relation.target.clone(),
171            kind: match &relation.kind {
172                RelationKind::Part => Edge::Part,
173                RelationKind::Instruction { eval_id, name } => Edge::Instruction {
174                    eval_id: eval_id.clone(),
175                    name: name.clone(),
176                },
177                RelationKind::Argument {
178                    eval_id,
179                    index,
180                    name,
181                    path,
182                } => Edge::Argv {
183                    eval_id: eval_id.clone(),
184                    index: *index,
185                    name: name.clone(),
186                    path: path.clone(),
187                },
188            },
189        })
190        .collect();
191    relations.sort();
192    Structure {
193        artifacts,
194        evals,
195        relations,
196    }
197}
198
199/// Reload declarations, not file contents: tools and end-of-review rechecks see current state.
200pub fn read(repo: &Path) -> Result<Structure, String> {
201    crate::config::read_workspace_declarations(repo)
202        .map(|config| extract(&config))
203        .map_err(|error| error.to_string())
204}
205
206impl Structure {
207    pub fn fingerprint(&self) -> crate::types::Fingerprint {
208        let mut value = serde_json::to_value(self).expect("graph structure is JSON");
209        value.sort_all_objects();
210        let mut digest = Sha256::new();
211        digest.update(FORMAT);
212        digest.update(serde_json::to_vec(&value).expect("graph structure is JSON"));
213        let hex: String = digest
214            .finalize()
215            .iter()
216            .map(|byte| format!("{byte:02x}"))
217            .collect();
218        format!("graph:{hex}")
219            .parse()
220            .expect("graph fingerprint is nonblank")
221    }
222
223    /// A flat, cycle-safe entity tree; arrows always run from input to consumer.
224    /// The criteria JSON exposes exactly the data hashed, not a separate graph projection.
225    pub fn tree(&self) -> String {
226        let mut text = format!("Artifact graph {}\n", self.fingerprint());
227        for (name, artifact) in &self.artifacts {
228            writeln!(text, "{name} [{:?}]", artifact.kind).expect("write to String");
229            writeln!(
230                text,
231                "  definition: {}",
232                serde_json::to_string(artifact).expect("Artifact is JSON")
233            )
234            .expect("write to String");
235            for (id, eval) in self.evals.iter().filter(|(_, eval)| &eval.target == name) {
236                writeln!(text, "  ├─ {id}: {}", eval.title).expect("write to String");
237                writeln!(
238                    text,
239                    "  │  criteria: {}",
240                    serde_json::to_string(eval).expect("Eval is JSON")
241                )
242                .expect("write to String");
243            }
244        }
245        for relation in &self.relations {
246            writeln!(
247                text,
248                "{} → {} {}",
249                relation.source,
250                relation.target,
251                serde_json::to_string(&relation.kind).expect("relation is JSON")
252            )
253            .expect("write to String");
254        }
255        text
256    }
257}
258
259/// The existing desktop application's detached launch path, with a current-project graph
260/// screen rather than a historical Run. No shell or second renderer is involved.
261/// Open the graph viewer on `repo`; its output reaches `run`'s Tool log until it exits. A
262/// failure hands the run back to be ended.
263pub(crate) fn launch(
264    repo: &Path,
265    run: crate::tools::human::log::Run,
266) -> Result<(), (String, crate::tools::human::log::Run)> {
267    // Validate the same structure before handing it to the desktop viewer.
268    if let Err(error) = read(repo) {
269        return Err((error, run));
270    }
271    let program = match crate::platform::program::resolve(Path::new("artifactize-desktop"), repo) {
272        Ok(program) => program,
273        Err(error) => return Err((format!("Cannot find artifactize-desktop: {error}"), run)),
274    };
275    crate::process::launch_watched(
276        program.as_os_str(),
277        &[
278            std::ffi::OsStr::new("graph"),
279            std::ffi::OsStr::new("--repo"),
280            repo.as_os_str(),
281        ],
282        repo,
283        run,
284    )
285    .map_err(|(error, run)| (error.to_string(), run))
286}
287
288#[cfg(test)]
289mod tests;