miden-note-schema 0.15.0

Host-side reader and codec registry for Miden note storage schemas
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Miden package discovery for note schema macros.

use std::{
    env, fs,
    path::{Path, PathBuf},
};

use miden_mast_package::Package;
use midenc_frontend_wasm_metadata::package_cache;

use crate::{Error, NoteStorageSchema, Result};

/// A loaded package artifact and its note storage schema.
pub struct NotePackageArtifact {
    path: PathBuf,
    schema: NoteStorageSchema,
    tracked_inputs: Vec<PathBuf>,
}

impl NotePackageArtifact {
    /// Returns the exact package path used to load the schema.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Returns the schema loaded from the package.
    pub const fn schema(&self) -> &NoteStorageSchema {
        &self.schema
    }

    /// Returns every manifest the resolver read to derive the package file name.
    ///
    /// A caller registers these files as rebuild inputs next to the package itself. A rename of
    /// the note package changes a manifest but leaves the old package file in place, so nothing
    /// else tells the caller that the selection changed.
    pub fn tracked_inputs(&self) -> &[PathBuf] {
        &self.tracked_inputs
    }
}

/// Resolves package artifacts for one note macro crate.
pub struct NotePackageResolver<'a> {
    macro_crate: &'a str,
}

impl<'a> NotePackageResolver<'a> {
    /// Creates a resolver whose diagnostics name `macro_crate`.
    pub const fn new(macro_crate: &'a str) -> Self {
        Self { macro_crate }
    }

    /// Loads the package built by a Miden project.
    pub fn from_project(&self, project: &str) -> Result<NotePackageArtifact> {
        let project_dir = self.resolve_manifest_path(project)?;
        if !project_dir.is_dir() {
            return Err(Error::new(format!(
                "{}: note project directory '{}' does not exist",
                self.macro_crate,
                project_dir.display()
            )));
        }
        let identity = project_identity(&project_dir);
        let stems = &identity.stems;
        let cache_dir = package_cache_dir()
            .map_err(|error| Error::new(format!("{}: {error}", self.macro_crate)))?;
        let package_path = resolve_project_package(&project_dir, stems, cache_dir.as_deref())
            .map_err(|error| Error::new(format!("{}: {error}", self.macro_crate)))?
            .ok_or_else(|| {
                Error::new(missing_project_package_message(
                    self.macro_crate,
                    &project_dir,
                    cache_dir.as_deref(),
                    stems,
                ))
            })?;
        self.load_package(package_path, identity.manifests)
    }

    /// Loads one exact Miden package path.
    pub fn from_package(&self, package: &str) -> Result<NotePackageArtifact> {
        let package_path = self.resolve_manifest_path(package)?;
        if !package_path.is_file() {
            return Err(Error::new(format!(
                "{}: Miden package '{}' does not exist",
                self.macro_crate,
                package_path.display()
            )));
        }
        self.load_package(package_path, Vec::new())
    }

    /// Resolves one path relative to the consuming crate manifest.
    fn resolve_manifest_path(&self, value: &str) -> Result<PathBuf> {
        let path = PathBuf::from(value);
        if path.is_absolute() {
            return Ok(path);
        }
        let manifest_dir = env::var_os("CARGO_MANIFEST_DIR").ok_or_else(|| {
            Error::new(format!(
                "{}: CARGO_MANIFEST_DIR is not set during macro expansion",
                self.macro_crate
            ))
        })?;
        Ok(PathBuf::from(manifest_dir).join(path))
    }

    /// Loads the package and its unique schema section.
    fn load_package(
        &self,
        path: PathBuf,
        tracked_inputs: Vec<PathBuf>,
    ) -> Result<NotePackageArtifact> {
        let path = path.canonicalize().map_err(|error| {
            Error::new(format!(
                "{}: failed to resolve Miden package '{}': {error}",
                self.macro_crate,
                path.display()
            ))
        })?;
        let package = Package::deserialize_from_file(&path).map_err(|error| {
            Error::new(format!(
                "{}: failed to read Miden package '{}': {error}",
                self.macro_crate,
                path.display()
            ))
        })?;
        let schema = NoteStorageSchema::from_package(&package).map_err(|error| {
            Error::new(format!(
                "{}: failed to read note storage schema from '{}': {error}",
                self.macro_crate,
                path.display()
            ))
        })?;
        Ok(NotePackageArtifact {
            path,
            schema,
            tracked_inputs,
        })
    }
}

