mars-agents 0.13.0

Agent package manager for .agents/ directories
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

use indexmap::IndexMap;
use semver::VersionReq;

use super::compat::CompatibilityResult;
use crate::config::{FilterMode, Manifest};
use crate::error::ResolutionError;
use crate::lock::ItemKind;
use crate::source::ResolvedRef;
use crate::types::{ItemName, SourceId, SourceName};

/// The resolved dependency graph — all sources with concrete versions.
///
/// Produced by the resolver after fetching sources, reading manifests,
/// intersecting version constraints, and deterministic ordering.
#[derive(Debug, Clone)]
pub struct ResolvedGraph {
    pub nodes: IndexMap<SourceName, ResolvedNode>,
    /// Deterministic alphabetical order (prompt packages don't require dependency ordering).
    pub order: Vec<SourceName>,
    /// All filter constraints collected for each source (direct + transitive).
    pub filters: HashMap<SourceName, Vec<FilterMode>>,
    /// All version constraints collected for each source (direct + transitive).
    pub version_constraints: HashMap<SourceName, Vec<(String, VersionConstraint)>>,
    /// Hook surfaces that cannot be compiled because they use a removed schema.
    ///
    /// This is classified during staging and consumed only by the recovery halt
    /// gate at the reader/compiler boundary.
    pub unreadable_hook_surfaces:
        std::collections::BTreeMap<SourceName, std::collections::BTreeSet<String>>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct EngineFallbackSkippedVersion {
    pub version: String,
    pub requirements: Vec<EngineFallbackRequirement>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct EngineFallbackRequirement {
    pub engine: String,
    pub requirement: String,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct EngineFallback {
    pub source: String,
    pub skipped: Vec<EngineFallbackSkippedVersion>,
    pub selected_version: String,
    pub engines: Vec<String>,
}

/// A single node in the resolved graph.
#[derive(Debug, Clone)]
pub struct ResolvedNode {
    pub source_name: SourceName,
    pub source_id: SourceId,
    pub rooted_ref: RootedSourceRef,
    pub resolved_ref: ResolvedRef,
    /// None if source has no mars.toml.
    pub manifest: Option<Manifest>,
    /// Source names this depends on.
    pub deps: Vec<SourceName>,
}

/// Source checkout provenance and rooted package boundary.
#[derive(Debug, Clone)]
pub struct RootedSourceRef {
    pub checkout_root: PathBuf,
    pub package_root: PathBuf,
}

/// How a version constraint was specified.
#[derive(Debug, Clone)]
pub enum VersionConstraint {
    /// Semver requirement (^1.0, >=0.5.0, ~2.1, exact version).
    Semver(VersionReq),
    /// Any version, prefer newest.
    Latest,
    /// Branch or commit pin — no semver resolution.
    RefPin(String),
}

impl std::fmt::Display for VersionConstraint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VersionConstraint::Semver(req) => write!(f, "{req}"),
            VersionConstraint::Latest => write!(f, "latest"),
            VersionConstraint::RefPin(reference) => write!(f, "ref:{reference}"),
        }
    }
}

/// An item waiting to be processed in DFS traversal.
#[derive(Debug, Clone)]
pub struct PendingItem {
    /// Package containing this item.
    pub package: SourceName,
    /// Item name.
    pub item: ItemName,
    /// Agent or Skill.
    pub kind: ItemKind,
    /// Version constraint from config.
    pub constraint: VersionConstraint,
    /// Who requested this item (for error context).
    pub required_by: String,
    /// True if from a local path dependency (skip version checks).
    pub is_local: bool,
}

/// Result of checking whether an item was seen already.
#[derive(Debug)]
pub enum VersionCheckResult {
    /// Item has not been visited yet.
    NotSeen,
    /// Item was visited with a compatible version.
    SameVersion,
    /// Item was visited with a potentially conflicting version (latest vs pinned).
    PotentiallyConflicting {
        existing: VersionConstraint,
        requested: VersionConstraint,
    },
    /// Item was visited with a conflicting version.
    DifferentVersion {
        existing: VersionConstraint,
        requested: VersionConstraint,
    },
}

/// Stable key for visited items.
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
struct VisitedItem {
    package: SourceName,
    item: ItemName,
}

/// Stored version information for a visited item.
#[derive(Debug, Clone)]
pub struct ResolvedVersion {
    pub constraint: VersionConstraint,
    pub resolved_ref: ResolvedRef,
}

