1use 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 Package,
25 AuthoredLocal,
28 Project,
31}
32
33pub const LOCAL_SOURCE_DIR: &str = ".mars-src";
35
36pub 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#[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 Foreign(DialectChoice),
63 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 Generated,
74 Edited {
75 paths: Vec<Vec<PathSegment>>,
76 },
77 FullyRewritten,
78}
79
80#[derive(Debug, Clone, Serialize)]
81pub struct PreparedManifest {
82 #[serde(skip_serializing_if = "Option::is_none")]
84 pub source_path: Option<String>,
85 pub output_path: String,
86 #[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 #[serde(skip)]
101 pub skill_root: Option<String>,
102 #[serde(with = "serde_bytes")]
104 pub normalized_bytes: Vec<u8>,
105 pub reading: Reading,
107 pub change: ChangeRecord,
108}
109
110#[derive(Debug, Clone, Serialize)]
113pub struct PreparedMcpServer {
114 pub name: String,
115 pub source_path: String,
117 pub output_path: String,
118 #[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 #[serde(skip_serializing_if = "Vec::is_empty")]
137 pub mcp_servers: Vec<PreparedMcpServer>,
138 pub payload: Vec<PayloadEntry>,
139 pub selection: SelectionFacts,
141 pub diagnostics: BTreeMap<String, Vec<SchemaDiagnostic>>,
145 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
149 pub changes: BTreeMap<String, Vec<SchemaDiagnostic>>,
150}
151
152pub(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 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 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 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 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#[derive(Default, Clone, Copy)]
259pub(crate) struct RootOptions<'a> {
260 pub as_plugin: Option<AsPlugin<'a>>,
261 pub selection: Option<&'a BTreeSet<String>>,
263 pub fallback_name: Option<&'a str>,
265 pub migrate: bool,
270}
271
272pub(crate) struct Rooted {
274 pub prepared: Prepared,
275 pub dispatched: Dispatched,
276}
277
278pub 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
287pub 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 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
415fn 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
524type Rewrite = fn(DefinitionKind, &str) -> Result<UpgradeResult, UpgradeError>;
526
527#[derive(Clone, Copy)]
529enum Shaping {
530 None,
532 Rewrite(Rewrite),
534 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 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 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 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
650struct Translated {
652 bytes: Vec<u8>,
653 change: ChangeRecord,
654 changes: Vec<SchemaDiagnostic>,
656 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
671fn 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
724fn 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}