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, 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 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 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 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 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#[derive(Default, Clone, Copy)]
272pub(crate) struct RootOptions<'a> {
273 pub as_plugin: Option<AsPlugin<'a>>,
274 pub selection: Option<&'a BTreeSet<String>>,
276 pub fallback_name: Option<&'a str>,
278 pub migrate: bool,
283}
284
285pub(crate) struct Rooted {
287 pub prepared: Prepared,
288 pub dispatched: Dispatched,
289}
290
291pub 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
300pub 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 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
441fn 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 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 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
489fn 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
598type Rewrite = fn(DefinitionKind, &str) -> Result<UpgradeResult, UpgradeError>;
600
601#[derive(Clone, Copy)]
603enum Shaping {
604 None,
606 Rewrite(Rewrite),
608 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 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 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 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
724struct Translated {
726 bytes: Vec<u8>,
727 change: ChangeRecord,
728 changes: Vec<SchemaDiagnostic>,
730 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
745fn 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
798fn 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}