/// Resolves one project package by package identity and output-directory priority.
///
/// A set package-cache directory replaces the search: the build owns that directory, so the
/// output directories of the project are not consulted.
fn resolve_project_package(
    project_dir: &Path,
    stems: &[String],
    cache_dir: Option<&Path>,
) -> Result<Option<PathBuf>> {
    if let Some(cache_dir) = cache_dir {
        return Ok(find_project_package_in_cache(cache_dir, stems));
    }

    let profiles = candidate_profiles();
    for output_dir in project_output_dirs(project_dir, &profiles) {
        if let Some(package) = find_project_package_in_dir(&output_dir, stems)? {
            return Ok(Some(package));
        }
    }
    Ok(None)
}

/// Returns the configured package cache directory, treating an empty value as unset.
fn package_cache_dir() -> Result<Option<PathBuf>> {
    env::var_os(package_cache::PACKAGE_CACHE_ENV)
        .filter(|value| !value.is_empty())
        .map(|value| absolutize(PathBuf::from(value)))
        .transpose()
}

/// Returns Cargo and Miden profile names in lookup order.
fn candidate_profiles() -> Vec<String> {
    let mut profiles = Vec::new();
    if let Ok(profile) = env::var("PROFILE") {
        push_profile(&mut profiles, profile);
    }
    push_profile(&mut profiles, "release".to_owned());
    push_profile(&mut profiles, "debug".to_owned());
    push_profile(&mut profiles, "dev".to_owned());
    profiles
}

/// Returns candidate output directories for one project.
fn project_output_dirs(project_dir: &Path, profiles: &[String]) -> Vec<PathBuf> {
    let mut dirs = Vec::new();

    // Keep this policy in parity with base-macros/src/dependency_package.rs. The crates cannot
    // share the implementation without adding the full SDK macro dependency graph.
    push_profile_dirs(&mut dirs, project_dir.join("target"), profiles);
    push_manifest_ancestor_target_profile_dirs(&mut dirs, project_dir, profiles);
    push_ancestor_target_profile_dirs(&mut dirs, project_dir, profiles);

    if let Some(target_dir) = env::var_os("CARGO_TARGET_DIR") {
        push_profile_dirs(&mut dirs, PathBuf::from(target_dir), profiles);
    }
    if let Some(out_dir) = env::var_os("OUT_DIR") {
        for ancestor in Path::new(&out_dir).ancestors() {
            push_profile_dirs(&mut dirs, ancestor.to_path_buf(), profiles);
        }
    }
    if let Ok(current_dir) = env::current_dir() {
        push_profile_dirs(&mut dirs, current_dir.join("target"), profiles);
        push_manifest_ancestor_target_profile_dirs(&mut dirs, &current_dir, profiles);
        push_ancestor_target_profile_dirs(&mut dirs, &current_dir, profiles);
    }
    dirs
}

/// Adds `target/miden/<profile>` directories while preserving order.
fn push_profile_dirs(dirs: &mut Vec<PathBuf>, target_root: PathBuf, profiles: &[String]) {
    for profile in profiles {
        let dir = target_root.join("miden").join(profile);
        if !dirs.contains(&dir) {
            dirs.push(dir);
        }
    }
}

/// Adds target directories found among the ancestors of `path`.
fn push_ancestor_target_profile_dirs(dirs: &mut Vec<PathBuf>, path: &Path, profiles: &[String]) {
    for ancestor in path.ancestors() {
        if ancestor.file_name().is_some_and(|name| name == "target") {
            push_profile_dirs(dirs, ancestor.to_path_buf(), profiles);
        }
    }
}

/// Adds target directories for Cargo manifest ancestors of `path`.
fn push_manifest_ancestor_target_profile_dirs(
    dirs: &mut Vec<PathBuf>,
    path: &Path,
    profiles: &[String],
) {
    for ancestor in path.ancestors() {
        if ancestor.join("Cargo.toml").is_file() || ancestor.join("Cargo.lock").is_file() {
            push_profile_dirs(dirs, ancestor.join("target"), profiles);
        }
    }
}

/// Finds a project package in the build-owned package cache.
fn find_project_package_in_cache(dir: &Path, stems: &[String]) -> Option<PathBuf> {
    stems
        .iter()
        .map(|stem| dir.join(package_cache::package_file_name(stem)))
        .find(|path| path.is_file())
}

