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::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 Package,
26 AuthoredLocal,
29 Project,
32}
33
34pub const LOCAL_SOURCE_DIR: &str = ".mars-src";
36
37pub 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#[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 Foreign(DialectChoice),
64 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 Generated,
75 Edited {
76 paths: Vec<Vec<PathSegment>>,
77 },
78 FullyRewritten,
79}
80
81#[derive(Debug, Clone, Serialize)]
82pub struct PreparedManifest {
83 #[serde(skip_serializing_if = "Option::is_none")]
85 pub source_path: Option<String>,
86 pub output_path: String,
87 #[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 #[serde(skip)]
102 pub skill_root: Option<String>,
103 #[serde(with = "serde_bytes")]
105 pub normalized_bytes: Vec<u8>,
106 pub reading: Reading,
108 pub change: ChangeRecord,
109}
110
111#[derive(Debug, Clone, Serialize)]
114pub struct PreparedMcpServer {
115 pub name: String,
116 pub source_path: String,
118 pub output_path: String,
119 #[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 #[serde(skip_serializing_if = "Vec::is_empty")]
138 pub mcp_servers: Vec<PreparedMcpServer>,
139 pub payload: Vec<PayloadEntry>,
140 pub selection: SelectionFacts,
142 pub diagnostics: BTreeMap<String, Vec<SchemaDiagnostic>>,
146 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
150 pub changes: BTreeMap<String, Vec<SchemaDiagnostic>>,
151}
152
153pub(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 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 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 pub fn changed_files(&self) -> usize {
226 self.manifest
227 .iter()
228 .map(|manifest| &manifest.change)
229 .chain(self.definitions.iter().map(|definition| &definition.change))
230 .filter(|change| !matches!(change, ChangeRecord::None | ChangeRecord::Generated))
231 .count()
232 }
233
234 pub fn all_diagnostics(&self) -> BTreeMap<&str, Vec<&SchemaDiagnostic>> {
236 let mut all: BTreeMap<&str, Vec<&SchemaDiagnostic>> = BTreeMap::new();
237 for (path, diagnostics) in &self.diagnostics {
238 all.entry(path).or_default().extend(diagnostics);
239 }
240 if let Some(manifest) = &self.manifest
241 && let Some(path) = &manifest.source_path
242 {
243 all.entry(path)
244 .or_default()
245 .extend(&manifest.reading.package.diagnostics);
246 }
247 for definition in &self.definitions {
248 all.entry(&definition.source_path)
249 .or_default()
250 .extend(definition.reading.diagnostics());
251 }
252 all.retain(|_, diagnostics| !diagnostics.is_empty());
253 all
254 }
255}
256
257#[derive(Default, Clone, Copy)]
260pub(crate) struct RootOptions<'a> {
261 pub as_plugin: Option<AsPlugin<'a>>,
262 pub selection: Option<&'a BTreeSet<String>>,
264 pub fallback_name: Option<&'a str>,
266 pub migrate: bool,
271}
272
273pub(crate) struct Rooted {
275 pub prepared: Prepared,
276 pub dispatched: Dispatched,
277}
278
279pub fn prepare(
281 source: &impl TreeSource,
282 context: PrepareContext,
283 declared_dialect: Option<Dialect>,
284) -> Prepared {
285 prepare_root(source, context, declared_dialect, RootOptions::default()).prepared
286}
287
288pub fn prepare_for_migration(
291 source: &impl TreeSource,
292 context: PrepareContext,
293 declared_dialect: Option<Dialect>,
294) -> Prepared {
295 let options = RootOptions {
296 migrate: true,
297 ..RootOptions::default()
298 };
299 prepare_root(source, context, declared_dialect, options).prepared
300}
301
302pub(crate) fn prepare_root(
303 source: &impl TreeSource,
304 context: PrepareContext,
305 declared_dialect: Option<Dialect>,
306 options: RootOptions<'_>,
307) -> Rooted {
308 let mut dispatched = dispatch(
309 source,
310 context,
311 declared_dialect,
312 options.as_plugin,
313 options.fallback_name,
314 );
315 let classification = dispatched.classification.clone();
316 let manifest_bytes = dispatched.manifest.take();
317 let mut diagnostics = std::mem::take(&mut dispatched.discovery.diagnostics);
318 let mut changes = BTreeMap::new();
319
320 let mut manifest = manifest_bytes.as_deref().map(|bytes| {
321 prepare_manifest(
322 bytes,
323 classification == Classification::MarsLegacy
324 || (options.migrate && classification == Classification::Schema1),
325 &mut diagnostics,
326 &mut changes,
327 )
328 });
329
330 let can_read_definitions = !matches!(
331 classification,
332 Classification::Invalid
333 | Classification::SchemaNewer { .. }
334 | Classification::Empty
335 | Classification::Marketplace
336 );
337 let all = &dispatched.discovery.definitions;
338 let selected = all
339 .iter()
340 .filter(|definition| {
341 options
342 .selection
343 .is_none_or(|selection| selection.contains(&definition.source_path))
344 })
345 .collect::<Vec<_>>();
346 let shaping = Shaping::of(&classification, options.migrate);
347 let definitions = if can_read_definitions {
348 selected
349 .iter()
350 .map(|definition| {
351 let mut prepared =
352 prepare_definition(source, definition, shaping, &mut diagnostics, &mut changes);
353 if let Some(manifest) = &manifest {
354 add_package_tools(&mut prepared, &manifest.reading);
355 }
356 prepared
357 })
358 .collect::<Vec<_>>()
359 } else {
360 Vec::new()
361 };
362 let payload = if can_read_definitions {
363 payload_paths(
364 source,
365 &dispatched.discovery,
366 matches!(classification, Classification::Foreign(_)),
367 selected.iter().copied(),
368 &mut diagnostics,
369 )
370 .into_iter()
371 .map(|(source_path, output_path)| PayloadEntry {
372 source_path,
373 output_path,
374 })
375 .collect()
376 } else {
377 Vec::new()
378 };
379
380 let mut mcp_servers = Vec::new();
381 if can_read_definitions {
382 report_unconverted(source, &dispatched, &mut diagnostics);
383 if let Layout::Claude(spec) = &dispatched.layout
385 && !spec.is_bare_tree()
386 {
387 let imported = crate::claude::mcp::import(source, spec);
388 for (path, diagnostic) in imported.diagnostics {
389 push(&mut diagnostics, &path, diagnostic);
390 }
391 mcp_servers = imported
392 .servers
393 .into_iter()
394 .map(|server| PreparedMcpServer {
395 output_path: format!("mcp/{}/mcp.toml", server.name),
396 normalized_bytes: crate::mcp_server::render_mcp_toml(&server.def).into_bytes(),
397 name: server.name,
398 source_path: server.source_path,
399 })
400 .collect();
401 }
402 }
403 diagnostics.retain(|_, diagnostics| !diagnostics.is_empty());
404 changes.retain(|_, diagnostics| !diagnostics.is_empty());
405 let manifest = manifest.take();
406 let prepared = Prepared {
407 classification,
408 selection: selection_facts(manifest.as_ref(), &definitions),
409 manifest,
410 definitions,
411 mcp_servers,
412 payload,
413 diagnostics,
414 changes,
415 };
416 Rooted {
417 prepared,
418 dispatched,
419 }
420}
421
422fn add_package_tools(
426 definition: &mut PreparedDefinition,
427 manifest: &crate::manifest::ManifestRead,
428) {
429 let Reading::Agent(read) = &mut definition.reading else {
430 return;
431 };
432 if let Some(error) = manifest.first_error() {
435 read.diagnostics.push(SchemaDiagnostic::new(
436 "package-tools.unreadable",
437 Severity::Error,
438 Vec::new(),
439 format!(
440 "the package's mars.toml has an error, so its `[package.tools]` rules cannot be added and `mars sync` refuses the package: {}",
441 error.message
442 ),
443 ));
444 return;
445 }
446 let (Some(package), Some(fields)) = (
447 manifest
448 .package
449 .fields
450 .as_ref()
451 .map(|package| &package.tools),
452 read.fields.as_mut(),
453 ) else {
454 return;
455 };
456 let Some(profile) = std::str::from_utf8(&definition.normalized_bytes)
458 .ok()
459 .and_then(|text| Frontmatter::parse(text).ok())
460 else {
461 return;
462 };
463 for (name, action) in crate::package_tools::missing(&profile, package) {
464 fields.tools.push_unique(
465 ToolRule::from_parsed(name.parsed().clone(), action).with_origin(RuleOrigin::Package),
466 );
467 }
468}
469
470fn report_unconverted(
473 source: &impl TreeSource,
474 dispatched: &Dispatched,
475 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
476) {
477 let Layout::Claude(spec) = &dispatched.layout else {
478 return;
479 };
480 let mut warn = |path: &str, code: &str, message: String| {
481 diagnostics
482 .entry(path.to_owned())
483 .or_default()
484 .push(SchemaDiagnostic::new(
485 code,
486 Severity::Warning,
487 Vec::new(),
488 message,
489 ));
490 };
491 if !dispatched.discovery.dropped.is_empty() {
492 warn(
493 "commands",
494 "import.commands-dropped",
495 format!(
496 "commands are not imported (convert one to a skill): {}",
497 dispatched
498 .discovery
499 .dropped
500 .iter()
501 .map(|command| command.source_path.as_str())
502 .collect::<Vec<_>>()
503 .join(", ")
504 ),
505 );
506 }
507 if spec.is_bare_tree() && source.is_file(".mcp.json") {
508 warn(
509 ".mcp.json",
510 "import.mcp-not-imported",
511 "this is a skill tree, not a Claude plugin (it has no `.claude-plugin/plugin.json`), so its MCP servers were not imported".into(),
512 );
513 }
514 if source.is_file("hooks/hooks.json") || spec.hooks {
515 let path = if source.is_file("hooks/hooks.json") {
516 "hooks/hooks.json"
517 } else {
518 crate::claude::manifest::PLUGIN_MANIFEST
519 };
520 warn(
521 path,
522 "import.hooks-not-converted",
523 "hooks are not converted yet".into(),
524 );
525 }
526}
527
528fn prepare_manifest(
529 bytes: &[u8],
530 upgrade: bool,
531 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
532 changes: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
533) -> PreparedManifest {
534 let invalid_utf8 = std::str::from_utf8(bytes).err().map(|error| {
535 SchemaDiagnostic::new(
536 "text.invalid-utf8",
537 Severity::Error,
538 Vec::new(),
539 format!("mars.toml is not UTF-8: {error}"),
540 )
541 });
542 let (normalized_bytes, change, upgraded) = match std::str::from_utf8(bytes) {
543 Ok(text) if upgrade => match crate::upgrade::upgrade_manifest(text) {
544 Ok(result) => upgrade_result(text, result),
545 Err(error) => {
546 push(
547 diagnostics,
548 "mars.toml",
549 SchemaDiagnostic::new(
550 "manifest.upgrade-failed",
551 Severity::Error,
552 Vec::new(),
553 error.to_string(),
554 ),
555 );
556 (bytes.to_vec(), ChangeRecord::None, Vec::new())
557 }
558 },
559 Ok(_) => (bytes.to_vec(), ChangeRecord::None, Vec::new()),
560 Err(_) => (bytes.to_vec(), ChangeRecord::None, Vec::new()),
561 };
562 changes
563 .entry("mars.toml".to_string())
564 .or_default()
565 .extend(upgraded);
566 let reading = std::str::from_utf8(&normalized_bytes).map_or_else(
567 |_| crate::manifest::ManifestRead::unread(invalid_utf8.into_iter().collect()),
568 crate::manifest::read,
569 );
570 PreparedManifest {
571 source_path: Some("mars.toml".to_string()),
572 output_path: "mars.toml".to_string(),
573 normalized_bytes,
574 reading,
575 change,
576 }
577}
578
579type Rewrite = fn(DefinitionKind, &str) -> Result<UpgradeResult, UpgradeError>;
581
582#[derive(Clone, Copy)]
584enum Shaping {
585 None,
587 Rewrite(Rewrite),
589 Foreign(Dialect),
591}
592
593impl Shaping {
594 fn of(classification: &Classification, migrate: bool) -> Self {
595 match classification {
596 Classification::MarsLegacy => Self::Rewrite(crate::upgrade::upgrade_definition),
597 Classification::Schema1 if migrate => Self::Rewrite(crate::upgrade::migrate_definition),
599 Classification::Foreign(choice) => Self::Foreign(choice.dialect),
600 _ => Self::None,
601 }
602 }
603}
604
605fn prepare_definition(
606 source: &impl TreeSource,
607 selected: &SelectedDefinition,
608 shaping: Shaping,
609 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
610 changes: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
611) -> PreparedDefinition {
612 let Some(bytes) = source.read(&selected.source_path) else {
613 return PreparedDefinition {
614 kind: selected.kind,
615 slug: selected.slug.clone(),
616 source_path: selected.source_path.clone(),
617 output_path: selected.output_path.clone(),
618 skill_root: selected.skill_root.clone(),
619 normalized_bytes: Vec::new(),
620 reading: unreadable(
621 selected.kind,
622 SchemaDiagnostic::new(
623 "definition.read-missing",
624 Severity::Error,
625 Vec::new(),
626 "selected definition could not be read",
627 ),
628 ),
629 change: ChangeRecord::None,
630 };
631 };
632 let (mut notes, mut findings) = (Vec::new(), Vec::new());
633 let (normalized_bytes, change) = match std::str::from_utf8(&bytes) {
634 Ok(text) => match shaping {
635 Shaping::Rewrite(rewrite) => match rewrite(selected.kind, text) {
636 Ok(result) => {
637 let (rewritten, change, upgrade_notes) = upgrade_result(text, result);
638 notes = upgrade_notes;
639 (rewritten, change)
640 }
641 Err(UpgradeError::Frontmatter(_)) => (bytes.clone(), ChangeRecord::None),
644 Err(error) => {
645 push(
646 diagnostics,
647 &selected.source_path,
648 SchemaDiagnostic::new(
649 "definition.upgrade-failed",
650 Severity::Error,
651 Vec::new(),
652 error.to_string(),
653 ),
654 );
655 (bytes.clone(), ChangeRecord::None)
656 }
657 },
658 Shaping::Foreign(dialect) => {
659 let translated = translate_foreign(text, dialect, selected, &bytes);
660 notes = translated.changes;
661 findings = translated.findings;
662 (translated.bytes, translated.change)
663 }
664 Shaping::None => (bytes.clone(), ChangeRecord::None),
665 },
666 Err(_) => (bytes.clone(), ChangeRecord::None),
667 };
668 changes
669 .entry(selected.source_path.clone())
670 .or_default()
671 .extend(notes);
672 diagnostics
673 .entry(selected.source_path.clone())
674 .or_default()
675 .extend(findings);
676
677 let reading = match std::str::from_utf8(&normalized_bytes) {
679 Ok(text) => read_definition(selected.kind, text),
680 Err(error) => unreadable(
681 selected.kind,
682 SchemaDiagnostic::new(
683 "text.invalid-utf8",
684 Severity::Error,
685 Vec::new(),
686 format!("definition is not UTF-8: {error}"),
687 ),
688 ),
689 };
690
691 PreparedDefinition {
692 kind: selected.kind,
693 slug: selected.slug.clone(),
694 source_path: selected.source_path.clone(),
695 output_path: selected.output_path.clone(),
696 skill_root: selected.skill_root.clone(),
697 normalized_bytes,
698 reading,
699 change,
700 }
701}
702
703struct Translated {
705 bytes: Vec<u8>,
706 change: ChangeRecord,
707 changes: Vec<SchemaDiagnostic>,
709 findings: Vec<SchemaDiagnostic>,
711}
712
713impl Translated {
714 fn untouched(bytes: &[u8]) -> Self {
715 Self {
716 bytes: bytes.to_vec(),
717 change: ChangeRecord::None,
718 changes: Vec::new(),
719 findings: Vec::new(),
720 }
721 }
722}
723
724fn translate_foreign(
728 text: &str,
729 dialect: Dialect,
730 selected: &SelectedDefinition,
731 bytes: &[u8],
732) -> Translated {
733 let claude = matches!(dialect, Dialect::Claude | Dialect::AgentSkills);
734 let mut changes = Vec::new();
735 let mut repaired = false;
736 let frontmatter = match Frontmatter::parse(text) {
737 Ok(frontmatter) => frontmatter,
738 Err(_) if claude && selected.kind == DefinitionKind::Skill => {
739 match crate::claude::translate::repair_description(text)
740 .and_then(|fixed| Frontmatter::parse(&fixed).ok())
741 {
742 Some(frontmatter) => {
743 repaired = true;
744 changes.push(crate::claude::translate::repaired_diagnostic());
745 frontmatter
746 }
747 None => return Translated::untouched(bytes),
748 }
749 }
750 Err(_) => return Translated::untouched(bytes),
751 };
752 let lifted = crate::lift::lift_frontmatter(dialect, selected.kind, &frontmatter);
753 changes.extend(lifted.changes);
754 let mut findings = lifted.findings;
755 if claude && selected.kind == DefinitionKind::Skill {
756 findings.extend(crate::claude::checks::skill_checks(
757 selected,
758 &lifted.frontmatter,
759 ));
760 }
761 let (bytes, change) = if lifted.changed || repaired {
762 (
763 lifted.frontmatter.render().into_bytes(),
764 ChangeRecord::FullyRewritten,
765 )
766 } else {
767 (bytes.to_vec(), ChangeRecord::None)
768 };
769 Translated {
770 bytes,
771 change,
772 changes,
773 findings,
774 }
775}
776
777fn unreadable(kind: DefinitionKind, diagnostic: SchemaDiagnostic) -> Reading {
779 match kind {
780 DefinitionKind::Agent => Reading::Agent(DefinitionRead::unread(vec![diagnostic])),
781 DefinitionKind::Skill => Reading::Skill(DefinitionRead::unread(vec![diagnostic])),
782 }
783}
784
785fn upgrade_result(
786 original: &str,
787 result: UpgradeResult,
788) -> (Vec<u8>, ChangeRecord, Vec<SchemaDiagnostic>) {
789 let change = if !result.changed_from(original) {
790 ChangeRecord::None
791 } else if result.fully_rewritten {
792 ChangeRecord::FullyRewritten
793 } else {
794 ChangeRecord::Edited {
795 paths: result.edited_paths,
796 }
797 };
798 (result.text.into_bytes(), change, result.diagnostics)
799}
800
801fn push(
802 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
803 path: &str,
804 diagnostic: SchemaDiagnostic,
805) {
806 diagnostics
807 .entry(path.to_owned())
808 .or_default()
809 .push(diagnostic);
810}