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(code, Severity::Warning, Vec::new(), message).losing());
459 };
460 if !dispatched.discovery.dropped.is_empty() {
461 warn(
462 "commands",
463 "import.commands-dropped",
464 format!(
465 "commands are not imported (convert one to a skill): {}",
466 dispatched
467 .discovery
468 .dropped
469 .iter()
470 .map(|command| command.source_path.as_str())
471 .collect::<Vec<_>>()
472 .join(", ")
473 ),
474 );
475 }
476 if spec.is_bare_tree() && source.is_file(".mcp.json") {
477 warn(
478 ".mcp.json",
479 "import.mcp-not-imported",
480 "this is a skill tree, not a Claude plugin (it has no `.claude-plugin/plugin.json`), so its MCP servers were not imported".into(),
481 );
482 }
483 if source.is_file("hooks/hooks.json") || spec.hooks {
484 let path = if source.is_file("hooks/hooks.json") {
485 "hooks/hooks.json"
486 } else {
487 crate::claude::manifest::PLUGIN_MANIFEST
488 };
489 warn(
490 path,
491 "import.hooks-not-converted",
492 "hooks are not converted yet".into(),
493 );
494 }
495}
496
497pub(crate) fn prepare_manifest(bytes: &[u8]) -> PreparedManifest {
498 let reading = match std::str::from_utf8(bytes) {
499 Ok(text) => crate::manifest::read(text),
500 Err(error) => crate::manifest::ManifestRead::unread(vec![SchemaDiagnostic::new(
501 "text.invalid-utf8",
502 Severity::Error,
503 Vec::new(),
504 format!("mars.toml is not UTF-8: {error}"),
505 )]),
506 };
507 PreparedManifest {
508 source_path: Some("mars.toml".to_string()),
509 output_path: "mars.toml".to_string(),
510 normalized_bytes: bytes.to_vec(),
511 reading,
512 change: ChangeRecord::None,
513 }
514}
515
516fn prepare_definition(
517 source: &impl TreeSource,
518 selected: &SelectedDefinition,
519 classification: &Classification,
520 authored: bool,
521 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
522 changes: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
523) -> PreparedDefinition {
524 let Some(bytes) = source.read(&selected.source_path) else {
525 return PreparedDefinition {
526 kind: selected.kind,
527 slug: selected.slug.clone(),
528 source_path: selected.source_path.clone(),
529 output_path: selected.output_path.clone(),
530 skill_root: selected.skill_root.clone(),
531 normalized_bytes: Vec::new(),
532 reading: unreadable(
533 selected.kind,
534 SchemaDiagnostic::new(
535 "definition.read-missing",
536 Severity::Error,
537 Vec::new(),
538 "selected definition could not be read",
539 ),
540 ),
541 change: ChangeRecord::None,
542 };
543 };
544 let (mut notes, mut findings) = (Vec::new(), Vec::new());
545 let (normalized_bytes, change) = match (std::str::from_utf8(&bytes), classification) {
546 (Ok(text), Classification::Foreign(choice)) => {
547 let translated = translate_foreign(text, choice.dialect, selected, &bytes);
548 notes = translated.changes;
549 findings = translated.findings;
550 (translated.bytes, translated.change)
551 }
552 _ => (bytes.clone(), ChangeRecord::None),
553 };
554 changes
555 .entry(selected.source_path.clone())
556 .or_default()
557 .extend(notes);
558 diagnostics
559 .entry(selected.source_path.clone())
560 .or_default()
561 .extend(findings);
562
563 let reading = match std::str::from_utf8(&normalized_bytes) {
565 Ok(text) if authored => read_authored(selected.kind, text),
566 Ok(text) => read_definition(selected.kind, text),
567 Err(error) => unreadable(
568 selected.kind,
569 SchemaDiagnostic::new(
570 "text.invalid-utf8",
571 Severity::Error,
572 Vec::new(),
573 format!("definition is not UTF-8: {error}"),
574 ),
575 ),
576 };
577
578 PreparedDefinition {
579 kind: selected.kind,
580 slug: selected.slug.clone(),
581 source_path: selected.source_path.clone(),
582 output_path: selected.output_path.clone(),
583 skill_root: selected.skill_root.clone(),
584 normalized_bytes,
585 reading,
586 change,
587 }
588}
589
590struct Translated {
592 bytes: Vec<u8>,
593 change: ChangeRecord,
594 changes: Vec<SchemaDiagnostic>,
596 findings: Vec<SchemaDiagnostic>,
598}
599
600impl Translated {
601 fn untouched(bytes: &[u8]) -> Self {
602 Self {
603 bytes: bytes.to_vec(),
604 change: ChangeRecord::None,
605 changes: Vec::new(),
606 findings: Vec::new(),
607 }
608 }
609}
610
611fn translate_foreign(
615 text: &str,
616 dialect: Dialect,
617 selected: &SelectedDefinition,
618 bytes: &[u8],
619) -> Translated {
620 let claude = matches!(dialect, Dialect::Claude | Dialect::AgentSkills);
621 let mut changes = Vec::new();
622 let mut repaired = false;
623 let frontmatter = match Frontmatter::parse(text) {
624 Ok(frontmatter) => frontmatter,
625 Err(FrontmatterError::MalformedYaml(_)) if claude => {
626 match crate::claude::translate::repair_plain_values(text)
627 .and_then(|(fixed, keys)| Some((Frontmatter::parse(&fixed).ok()?, keys)))
628 {
629 Some((frontmatter, keys)) => {
630 repaired = true;
631 changes.push(crate::claude::translate::repaired_diagnostic(&keys));
632 frontmatter
633 }
634 None => return Translated::untouched(bytes),
635 }
636 }
637 Err(_) => return Translated::untouched(bytes),
638 };
639 let lifted = crate::lift::lift_frontmatter(dialect, selected.kind, &frontmatter);
640 changes.extend(lifted.changes);
641 let mut findings = lifted.findings;
642 if claude && selected.kind == DefinitionKind::Skill {
643 findings.extend(crate::claude::checks::skill_checks(&lifted.frontmatter));
644 }
645 let (bytes, change) = if lifted.changed || repaired {
646 (
647 lifted.frontmatter.render().into_bytes(),
648 ChangeRecord::FullyRewritten,
649 )
650 } else {
651 (bytes.to_vec(), ChangeRecord::None)
652 };
653 Translated {
654 bytes,
655 change,
656 changes,
657 findings,
658 }
659}
660
661fn unreadable(kind: DefinitionKind, diagnostic: SchemaDiagnostic) -> Reading {
663 match kind {
664 DefinitionKind::Agent => Reading::Agent(DefinitionRead::unread(vec![diagnostic])),
665 DefinitionKind::Skill => Reading::Skill(DefinitionRead::unread(vec![diagnostic])),
666 }
667}
668
669fn push(
670 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
671 path: &str,
672 diagnostic: SchemaDiagnostic,
673) {
674 diagnostics
675 .entry(path.to_owned())
676 .or_default()
677 .push(diagnostic);
678}