/// Tracks visited items with version-aware lookup for DFS traversal.
pub struct VisitedSet {
    /// Fast lookup by (package, item).
    index: HashMap<(SourceName, ItemName), ResolvedVersion>,
}

impl Default for VisitedSet {
    fn default() -> Self {
        Self::new()
    }
}

impl VisitedSet {
    pub fn new() -> Self {
        Self {
            index: HashMap::new(),
        }
    }

    fn index_key(package: &SourceName, item: &ItemName) -> (SourceName, ItemName) {
        let key = VisitedItem {
            package: package.clone(),
            item: item.clone(),
        };
        (key.package, key.item)
    }

    /// Check whether an item was visited and compare version constraints.
    pub fn check_version(
        &self,
        package: &SourceName,
        item: &ItemName,
        constraint: &VersionConstraint,
    ) -> VersionCheckResult {
        match self.index.get(&Self::index_key(package, item)) {
            None => VersionCheckResult::NotSeen,
            Some(existing) => match existing
                .constraint
                .compatible_with_resolved(constraint, existing.resolved_ref.version.as_ref())
            {
                CompatibilityResult::Compatible => VersionCheckResult::SameVersion,
                CompatibilityResult::PotentiallyConflicting => {
                    VersionCheckResult::PotentiallyConflicting {
                        existing: existing.constraint.clone(),
                        requested: constraint.clone(),
                    }
                }
                CompatibilityResult::Conflicting => VersionCheckResult::DifferentVersion {
                    existing: existing.constraint.clone(),
                    requested: constraint.clone(),
                },
            },
        }
    }

    /// Insert an item as visited.
    pub fn insert(
        &mut self,
        package: SourceName,
        item: ItemName,
        constraint: VersionConstraint,
        resolved_ref: ResolvedRef,
    ) {
        self.index.insert(
            Self::index_key(&package, &item),
            ResolvedVersion {
                constraint,
                resolved_ref,
            },
        );
    }
}

/// Tracks resolved version per package and rejects divergent refs.
pub struct PackageVersions {
    /// package -> (resolved_ref, first_constraint, first_required_by)
    versions: HashMap<SourceName, (ResolvedRef, VersionConstraint, String)>,
}

impl Default for PackageVersions {
    fn default() -> Self {
        Self::new()
    }
}

impl PackageVersions {
    pub fn new() -> Self {
        Self {
            versions: HashMap::new(),
        }
    }

    /// Check existing package version or insert if first time seen.
    pub fn check_or_insert(
        &mut self,
        package: &SourceName,
        resolved: &ResolvedRef,
        requested: &VersionConstraint,
        required_by: &str,
        is_local: bool,
    ) -> Result<(), ResolutionError> {
        if is_local {
            return Ok(());
        }

        match self.versions.entry(package.clone()) {
            Entry::Vacant(entry) => {
                entry.insert((resolved.clone(), requested.clone(), required_by.to_string()));
                Ok(())
            }
            Entry::Occupied(entry) => {
                let (existing_ref, existing_constraint, existing_by) = entry.get();
                match existing_constraint.compatible_with_resolved(
                    requested,
                    existing_ref.version.as_ref().or(resolved.version.as_ref()),
                ) {
                    CompatibilityResult::Compatible
                    | CompatibilityResult::PotentiallyConflicting => {
                        if resolved_ref_matches(existing_ref, resolved) {
                            Ok(())
                        } else {
                            Err(ResolutionError::PackageVersionConflict {
                                package: package.to_string(),
                                existing: format!("{existing_ref:?} (required by {existing_by})"),
                                requested: format!("{resolved:?} (required by {required_by})"),
                                chain: required_by.to_string(),
                            })
                        }
                    }
                    CompatibilityResult::Conflicting => {
                        Err(ResolutionError::PackageVersionConflict {
                            package: package.to_string(),
                            existing: format!("{existing_constraint} (required by {existing_by})"),
                            requested: format!("{requested} (required by {required_by})"),
                            chain: required_by.to_string(),
                        })
                    }
                }
            }
        }
    }
}

fn resolved_ref_matches(existing: &ResolvedRef, incoming: &ResolvedRef) -> bool {
    existing.source_name == incoming.source_name
        && existing.version == incoming.version
        && existing.version_tag == incoming.version_tag
        && existing.commit == incoming.commit
        && crate::target::paths_equivalent(
            &existing.tree_path.to_string_lossy(),
            &incoming.tree_path.to_string_lossy(),
        )
}

