1use std::{collections::BTreeMap, fmt::Write, path::Path};
5
6use serde::Serialize;
7
8use sha2::{Digest, Sha256};
9
10use crate::{
11 config::{ArtifactKind, Fingerprint, Profile, RepoConfig, Views},
12 scope::{Argument, RelationKind},
13 types::{ArtifactName, EvalId},
14};
15
16const FORMAT: &[u8] = b"artifactize-graph-v2\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 path: String,
32 pub toolsets: Vec<String>,
35 pub tools: Views,
36 pub basis: Option<bool>,
37 pub fingerprint: Coverage,
38 #[serde(skip_serializing_if = "Vec::is_empty")]
40 pub select: Vec<crate::config::LogicalPath>,
41}
42
43#[derive(Debug, Serialize)]
44#[serde(tag = "kind", rename_all = "lowercase")]
45pub enum Coverage {
46 Graph,
47 Disabled,
48 Artifactsum {
49 files: Vec<crate::config::LogicalPath>,
50 ignore: Vec<String>,
51 },
52 Script {
53 command: String,
54 args: Vec<Argument>,
55 files: Vec<crate::config::LogicalPath>,
56 },
57}
58
59#[derive(Debug, Serialize)]
60#[serde(rename_all = "camelCase")]
61pub struct Eval {
62 pub target: ArtifactName,
63 pub title: String,
64 pub criteria: Criteria,
65 pub instruction: Option<String>,
66 #[serde(skip_serializing_if = "Vec::is_empty")]
67 pub inputs: Vec<ArtifactName>,
68 #[serde(skip_serializing_if = "Vec::is_empty")]
70 pub reads: Vec<ArtifactName>,
71}
72
73#[derive(Debug, Serialize)]
75#[serde(tag = "kind", rename_all = "lowercase")]
76pub enum Criteria {
77 Agent {
78 #[serde(rename = "redAt", skip_serializing_if = "Option::is_none")]
79 red_at: Option<crate::config::Priority>,
80 },
81 Human,
82 Runtime {
83 command: String,
84 args: Vec<Argument>,
85 },
86}
87
88#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
89pub struct Relation {
90 pub source: ArtifactName,
91 pub target: ArtifactName,
92 #[serde(flatten)]
93 pub kind: Edge,
94}
95
96#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
97#[serde(tag = "kind", rename_all = "lowercase")]
98pub enum Edge {
99 Part,
100 Instruction {
101 eval_id: EvalId,
102 name: crate::config::ReferenceName,
103 },
104 Argv {
105 eval_id: EvalId,
106 index: usize,
107 name: crate::config::ReferenceName,
108 path: crate::scope::LogicalTarget,
109 },
110 Input {
111 eval_id: EvalId,
112 name: crate::config::ReferenceName,
113 },
114}
115
116pub fn extract(config: &RepoConfig) -> Structure {
117 extract_where(config, |_, _| true)
118}
119
120fn extract_where(
121 config: &RepoConfig,
122 include: impl Fn(&ArtifactName, &crate::config::Artifact) -> bool,
123) -> Structure {
124 let artifacts: BTreeMap<_, _> = config
125 .artifacts
126 .iter()
127 .filter(|(name, artifact)| include(name, artifact))
128 .map(|(name, artifact)| {
129 let fingerprint = match &artifact.fingerprint {
130 Some(Fingerprint::Graph) => Coverage::Graph,
131 None => Coverage::Disabled,
132 Some(Fingerprint::Artifactsum { files, ignore }) => Coverage::Artifactsum {
133 files: files.clone(),
134 ignore: ignore.patterns().to_vec(),
135 },
136 Some(Fingerprint::Script {
137 command,
138 args,
139 files,
140 ..
141 }) => Coverage::Script {
142 command: crate::platform::program_text(command),
143 args: args.clone(),
144 files: files.clone(),
145 },
146 };
147 (
148 name.clone(),
149 Artifact {
150 kind: artifact.kind(),
151 path: artifact.path.to_string(),
152 toolsets: artifact.toolsets.clone(),
153 tools: artifact.views.clone(),
154 basis: artifact.basis,
155 fingerprint,
156 select: artifact.select().to_vec(),
157 },
158 )
159 })
160 .collect();
161 let evals = config
162 .evals
163 .iter()
164 .filter(|eval| artifacts.contains_key(&eval.target))
165 .map(|eval| {
166 let declaration = &eval.declaration;
167 let criteria = match declaration.profile() {
168 Profile::Agent { .. } => Criteria::Agent {
169 red_at: declaration.red_at(),
170 },
171 Profile::Human {} => Criteria::Human,
172 Profile::Runtime { command, args, .. } => Criteria::Runtime {
173 command: crate::platform::program_text(command),
174 args: args.clone(),
175 },
176 };
177 (
178 eval.id.clone(),
179 Eval {
180 target: eval.target.clone(),
181 title: declaration.title.clone(),
182 criteria,
183 instruction: declaration.instruction().map(str::to_owned),
184 inputs: declaration.inputs().to_vec(),
185 reads: Vec::new(),
186 },
187 )
188 })
189 .collect();
190 let mut relations: Vec<_> = config
191 .relations
192 .iter()
193 .filter(|relation| {
194 artifacts.contains_key(&relation.source) && artifacts.contains_key(&relation.target)
195 })
196 .map(|relation| Relation {
197 source: relation.source.clone(),
198 target: relation.target.clone(),
199 kind: match &relation.kind {
200 RelationKind::Part => Edge::Part,
201 RelationKind::Instruction { eval_id, name } => Edge::Instruction {
202 eval_id: eval_id.clone(),
203 name: name.clone(),
204 },
205 RelationKind::Argument {
206 eval_id,
207 index,
208 name,
209 path,
210 } => Edge::Argv {
211 eval_id: eval_id.clone(),
212 index: *index,
213 name: name.clone(),
214 path: path.clone(),
215 },
216 RelationKind::Input { eval_id, name } => Edge::Input {
217 eval_id: eval_id.clone(),
218 name: name.clone(),
219 },
220 },
221 })
222 .collect();
223 relations.sort();
224 Structure {
225 artifacts,
226 evals,
227 relations,
228 }
229}
230
231pub fn read(repo: &Path) -> Result<Structure, String> {
233 crate::config::read_workspace_declarations(repo)
234 .map(|config| extract(&config))
235 .map_err(|error| error.to_string())
236}
237
238pub fn read_scoped(repo: &Path, owner: &crate::config::Artifact) -> Result<Structure, String> {
241 let Some(target) = owner
242 .path
243 .local()
244 .filter(|path| path.starts_with(".artifactize"))
245 else {
246 return Err("The scoped declarations tool must target .artifactize/.".into());
247 };
248 let config =
249 crate::config::read_workspace_declarations(repo).map_err(|error| error.to_string())?;
250 let mut structure = extract_where(&config, |_, artifact| {
251 let definition = artifact.declaration_path();
252 if owner.kind() == ArtifactKind::File {
253 return definition == target;
254 }
255 definition.strip_prefix(target).is_ok_and(|path| {
256 owner.select().is_empty()
257 || owner
258 .select()
259 .iter()
260 .any(|selection| path.starts_with(Path::new(selection.as_str())))
261 })
262 });
263 for eval in &config.evals {
264 if let Some(scoped) = structure.evals.get_mut(&eval.id) {
265 scoped.reads.clone_from(&eval.deps);
266 }
267 }
268 Ok(structure)
269}
270
271impl Structure {
272 pub fn fingerprint(&self) -> crate::types::Fingerprint {
273 let mut value = serde_json::to_value(self).expect("graph structure is JSON");
274 value.sort_all_objects();
275 let mut digest = Sha256::new();
276 digest.update(FORMAT);
277 digest.update(serde_json::to_vec(&value).expect("graph structure is JSON"));
278 let hex: String = digest
279 .finalize()
280 .iter()
281 .map(|byte| format!("{byte:02x}"))
282 .collect();
283 format!("graph:{hex}")
284 .parse()
285 .expect("graph fingerprint is nonblank")
286 }
287
288 pub fn tree(&self) -> String {
291 let mut text = format!("Artifact graph {}\n", self.fingerprint());
292 for (name, artifact) in &self.artifacts {
293 writeln!(text, "{name} [{:?}]", artifact.kind).expect("write to String");
294 writeln!(
295 text,
296 " definition: {}",
297 serde_json::to_string(artifact).expect("Artifact is JSON")
298 )
299 .expect("write to String");
300 for (id, eval) in self.evals.iter().filter(|(_, eval)| &eval.target == name) {
301 writeln!(text, " ├─ {id}: {}", eval.title).expect("write to String");
302 writeln!(
303 text,
304 " │ criteria: {}",
305 serde_json::to_string(eval).expect("Eval is JSON")
306 )
307 .expect("write to String");
308 }
309 }
310 for relation in &self.relations {
311 writeln!(
312 text,
313 "{} → {} {}",
314 relation.source,
315 relation.target,
316 serde_json::to_string(&relation.kind).expect("relation is JSON")
317 )
318 .expect("write to String");
319 }
320 text
321 }
322}
323
324pub(crate) fn launch(
329 repo: &Path,
330 run: crate::tools::human::log::Run,
331) -> Result<(), (String, crate::tools::human::log::Run)> {
332 if let Err(error) = read(repo) {
334 return Err((error, run));
335 }
336 let program = match crate::platform::program::resolve(Path::new("artifactize-desktop"), repo) {
337 Ok(program) => program,
338 Err(error) => return Err((format!("Cannot find artifactize-desktop: {error}"), run)),
339 };
340 crate::process::launch_watched(
341 program.as_os_str(),
342 &[
343 std::ffi::OsStr::new("graph"),
344 std::ffi::OsStr::new("--repo"),
345 repo.as_os_str(),
346 ],
347 repo,
348 run,
349 )
350 .map_err(|(error, run)| (error.to_string(), run))
351}
352
353#[cfg(test)]
354mod tests;