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_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 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 authored = matches!(classification, Classification::Schema1);
348 let definitions = if can_read_definitions {
349 selected
350 .iter()
351 .map(|definition| {
352 let mut prepared = prepare_definition(
353 source,
354 definition,
355 shaping,
356 authored,
357 &mut diagnostics,
358 &mut changes,
359 );
360 if let Some(manifest) = &manifest {
361 add_package_tools(&mut prepared, &manifest.reading);
362 }
363 prepared
364 })
365 .collect::<Vec<_>>()
366 } else {
367 Vec::new()
368 };
369 let payload = if can_read_definitions {
370 payload_paths(
371 source,
372 &dispatched.discovery,
373 matches!(classification, Classification::Foreign(_)),
374 selected.iter().copied(),
375 &mut diagnostics,
376 )
377 .into_iter()
378 .map(|(source_path, output_path)| PayloadEntry {
379 source_path,
380 output_path,
381 })
382 .collect()
383 } else {
384 Vec::new()
385 };
386
387 let mut mcp_servers = Vec::new();
388 if can_read_definitions {
389 report_unconverted(source, &dispatched, &mut diagnostics);
390 if let Layout::Claude(spec) = &dispatched.layout
392 && !spec.is_bare_tree()
393 {
394 let imported = crate::claude::mcp::import(source, spec);
395 for (path, diagnostic) in imported.diagnostics {
396 push(&mut diagnostics, &path, diagnostic);
397 }
398 mcp_servers = imported
399 .servers
400 .into_iter()
401 .map(|server| PreparedMcpServer {
402 output_path: format!("mcp/{}/mcp.toml", server.name),
403 normalized_bytes: crate::mcp_server::render_mcp_toml(&server.def).into_bytes(),
404 name: server.name,
405 source_path: server.source_path,
406 })
407 .collect();
408 }
409 }
410 diagnostics.retain(|_, diagnostics| !diagnostics.is_empty());
411 changes.retain(|_, diagnostics| !diagnostics.is_empty());
412 let manifest = manifest.take();
413 let prepared = Prepared {
414 classification,
415 selection: selection_facts(manifest.as_ref(), &definitions),
416 manifest,
417 definitions,
418 mcp_servers,
419 payload,
420 diagnostics,
421 changes,
422 };
423 Rooted {
424 prepared,
425 dispatched,
426 }
427}
428
429fn add_package_tools(
433 definition: &mut PreparedDefinition,
434 manifest: &crate::manifest::ManifestRead,
435) {
436 let Reading::Agent(read) = &mut definition.reading else {
437 return;
438 };
439 if let Some(error) = manifest.first_error() {
442 read.diagnostics.push(SchemaDiagnostic::new(
443 "package-tools.unreadable",
444 Severity::Error,
445 Vec::new(),
446 format!(
447 "the package's mars.toml has an error, so its `[package.tools]` rules cannot be added and `mars sync` refuses the package: {}",
448 error.message
449 ),
450 ));
451 return;
452 }
453 let (Some(package), Some(fields)) = (
454 manifest
455 .package
456 .fields
457 .as_ref()
458 .map(|package| &package.tools),
459 read.fields.as_mut(),
460 ) else {
461 return;
462 };
463 let Some(profile) = std::str::from_utf8(&definition.normalized_bytes)
465 .ok()
466 .and_then(|text| Frontmatter::parse(text).ok())
467 else {
468 return;
469 };
470 for (name, action) in crate::package_tools::missing(&profile, package) {
471 fields.tools.push_unique(
472 ToolRule::from_parsed(name.parsed().clone(), action).with_origin(RuleOrigin::Package),
473 );
474 }
475}
476
477fn report_unconverted(
480 source: &impl TreeSource,
481 dispatched: &Dispatched,
482 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
483) {
484 let Layout::Claude(spec) = &dispatched.layout else {
485 return;
486 };
487 let mut warn = |path: &str, code: &str, message: String| {
488 diagnostics
489 .entry(path.to_owned())
490 .or_default()
491 .push(SchemaDiagnostic::new(
492 code,
493 Severity::Warning,
494 Vec::new(),
495 message,
496 ));
497 };
498 if !dispatched.discovery.dropped.is_empty() {
499 warn(
500 "commands",
501 "import.commands-dropped",
502 format!(
503 "commands are not imported (convert one to a skill): {}",
504 dispatched
505 .discovery
506 .dropped
507 .iter()
508 .map(|command| command.source_path.as_str())
509 .collect::<Vec<_>>()
510 .join(", ")
511 ),
512 );
513 }
514 if spec.is_bare_tree() && source.is_file(".mcp.json") {
515 warn(
516 ".mcp.json",
517 "import.mcp-not-imported",
518 "this is a skill tree, not a Claude plugin (it has no `.claude-plugin/plugin.json`), so its MCP servers were not imported".into(),
519 );
520 }
521 if source.is_file("hooks/hooks.json") || spec.hooks {
522 let path = if source.is_file("hooks/hooks.json") {
523 "hooks/hooks.json"
524 } else {
525 crate::claude::manifest::PLUGIN_MANIFEST
526 };
527 warn(
528 path,
529 "import.hooks-not-converted",
530 "hooks are not converted yet".into(),
531 );
532 }
533}
534
535fn prepare_manifest(
536 bytes: &[u8],
537 upgrade: bool,
538 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
539 changes: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
540) -> PreparedManifest {
541 let invalid_utf8 = std::str::from_utf8(bytes).err().map(|error| {
542 SchemaDiagnostic::new(
543 "text.invalid-utf8",
544 Severity::Error,
545 Vec::new(),
546 format!("mars.toml is not UTF-8: {error}"),
547 )
548 });
549 let (normalized_bytes, change, upgraded) = match std::str::from_utf8(bytes) {
550 Ok(text) if upgrade => match crate::upgrade::upgrade_manifest(text) {
551 Ok(result) => upgrade_result(text, result),
552 Err(error) => {
553 push(
554 diagnostics,
555 "mars.toml",
556 SchemaDiagnostic::new(
557 "manifest.upgrade-failed",
558 Severity::Error,
559 Vec::new(),
560 error.to_string(),
561 ),
562 );
563 (bytes.to_vec(), ChangeRecord::None, Vec::new())
564 }
565 },
566 Ok(_) => (bytes.to_vec(), ChangeRecord::None, Vec::new()),
567 Err(_) => (bytes.to_vec(), ChangeRecord::None, Vec::new()),
568 };
569 changes
570 .entry("mars.toml".to_string())
571 .or_default()
572 .extend(upgraded);
573 let reading = std::str::from_utf8(&normalized_bytes).map_or_else(
574 |_| crate::manifest::ManifestRead::unread(invalid_utf8.into_iter().collect()),
575 crate::manifest::read,
576 );
577 PreparedManifest {
578 source_path: Some("mars.toml".to_string()),
579 output_path: "mars.toml".to_string(),
580 normalized_bytes,
581 reading,
582 change,
583 }
584}
585
586type Rewrite = fn(DefinitionKind, &str) -> Result<UpgradeResult, UpgradeError>;
588
589#[derive(Clone, Copy)]
591enum Shaping {
592 None,
594 Rewrite(Rewrite),
596 Foreign(Dialect),
598}
599
600impl Shaping {
601 fn of(classification: &Classification, migrate: bool) -> Self {
602 match classification {
603 Classification::MarsLegacy => Self::Rewrite(crate::upgrade::upgrade_definition),
604 Classification::Schema1 if migrate => Self::Rewrite(crate::upgrade::migrate_definition),
606 Classification::Foreign(choice) => Self::Foreign(choice.dialect),
607 _ => Self::None,
608 }
609 }
610}
611
612fn prepare_definition(
613 source: &impl TreeSource,
614 selected: &SelectedDefinition,
615 shaping: Shaping,
616 authored: bool,
617 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
618 changes: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
619) -> PreparedDefinition {
620 let Some(bytes) = source.read(&selected.source_path) else {
621 return PreparedDefinition {
622 kind: selected.kind,
623 slug: selected.slug.clone(),
624 source_path: selected.source_path.clone(),
625 output_path: selected.output_path.clone(),
626 skill_root: selected.skill_root.clone(),
627 normalized_bytes: Vec::new(),
628 reading: unreadable(
629 selected.kind,
630 SchemaDiagnostic::new(
631 "definition.read-missing",
632 Severity::Error,
633 Vec::new(),
634 "selected definition could not be read",
635 ),
636 ),
637 change: ChangeRecord::None,
638 };
639 };
640 let (mut notes, mut findings) = (Vec::new(), Vec::new());
641 let (normalized_bytes, change) = match std::str::from_utf8(&bytes) {
642 Ok(text) => match shaping {
643 Shaping::Rewrite(rewrite) => match rewrite(selected.kind, text) {
644 Ok(result) => {
645 let (rewritten, change, upgrade_notes) = upgrade_result(text, result);
646 notes = upgrade_notes;
647 (rewritten, change)
648 }
649 Err(UpgradeError::Frontmatter(_)) => (bytes.clone(), ChangeRecord::None),
652 Err(error) => {
653 push(
654 diagnostics,
655 &selected.source_path,
656 SchemaDiagnostic::new(
657 "definition.upgrade-failed",
658 Severity::Error,
659 Vec::new(),
660 error.to_string(),
661 ),
662 );
663 (bytes.clone(), ChangeRecord::None)
664 }
665 },
666 Shaping::Foreign(dialect) => {
667 let translated = translate_foreign(text, dialect, selected, &bytes);
668 notes = translated.changes;
669 findings = translated.findings;
670 (translated.bytes, translated.change)
671 }
672 Shaping::None => (bytes.clone(), ChangeRecord::None),
673 },
674 Err(_) => (bytes.clone(), ChangeRecord::None),
675 };
676 changes
677 .entry(selected.source_path.clone())
678 .or_default()
679 .extend(notes);
680 diagnostics
681 .entry(selected.source_path.clone())
682 .or_default()
683 .extend(findings);
684
685 let reading = match std::str::from_utf8(&normalized_bytes) {
687 Ok(text) if authored => read_authored(selected.kind, text),
688 Ok(text) => read_definition(selected.kind, text),
689 Err(error) => unreadable(
690 selected.kind,
691 SchemaDiagnostic::new(
692 "text.invalid-utf8",
693 Severity::Error,
694 Vec::new(),
695 format!("definition is not UTF-8: {error}"),
696 ),
697 ),
698 };
699
700 PreparedDefinition {
701 kind: selected.kind,
702 slug: selected.slug.clone(),
703 source_path: selected.source_path.clone(),
704 output_path: selected.output_path.clone(),
705 skill_root: selected.skill_root.clone(),
706 normalized_bytes,
707 reading,
708 change,
709 }
710}
711
712struct Translated {
714 bytes: Vec<u8>,
715 change: ChangeRecord,
716 changes: Vec<SchemaDiagnostic>,
718 findings: Vec<SchemaDiagnostic>,
720}
721
722impl Translated {
723 fn untouched(bytes: &[u8]) -> Self {
724 Self {
725 bytes: bytes.to_vec(),
726 change: ChangeRecord::None,
727 changes: Vec::new(),
728 findings: Vec::new(),
729 }
730 }
731}
732
733fn translate_foreign(
737 text: &str,
738 dialect: Dialect,
739 selected: &SelectedDefinition,
740 bytes: &[u8],
741) -> Translated {
742 let claude = matches!(dialect, Dialect::Claude | Dialect::AgentSkills);
743 let mut changes = Vec::new();
744 let mut repaired = false;
745 let frontmatter = match Frontmatter::parse(text) {
746 Ok(frontmatter) => frontmatter,
747 Err(_) if claude && selected.kind == DefinitionKind::Skill => {
748 match crate::claude::translate::repair_description(text)
749 .and_then(|fixed| Frontmatter::parse(&fixed).ok())
750 {
751 Some(frontmatter) => {
752 repaired = true;
753 changes.push(crate::claude::translate::repaired_diagnostic());
754 frontmatter
755 }
756 None => return Translated::untouched(bytes),
757 }
758 }
759 Err(_) => return Translated::untouched(bytes),
760 };
761 let lifted = crate::lift::lift_frontmatter(dialect, selected.kind, &frontmatter);
762 changes.extend(lifted.changes);
763 let mut findings = lifted.findings;
764 if claude && selected.kind == DefinitionKind::Skill {
765 findings.extend(crate::claude::checks::skill_checks(
766 selected,
767 &lifted.frontmatter,
768 ));
769 }
770 let (bytes, change) = if lifted.changed || repaired {
771 (
772 lifted.frontmatter.render().into_bytes(),
773 ChangeRecord::FullyRewritten,
774 )
775 } else {
776 (bytes.to_vec(), ChangeRecord::None)
777 };
778 Translated {
779 bytes,
780 change,
781 changes,
782 findings,
783 }
784}
785
786fn unreadable(kind: DefinitionKind, diagnostic: SchemaDiagnostic) -> Reading {
788 match kind {
789 DefinitionKind::Agent => Reading::Agent(DefinitionRead::unread(vec![diagnostic])),
790 DefinitionKind::Skill => Reading::Skill(DefinitionRead::unread(vec![diagnostic])),
791 }
792}
793
794fn upgrade_result(
795 original: &str,
796 result: UpgradeResult,
797) -> (Vec<u8>, ChangeRecord, Vec<SchemaDiagnostic>) {
798 let change = if !result.changed_from(original) {
799 ChangeRecord::None
800 } else if result.fully_rewritten {
801 ChangeRecord::FullyRewritten
802 } else {
803 ChangeRecord::Edited {
804 paths: result.edited_paths,
805 }
806 };
807 (result.text.into_bytes(), change, result.diagnostics)
808}
809
810fn push(
811 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
812 path: &str,
813 diagnostic: SchemaDiagnostic,
814) {
815 diagnostics
816 .entry(path.to_owned())
817 .or_default()
818 .push(diagnostic);
819}