/// High-level resolver mode shared by sync and upgrade.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolveMode {
    /// Normal sync: replay compatible lock entries, otherwise pick newest compatible.
    Sync,
    /// Frozen sync: require the lock to replay exactly.
    Frozen,
    /// Upgrade: bypass lock replay for targets, leave non-targets lock-preferred.
    Upgrade {
        /// Empty means every source is an upgrade target.
        targets: HashSet<SourceName>,
        /// Treat direct target constraints as unconstrained so the manifest can be bumped.
        bump_direct_constraints: bool,
    },
}

/// Options controlling resolution behavior.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolveOptions {
    pub mode: ResolveMode,
    /// Running mars version override. Production uses the crate version.
    pub mars_version: Option<semver::Version>,
    /// Running meridian version override. Production reads `MERIDIAN_VERSION`.
    pub meridian_version: Option<semver::Version>,
    pub ignore_requires_mars: bool,
    pub ignore_requires_meridian: bool,
    /// Per-project directory for dependency-scoped canonical source staging.
    pub staging_root: Option<std::path::PathBuf>,
    /// Local source substitutions, including names first introduced transitively.
    pub(crate) source_overrides: indexmap::IndexMap<SourceName, std::path::PathBuf>,
}

impl Default for ResolveOptions {
    fn default() -> Self {
        Self {
            mode: ResolveMode::Sync,
            mars_version: None,
            meridian_version: None,
            ignore_requires_mars: false,
            ignore_requires_meridian: false,
            staging_root: None,
            source_overrides: indexmap::IndexMap::new(),
        }
    }
}

/// Version-selection behavior for a single source in the current resolve mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum VersionSelectionPolicy {
    /// Use compatible locked version when available; otherwise newest compatible.
    PreferLockThenLatest,
    /// Upgrade mode: choose newest compatible version and bypass lock preference.
    LatestOnly,
    /// Lock must be honored exactly; fail when lock cannot be used.
    LockOnly,
}

impl ResolveOptions {
    pub fn sync() -> Self {
        Self {
            mode: ResolveMode::Sync,
            mars_version: None,
            meridian_version: None,
            ignore_requires_mars: false,
            ignore_requires_meridian: false,
            staging_root: None,
            source_overrides: indexmap::IndexMap::new(),
        }
    }

    pub fn frozen() -> Self {
        Self {
            mode: ResolveMode::Frozen,
            mars_version: None,
            meridian_version: None,
            ignore_requires_mars: false,
            ignore_requires_meridian: false,
            staging_root: None,
            source_overrides: indexmap::IndexMap::new(),
        }
    }

    pub fn upgrade(targets: HashSet<SourceName>, bump_direct_constraints: bool) -> Self {
        Self {
            mode: ResolveMode::Upgrade {
                targets,
                bump_direct_constraints,
            },
            mars_version: None,
            meridian_version: None,
            ignore_requires_mars: false,
            ignore_requires_meridian: false,
            staging_root: None,
            source_overrides: indexmap::IndexMap::new(),
        }
    }

    pub fn with_staging_root(mut self, staging_root: std::path::PathBuf) -> Self {
        self.staging_root = Some(staging_root);
        self
    }

    pub(crate) fn with_source_overrides(
        mut self,
        source_overrides: indexmap::IndexMap<SourceName, std::path::PathBuf>,
    ) -> Self {
        self.source_overrides = source_overrides;
        self
    }

    pub(crate) fn direct_constraint_for(
        &self,
        source_name: &SourceName,
        declared: VersionConstraint,
    ) -> VersionConstraint {
        if matches!(
            &self.mode,
            ResolveMode::Upgrade {
                bump_direct_constraints: true,
                ..
            }
        ) && self.is_upgrade_target(source_name)
        {
            VersionConstraint::Latest
        } else {
            declared
        }
    }

    pub(crate) fn is_upgrade_target(&self, source_name: &SourceName) -> bool {
        match &self.mode {
            ResolveMode::Upgrade { targets, .. } => {
                targets.is_empty() || targets.contains(source_name)
            }
            ResolveMode::Sync | ResolveMode::Frozen => false,
        }
    }

    pub(crate) fn version_selection_policy(
        &self,
        source_name: &SourceName,
    ) -> VersionSelectionPolicy {
        match &self.mode {
            ResolveMode::Frozen => VersionSelectionPolicy::LockOnly,
            ResolveMode::Upgrade { .. } if self.is_upgrade_target(source_name) => {
                VersionSelectionPolicy::LatestOnly
            }
            ResolveMode::Sync | ResolveMode::Upgrade { .. } => {
                VersionSelectionPolicy::PreferLockThenLatest
            }
        }
    }
}