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