1use std::collections::{BTreeMap, BTreeSet};
4
5use serde::{Deserialize, Serialize};
6
7use crate::diagnostic::{SchemaDiagnostic, Severity};
8use crate::dialect::{Dialect, DialectChoice};
9use crate::discover::{SelectedDefinition, payload_paths};
10use crate::dispatch::{AsPlugin, Dispatched, Layout, dispatch};
11use crate::frontmatter::{Frontmatter, FrontmatterError};
12use crate::item::DefinitionKind;
13use crate::read::{DefinitionRead, Reading, read_authored, read_definition};
14use crate::selection::{Definition, Request, SelectionFacts};
15use crate::tool_policy::{RuleOrigin, ToolRule};
16use crate::tree::TreeSource;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "kebab-case")]
20pub enum PrepareContext {
21 Package,
24 AuthoredLocal,
27 Project,
30}
31
32pub const LOCAL_SOURCE_DIR: &str = ".mars-src";
34
35#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
37#[serde(tag = "kind", rename_all = "kebab-case")]
38pub enum Classification {
39 #[serde(rename = "schema-1")]
40 Schema1,
41 SchemaNewer {
42 schema: u64,
43 },
44 Invalid,
45 Foreign(DialectChoice),
47 Marketplace,
49 Empty,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
53#[serde(tag = "kind", rename_all = "kebab-case")]
54pub enum ChangeRecord {
55 None,
56 Generated,
58 FullyRewritten,
59}
60
61#[derive(Debug, Clone, Serialize)]
62pub struct PreparedManifest {
63 #[serde(skip_serializing_if = "Option::is_none")]
65 pub source_path: Option<String>,
66 pub output_path: String,
67 #[serde(with = "serde_bytes")]
69 pub normalized_bytes: Vec<u8>,
70 pub reading: crate::manifest::ManifestRead,
71 pub change: ChangeRecord,
72}
73
74#[derive(Debug, Clone, Serialize)]
75pub struct PreparedDefinition {
76 pub kind: DefinitionKind,
77 pub slug: String,
78 pub source_path: String,
79 pub output_path: String,
80 #[serde(skip)]
82 pub skill_root: Option<String>,
83 #[serde(with = "serde_bytes")]
85 pub normalized_bytes: Vec<u8>,
86 pub reading: Reading,
88 pub change: ChangeRecord,
89}
90
91#[derive(Debug, Clone, Serialize)]
94pub struct PreparedMcpServer {
95 pub name: String,
96 pub source_path: String,
98 pub output_path: String,
99 #[serde(with = "serde_bytes")]
101 pub normalized_bytes: Vec<u8>,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
105pub struct PayloadEntry {
106 pub source_path: String,
107 pub output_path: String,
108}
109
110#[derive(Debug, Clone, Serialize)]
111pub struct Prepared {
112 pub classification: Classification,
113 #[serde(skip_serializing_if = "Option::is_none")]
114 pub manifest: Option<PreparedManifest>,
115 pub definitions: Vec<PreparedDefinition>,
116 #[serde(skip_serializing_if = "Vec::is_empty")]
118 pub mcp_servers: Vec<PreparedMcpServer>,
119 pub payload: Vec<PayloadEntry>,
120 pub selection: SelectionFacts,
122 pub diagnostics: BTreeMap<String, Vec<SchemaDiagnostic>>,
126 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
129 pub changes: BTreeMap<String, Vec<SchemaDiagnostic>>,
130}
131
132pub(crate) fn selection_facts(
135 classification: &Classification,
136 manifest: Option<&PreparedManifest>,
137 definitions: &[PreparedDefinition],
138) -> SelectionFacts {
139 let reading = manifest.map(|manifest| &manifest.reading);
140 SelectionFacts {
141 definitions: definitions
142 .iter()
143 .map(|definition| Definition {
144 kind: definition.kind,
145 slug: definition.slug.clone(),
146 output_path: definition.output_path.clone(),
147 skills: match &definition.reading {
148 Reading::Agent(read) => read
149 .fields
150 .as_ref()
151 .map(|profile| profile.skills.all())
152 .unwrap_or_default(),
153 _ => Vec::new(),
154 },
155 })
156 .collect(),
157 edges: reading
158 .map(|reading| {
159 reading
160 .dependencies
161 .dependencies
162 .iter()
163 .map(|(name, entry)| Request {
164 name: name.clone(),
165 filter: entry.filter.to_mode(),
166 })
167 .collect()
168 })
169 .unwrap_or_default(),
170 uses_providers: reading
171 .and_then(|reading| reading.package.fields.as_ref())
172 .map(|package| package.uses_providers.clone())
173 .unwrap_or_default(),
174 unreadable: matches!(
175 classification,
176 Classification::Invalid | Classification::SchemaNewer { .. }
177 ),
178 }
179}
180
181impl Prepared {
182 pub fn lost_restrictions(&self) -> impl Iterator<Item = (&str, &SchemaDiagnostic)> {
186 self.changes.iter().flat_map(|(path, changes)| {
187 changes
188 .iter()
189 .filter(|change| change.code == crate::set_aside::RESTRICTION_LOST)
190 .map(move |change| (path.as_str(), change))
191 })
192 }
193
194 pub fn ignored_execution_fields(&self) -> impl Iterator<Item = (&str, &SchemaDiagnostic)> {
198 self.changes.iter().flat_map(|(path, changes)| {
199 changes
200 .iter()
201 .filter(|change| change.code == crate::set_aside::EXECUTION_IGNORED)
202 .map(move |change| (path.as_str(), change))
203 })
204 }
205
206 pub fn repaired_values(&self) -> impl Iterator<Item = (&str, &SchemaDiagnostic)> {
210 self.changes.iter().flat_map(|(path, changes)| {
211 changes
212 .iter()
213 .filter(|change| change.code == crate::claude::translate::REPAIRED)
214 .map(move |change| (path.as_str(), change))
215 })
216 }
217
218 pub fn changed_files(&self) -> usize {
221 self.manifest
222 .iter()
223 .map(|manifest| &manifest.change)
224 .chain(self.definitions.iter().map(|definition| &definition.change))
225 .filter(|change| !matches!(change, ChangeRecord::None | ChangeRecord::Generated))
226 .count()
227 }
228
229 pub fn all_diagnostics(&self) -> BTreeMap<&str, Vec<&SchemaDiagnostic>> {
231 let mut all: BTreeMap<&str, Vec<&SchemaDiagnostic>> = BTreeMap::new();
232 for (path, diagnostics) in &self.diagnostics {
233 all.entry(path).or_default().extend(diagnostics);
234 }
235 if let Some(manifest) = &self.manifest
236 && let Some(path) = &manifest.source_path
237 {
238 all.entry(path)
239 .or_default()
240 .extend(&manifest.reading.package.diagnostics);
241 }
242 for definition in &self.definitions {
243 all.entry(&definition.source_path)
244 .or_default()
245 .extend(definition.reading.diagnostics());
246 }
247 all.retain(|_, diagnostics| !diagnostics.is_empty());
248 all
249 }
250}
251
252#[derive(Default, Clone, Copy)]
255pub(crate) struct RootOptions<'a> {
256 pub as_plugin: Option<AsPlugin<'a>>,
257 pub selection: Option<&'a BTreeSet<String>>,
259 pub fallback_name: Option<&'a str>,
261}
262
263pub(crate) struct Rooted {
265 pub prepared: Prepared,
266 pub dispatched: Dispatched,
267}
268
269pub fn prepare(
271 source: &impl TreeSource,
272 context: PrepareContext,
273 declared_dialect: Option<Dialect>,
274) -> Prepared {
275 prepare_root(source, context, declared_dialect, RootOptions::default()).prepared
276}
277
278pub(crate) fn prepare_root(
279 source: &impl TreeSource,
280 context: PrepareContext,
281 declared_dialect: Option<Dialect>,
282 options: RootOptions<'_>,
283) -> Rooted {
284 let mut dispatched = dispatch(
285 source,
286 context,
287 declared_dialect,
288 options.as_plugin,
289 options.fallback_name,
290 );
291 let classification = dispatched.classification.clone();
292 let manifest_bytes = dispatched.manifest.take();
293 let mut diagnostics = std::mem::take(&mut dispatched.discovery.diagnostics);
294 let mut changes = BTreeMap::new();
295
296 let mut manifest = manifest_bytes.as_deref().map(prepare_manifest);
297
298 let can_read_definitions = !matches!(
299 classification,
300 Classification::Invalid
301 | Classification::SchemaNewer { .. }
302 | Classification::Empty
303 | Classification::Marketplace
304 );
305 let all = &dispatched.discovery.definitions;
306 let selected = all
307 .iter()
308 .filter(|definition| {
309 options
310 .selection
311 .is_none_or(|selection| selection.contains(&definition.source_path))
312 })
313 .collect::<Vec<_>>();
314 let authored = matches!(classification, Classification::Schema1);
315 let definitions = if can_read_definitions {
316 selected
317 .iter()
318 .map(|definition| {
319 let mut prepared = prepare_definition(
320 source,
321 definition,
322 &classification,
323 authored,
324 &mut diagnostics,
325 &mut changes,
326 );
327 if let Some(manifest) = &manifest {
328 add_package_tools(&mut prepared, &manifest.reading);
329 }
330 prepared
331 })
332 .collect::<Vec<_>>()
333 } else {
334 Vec::new()
335 };
336 let payload = if can_read_definitions {
337 payload_paths(
338 source,
339 &dispatched.discovery,
340 matches!(classification, Classification::Foreign(_)),
341 selected.iter().copied(),
342 &mut diagnostics,
343 )
344 .into_iter()
345 .map(|(source_path, output_path)| PayloadEntry {
346 source_path,
347 output_path,
348 })
349 .collect()
350 } else {
351 Vec::new()
352 };
353
354 let mut mcp_servers = Vec::new();
355 if can_read_definitions {
356 report_unconverted(source, &dispatched, &mut diagnostics);
357 if let Layout::Claude(spec) = &dispatched.layout
359 && !spec.is_bare_tree()
360 {
361 let imported = crate::claude::mcp::import(source, spec);
362 for (path, diagnostic) in imported.diagnostics {
363 push(&mut diagnostics, &path, diagnostic);
364 }
365 mcp_servers = imported
366 .servers
367 .into_iter()
368 .map(|server| PreparedMcpServer {
369 output_path: format!("mcp/{}/mcp.toml", server.name),
370 normalized_bytes: crate::mcp_server::render_mcp_toml(&server.def).into_bytes(),
371 name: server.name,
372 source_path: server.source_path,
373 })
374 .collect();
375 }
376 }
377 diagnostics.retain(|_, diagnostics| !diagnostics.is_empty());
378 changes.retain(|_, diagnostics| !diagnostics.is_empty());
379 let manifest = manifest.take();
380 let prepared = Prepared {
381 selection: selection_facts(&classification, manifest.as_ref(), &definitions),
382 classification,
383 manifest,
384 definitions,
385 mcp_servers,
386 payload,
387 diagnostics,
388 changes,
389 };
390 Rooted {
391 prepared,
392 dispatched,
393 }
394}
395
396fn add_package_tools(
400 definition: &mut PreparedDefinition,
401 manifest: &crate::manifest::ManifestRead,
402) {
403 let Reading::Agent(read) = &mut definition.reading else {
404 return;
405 };
406 if let Some(error) = manifest.first_error() {
409 read.diagnostics.push(SchemaDiagnostic::new(
410 "package-tools.unreadable",
411 Severity::Error,
412 Vec::new(),
413 format!(
414 "the package's mars.toml has an error, so its `[package.tools]` rules cannot be added and `mars sync` refuses the package: {}",
415 error.message
416 ),
417 ));
418 return;
419 }
420 let (Some(package), Some(fields)) = (
421 manifest
422 .package
423 .fields
424 .as_ref()
425 .map(|package| &package.tools),
426 read.fields.as_mut(),
427 ) else {
428 return;
429 };
430 let Some(profile) = std::str::from_utf8(&definition.normalized_bytes)
432 .ok()
433 .and_then(|text| Frontmatter::parse(text).ok())
434 else {
435 return;
436 };
437 for (name, action) in crate::package_tools::missing(&profile, package) {
438 fields.tools.push_unique(
439 ToolRule::from_parsed(name.parsed().clone(), action).with_origin(RuleOrigin::Package),
440 );
441 }
442}
443
444fn report_unconverted(
447 source: &impl TreeSource,
448 dispatched: &Dispatched,
449 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
450) {
451 let Layout::Claude(spec) = &dispatched.layout else {
452 return;
453 };
454 let mut warn = |path: &str, code: &str, message: String| {
455 diagnostics
456 .entry(path.to_owned())
457 .or_default()
458 .push(SchemaDiagnostic::new(
459 code,
460 Severity::Warning,
461 Vec::new(),
462 message,
463 ));
464 };
465 if !dispatched.discovery.dropped.is_empty() {
466 warn(
467 "commands",
468 "import.commands-dropped",
469 format!(
470 "commands are not imported (convert one to a skill): {}",
471 dispatched
472 .discovery
473 .dropped
474 .iter()
475 .map(|command| command.source_path.as_str())
476 .collect::<Vec<_>>()
477 .join(", ")
478 ),
479 );
480 }
481 if spec.is_bare_tree() && source.is_file(".mcp.json") {
482 warn(
483 ".mcp.json",
484 "import.mcp-not-imported",
485 "this is a skill tree, not a Claude plugin (it has no `.claude-plugin/plugin.json`), so its MCP servers were not imported".into(),
486 );
487 }
488 if source.is_file("hooks/hooks.json") || spec.hooks {
489 let path = if source.is_file("hooks/hooks.json") {
490 "hooks/hooks.json"
491 } else {
492 crate::claude::manifest::PLUGIN_MANIFEST
493 };
494 warn(
495 path,
496 "import.hooks-not-converted",
497 "hooks are not converted yet".into(),
498 );
499 }
500}
501
502pub(crate) fn prepare_manifest(bytes: &[u8]) -> PreparedManifest {
503 let reading = match std::str::from_utf8(bytes) {
504 Ok(text) => crate::manifest::read(text),
505 Err(error) => crate::manifest::ManifestRead::unread(vec![SchemaDiagnostic::new(
506 "text.invalid-utf8",
507 Severity::Error,
508 Vec::new(),
509 format!("mars.toml is not UTF-8: {error}"),
510 )]),
511 };
512 PreparedManifest {
513 source_path: Some("mars.toml".to_string()),
514 output_path: "mars.toml".to_string(),
515 normalized_bytes: bytes.to_vec(),
516 reading,
517 change: ChangeRecord::None,
518 }
519}
520
521fn prepare_definition(
522 source: &impl TreeSource,
523 selected: &SelectedDefinition,
524 classification: &Classification,
525 authored: bool,
526 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
527 changes: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
528) -> PreparedDefinition {
529 let Some(bytes) = source.read(&selected.source_path) else {
530 return PreparedDefinition {
531 kind: selected.kind,
532 slug: selected.slug.clone(),
533 source_path: selected.source_path.clone(),
534 output_path: selected.output_path.clone(),
535 skill_root: selected.skill_root.clone(),
536 normalized_bytes: Vec::new(),
537 reading: unreadable(
538 selected.kind,
539 SchemaDiagnostic::new(
540 "definition.read-missing",
541 Severity::Error,
542 Vec::new(),
543 "selected definition could not be read",
544 ),
545 ),
546 change: ChangeRecord::None,
547 };
548 };
549 let (mut notes, mut findings) = (Vec::new(), Vec::new());
550 let (normalized_bytes, change) = match (std::str::from_utf8(&bytes), classification) {
551 (Ok(text), Classification::Foreign(choice)) => {
552 let translated = translate_foreign(text, choice.dialect, selected, &bytes);
553 notes = translated.changes;
554 findings = translated.findings;
555 (translated.bytes, translated.change)
556 }
557 _ => (bytes.clone(), ChangeRecord::None),
558 };
559 changes
560 .entry(selected.source_path.clone())
561 .or_default()
562 .extend(notes);
563 diagnostics
564 .entry(selected.source_path.clone())
565 .or_default()
566 .extend(findings);
567
568 let reading = match std::str::from_utf8(&normalized_bytes) {
570 Ok(text) if authored => read_authored(selected.kind, text),
571 Ok(text) => read_definition(selected.kind, text),
572 Err(error) => unreadable(
573 selected.kind,
574 SchemaDiagnostic::new(
575 "text.invalid-utf8",
576 Severity::Error,
577 Vec::new(),
578 format!("definition is not UTF-8: {error}"),
579 ),
580 ),
581 };
582
583 PreparedDefinition {
584 kind: selected.kind,
585 slug: selected.slug.clone(),
586 source_path: selected.source_path.clone(),
587 output_path: selected.output_path.clone(),
588 skill_root: selected.skill_root.clone(),
589 normalized_bytes,
590 reading,
591 change,
592 }
593}
594
595struct Translated {
597 bytes: Vec<u8>,
598 change: ChangeRecord,
599 changes: Vec<SchemaDiagnostic>,
601 findings: Vec<SchemaDiagnostic>,
603}
604
605impl Translated {
606 fn untouched(bytes: &[u8]) -> Self {
607 Self {
608 bytes: bytes.to_vec(),
609 change: ChangeRecord::None,
610 changes: Vec::new(),
611 findings: Vec::new(),
612 }
613 }
614}
615
616fn translate_foreign(
620 text: &str,
621 dialect: Dialect,
622 selected: &SelectedDefinition,
623 bytes: &[u8],
624) -> Translated {
625 let claude = matches!(dialect, Dialect::Claude | Dialect::AgentSkills);
626 let mut changes = Vec::new();
627 let mut repaired = false;
628 let frontmatter = match Frontmatter::parse(text) {
629 Ok(frontmatter) => frontmatter,
630 Err(FrontmatterError::MalformedYaml(_)) if claude => {
631 match crate::claude::translate::repair_plain_values(text)
632 .and_then(|(fixed, keys)| Some((Frontmatter::parse(&fixed).ok()?, keys)))
633 {
634 Some((frontmatter, keys)) => {
635 repaired = true;
636 changes.push(crate::claude::translate::repaired_diagnostic(&keys));
637 frontmatter
638 }
639 None => return Translated::untouched(bytes),
640 }
641 }
642 Err(_) => return Translated::untouched(bytes),
643 };
644 let lifted = crate::lift::lift_frontmatter(dialect, selected.kind, &frontmatter);
645 changes.extend(lifted.changes);
646 let mut findings = lifted.findings;
647 if claude && selected.kind == DefinitionKind::Skill {
648 findings.extend(crate::claude::checks::skill_checks(&lifted.frontmatter));
649 }
650 let (bytes, change) = if lifted.changed || repaired {
651 (
652 lifted.frontmatter.render().into_bytes(),
653 ChangeRecord::FullyRewritten,
654 )
655 } else {
656 (bytes.to_vec(), ChangeRecord::None)
657 };
658 Translated {
659 bytes,
660 change,
661 changes,
662 findings,
663 }
664}
665
666fn unreadable(kind: DefinitionKind, diagnostic: SchemaDiagnostic) -> Reading {
668 match kind {
669 DefinitionKind::Agent => Reading::Agent(DefinitionRead::unread(vec![diagnostic])),
670 DefinitionKind::Skill => Reading::Skill(DefinitionRead::unread(vec![diagnostic])),
671 }
672}
673
674fn push(
675 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
676 path: &str,
677 diagnostic: SchemaDiagnostic,
678) {
679 diagnostics
680 .entry(path.to_owned())
681 .or_default()
682 .push(diagnostic);
683}