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