Skip to main content

artifactize_core/config/
migrate.rs

1//! One-way conversion. Normal discovery never invokes the old reader.
2use super::*;
3
4#[derive(Debug, serde::Serialize)]
5#[serde(rename_all = "camelCase")]
6pub struct Migration {
7    #[serde(serialize_with = "crate::platform::path_serde::pairs")]
8    pub files: Vec<(PathBuf, PathBuf)>,
9    pub explicit_parts: BTreeMap<ArtifactName, Vec<ArtifactName>>,
10    pub ignored: Vec<ArtifactName>,
11    #[serde(skip_serializing_if = "Vec::is_empty")]
12    pub typed: Vec<ArtifactName>,
13    #[serde(serialize_with = "crate::platform::serialize_paths")]
14    pub separate_projects: Vec<PathBuf>,
15}
16
17/// Validate the complete converted project before changing any of its files.
18pub fn migrate(repo: &Path) -> Result<Migration, ConfigError> {
19    let root =
20        crate::platform::canonicalize(repo).map_err(|error| ConfigError::new(repo, error))?;
21    let destination = root.join(discovery::DEFINITION_DIR);
22    let existed = crate::platform::paths::reusable_directory(&root, discovery::DEFINITION_DIR)
23        .map_err(|error| ConfigError::new(&destination, error))?;
24    if existed {
25        let sources = discovery::sources(&root)?;
26        if !sources.is_empty() {
27            return migrate_tools(&root, &destination, sources);
28        }
29    }
30    let old = legacy::read_workspace_config(&root)?;
31    let mut sources = BTreeMap::new();
32    let mut report = Migration {
33        files: Vec::new(),
34        explicit_parts: BTreeMap::new(),
35        ignored: Vec::new(),
36        typed: Vec::new(),
37        separate_projects: Vec::new(),
38    };
39    let mut originals = BTreeMap::new();
40    let mut problems = Vec::new();
41    let mut names = BTreeMap::new();
42    for (name, artifact) in &old.artifacts {
43        if let Err(error) = discovery::definition_name(name) {
44            problems.push(error);
45        }
46        if let Some(previous) = names.insert(name.to_ascii_lowercase(), name) {
47            problems.push(format!("Names collide ignoring case: {previous}, {name}."));
48        }
49        let file = root.join(artifact.declaration_path());
50        let source = read_regular_text(&file).map_err(|error| ConfigError::new(&file, error))?;
51        let mut doc = source
52            .parse::<toml_edit::DocumentMut>()
53            .map_err(|error| ConfigError::new(&file, error))?;
54        // Keep the removed name's prefix comments on PATH.
55        let prefix = doc
56            .get("name")
57            .and_then(toml_edit::Item::as_value)
58            .map(|value| value.decor().clone());
59        let key_decor = doc.key("name").map(|key| key.leaf_decor().clone());
60        doc.remove("name");
61        let target = match artifact.kind() {
62            ArtifactKind::Graph => ".artifactize/".to_owned(),
63            ArtifactKind::Folder | ArtifactKind::Aspect => {
64                if artifact.folder().as_os_str().is_empty() {
65                    "./".to_owned()
66                } else {
67                    format!("{}/", crate::platform::path_text(artifact.folder()))
68                }
69            }
70            ArtifactKind::File => artifact.path.to_string(),
71            ArtifactKind::Live => unreachable!("legacy reader has no Live targets"),
72        };
73        doc.insert("path", toml_edit::value(target));
74        if let Some(decor) = key_decor {
75            *doc.key_mut("path").expect("path key").leaf_decor_mut() = decor;
76        }
77        if let Some(decor) = prefix {
78            *doc["path"]
79                .as_value_mut()
80                .expect("path is a value")
81                .decor_mut() = decor;
82        }
83        if !artifact.parts.is_empty() {
84            let mut parts = doc
85                .get("parts")
86                .and_then(toml_edit::Item::as_array)
87                .cloned()
88                .unwrap_or_default();
89            for part in &artifact.parts {
90                if !parts
91                    .iter()
92                    .any(|value| value.as_str() == Some(part.as_str()))
93                {
94                    parts.push(part.as_str());
95                }
96            }
97            doc.insert("parts", toml_edit::value(parts));
98            report
99                .explicit_parts
100                .insert(name.clone(), artifact.parts.iter().cloned().collect());
101        }
102        if artifact.kind() == ArtifactKind::Folder
103            && artifact.folder().as_os_str().is_empty()
104            && matches!(artifact.fingerprint, Some(Fingerprint::Artifactsum { .. }))
105        {
106            if doc.get("fingerprint").is_none() {
107                doc["fingerprint"] = toml_edit::Item::Table(toml_edit::Table::new());
108            }
109            let fingerprint = doc["fingerprint"]
110                .as_table_like_mut()
111                .ok_or_else(|| ConfigError::new(&file, "fingerprint must be a table."))?;
112            let ignores = fingerprint
113                .entry("ignore")
114                .or_insert(toml_edit::value(toml_edit::Array::new()))
115                .as_array_mut()
116                .ok_or_else(|| ConfigError::new(&file, "fingerprint.ignore must be an array."))?;
117            ignores.push(".artifactize/");
118            report.ignored.push(name.clone());
119        }
120        let new = destination.join(format!("{name}.artf"));
121        report.files.push((
122            file.strip_prefix(&root).unwrap().to_owned(),
123            new.strip_prefix(&root).unwrap().to_owned(),
124        ));
125        originals.insert(file, source);
126        normalize_commands(doc.as_table_mut());
127        drop_agent_schemas(doc.as_table_mut());
128        sources.insert(new, doc.to_string());
129    }
130    if !problems.is_empty() {
131        return Err(ConfigError::new(&root, problems.join("\n")));
132    }
133    report.typed = type_missing(&root, &mut sources)?;
134    discovery::read_sources(root.clone(), &sources)?;
135    // Report nested old projects without interpreting them as part of this project.
136    let ignored = legacy::discovery_ignore(&root)?;
137    let opened =
138        crate::platform::open_directory(&root).map_err(|error| ConfigError::new(&root, error))?;
139    let mut pending = vec![(root.clone(), opened)];
140    while let Some((directory, opened)) = pending.pop() {
141        for entry in crate::platform::read_dir(&opened)
142            .map_err(|error| ConfigError::new(&directory, error))?
143        {
144            let entry = entry.map_err(|error| ConfigError::new(&directory, error))?;
145            let name = entry.file_name();
146            let file = directory.join(&name);
147            let kind = entry
148                .file_type()
149                .map_err(|error| ConfigError::new(&file, error))?;
150            if kind == crate::platform::FileKind::Directory
151                && name != ".git"
152                && name != "node_modules"
153                && name != "target"
154            {
155                let child = crate::platform::paths::open_named(&opened, &name)
156                    .map_err(|error| ConfigError::new(&file, error))?;
157                pending.push((file, child));
158            } else if kind == crate::platform::FileKind::File
159                && file
160                    .extension()
161                    .is_some_and(|extension| extension == "artf")
162                && !originals.contains_key(&file)
163                && ignored
164                    .matched_path_or_any_parents(&file, false)
165                    .is_ignore()
166            {
167                report
168                    .separate_projects
169                    .push(file.strip_prefix(&root).unwrap().to_owned());
170            }
171        }
172    }
173    let ignore = root.join(IGNORE_FILE);
174    if crate::platform::path_kind(&ignore).is_ok_and(|kind| kind == crate::platform::FileKind::File)
175    {
176        originals.insert(
177            ignore.clone(),
178            read_regular_text(&ignore).map_err(|error| ConfigError::new(&ignore, error))?,
179        );
180    }
181    if existed {
182        refuse_case_aliases(&destination, &sources)?;
183    }
184    let staged = tempfile::Builder::new()
185        .prefix(".artifactize-migrate-")
186        .tempdir_in(&root)
187        .map_err(|error| ConfigError::new(&root, error))?;
188    for (file, source) in &sources {
189        let file = staged
190            .path()
191            .join(file.file_name().expect("definition filename"));
192        std::fs::write(&file, source).map_err(|error| ConfigError::new(&file, error))?;
193    }
194    if !existed {
195        std::fs::create_dir(&destination).map_err(|error| ConfigError::new(&destination, error))?;
196    }
197    let mut created: Vec<PathBuf> = Vec::new();
198    for file in sources.keys() {
199        let final_file = destination.join(file.file_name().expect("definition filename"));
200        if let Err(error) = crate::platform::paths::rename_open_file(
201            &staged
202                .path()
203                .join(file.file_name().expect("definition filename")),
204            &final_file,
205        ) {
206            for created in created {
207                let _ = crate::platform::paths::remove_regular(&created);
208            }
209            if !existed {
210                let _ = std::fs::remove_dir(&destination);
211            }
212            return Err(ConfigError::new(&final_file, error));
213        }
214        created.push(final_file);
215    }
216    for file in originals.keys() {
217        if let Err(error) = crate::platform::paths::remove_regular(file) {
218            for (file, source) in &originals {
219                let _ = crate::platform::paths::restore_file(file, source.as_bytes());
220            }
221            for file in &created {
222                let _ = crate::platform::paths::remove_regular(file);
223            }
224            if !existed {
225                let _ = std::fs::remove_dir(&destination);
226            }
227            return Err(ConfigError::new(file, error));
228        }
229    }
230    Ok(report)
231}
232
233/// Add the file plugin only where an eval needs one of its tool kinds. Preserve any
234/// custom tools; an inherited operation with the same name cannot safely replace one.
235fn type_missing(
236    root: &Path,
237    sources: &mut BTreeMap<PathBuf, String>,
238) -> Result<Vec<ArtifactName>, ConfigError> {
239    let config = discovery::read_sources_for_migration(root.to_owned(), sources)?;
240    let missing: BTreeSet<_> = crate::scope::missing_eval_tools(&config)
241        .map(|(_, artifact, _)| &artifact.name)
242        .collect();
243    for name in &missing {
244        let artifact = &config.artifacts[*name];
245        let path = root.join(artifact.declaration_path());
246        if artifact.type_name.is_some() || artifact.kind() == ArtifactKind::Live {
247            continue; // The final check names exactly the tool that still needs a declaration.
248        }
249        let source = sources.get_mut(&path).expect("declaration is in sources");
250        let original = source.clone();
251        let masked = artifactize_tools::artf::mask(&original).map_err(|error| {
252            ConfigError::new(
253                &path,
254                location::positioned_message(&original, error.offset, error.message),
255            )
256        })?;
257        let mut doc = masked
258            .toml
259            .parse::<toml_edit::DocumentMut>()
260            .map_err(|error| ConfigError::new(&path, error))?;
261        let redundant = artifact.views.agent_tools.iter().filter_map(|(name, view)| {
262            let builtin = match name.as_str() {
263                "read" => Builtin::Read,
264                "list" => Builtin::List,
265                "glob" => Builtin::Glob,
266                "grep" => Builtin::Grep,
267                _ => return None,
268            };
269            Some((name, matches!(view, AgentTool::Builtin(tool) if tool.builtin == builtin && tool.args.is_none() && tool.description.is_none())))
270        }).collect::<Vec<_>>();
271        if artifact.views.human_tools.contains_key("view")
272            || redundant.iter().any(|(_, same)| !same)
273        {
274            // Don't change a custom operation. The final check tells its author what to add.
275            continue;
276        }
277        for (name, _) in redundant {
278            let tools = doc["views"]["agent_tools"]
279                .as_table_like_mut()
280                .expect("declared tools");
281            tools.remove(name);
282        }
283        doc.insert("type", toml_edit::value("files"));
284        *source = masked.unmask(&doc.to_string(), &original);
285    }
286    discovery::read_sources(root.to_owned(), sources)?;
287    Ok(missing.into_iter().cloned().collect())
288}
289
290fn migrate_tools(
291    root: &Path,
292    destination: &Path,
293    original: BTreeMap<PathBuf, String>,
294) -> Result<Migration, ConfigError> {
295    let mut sources = original.clone();
296    let typed = type_missing(root, &mut sources)?;
297    if typed.is_empty() {
298        return Err(ConfigError::new(
299            destination,
300            ".artifactize/ already holds definitions; no migration is needed.",
301        ));
302    }
303    let mut staged = Vec::new();
304    for (file, source) in sources
305        .iter()
306        .filter(|(file, source)| original[*file] != **source)
307    {
308        use std::io::Write;
309        let mut temp = tempfile::NamedTempFile::new_in(file.parent().expect("definition folder"))
310            .map_err(|error| ConfigError::new(file, error))?;
311        temp.write_all(source.as_bytes())
312            .map_err(|error| ConfigError::new(file, error))?;
313        staged.push((file, temp));
314    }
315    for (file, _) in &staged {
316        if read_regular_text(file).map_err(|error| ConfigError::new(*file, error))?
317            != original[*file]
318        {
319            return Err(ConfigError::new(
320                *file,
321                "Definition changed during migration; nothing was written.",
322            ));
323        }
324    }
325    let mut written = Vec::new();
326    for (file, temp) in staged {
327        if let Err(error) = crate::platform::paths::replace_open_file(temp, file) {
328            for file in written {
329                let _ = crate::platform::paths::restore_file(file, original[file].as_bytes());
330            }
331            return Err(ConfigError::new(file, error));
332        }
333        written.push(file);
334    }
335    Ok(Migration {
336        files: Vec::new(),
337        explicit_parts: BTreeMap::new(),
338        ignored: Vec::new(),
339        typed,
340        separate_projects: Vec::new(),
341    })
342}
343
344/// A name `.artifactize/` already holds in another case is the same file on a case-insensitive
345/// volume, which the rename would replace: refuse it on every volume, so migration writes the
346/// same on all of them.
347fn refuse_case_aliases(
348    destination: &Path,
349    sources: &BTreeMap<PathBuf, String>,
350) -> Result<(), ConfigError> {
351    let wanted = sources.keys().filter_map(|file| file.file_name());
352    match crate::platform::paths::conflicting_entry(destination, wanted)
353        .map_err(|error| ConfigError::new(destination, error))?
354    {
355        None => Ok(()),
356        Some(name) => Err(ConfigError::new(
357            destination.join(name),
358            "This name is taken in .artifactize/ in another case; migration writes nothing.",
359        )),
360    }
361}
362
363/// Agent evals report prioritized findings: drop their old result schemas, and with them every
364/// subtable and comment inside. Human evals keep theirs.
365fn drop_agent_schemas(doc: &mut toml_edit::Table) {
366    let Some(evals) = doc
367        .get_mut("evals")
368        .and_then(toml_edit::Item::as_table_like_mut)
369    else {
370        return;
371    };
372    for (_, eval) in evals.iter_mut() {
373        let Some(eval) = eval.as_table_like_mut() else {
374            continue;
375        };
376        let agent = eval
377            .get("profile")
378            .and_then(|profile| profile.get("kind"))
379            .and_then(toml_edit::Item::as_str)
380            == Some("agent");
381        if agent {
382            eval.remove("pass_schema");
383            eval.remove("fail_schema");
384        }
385    }
386}
387
388/// Normalize only executable fields, retaining all other text and the lines' comments.
389fn normalize_commands(table: &mut dyn toml_edit::TableLike) {
390    use toml_edit::{Formatted, Item, Value};
391    fn visit(item: &mut Item) {
392        if let Some(table) = item.as_table_like_mut() {
393            normalize_commands(table);
394        } else if let Some(tables) = item.as_array_of_tables_mut() {
395            for table in tables.iter_mut() {
396                normalize_commands(table);
397            }
398        } else if let Some(array) = item.as_array_mut() {
399            for value in array.iter_mut() {
400                if let Some(table) = value.as_inline_table_mut() {
401                    normalize_commands(table);
402                }
403            }
404        }
405    }
406    for (key, item) in table.iter_mut() {
407        if key.get() == "command"
408            && let Some(Value::String(command)) = item.as_value_mut()
409        {
410            let portable = crate::platform::program_text(command.value());
411            if &portable != command.value() {
412                let mut normalized = Formatted::new(portable);
413                *normalized.decor_mut() = command.decor().clone();
414                *command = normalized;
415            }
416        } else {
417            visit(item);
418        }
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425
426    #[test]
427    fn migration_refuses_a_definition_name_taken_in_another_case() {
428        let temp = crate::test_os::tempdir();
429        let root = temp.path();
430        let original = root.join("index.artf");
431        let source = "name = 'root'\nbasis = true\n";
432        std::fs::write(&original, source).unwrap();
433        let destination = root.join(discovery::DEFINITION_DIR);
434        std::fs::create_dir(&destination).unwrap();
435        let alias = destination.join("ROOT.ARTF");
436        std::fs::write(&alias, "kept").unwrap();
437
438        let error = migrate(root).unwrap_err();
439        assert!(error.message.contains("another case"), "{}", error.message);
440        assert_eq!(std::fs::read_to_string(&alias).unwrap(), "kept");
441        assert_eq!(std::fs::read_to_string(&original).unwrap(), source);
442        assert_eq!(std::fs::read_dir(&destination).unwrap().count(), 1);
443    }
444
445    #[test]
446    fn migration_refuses_a_destination_link_or_case_alias_without_writing() {
447        let temp = crate::test_os::tempdir();
448        let root = temp.path();
449        let original = root.join("index.artf");
450        let source = "name = 'root'\nbasis = true\n";
451        std::fs::write(&original, source).unwrap();
452
453        let target = root.join("linked");
454        std::fs::create_dir(&target).unwrap();
455        let destination = root.join(discovery::DEFINITION_DIR);
456        crate::test_os::link_dir(&target, &destination);
457        assert!(migrate(root).unwrap_err().message.contains("exact name"));
458        assert_eq!(std::fs::read_dir(&target).unwrap().count(), 0);
459        assert_eq!(std::fs::read_to_string(&original).unwrap(), source);
460        crate::test_os::remove_link_dir(&destination);
461
462        let alias = root.join(discovery::DEFINITION_DIR.to_ascii_uppercase());
463        std::fs::create_dir(&alias).unwrap();
464        assert!(migrate(root).unwrap_err().message.contains("exact name"));
465        assert_eq!(std::fs::read_dir(&alias).unwrap().count(), 0);
466        assert_eq!(std::fs::read_to_string(&original).unwrap(), source);
467        std::fs::remove_dir(&alias).unwrap();
468        std::fs::create_dir(&destination).unwrap();
469
470        migrate(root).unwrap();
471        assert!(destination.join("root.artf").is_file());
472        assert!(!original.exists());
473    }
474}