/// Finds a package in one output directory by ordered package identity.
fn find_project_package_in_dir(dir: &Path, stems: &[String]) -> Result<Option<PathBuf>> {
    if !dir.is_dir() {
        return Ok(None);
    }

    let packages = fs::read_dir(dir)
        .map_err(|error| Error::new(format!("failed to read '{}': {error}", dir.display())))?
        .collect::<core::result::Result<Vec<_>, _>>()
        .map_err(|error| {
            Error::new(format!("failed to read an entry in '{}': {error}", dir.display()))
        })?
        .into_iter()
        .map(|entry| entry.path())
        .filter(|path| {
            path.is_file() && path.extension().is_some_and(|extension| extension == "masp")
        })
        .collect::<Vec<_>>();

    // The stems are ordered by identity. The canonical miden-project package name comes first,
    // followed by legacy aliases. This matches base-macros/src/dependency_package.rs and prevents
    // a newer legacy artifact from shadowing the canonical package.
    for stem in stems {
        if let Some(package) = packages
            .iter()
            .find(|path| path.file_stem().and_then(|value| value.to_str()) == Some(stem.as_str()))
        {
            return Ok(Some(package.clone()));
        }
    }
    Ok(None)
}

/// The package file name stems of one project and the manifests they came from.
struct ProjectIdentity {
    /// Ordered package file name stems, canonical identity first.
    stems: Vec<String>,
    /// The manifests that were read, in the order they were read.
    manifests: Vec<PathBuf>,
}

/// Returns ordered package filename stems for one project, and the manifests they came from.
fn project_identity(project_dir: &Path) -> ProjectIdentity {
    let mut stems = Vec::new();
    let mut manifests = Vec::new();
    for manifest in [project_dir.join("miden-project.toml"), project_dir.join("Cargo.toml")] {
        if let Some(name) = package_name_from_manifest(&manifest) {
            push_package_stem(&mut stems, &name);
            manifests.push(manifest);
        }
    }
    if let Some(name) = project_dir.file_name().and_then(|name| name.to_str()) {
        push_package_stem(&mut stems, name);
    }
    ProjectIdentity { stems, manifests }
}

/// Reads a package name from one TOML manifest.
fn package_name_from_manifest(manifest_path: &Path) -> Option<String> {
    let manifest = fs::read_to_string(manifest_path).ok()?;
    let manifest = manifest.parse::<toml::Table>().ok()?;
    manifest
        .get("package")
        .and_then(toml::Value::as_table)
        .and_then(|package| package.get("name"))
        .and_then(toml::Value::as_str)
        .map(ToOwned::to_owned)
}

/// Adds a package filename stem and its underscore alias.
fn push_package_stem(stems: &mut Vec<String>, name: &str) {
    if !name.is_empty() && !stems.iter().any(|existing| existing == name) {
        stems.push(name.to_owned());
    }
    let normalized = name.replace('-', "_");
    if !normalized.is_empty() && !stems.contains(&normalized) {
        stems.push(normalized);
    }
}

/// Makes a cache path absolute for generated `include_bytes!` inputs.
fn absolutize(path: PathBuf) -> Result<PathBuf> {
    if path.is_absolute() {
        return Ok(path);
    }
    Ok(env::current_dir()
        .map_err(|error| Error::new(format!("failed to resolve current directory: {error}")))?
        .join(path))
}

/// Adds one profile name once.
fn push_profile(profiles: &mut Vec<String>, profile: String) {
    if !profile.is_empty() && !profiles.contains(&profile) {
        profiles.push(profile);
    }
}

