Skip to main content

mars_schema/
prepare.rs

1//! One-pass package classification, normalization, selection, and strict reading.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::{Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7
8use crate::diagnostic::{PathSegment, SchemaDiagnostic, Severity};
9use crate::dialect::{Dialect, DialectChoice};
10use crate::discover::{SelectedDefinition, payload_paths};
11use crate::dispatch::{AsPlugin, Dispatched, Layout, dispatch};
12use crate::frontmatter::{Frontmatter, FrontmatterError};
13use crate::item::DefinitionKind;
14use crate::read::{DefinitionRead, Reading, read_authored, read_definition};
15use crate::selection::{Definition, Request, SelectionFacts};
16use crate::tool_policy::{RuleOrigin, ToolRule};
17use crate::tree::TreeSource;
18use crate::upgrade::{UpgradeError, UpgradeResult};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "kebab-case")]
22pub enum PrepareContext {
23    /// A package root (a dependency, or the package being published): its `mars.toml` must
24    /// declare `[package]`, and a root with no manifest is read as the dialect it looks like.
25    Package,
26    /// A consumer's own authored directory (`.mars-src`): content without a manifest is Mars
27    /// convention, and a `mars.toml` without `[package]` is consumer configuration, not read.
28    AuthoredLocal,
29    /// A directory that is either: `Package` unless its `mars.toml` has no `[package]`, which
30    /// makes it a consumer project whose tree is read as `AuthoredLocal` content.
31    Project,
32}
33
34/// The directory below a consumer project that holds its own authored content.
35pub const LOCAL_SOURCE_DIR: &str = ".mars-src";
36
37/// Where a project directory's authored content lives and how it is read, from its `mars.toml`
38/// bytes: the project root as a `Package`, or, when the manifest is consumer configuration with
39/// no `[package]`, its `.mars-src` as `AuthoredLocal`. A caller that writes to the authored
40/// files, as `mars migrate` does, asks here instead of parsing `mars.toml` itself.
41pub fn project_authored_root(project: &Path, manifest: Option<&[u8]>) -> (PathBuf, PrepareContext) {
42    match crate::package::classify_manifest(manifest) {
43        crate::package::ManifestClassification::ConsumerConfig => (
44            project.join(LOCAL_SOURCE_DIR),
45            PrepareContext::AuthoredLocal,
46        ),
47        _ => (project.to_path_buf(), PrepareContext::Package),
48    }
49}
50
51/// What a package root is, once its manifest, declared dialect and contents have been weighed.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
53#[serde(tag = "kind", rename_all = "kebab-case")]
54pub enum Classification {
55    #[serde(rename = "schema-1")]
56    Schema1,
57    MarsLegacy,
58    SchemaNewer {
59        schema: u64,
60    },
61    Invalid,
62    /// Another harness's layout, read as the dialect chosen.
63    Foreign(DialectChoice),
64    /// A Claude marketplace: it lists plugins and holds no definitions of its own.
65    Marketplace,
66    Empty,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
70#[serde(tag = "kind", rename_all = "kebab-case")]
71pub enum ChangeRecord {
72    None,
73    /// The file has no source: `normalize` wrote it (a package's generated `mars.toml`).
74    Generated,
75    Edited {
76        paths: Vec<Vec<PathSegment>>,
77    },
78    FullyRewritten,
79}
80
81#[derive(Debug, Clone, Serialize)]
82pub struct PreparedManifest {
83    /// `None` for a generated manifest.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub source_path: Option<String>,
86    pub output_path: String,
87    /// The normalized file; crosses to JavaScript as a `Uint8Array`.
88    #[serde(with = "serde_bytes")]
89    pub normalized_bytes: Vec<u8>,
90    pub reading: crate::manifest::ManifestRead,
91    pub change: ChangeRecord,
92}
93
94#[derive(Debug, Clone, Serialize)]
95pub struct PreparedDefinition {
96    pub kind: DefinitionKind,
97    pub slug: String,
98    pub source_path: String,
99    pub output_path: String,
100    /// A skill's folder in the package tree (empty for a root skill); `None` for an agent.
101    #[serde(skip)]
102    pub skill_root: Option<String>,
103    /// The normalized file; crosses to JavaScript as a `Uint8Array`.
104    #[serde(with = "serde_bytes")]
105    pub normalized_bytes: Vec<u8>,
106    /// The Agent or skill reading `kind` names.
107    pub reading: Reading,
108    pub change: ChangeRecord,
109}
110
111/// An MCP server translated from another dialect's declaration, as the `mcp/<name>/mcp.toml` it
112/// is written to. The same shape as a definition's output so a caller writes it the same way.
113#[derive(Debug, Clone, Serialize)]
114pub struct PreparedMcpServer {
115    pub name: String,
116    /// The file that declared the server (`.mcp.json`, `plugin.json`).
117    pub source_path: String,
118    pub output_path: String,
119    /// The rendered `mcp.toml`; crosses to JavaScript as a `Uint8Array`.
120    #[serde(with = "serde_bytes")]
121    pub normalized_bytes: Vec<u8>,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
125pub struct PayloadEntry {
126    pub source_path: String,
127    pub output_path: String,
128}
129
130#[derive(Debug, Clone, Serialize)]
131pub struct Prepared {
132    pub classification: Classification,
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub manifest: Option<PreparedManifest>,
135    pub definitions: Vec<PreparedDefinition>,
136    /// The MCP servers a foreign plugin declares, translated. Selection does not apply to them.
137    #[serde(skip_serializing_if = "Vec::is_empty")]
138    pub mcp_servers: Vec<PreparedMcpServer>,
139    pub payload: Vec<PayloadEntry>,
140    /// What item selection reads of this package (see [`selection_facts`]).
141    pub selection: SelectionFacts,
142    /// Package-level findings by source path: what discovery and translation met and could not
143    /// convert. A definition's own reading diagnostics live on its `reading` only; see
144    /// [`Prepared::all_diagnostics`].
145    pub diagnostics: BTreeMap<String, Vec<SchemaDiagnostic>>,
146    /// What preparing changed in each file, by source path: the keys a pre-v1 upgrade or a
147    /// foreign translation dropped, moved or repaired. A caller that only reads the package
148    /// reports [`Prepared::changed_files`]; `mars migrate` lists these.
149    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
150    pub changes: BTreeMap<String, Vec<SchemaDiagnostic>>,
151}
152
153/// What item selection reads of a prepared package: its Agents' and skills' skill refs, and the
154/// `[dependencies]` entries and `uses-providers` its manifest reads.
155pub(crate) fn selection_facts(
156    manifest: Option<&PreparedManifest>,
157    definitions: &[PreparedDefinition],
158) -> SelectionFacts {
159    let reading = manifest.map(|manifest| &manifest.reading);
160    SelectionFacts {
161        definitions: definitions
162            .iter()
163            .map(|definition| Definition {
164                kind: definition.kind,
165                slug: definition.slug.clone(),
166                output_path: definition.output_path.clone(),
167                skills: match &definition.reading {
168                    Reading::Agent(read) => read
169                        .fields
170                        .as_ref()
171                        .map(|profile| profile.skills.all())
172                        .unwrap_or_default(),
173                    _ => Vec::new(),
174                },
175            })
176            .collect(),
177        edges: reading
178            .map(|reading| {
179                reading
180                    .dependencies
181                    .dependencies
182                    .iter()
183                    .map(|(name, entry)| Request {
184                        name: name.clone(),
185                        filter: entry.filter.to_mode(),
186                    })
187                    .collect()
188            })
189            .unwrap_or_default(),
190        uses_providers: reading
191            .and_then(|reading| reading.package.fields.as_ref())
192            .map(|package| package.uses_providers.clone())
193            .unwrap_or_default(),
194    }
195}
196
197impl Prepared {
198    /// The changes that lost a restriction (a `deny` or `ask` tool entry, `permission`,
199    /// `sandbox`, `approval`), by source path. Unlike the rest of `changes`, a caller reports
200    /// these on every run: each leaves an agent less restricted than its file says.
201    pub fn lost_restrictions(&self) -> impl Iterator<Item = (&str, &SchemaDiagnostic)> {
202        self.changes.iter().flat_map(|(path, changes)| {
203            changes
204                .iter()
205                .filter(|change| change.code == crate::set_aside::RESTRICTION_LOST)
206                .map(move |change| (path.as_str(), change))
207        })
208    }
209
210    /// The changes that ignored a non-string `effort`, `mode` or `harness`, by source path. A
211    /// sync leaves these in the count of changed files; `mars check` prints them, because the
212    /// author of the file can fix them.
213    pub fn ignored_execution_fields(&self) -> impl Iterator<Item = (&str, &SchemaDiagnostic)> {
214        self.changes.iter().flat_map(|(path, changes)| {
215            changes
216                .iter()
217                .filter(|change| change.code == crate::set_aside::EXECUTION_IGNORED)
218                .map(move |change| (path.as_str(), change))
219        })
220    }
221
222    /// The changes that quoted a value YAML could not read as plain text, by source path. Like
223    /// [`Self::ignored_execution_fields`], `mars check` prints them for the author to fix and a
224    /// sync only counts the file.
225    pub fn repaired_values(&self) -> impl Iterator<Item = (&str, &SchemaDiagnostic)> {
226        self.changes.iter().flat_map(|(path, changes)| {
227            changes
228                .iter()
229                .filter(|change| change.code == crate::claude::translate::REPAIRED)
230                .map(move |change| (path.as_str(), change))
231        })
232    }
233
234    /// How many authored files preparation changed: the prepared bytes differ from the file, and
235    /// for a pre-v1 package `mars migrate` writes them back. A generated `mars.toml` has no file
236    /// to change and is not counted.
237    pub fn changed_files(&self) -> usize {
238        self.manifest
239            .iter()
240            .map(|manifest| &manifest.change)
241            .chain(self.definitions.iter().map(|definition| &definition.change))
242            .filter(|change| !matches!(change, ChangeRecord::None | ChangeRecord::Generated))
243            .count()
244    }
245
246    /// Every diagnostic by source path: package-level first, then the file's reading.
247    pub fn all_diagnostics(&self) -> BTreeMap<&str, Vec<&SchemaDiagnostic>> {
248        let mut all: BTreeMap<&str, Vec<&SchemaDiagnostic>> = BTreeMap::new();
249        for (path, diagnostics) in &self.diagnostics {
250            all.entry(path).or_default().extend(diagnostics);
251        }
252        if let Some(manifest) = &self.manifest
253            && let Some(path) = &manifest.source_path
254        {
255            all.entry(path)
256                .or_default()
257                .extend(&manifest.reading.package.diagnostics);
258        }
259        for definition in &self.definitions {
260            all.entry(&definition.source_path)
261                .or_default()
262                .extend(definition.reading.diagnostics());
263        }
264        all.retain(|_, diagnostics| !diagnostics.is_empty());
265        all
266    }
267}
268
269/// What a caller adds when it reads a root as one plugin of a marketplace, or imports only some
270/// of the items.
271#[derive(Default, Clone, Copy)]
272pub(crate) struct RootOptions<'a> {
273    pub as_plugin: Option<AsPlugin<'a>>,
274    /// Source paths of the definitions to import; `None` imports every one found.
275    pub selection: Option<&'a BTreeSet<String>>,
276    /// Names a root `SKILL.md` when its own `name` cannot.
277    pub fallback_name: Option<&'a str>,
278    /// Convert what a schema 1 package still carries of pre-v1 Mars (`upgrade::PRE_V1`), in its
279    /// definitions and its `mars.toml`. Only `mars migrate` asks, because it
280    /// writes the result back; a reader leaves it off, because an authored schema 1 file is read
281    /// exactly as written.
282    pub migrate: bool,
283}
284
285/// `prepare` plus what was discovered, for `inspect` and `normalize`.
286pub(crate) struct Rooted {
287    pub prepared: Prepared,
288    pub dispatched: Dispatched,
289}
290
291/// Prepare one rooted package without reading payload bytes.
292pub fn prepare(
293    source: &impl TreeSource,
294    context: PrepareContext,
295    declared_dialect: Option<Dialect>,
296) -> Prepared {
297    prepare_root(source, context, declared_dialect, RootOptions::default()).prepared
298}
299
300/// `prepare` as `mars migrate` runs it: a definition it could repair is repaired in
301/// `normalized_bytes`, for the migration to write back to the authored file.
302pub fn prepare_for_migration(
303    source: &impl TreeSource,
304    context: PrepareContext,
305    declared_dialect: Option<Dialect>,
306) -> Prepared {
307    let options = RootOptions {
308        migrate: true,
309        ..RootOptions::default()
310    };
311    prepare_root(source, context, declared_dialect, options).prepared
312}
313
314pub(crate) fn prepare_root(
315    source: &impl TreeSource,
316    context: PrepareContext,
317    declared_dialect: Option<Dialect>,
318    options: RootOptions<'_>,
319) -> Rooted {
320    let mut dispatched = dispatch(
321        source,
322        context,
323        declared_dialect,
324        options.as_plugin,
325        options.fallback_name,
326    );
327    let classification = dispatched.classification.clone();
328    let manifest_bytes = dispatched.manifest.take();
329    let mut diagnostics = std::mem::take(&mut dispatched.discovery.diagnostics);
330    let mut changes = BTreeMap::new();
331
332    let mut manifest = manifest_bytes.as_deref().map(|bytes| {
333        prepare_manifest(
334            bytes,
335            classification == Classification::MarsLegacy
336                || (options.migrate && classification == Classification::Schema1),
337            &mut diagnostics,
338            &mut changes,
339        )
340    });
341
342    let can_read_definitions = !matches!(
343        classification,
344        Classification::Invalid
345            | Classification::SchemaNewer { .. }
346            | Classification::Empty
347            | Classification::Marketplace
348    );
349    let all = &dispatched.discovery.definitions;
350    let selected = all
351        .iter()
352        .filter(|definition| {
353            options
354                .selection
355                .is_none_or(|selection| selection.contains(&definition.source_path))
356        })
357        .collect::<Vec<_>>();
358    let shaping = Shaping::of(&classification, options.migrate);
359    let authored = matches!(classification, Classification::Schema1);
360    let definitions = if can_read_definitions {
361        selected
362            .iter()
363            .map(|definition| {
364                let mut prepared = prepare_definition(
365                    source,
366                    definition,
367                    shaping,
368                    authored,
369                    &mut diagnostics,
370                    &mut changes,
371                );
372                if let Some(manifest) = &manifest {
373                    add_package_tools(&mut prepared, &manifest.reading);
374                }
375                prepared
376            })
377            .collect::<Vec<_>>()
378    } else {
379        Vec::new()
380    };
381    let payload = if can_read_definitions {
382        payload_paths(
383            source,
384            &dispatched.discovery,
385            matches!(classification, Classification::Foreign(_)),
386            selected.iter().copied(),
387            &mut diagnostics,
388        )
389        .into_iter()
390        .map(|(source_path, output_path)| PayloadEntry {
391            source_path,
392            output_path,
393        })
394        .collect()
395    } else {
396        Vec::new()
397    };
398
399    let mut mcp_servers = Vec::new();
400    if can_read_definitions {
401        report_unconverted(source, &dispatched, &mut diagnostics);
402        // A bare skill tree's `.mcp.json` is usually its contributors' own, not a plugin's.
403        if let Layout::Claude(spec) = &dispatched.layout
404            && !spec.is_bare_tree()
405        {
406            let imported = crate::claude::mcp::import(source, spec);
407            for (path, diagnostic) in imported.diagnostics {
408                push(&mut diagnostics, &path, diagnostic);
409            }
410            mcp_servers = imported
411                .servers
412                .into_iter()
413                .map(|server| PreparedMcpServer {
414                    output_path: format!("mcp/{}/mcp.toml", server.name),
415                    normalized_bytes: crate::mcp_server::render_mcp_toml(&server.def).into_bytes(),
416                    name: server.name,
417                    source_path: server.source_path,
418                })
419                .collect();
420        }
421    }
422    diagnostics.retain(|_, diagnostics| !diagnostics.is_empty());
423    changes.retain(|_, diagnostics| !diagnostics.is_empty());
424    let manifest = manifest.take();
425    let prepared = Prepared {
426        classification,
427        selection: selection_facts(manifest.as_ref(), &definitions),
428        manifest,
429        definitions,
430        mcp_servers,
431        payload,
432        diagnostics,
433        changes,
434    };
435    Rooted {
436        prepared,
437        dispatched,
438    }
439}
440
441/// Add the package's `[package.tools]` rules to an Agent's reading, as `mars sync` writes them
442/// into the installed file (`package_tools::missing`). `normalized_bytes` stay the file's: the
443/// rules belong to the package, not to the authored profile.
444fn add_package_tools(
445    definition: &mut PreparedDefinition,
446    manifest: &crate::manifest::ManifestRead,
447) {
448    let Reading::Agent(read) = &mut definition.reading else {
449        return;
450    };
451    // `mars sync` refuses a manifest with any error and installs none of its Agents, so an
452    // Agent read beside one carries the failure instead of reading clean without the rules.
453    if let Some(error) = manifest.first_error() {
454        read.diagnostics.push(SchemaDiagnostic::new(
455            "package-tools.unreadable",
456            Severity::Error,
457            Vec::new(),
458            format!(
459                "the package's mars.toml has an error, so its `[package.tools]` rules cannot be added and `mars sync` refuses the package: {}",
460                error.message
461            ),
462        ));
463        return;
464    }
465    let (Some(package), Some(fields)) = (
466        manifest
467            .package
468            .fields
469            .as_ref()
470            .map(|package| &package.tools),
471        read.fields.as_mut(),
472    ) else {
473        return;
474    };
475    // The reading's own `frontmatter` is ordered JSON; the shared rule reads the YAML mapping.
476    let Some(profile) = std::str::from_utf8(&definition.normalized_bytes)
477        .ok()
478        .and_then(|text| Frontmatter::parse(text).ok())
479    else {
480        return;
481    };
482    for (name, action) in crate::package_tools::missing(&profile, package) {
483        fields.tools.push_unique(
484            ToolRule::from_parsed(name.parsed().clone(), action).with_origin(RuleOrigin::Package),
485        );
486    }
487}
488
489/// Commands are dropped and hooks are not converted yet. MCP servers are translated, not
490/// reported here (`claude::mcp`).
491fn report_unconverted(
492    source: &impl TreeSource,
493    dispatched: &Dispatched,
494    diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
495) {
496    let Layout::Claude(spec) = &dispatched.layout else {
497        return;
498    };
499    let mut warn = |path: &str, code: &str, message: String| {
500        diagnostics
501            .entry(path.to_owned())
502            .or_default()
503            .push(SchemaDiagnostic::new(
504                code,
505                Severity::Warning,
506                Vec::new(),
507                message,
508            ));
509    };
510    if !dispatched.discovery.dropped.is_empty() {
511        warn(
512            "commands",
513            "import.commands-dropped",
514            format!(
515                "commands are not imported (convert one to a skill): {}",
516                dispatched
517                    .discovery
518                    .dropped
519                    .iter()
520                    .map(|command| command.source_path.as_str())
521                    .collect::<Vec<_>>()
522                    .join(", ")
523            ),
524        );
525    }
526    if spec.is_bare_tree() && source.is_file(".mcp.json") {
527        warn(
528            ".mcp.json",
529            "import.mcp-not-imported",
530            "this is a skill tree, not a Claude plugin (it has no `.claude-plugin/plugin.json`), so its MCP servers were not imported".into(),
531        );
532    }
533    if source.is_file("hooks/hooks.json") || spec.hooks {
534        let path = if source.is_file("hooks/hooks.json") {
535            "hooks/hooks.json"
536        } else {
537            crate::claude::manifest::PLUGIN_MANIFEST
538        };
539        warn(
540            path,
541            "import.hooks-not-converted",
542            "hooks are not converted yet".into(),
543        );
544    }
545}
546
547fn prepare_manifest(
548    bytes: &[u8],
549    upgrade: bool,
550    diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
551    changes: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
552) -> PreparedManifest {
553    let invalid_utf8 = std::str::from_utf8(bytes).err().map(|error| {
554        SchemaDiagnostic::new(
555            "text.invalid-utf8",
556            Severity::Error,
557            Vec::new(),
558            format!("mars.toml is not UTF-8: {error}"),
559        )
560    });
561    let (normalized_bytes, change, upgraded) = match std::str::from_utf8(bytes) {
562        Ok(text) if upgrade => match crate::upgrade::upgrade_manifest(text) {
563            Ok(result) => upgrade_result(text, result),
564            Err(error) => {
565                push(
566                    diagnostics,
567                    "mars.toml",
568                    SchemaDiagnostic::new(
569                        "manifest.upgrade-failed",
570                        Severity::Error,
571                        Vec::new(),
572                        error.to_string(),
573                    ),
574                );
575                (bytes.to_vec(), ChangeRecord::None, Vec::new())
576            }
577        },
578        Ok(_) => (bytes.to_vec(), ChangeRecord::None, Vec::new()),
579        Err(_) => (bytes.to_vec(), ChangeRecord::None, Vec::new()),
580    };
581    changes
582        .entry("mars.toml".to_string())
583        .or_default()
584        .extend(upgraded);
585    let reading = std::str::from_utf8(&normalized_bytes).map_or_else(
586        |_| crate::manifest::ManifestRead::unread(invalid_utf8.into_iter().collect()),
587        crate::manifest::read,
588    );
589    PreparedManifest {
590        source_path: Some("mars.toml".to_string()),
591        output_path: "mars.toml".to_string(),
592        normalized_bytes,
593        reading,
594        change,
595    }
596}
597
598/// A definition's authored keys, made schema v1.
599type Rewrite = fn(DefinitionKind, &str) -> Result<UpgradeResult, UpgradeError>;
600
601/// How the root's definitions are made schema v1, decided once for the root.
602#[derive(Clone, Copy)]
603enum Shaping {
604    /// Nothing to convert: each file is read as written.
605    None,
606    /// The pre-v1 upgrade, or `mars migrate`'s repair of a schema 1 file.
607    Rewrite(Rewrite),
608    /// A foreign dialect, translated into schema v1.
609    Foreign(Dialect),
610}
611
612impl Shaping {
613    fn of(classification: &Classification, migrate: bool) -> Self {
614        match classification {
615            Classification::MarsLegacy => Self::Rewrite(crate::upgrade::upgrade_definition),
616            // Only `mars migrate` writes the result back, so only it repairs a schema 1 file.
617            Classification::Schema1 if migrate => Self::Rewrite(crate::upgrade::migrate_definition),
618            Classification::Foreign(choice) => Self::Foreign(choice.dialect),
619            _ => Self::None,
620        }
621    }
622}
623
624fn prepare_definition(
625    source: &impl TreeSource,
626    selected: &SelectedDefinition,
627    shaping: Shaping,
628    authored: bool,
629    diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
630    changes: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
631) -> PreparedDefinition {
632    let Some(bytes) = source.read(&selected.source_path) else {
633        return PreparedDefinition {
634            kind: selected.kind,
635            slug: selected.slug.clone(),
636            source_path: selected.source_path.clone(),
637            output_path: selected.output_path.clone(),
638            skill_root: selected.skill_root.clone(),
639            normalized_bytes: Vec::new(),
640            reading: unreadable(
641                selected.kind,
642                SchemaDiagnostic::new(
643                    "definition.read-missing",
644                    Severity::Error,
645                    Vec::new(),
646                    "selected definition could not be read",
647                ),
648            ),
649            change: ChangeRecord::None,
650        };
651    };
652    let (mut notes, mut findings) = (Vec::new(), Vec::new());
653    let (normalized_bytes, change) = match std::str::from_utf8(&bytes) {
654        Ok(text) => match shaping {
655            Shaping::Rewrite(rewrite) => match rewrite(selected.kind, text) {
656                Ok(result) => {
657                    let (rewritten, change, upgrade_notes) = upgrade_result(text, result);
658                    notes = upgrade_notes;
659                    (rewritten, change)
660                }
661                // The reader reports a file that does not parse; the upgrade only met its
662                // error, so a second diagnostic would say the same thing twice.
663                Err(UpgradeError::Frontmatter(_)) => (bytes.clone(), ChangeRecord::None),
664                Err(error) => {
665                    push(
666                        diagnostics,
667                        &selected.source_path,
668                        SchemaDiagnostic::new(
669                            "definition.upgrade-failed",
670                            Severity::Error,
671                            Vec::new(),
672                            error.to_string(),
673                        ),
674                    );
675                    (bytes.clone(), ChangeRecord::None)
676                }
677            },
678            Shaping::Foreign(dialect) => {
679                let translated = translate_foreign(text, dialect, selected, &bytes);
680                notes = translated.changes;
681                findings = translated.findings;
682                (translated.bytes, translated.change)
683            }
684            Shaping::None => (bytes.clone(), ChangeRecord::None),
685        },
686        Err(_) => (bytes.clone(), ChangeRecord::None),
687    };
688    changes
689        .entry(selected.source_path.clone())
690        .or_default()
691        .extend(notes);
692    diagnostics
693        .entry(selected.source_path.clone())
694        .or_default()
695        .extend(findings);
696
697    // Only text is upgraded or translated, so these bytes are the file's when they are not text.
698    let reading = match std::str::from_utf8(&normalized_bytes) {
699        Ok(text) if authored => read_authored(selected.kind, text),
700        Ok(text) => read_definition(selected.kind, text),
701        Err(error) => unreadable(
702            selected.kind,
703            SchemaDiagnostic::new(
704                "text.invalid-utf8",
705                Severity::Error,
706                Vec::new(),
707                format!("definition is not UTF-8: {error}"),
708            ),
709        ),
710    };
711
712    PreparedDefinition {
713        kind: selected.kind,
714        slug: selected.slug.clone(),
715        source_path: selected.source_path.clone(),
716        output_path: selected.output_path.clone(),
717        skill_root: selected.skill_root.clone(),
718        normalized_bytes,
719        reading,
720        change,
721    }
722}
723
724/// What translating one foreign definition produced.
725struct Translated {
726    bytes: Vec<u8>,
727    change: ChangeRecord,
728    /// What the translation dropped, moved or repaired.
729    changes: Vec<SchemaDiagnostic>,
730    /// What it met and could not convert.
731    findings: Vec<SchemaDiagnostic>,
732}
733
734impl Translated {
735    fn untouched(bytes: &[u8]) -> Self {
736        Self {
737            bytes: bytes.to_vec(),
738            change: ChangeRecord::None,
739            changes: Vec::new(),
740            findings: Vec::new(),
741        }
742    }
743}
744
745/// Lift a foreign definition's frontmatter into schema v1. Frontmatter that cannot be read
746/// stays as written, with the reader's error; a Claude definition's unquoted values that YAML
747/// cannot read are quoted first.
748fn translate_foreign(
749    text: &str,
750    dialect: Dialect,
751    selected: &SelectedDefinition,
752    bytes: &[u8],
753) -> Translated {
754    let claude = matches!(dialect, Dialect::Claude | Dialect::AgentSkills);
755    let mut changes = Vec::new();
756    let mut repaired = false;
757    let frontmatter = match Frontmatter::parse(text) {
758        Ok(frontmatter) => frontmatter,
759        Err(FrontmatterError::MalformedYaml(_)) if claude => {
760            match crate::claude::translate::repair_plain_values(text)
761                .and_then(|(fixed, keys)| Some((Frontmatter::parse(&fixed).ok()?, keys)))
762            {
763                Some((frontmatter, keys)) => {
764                    repaired = true;
765                    changes.push(crate::claude::translate::repaired_diagnostic(&keys));
766                    frontmatter
767                }
768                None => return Translated::untouched(bytes),
769            }
770        }
771        Err(_) => return Translated::untouched(bytes),
772    };
773    let lifted = crate::lift::lift_frontmatter(dialect, selected.kind, &frontmatter);
774    changes.extend(lifted.changes);
775    let mut findings = lifted.findings;
776    if claude && selected.kind == DefinitionKind::Skill {
777        findings.extend(crate::claude::checks::skill_checks(
778            selected,
779            &lifted.frontmatter,
780        ));
781    }
782    let (bytes, change) = if lifted.changed || repaired {
783        (
784            lifted.frontmatter.render().into_bytes(),
785            ChangeRecord::FullyRewritten,
786        )
787    } else {
788        (bytes.to_vec(), ChangeRecord::None)
789    };
790    Translated {
791        bytes,
792        change,
793        changes,
794        findings,
795    }
796}
797
798/// A definition with no fields to read, only why.
799fn unreadable(kind: DefinitionKind, diagnostic: SchemaDiagnostic) -> Reading {
800    match kind {
801        DefinitionKind::Agent => Reading::Agent(DefinitionRead::unread(vec![diagnostic])),
802        DefinitionKind::Skill => Reading::Skill(DefinitionRead::unread(vec![diagnostic])),
803    }
804}
805
806fn upgrade_result(
807    original: &str,
808    result: UpgradeResult,
809) -> (Vec<u8>, ChangeRecord, Vec<SchemaDiagnostic>) {
810    let change = if !result.changed_from(original) {
811        ChangeRecord::None
812    } else if result.fully_rewritten {
813        ChangeRecord::FullyRewritten
814    } else {
815        ChangeRecord::Edited {
816            paths: result.edited_paths,
817        }
818    };
819    (result.text.into_bytes(), change, result.diagnostics)
820}
821
822fn push(
823    diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
824    path: &str,
825    diagnostic: SchemaDiagnostic,
826) {
827    diagnostics
828        .entry(path.to_owned())
829        .or_default()
830        .push(diagnostic);
831}