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::tree::TreeSource;
17use crate::upgrade::{UpgradeError, UpgradeResult};
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(rename_all = "kebab-case")]
21pub enum PrepareContext {
22 Package,
25 AuthoredLocal,
28 Project,
31}
32
33pub const LOCAL_SOURCE_DIR: &str = ".mars-src";
35
36pub fn project_authored_root(project: &Path, manifest: Option<&[u8]>) -> (PathBuf, PrepareContext) {
41 match crate::package::classify_manifest(manifest) {
42 crate::package::ManifestClassification::ConsumerConfig => (
43 project.join(LOCAL_SOURCE_DIR),
44 PrepareContext::AuthoredLocal,
45 ),
46 _ => (project.to_path_buf(), PrepareContext::Package),
47 }
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
52#[serde(tag = "kind", rename_all = "kebab-case")]
53pub enum Classification {
54 #[serde(rename = "schema-1")]
55 Schema1,
56 MarsLegacy,
57 SchemaNewer {
58 schema: u64,
59 },
60 Invalid,
61 Foreign(DialectChoice),
63 Marketplace,
65 Empty,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
69#[serde(tag = "kind", rename_all = "kebab-case")]
70pub enum ChangeRecord {
71 None,
72 Generated,
74 Edited {
75 paths: Vec<Vec<PathSegment>>,
76 },
77 FullyRewritten,
78}
79
80#[derive(Debug, Clone, Serialize)]
81pub struct PreparedManifest {
82 #[serde(skip_serializing_if = "Option::is_none")]
84 pub source_path: Option<String>,
85 pub output_path: String,
86 #[serde(with = "serde_bytes")]
88 pub normalized_bytes: Vec<u8>,
89 pub reading: crate::manifest::ManifestRead,
90 pub change: ChangeRecord,
91}
92
93#[derive(Debug, Clone, Serialize)]
94pub struct PreparedDefinition {
95 pub kind: DefinitionKind,
96 pub slug: String,
97 pub source_path: String,
98 pub output_path: String,
99 #[serde(skip)]
101 pub skill_root: Option<String>,
102 #[serde(with = "serde_bytes")]
104 pub normalized_bytes: Vec<u8>,
105 pub reading: Reading,
107 pub change: ChangeRecord,
108}
109
110#[derive(Debug, Clone, Serialize)]
113pub struct PreparedMcpServer {
114 pub name: String,
115 pub source_path: String,
117 pub output_path: String,
118 #[serde(with = "serde_bytes")]
120 pub normalized_bytes: Vec<u8>,
121}
122
123#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
124pub struct PayloadEntry {
125 pub source_path: String,
126 pub output_path: String,
127}
128
129#[derive(Debug, Clone, Serialize)]
130pub struct Prepared {
131 pub classification: Classification,
132 #[serde(skip_serializing_if = "Option::is_none")]
133 pub manifest: Option<PreparedManifest>,
134 pub definitions: Vec<PreparedDefinition>,
135 #[serde(skip_serializing_if = "Vec::is_empty")]
137 pub mcp_servers: Vec<PreparedMcpServer>,
138 pub payload: Vec<PayloadEntry>,
139 pub selection: SelectionFacts,
141 pub diagnostics: BTreeMap<String, Vec<SchemaDiagnostic>>,
145 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
149 pub changes: BTreeMap<String, Vec<SchemaDiagnostic>>,
150}
151
152pub(crate) fn selection_facts(
155 manifest: Option<&PreparedManifest>,
156 definitions: &[PreparedDefinition],
157) -> SelectionFacts {
158 let reading = manifest.map(|manifest| &manifest.reading);
159 SelectionFacts {
160 definitions: definitions
161 .iter()
162 .map(|definition| Definition {
163 kind: definition.kind,
164 slug: definition.slug.clone(),
165 output_path: definition.output_path.clone(),
166 skills: match &definition.reading {
167 Reading::Agent(read) => read
168 .fields
169 .as_ref()
170 .map(|profile| profile.skills.all())
171 .unwrap_or_default(),
172 _ => Vec::new(),
173 },
174 })
175 .collect(),
176 edges: reading
177 .map(|reading| {
178 reading
179 .dependencies
180 .dependencies
181 .iter()
182 .map(|(name, entry)| Request {
183 name: name.clone(),
184 filter: entry.filter.to_mode(),
185 })
186 .collect()
187 })
188 .unwrap_or_default(),
189 uses_providers: reading
190 .and_then(|reading| reading.package.fields.as_ref())
191 .map(|package| package.uses_providers.clone())
192 .unwrap_or_default(),
193 }
194}
195
196impl Prepared {
197 pub fn lost_restrictions(&self) -> impl Iterator<Item = (&str, &SchemaDiagnostic)> {
201 self.changes.iter().flat_map(|(path, changes)| {
202 changes
203 .iter()
204 .filter(|change| change.code == crate::set_aside::RESTRICTION_LOST)
205 .map(move |change| (path.as_str(), change))
206 })
207 }
208
209 pub fn ignored_execution_fields(&self) -> impl Iterator<Item = (&str, &SchemaDiagnostic)> {
213 self.changes.iter().flat_map(|(path, changes)| {
214 changes
215 .iter()
216 .filter(|change| change.code == crate::set_aside::EXECUTION_IGNORED)
217 .map(move |change| (path.as_str(), change))
218 })
219 }
220
221 pub fn changed_files(&self) -> usize {
225 self.manifest
226 .iter()
227 .map(|manifest| &manifest.change)
228 .chain(self.definitions.iter().map(|definition| &definition.change))
229 .filter(|change| !matches!(change, ChangeRecord::None | ChangeRecord::Generated))
230 .count()
231 }
232
233 pub fn all_diagnostics(&self) -> BTreeMap<&str, Vec<&SchemaDiagnostic>> {
235 let mut all: BTreeMap<&str, Vec<&SchemaDiagnostic>> = BTreeMap::new();
236 for (path, diagnostics) in &self.diagnostics {
237 all.entry(path).or_default().extend(diagnostics);
238 }
239 if let Some(manifest) = &self.manifest
240 && let Some(path) = &manifest.source_path
241 {
242 all.entry(path)
243 .or_default()
244 .extend(&manifest.reading.package.diagnostics);
245 }
246 for definition in &self.definitions {
247 all.entry(&definition.source_path)
248 .or_default()
249 .extend(definition.reading.diagnostics());
250 }
251 all.retain(|_, diagnostics| !diagnostics.is_empty());
252 all
253 }
254}
255
256#[derive(Default, Clone, Copy)]
259pub(crate) struct RootOptions<'a> {
260 pub as_plugin: Option<AsPlugin<'a>>,
261 pub selection: Option<&'a BTreeSet<String>>,
263 pub fallback_name: Option<&'a str>,
265 pub migrate: bool,
270}
271
272pub(crate) struct Rooted {
274 pub prepared: Prepared,
275 pub dispatched: Dispatched,
276}
277
278pub fn prepare(
280 source: &impl TreeSource,
281 context: PrepareContext,
282 declared_dialect: Option<Dialect>,
283) -> Prepared {
284 prepare_root(source, context, declared_dialect, RootOptions::default()).prepared
285}
286
287pub fn prepare_for_migration(
290 source: &impl TreeSource,
291 context: PrepareContext,
292 declared_dialect: Option<Dialect>,
293) -> Prepared {
294 let options = RootOptions {
295 migrate: true,
296 ..RootOptions::default()
297 };
298 prepare_root(source, context, declared_dialect, options).prepared
299}
300
301pub(crate) fn prepare_root(
302 source: &impl TreeSource,
303 context: PrepareContext,
304 declared_dialect: Option<Dialect>,
305 options: RootOptions<'_>,
306) -> Rooted {
307 let mut dispatched = dispatch(
308 source,
309 context,
310 declared_dialect,
311 options.as_plugin,
312 options.fallback_name,
313 );
314 let classification = dispatched.classification.clone();
315 let manifest_bytes = dispatched.manifest.take();
316 let mut diagnostics = std::mem::take(&mut dispatched.discovery.diagnostics);
317 let mut changes = BTreeMap::new();
318
319 let mut manifest = manifest_bytes.as_deref().map(|bytes| {
320 prepare_manifest(
321 bytes,
322 classification == Classification::MarsLegacy
323 || (options.migrate && classification == Classification::Schema1),
324 &mut diagnostics,
325 &mut changes,
326 )
327 });
328
329 let can_read_definitions = !matches!(
330 classification,
331 Classification::Invalid
332 | Classification::SchemaNewer { .. }
333 | Classification::Empty
334 | Classification::Marketplace
335 );
336 let all = &dispatched.discovery.definitions;
337 let selected = all
338 .iter()
339 .filter(|definition| {
340 options
341 .selection
342 .is_none_or(|selection| selection.contains(&definition.source_path))
343 })
344 .collect::<Vec<_>>();
345 let shaping = Shaping::of(&classification, options.migrate);
346 let definitions = if can_read_definitions {
347 selected
348 .iter()
349 .map(|definition| {
350 prepare_definition(source, definition, shaping, &mut diagnostics, &mut changes)
351 })
352 .collect::<Vec<_>>()
353 } else {
354 Vec::new()
355 };
356 let payload = if can_read_definitions {
357 payload_paths(
358 source,
359 &dispatched.discovery,
360 matches!(classification, Classification::Foreign(_)),
361 selected.iter().copied(),
362 &mut diagnostics,
363 )
364 .into_iter()
365 .map(|(source_path, output_path)| PayloadEntry {
366 source_path,
367 output_path,
368 })
369 .collect()
370 } else {
371 Vec::new()
372 };
373
374 let mut mcp_servers = Vec::new();
375 if can_read_definitions {
376 report_unconverted(source, &dispatched, &mut diagnostics);
377 if let Layout::Claude(spec) = &dispatched.layout
379 && !spec.is_bare_tree()
380 {
381 let imported = crate::claude::mcp::import(source, spec);
382 for (path, diagnostic) in imported.diagnostics {
383 push(&mut diagnostics, &path, diagnostic);
384 }
385 mcp_servers = imported
386 .servers
387 .into_iter()
388 .map(|server| PreparedMcpServer {
389 output_path: format!("mcp/{}/mcp.toml", server.name),
390 normalized_bytes: crate::mcp_server::render_mcp_toml(&server.def).into_bytes(),
391 name: server.name,
392 source_path: server.source_path,
393 })
394 .collect();
395 }
396 }
397 diagnostics.retain(|_, diagnostics| !diagnostics.is_empty());
398 changes.retain(|_, diagnostics| !diagnostics.is_empty());
399 let manifest = manifest.take();
400 let prepared = Prepared {
401 classification,
402 selection: selection_facts(manifest.as_ref(), &definitions),
403 manifest,
404 definitions,
405 mcp_servers,
406 payload,
407 diagnostics,
408 changes,
409 };
410 Rooted {
411 prepared,
412 dispatched,
413 }
414}
415
416fn report_unconverted(
419 source: &impl TreeSource,
420 dispatched: &Dispatched,
421 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
422) {
423 let Layout::Claude(spec) = &dispatched.layout else {
424 return;
425 };
426 let mut warn = |path: &str, code: &str, message: String| {
427 diagnostics
428 .entry(path.to_owned())
429 .or_default()
430 .push(SchemaDiagnostic::new(
431 code,
432 Severity::Warning,
433 Vec::new(),
434 message,
435 ));
436 };
437 if !dispatched.discovery.dropped.is_empty() {
438 warn(
439 "commands",
440 "import.commands-dropped",
441 format!(
442 "commands are not imported (convert one to a skill): {}",
443 dispatched
444 .discovery
445 .dropped
446 .iter()
447 .map(|command| command.source_path.as_str())
448 .collect::<Vec<_>>()
449 .join(", ")
450 ),
451 );
452 }
453 if spec.is_bare_tree() && source.is_file(".mcp.json") {
454 warn(
455 ".mcp.json",
456 "import.mcp-not-imported",
457 "this is a skill tree, not a Claude plugin (it has no `.claude-plugin/plugin.json`), so its MCP servers were not imported".into(),
458 );
459 }
460 if source.is_file("hooks/hooks.json") || spec.hooks {
461 let path = if source.is_file("hooks/hooks.json") {
462 "hooks/hooks.json"
463 } else {
464 crate::claude::manifest::PLUGIN_MANIFEST
465 };
466 warn(
467 path,
468 "import.hooks-not-converted",
469 "hooks are not converted yet".into(),
470 );
471 }
472}
473
474fn prepare_manifest(
475 bytes: &[u8],
476 upgrade: bool,
477 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
478 changes: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
479) -> PreparedManifest {
480 let invalid_utf8 = std::str::from_utf8(bytes).err().map(|error| {
481 SchemaDiagnostic::new(
482 "text.invalid-utf8",
483 Severity::Error,
484 Vec::new(),
485 format!("mars.toml is not UTF-8: {error}"),
486 )
487 });
488 let (normalized_bytes, change, upgraded) = match std::str::from_utf8(bytes) {
489 Ok(text) if upgrade => match crate::upgrade::upgrade_manifest(text) {
490 Ok(result) => upgrade_result(text, result),
491 Err(error) => {
492 push(
493 diagnostics,
494 "mars.toml",
495 SchemaDiagnostic::new(
496 "manifest.upgrade-failed",
497 Severity::Error,
498 Vec::new(),
499 error.to_string(),
500 ),
501 );
502 (bytes.to_vec(), ChangeRecord::None, Vec::new())
503 }
504 },
505 Ok(_) => (bytes.to_vec(), ChangeRecord::None, Vec::new()),
506 Err(_) => (bytes.to_vec(), ChangeRecord::None, Vec::new()),
507 };
508 changes
509 .entry("mars.toml".to_string())
510 .or_default()
511 .extend(upgraded);
512 let reading = std::str::from_utf8(&normalized_bytes).map_or_else(
513 |_| crate::manifest::ManifestRead::unread(invalid_utf8.into_iter().collect()),
514 crate::manifest::read,
515 );
516 PreparedManifest {
517 source_path: Some("mars.toml".to_string()),
518 output_path: "mars.toml".to_string(),
519 normalized_bytes,
520 reading,
521 change,
522 }
523}
524
525type Rewrite = fn(DefinitionKind, &str) -> Result<UpgradeResult, UpgradeError>;
527
528#[derive(Clone, Copy)]
530enum Shaping {
531 None,
533 Rewrite(Rewrite),
535 Foreign(Dialect),
537}
538
539impl Shaping {
540 fn of(classification: &Classification, migrate: bool) -> Self {
541 match classification {
542 Classification::MarsLegacy => Self::Rewrite(crate::upgrade::upgrade_definition),
543 Classification::Schema1 if migrate => Self::Rewrite(crate::upgrade::migrate_definition),
545 Classification::Foreign(choice) => Self::Foreign(choice.dialect),
546 _ => Self::None,
547 }
548 }
549}
550
551fn prepare_definition(
552 source: &impl TreeSource,
553 selected: &SelectedDefinition,
554 shaping: Shaping,
555 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
556 changes: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
557) -> PreparedDefinition {
558 let Some(bytes) = source.read(&selected.source_path) else {
559 return PreparedDefinition {
560 kind: selected.kind,
561 slug: selected.slug.clone(),
562 source_path: selected.source_path.clone(),
563 output_path: selected.output_path.clone(),
564 skill_root: selected.skill_root.clone(),
565 normalized_bytes: Vec::new(),
566 reading: unreadable(
567 selected.kind,
568 SchemaDiagnostic::new(
569 "definition.read-missing",
570 Severity::Error,
571 Vec::new(),
572 "selected definition could not be read",
573 ),
574 ),
575 change: ChangeRecord::None,
576 };
577 };
578 let (mut notes, mut findings) = (Vec::new(), Vec::new());
579 let (normalized_bytes, change) = match std::str::from_utf8(&bytes) {
580 Ok(text) => match shaping {
581 Shaping::Rewrite(rewrite) => match rewrite(selected.kind, text) {
582 Ok(result) => {
583 let (rewritten, change, upgrade_notes) = upgrade_result(text, result);
584 notes = upgrade_notes;
585 (rewritten, change)
586 }
587 Err(UpgradeError::Frontmatter(_)) => (bytes.clone(), ChangeRecord::None),
590 Err(error) => {
591 push(
592 diagnostics,
593 &selected.source_path,
594 SchemaDiagnostic::new(
595 "definition.upgrade-failed",
596 Severity::Error,
597 Vec::new(),
598 error.to_string(),
599 ),
600 );
601 (bytes.clone(), ChangeRecord::None)
602 }
603 },
604 Shaping::Foreign(dialect) => {
605 let translated = translate_foreign(text, dialect, selected, &bytes);
606 notes = translated.changes;
607 findings = translated.findings;
608 (translated.bytes, translated.change)
609 }
610 Shaping::None => (bytes.clone(), ChangeRecord::None),
611 },
612 Err(_) => (bytes.clone(), ChangeRecord::None),
613 };
614 changes
615 .entry(selected.source_path.clone())
616 .or_default()
617 .extend(notes);
618 diagnostics
619 .entry(selected.source_path.clone())
620 .or_default()
621 .extend(findings);
622
623 let reading = match std::str::from_utf8(&normalized_bytes) {
625 Ok(text) => read_definition(selected.kind, text),
626 Err(error) => unreadable(
627 selected.kind,
628 SchemaDiagnostic::new(
629 "text.invalid-utf8",
630 Severity::Error,
631 Vec::new(),
632 format!("definition is not UTF-8: {error}"),
633 ),
634 ),
635 };
636
637 PreparedDefinition {
638 kind: selected.kind,
639 slug: selected.slug.clone(),
640 source_path: selected.source_path.clone(),
641 output_path: selected.output_path.clone(),
642 skill_root: selected.skill_root.clone(),
643 normalized_bytes,
644 reading,
645 change,
646 }
647}
648
649struct Translated {
651 bytes: Vec<u8>,
652 change: ChangeRecord,
653 changes: Vec<SchemaDiagnostic>,
655 findings: Vec<SchemaDiagnostic>,
657}
658
659impl Translated {
660 fn untouched(bytes: &[u8]) -> Self {
661 Self {
662 bytes: bytes.to_vec(),
663 change: ChangeRecord::None,
664 changes: Vec::new(),
665 findings: Vec::new(),
666 }
667 }
668}
669
670fn translate_foreign(
674 text: &str,
675 dialect: Dialect,
676 selected: &SelectedDefinition,
677 bytes: &[u8],
678) -> Translated {
679 let claude = matches!(dialect, Dialect::Claude | Dialect::AgentSkills);
680 let mut changes = Vec::new();
681 let mut repaired = false;
682 let frontmatter = match Frontmatter::parse(text) {
683 Ok(frontmatter) => frontmatter,
684 Err(_) if claude && selected.kind == DefinitionKind::Skill => {
685 match crate::claude::translate::repair_description(text)
686 .and_then(|fixed| Frontmatter::parse(&fixed).ok())
687 {
688 Some(frontmatter) => {
689 repaired = true;
690 changes.push(crate::claude::translate::repaired_diagnostic());
691 frontmatter
692 }
693 None => return Translated::untouched(bytes),
694 }
695 }
696 Err(_) => return Translated::untouched(bytes),
697 };
698 let lifted = crate::lift::lift_frontmatter(dialect, selected.kind, &frontmatter);
699 changes.extend(lifted.changes);
700 let mut findings = lifted.findings;
701 if claude && selected.kind == DefinitionKind::Skill {
702 findings.extend(crate::claude::checks::skill_checks(
703 selected,
704 &lifted.frontmatter,
705 ));
706 }
707 let (bytes, change) = if lifted.changed || repaired {
708 (
709 lifted.frontmatter.render().into_bytes(),
710 ChangeRecord::FullyRewritten,
711 )
712 } else {
713 (bytes.to_vec(), ChangeRecord::None)
714 };
715 Translated {
716 bytes,
717 change,
718 changes,
719 findings,
720 }
721}
722
723fn unreadable(kind: DefinitionKind, diagnostic: SchemaDiagnostic) -> Reading {
725 match kind {
726 DefinitionKind::Agent => Reading::Agent(DefinitionRead::unread(vec![diagnostic])),
727 DefinitionKind::Skill => Reading::Skill(DefinitionRead::unread(vec![diagnostic])),
728 }
729}
730
731fn upgrade_result(
732 original: &str,
733 result: UpgradeResult,
734) -> (Vec<u8>, ChangeRecord, Vec<SchemaDiagnostic>) {
735 let change = if !result.changed_from(original) {
736 ChangeRecord::None
737 } else if result.fully_rewritten {
738 ChangeRecord::FullyRewritten
739 } else {
740 ChangeRecord::Edited {
741 paths: result.edited_paths,
742 }
743 };
744 (result.text.into_bytes(), change, result.diagnostics)
745}
746
747fn push(
748 diagnostics: &mut BTreeMap<String, Vec<SchemaDiagnostic>>,
749 path: &str,
750 diagnostic: SchemaDiagnostic,
751) {
752 diagnostics
753 .entry(path.to_owned())
754 .or_default()
755 .push(diagnostic);
756}