/// Formats the diagnostic for a project without a built package.
fn missing_project_package_message(
    macro_crate: &str,
    project_dir: &Path,
    cache_dir: Option<&Path>,
    stems: &[String],
) -> String {
    let manifest = project_dir.join("Cargo.toml");
    let build = if manifest.is_file() {
        format!("cargo miden build --manifest-path {} --release", manifest.display())
    } else {
        "cargo miden build --release".to_owned()
    };
    if let Some(cache_dir) = cache_dir {
        let expected_files = stems
            .iter()
            .map(|stem| format!("'{}'", package_cache::package_file_name(stem)))
            .collect::<Vec<_>>()
            .join(", ");
        return format!(
            "{macro_crate} could not find a built `.masp` package for note project '{}'. Expected \
             one of these package names: {expected_files}. Searched {} directory '{}'. Build the \
             note project first with `{build}` so the package is available during macro expansion.",
            project_dir.display(),
            package_cache::PACKAGE_CACHE_ENV,
            cache_dir.display(),
        );
    }
    format!(
        "{macro_crate} could not find a built `.masp` package under '{}'. Build the note project \
         first with `{build}`.",
        project_dir.join("target/miden/<profile>").display()
    )
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::{
        find_project_package_in_cache, find_project_package_in_dir,
        missing_project_package_message, project_identity, project_output_dirs,
    };

    #[test]
    fn canonical_project_identity_wins_over_legacy_aliases() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(
            temp.path().join("miden-project.toml"),
            "[package]\nname='canonical-note'\nversion='0.1.0'",
        )
        .unwrap();
        fs::write(temp.path().join("Cargo.toml"), "[package]\nname='legacy-note'\nversion='0.1.0'")
            .unwrap();
        let output = temp.path().join("output");
        fs::create_dir(&output).unwrap();
        fs::write(output.join("legacy-note.masp"), b"newer legacy package").unwrap();
        fs::write(output.join("canonical-note.masp"), b"canonical package").unwrap();

        let stems = project_identity(temp.path()).stems;
        let selected = find_project_package_in_dir(&output, &stems).unwrap().unwrap();
        assert_eq!(selected, output.join("canonical-note.masp"));
    }

    #[test]
    fn tracked_inputs_name_the_manifests_that_were_read() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(
            temp.path().join("miden-project.toml"),
            "[package]\nname='canonical-note'\nversion='0.1.0'",
        )
        .unwrap();
        fs::write(temp.path().join("Cargo.toml"), "[package]\nname='legacy-note'\nversion='0.1.0'")
            .unwrap();

        let identity = project_identity(temp.path());

        assert_eq!(
            identity.manifests,
            [temp.path().join("miden-project.toml"), temp.path().join("Cargo.toml")]
        );
    }

    #[test]
    fn tracked_inputs_skip_a_manifest_that_is_absent() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(temp.path().join("Cargo.toml"), "[package]\nname='legacy-note'\nversion='0.1.0'")
            .unwrap();

        let identity = project_identity(temp.path());

        assert_eq!(identity.manifests, [temp.path().join("Cargo.toml")]);
    }

    #[test]
    fn manifest_ancestor_target_directories_are_candidates() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(temp.path().join("Cargo.lock"), "").unwrap();
        let project = temp.path().join("crates/note");
        fs::create_dir_all(&project).unwrap();
        let profiles = vec!["release".to_owned()];

        let dirs = project_output_dirs(&project, &profiles);

        assert!(dirs.contains(&temp.path().join("target/miden/release")));
    }

    #[test]
    fn missing_package_diagnostic_names_macro_and_build_command() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(temp.path().join("Cargo.toml"), "[package]\nname='note'\nversion='0.1.0'")
            .unwrap();
        let stems = project_identity(temp.path()).stems;
        let message = missing_project_package_message("test-note-macro", temp.path(), None, &stems);
        assert!(message.contains("test-note-macro"));
        assert!(message.contains("cargo miden build --manifest-path"));
        assert!(message.contains("--release"));
    }

    #[test]
    fn missing_cached_package_diagnostic_names_cache_and_expected_files() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(temp.path().join("Cargo.toml"), "[package]\nname='test-note'\nversion='0.1.0'")
            .unwrap();
        let cache_dir = temp.path().join("package-cache");
        let stems = project_identity(temp.path()).stems;

        let message = missing_project_package_message(
            "test-note-macro",
            temp.path(),
            Some(&cache_dir),
            &stems,
        );

        assert!(message.contains(&cache_dir.display().to_string()));
        assert!(message.contains("'test-note.masp'"));
        assert!(message.contains("MIDENC_PACKAGE_CACHE"));
        assert!(!message.contains("target/miden/<profile>"));
    }

    #[test]
    fn cache_lookup_uses_the_shared_package_file_name() {
        let temp = tempfile::tempdir().unwrap();
        let package = temp.path().join("note.with.dot.masp");
        fs::write(&package, b"package").unwrap();

        let found = find_project_package_in_cache(temp.path(), &["note.with.dot".to_owned()]);

        assert_eq!(found, Some(package));
    }
}