harn-vm 0.8.0

Async bytecode virtual machine for the Harn programming language
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! Discovery and parsing of `invariants.harn` Flow predicate files.
//!
//! Mirrors `metadata_resolve` semantics: predicates declared in higher
//! directories apply to all descendants. This module owns the walk + parse;
//! hierarchy merging lives in [`super::compose`], and evaluation lives in
//! [`super::executor`].
//!
//! See parent epic #571 and ticket #579 for the design rationale.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use harn_lexer::{Lexer, Span};
use harn_parser::{peel_attributes, Attribute, AttributeArg, Node, Parser};
use sha2::{Digest, Sha256};

use super::executor::PredicateKind;
use crate::flow::slice::PredicateHash;

/// Filename used for per-directory Flow invariant declarations.
pub const INVARIANTS_FILE: &str = "invariants.harn";

/// One `invariants.harn` file discovered on disk, with its predicates
/// already parsed into typed metadata.
#[derive(Clone, Debug)]
pub struct DiscoveredInvariantFile {
    /// Absolute path to the source file.
    pub path: PathBuf,
    /// Path relative to the discovery root, normalised with `/` separators.
    pub relative_dir: String,
    /// Raw source — kept around so callers can render diagnostics.
    pub source: String,
    /// Predicates declared at the top level, in source order.
    pub predicates: Vec<DiscoveredPredicate>,
    /// Parse / attribute errors encountered when reading this file.
    pub diagnostics: Vec<DiscoveryDiagnostic>,
}

/// One Flow predicate declaration parsed out of an invariants file.
#[derive(Clone, Debug)]
pub struct DiscoveredPredicate {
    /// Function name. Composition uses this name plus the source directory
    /// ancestry to identify stricter-child override lineages.
    pub name: String,
    /// `Deterministic` (default) or `Semantic`.
    pub kind: PredicateKind,
    /// For `@semantic` predicates, the named deterministic predicate that
    /// carries the replayable enforcement path.
    pub fallback: Option<String>,
    /// Optional Archivist provenance block.
    pub archivist: Option<ArchivistMetadata>,
    /// Advisory historical flag — predicates that legalise existing state
    /// rather than gate new atoms.
    pub retroactive: bool,
    /// Stable content hash of the predicate declaration, including Flow
    /// attributes. Shipped slices pin this value so later predicate edits are
    /// append-only audit drift instead of retroactive blockers.
    pub source_hash: PredicateHash,
    /// Span of the function declaration in the source file (1-based).
    pub span: Span,
}

/// Provenance metadata pulled from `@archivist(...)`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ArchivistMetadata {
    pub evidence: Vec<String>,
    pub confidence: Option<f64>,
    pub source_date: Option<String>,
    pub coverage_examples: Vec<String>,
}

/// One diagnostic surfaced by discovery — covers both parse errors and
/// the structural attribute checks that go beyond the typechecker
/// (`@invariant` requires `@archivist`, etc.).
#[derive(Clone, Debug)]
pub struct DiscoveryDiagnostic {
    pub severity: DiagnosticSeverity,
    pub message: String,
    pub span: Option<Span>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DiagnosticSeverity {
    Warning,
    Error,
}

/// Walk from `root` down through every component of `target_dir`,
/// collecting `invariants.harn` at each level.
///
/// Returns the files in root-to-leaf order so composition can stamp source
/// depth and evaluate ancestor/child predicates together.
///
/// `target_dir` is interpreted relative to `root`. Absolute paths or
/// paths that escape `root` are silently clamped — discovery never reads
/// files outside `root`.
pub fn discover_invariants(root: &Path, target_dir: &Path) -> Vec<DiscoveredInvariantFile> {
    let mut files = Vec::new();
    let candidates = candidate_directories(root, target_dir);

    for dir in candidates {
        let path = dir.join(INVARIANTS_FILE);
        if !path.is_file() {
            continue;
        }
        let source = match std::fs::read_to_string(&path) {
            Ok(s) => s,
            Err(_) => continue,
        };
        let relative_dir = relative_dir_label(root, &dir);
        let parsed = parse_invariants_source(&source);
        files.push(DiscoveredInvariantFile {
            path,
            relative_dir,
            source,
            predicates: parsed.predicates,
            diagnostics: parsed.diagnostics,
        });
    }

    validate_semantic_fallbacks(&mut files);
    files
}

/// Parse a single `invariants.harn` source string. Exposed publicly for
/// tests, the LSP, and tooling that has the file contents in hand.
pub fn parse_invariants_source(source: &str) -> ParsedInvariantFile {
    let mut diagnostics = Vec::new();
    let tokens = match Lexer::new(source).tokenize() {
        Ok(t) => t,
        Err(error) => {
            diagnostics.push(DiscoveryDiagnostic {
                severity: DiagnosticSeverity::Error,
                message: format!("lex error: {error:?}"),
                span: None,
            });
            return ParsedInvariantFile {
                predicates: Vec::new(),
                diagnostics,
            };
        }
    };
    let program = match Parser::new(tokens).parse() {
        Ok(p) => p,
        Err(error) => {
            diagnostics.push(DiscoveryDiagnostic {
                severity: DiagnosticSeverity::Error,
                message: format!("parse error: {error:?}"),
                span: None,
            });
            return ParsedInvariantFile {
                predicates: Vec::new(),
                diagnostics,
            };
        }
    };

    let mut predicates = Vec::new();
    for node in &program {
        let (attrs, inner) = peel_attributes(node);
        let Node::FnDecl { name, .. } = &inner.node else {
            continue;
        };
        let Some(predicate) =
            predicate_from_attributes(source, name, attrs, inner.span, &mut diagnostics)
        else {
            continue;
        };
        predicates.push(predicate);
    }

    ParsedInvariantFile {
        predicates,
        diagnostics,
    }
}

/// Parsed-but-not-yet-located output of [`parse_invariants_source`].
#[derive(Clone, Debug, Default)]
pub struct ParsedInvariantFile {
    pub predicates: Vec<DiscoveredPredicate>,
    pub diagnostics: Vec<DiscoveryDiagnostic>,
}

fn predicate_from_attributes(
    source: &str,
    name: &str,
    attrs: &[Attribute],
    span: Span,
    diagnostics: &mut Vec<DiscoveryDiagnostic>,
) -> Option<DiscoveredPredicate> {
    // The Flow predicate marker is a *bare* `@invariant`. Anything with
    // arguments is the handler-IR form and is not part of Flow discovery.
    let invariant = attrs.iter().find(|a| a.name == "invariant")?;
    if !invariant.args.is_empty() {
        return None;
    }

    let deterministic = attrs.iter().any(|a| a.name == "deterministic");
    let semantic = attrs.iter().any(|a| a.name == "semantic");
    let kind = match (deterministic, semantic) {
        (true, true) => {
            diagnostics.push(DiscoveryDiagnostic {
                severity: DiagnosticSeverity::Error,
                message: format!(
                    "predicate `{name}` declares both `@deterministic` and \
                     `@semantic`; pick exactly one"
                ),
                span: Some(span),
            });
            PredicateKind::Deterministic
        }
        (false, false) => {
            // Default per design: predicates without an explicit mode are
            // deterministic.
            PredicateKind::Deterministic
        }
        (true, false) => PredicateKind::Deterministic,
        (false, true) => PredicateKind::Semantic,
    };

    let archivist = attrs
        .iter()
        .find(|a| a.name == "archivist")
        .map(parse_archivist_attribute);
    if archivist.is_none() {
        diagnostics.push(DiscoveryDiagnostic {
            severity: DiagnosticSeverity::Warning,
            message: format!(
                "predicate `{name}` is missing `@archivist(...)` provenance \
                 (evidence, confidence, source_date, coverage_examples)"
            ),
            span: Some(span),
        });
    }

    let retroactive = attrs.iter().any(|a| a.name == "retroactive");
    let fallback = attrs
        .iter()
        .find(|a| a.name == "semantic")
        .and_then(parse_semantic_fallback);
    if kind == PredicateKind::Semantic && fallback.is_none() {
        diagnostics.push(DiscoveryDiagnostic {
            severity: DiagnosticSeverity::Error,
            message: format!(
                "semantic predicate `{name}` must declare a deterministic fallback with \
                 `@semantic(fallback: \"predicate_name\")`"
            ),
            span: Some(span),
        });
    }
    let source_hash = predicate_source_hash(source, attrs, span);

    Some(DiscoveredPredicate {
        name: name.to_string(),
        kind,
        fallback,
        archivist,
        retroactive,
        source_hash,
        span,
    })
}

fn parse_semantic_fallback(attr: &Attribute) -> Option<String> {
    attr.args
        .iter()
        .find(|arg| arg.name.as_deref() == Some("fallback"))
        .or_else(|| attr.args.iter().find(|arg| arg.name.is_none()))
        .and_then(identifier_or_string_arg)
}

fn validate_semantic_fallbacks(files: &mut [DiscoveredInvariantFile]) {
    let mut visible_deterministic = BTreeMap::<String, PredicateHash>::new();

    for file in files {
        for predicate in &file.predicates {
            if predicate.kind == PredicateKind::Deterministic {
                visible_deterministic.insert(predicate.name.clone(), predicate.source_hash.clone());
            }
        }

        let diagnostics = file
            .predicates
            .iter()
            .filter(|predicate| predicate.kind == PredicateKind::Semantic)
            .filter_map(|predicate| {
                let fallback = predicate.fallback.as_ref()?;
                if visible_deterministic.contains_key(fallback) {
                    return None;
                }
                Some(DiscoveryDiagnostic {
                    severity: DiagnosticSeverity::Error,
                    message: format!(
                        "semantic predicate `{}` fallback `{fallback}` must name a \
                         deterministic predicate in the same invariants.harn file or an ancestor file",
                        predicate.name
                    ),
                    span: Some(predicate.span),
                })
            })
            .collect::<Vec<_>>();
        file.diagnostics.extend(diagnostics);
    }
}

fn predicate_source_hash(source: &str, attrs: &[Attribute], span: Span) -> PredicateHash {
    let start = attrs
        .iter()
        .map(|attr| attr.span.start)
        .min()
        .unwrap_or(span.start)
        .min(source.len());
    let end = span.end.min(source.len()).max(start);
    let bytes = &source.as_bytes()[start..end];
    PredicateHash::new(format!("sha256:{}", hex::encode(Sha256::digest(bytes))))
}

fn parse_archivist_attribute(attr: &Attribute) -> ArchivistMetadata {
    let mut metadata = ArchivistMetadata::default();
    for arg in &attr.args {
        let Some(name) = arg.name.as_deref() else {
            continue;
        };
        match name {
            "evidence" => metadata.evidence = string_list_arg(arg),
            "confidence" => metadata.confidence = number_arg(arg),
            "source_date" => metadata.source_date = string_arg(arg),
            "coverage_examples" => metadata.coverage_examples = string_list_arg(arg),
            _ => {}
        }
    }
    metadata
}

fn string_arg(arg: &AttributeArg) -> Option<String> {
    match &arg.value.node {
        Node::StringLiteral(s) | Node::RawStringLiteral(s) => Some(s.clone()),
        _ => None,
    }
}

fn identifier_or_string_arg(arg: &AttributeArg) -> Option<String> {
    match &arg.value.node {
        Node::Identifier(s) | Node::StringLiteral(s) | Node::RawStringLiteral(s) => Some(s.clone()),
        _ => None,
    }
}

fn number_arg(arg: &AttributeArg) -> Option<f64> {
    match &arg.value.node {
        Node::FloatLiteral(f) => Some(*f),
        Node::IntLiteral(i) => Some(*i as f64),
        _ => None,
    }
}

fn string_list_arg(arg: &AttributeArg) -> Vec<String> {
    match &arg.value.node {
        Node::ListLiteral(items) => items
            .iter()
            .filter_map(|item| match &item.node {
                Node::StringLiteral(s) | Node::RawStringLiteral(s) => Some(s.clone()),
                _ => None,
            })
            .collect(),
        Node::StringLiteral(s) | Node::RawStringLiteral(s) => vec![s.clone()],
        _ => Vec::new(),
    }
}

/// Build the root → target chain of directories to inspect, in order.
///
/// Mirrors `MetadataState::resolve`: starts at `root`, then descends one
/// component at a time. Empty / `.` / `..` components are stripped so a
/// caller can't escape the root.
fn candidate_directories(root: &Path, target_dir: &Path) -> Vec<PathBuf> {
    let mut chain = vec![root.to_path_buf()];

    // Make `target_dir` relative to `root` if it is absolute, otherwise
    // treat it as already-relative.
    let relative = target_dir.strip_prefix(root).unwrap_or_else(|_| {
        if target_dir.is_absolute() {
            Path::new("")
        } else {
            target_dir
        }
    });

    let mut current = root.to_path_buf();
    for component in relative.components() {
        use std::path::Component;
        match component {
            Component::Normal(name) => {
                current.push(name);
                chain.push(current.clone());
            }
            Component::CurDir => {}
            // Refuse to escape `root`.
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                continue;
            }
        }
    }

    chain
}

fn relative_dir_label(root: &Path, dir: &Path) -> String {
    let rel = dir.strip_prefix(root).unwrap_or(dir);
    let mut parts: Vec<String> = Vec::new();
    for component in rel.components() {
        if let std::path::Component::Normal(name) = component {
            parts.push(name.to_string_lossy().into_owned());
        }
    }
    if parts.is_empty() {
        ".".to_string()
    } else {
        parts.join("/")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::flow::resolve_predicates;
    use std::fs;
    use tempfile::TempDir;

    fn write(dir: &Path, name: &str, contents: &str) {
        fs::create_dir_all(dir).unwrap();
        fs::write(dir.join(name), contents).unwrap();
    }

    fn sample_predicate(name: &str) -> String {
        format!(
            r#"
@invariant
@deterministic
@archivist(evidence: ["https://example.com/spec"], confidence: 0.95, source_date: "2026-04-01")
fn {name}(slice) -> bool {{
    return true
}}
"#
        )
    }

    #[test]
    fn discover_walks_from_root_to_leaf() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        write(root, INVARIANTS_FILE, &sample_predicate("root_check"));
        let nested = root.join("crates").join("foo");
        write(&nested, INVARIANTS_FILE, &sample_predicate("inner_check"));

        let files = discover_invariants(root, &nested);
        let labels: Vec<_> = files.iter().map(|f| f.relative_dir.clone()).collect();
        assert_eq!(labels, vec![".".to_string(), "crates/foo".to_string()]);
        assert_eq!(files[0].predicates[0].name, "root_check");
        assert_eq!(files[0].predicates[0].kind, PredicateKind::Deterministic);
        assert_eq!(files[1].predicates[0].name, "inner_check");
    }

    #[test]
    fn discover_clamps_parent_dir_traversal() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().join("repo");
        fs::create_dir_all(&root).unwrap();
        write(&root, INVARIANTS_FILE, &sample_predicate("root_check"));

        let files = discover_invariants(&root, Path::new("../../escape"));
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].relative_dir, ".");
    }

    #[test]
    fn parse_picks_up_archivist_metadata() {
        let source = sample_predicate("foo");
        let parsed = parse_invariants_source(&source);
        assert!(parsed.diagnostics.is_empty(), "{:?}", parsed.diagnostics);
        let pred = &parsed.predicates[0];
        let arch = pred.archivist.as_ref().expect("archivist present");
        assert_eq!(arch.evidence, vec!["https://example.com/spec".to_string()]);
        assert_eq!(arch.confidence, Some(0.95));
        assert_eq!(arch.source_date.as_deref(), Some("2026-04-01"));
    }

    #[test]
    fn parse_pins_predicate_source_hash() {
        let source = sample_predicate("foo");
        let parsed = parse_invariants_source(&source);
        let original = parsed.predicates[0].source_hash.clone();

        let changed = sample_predicate("foo").replace("return true", "return false");
        let reparsed = parse_invariants_source(&changed);
        assert_ne!(reparsed.predicates[0].source_hash, original);
        assert!(original.as_str().starts_with("sha256:"));
    }

    #[test]
    fn parse_warns_when_archivist_missing() {
        let source = r#"
@invariant
@deterministic
fn missing_arch(slice) -> bool { return true }
"#;
        let parsed = parse_invariants_source(source);
        assert_eq!(parsed.predicates.len(), 1);
        assert!(parsed
            .diagnostics
            .iter()
            .any(|d| d.message.contains("missing `@archivist(...)`")));
    }

    #[test]
    fn parse_errors_when_kinds_collide() {
        let source = r#"
@invariant
@deterministic
@semantic
@archivist(evidence: ["x"])
fn both_modes(slice) -> bool { return true }
"#;
        let parsed = parse_invariants_source(source);
        assert!(parsed
            .diagnostics
            .iter()
            .any(|d| d.severity == DiagnosticSeverity::Error
                && d.message.contains("pick exactly one")));
    }

    #[test]
    fn parse_recognises_semantic_mode_and_retroactive() {
        let source = r#"
@invariant
@semantic(fallback: "fallback_check")
@retroactive
@archivist(evidence: ["https://x"], confidence: 0.5)
fn check(slice) -> bool { return true }

@invariant
@deterministic
@archivist(evidence: ["https://x"])
fn fallback_check(slice) -> bool { return true }
"#;
        let parsed = parse_invariants_source(source);
        assert_eq!(parsed.predicates.len(), 2);
        let pred = &parsed.predicates[0];
        assert_eq!(pred.kind, PredicateKind::Semantic);
        assert_eq!(pred.fallback.as_deref(), Some("fallback_check"));
        assert!(pred.retroactive);
    }

    #[test]
    fn parse_errors_when_semantic_fallback_missing() {
        let source = r#"
@invariant
@semantic
@archivist(evidence: ["https://x"], confidence: 0.5)
fn check(slice) -> bool { return true }
"#;
        let parsed = parse_invariants_source(source);
        assert!(parsed.diagnostics.iter().any(|d| {
            d.severity == DiagnosticSeverity::Error
                && d.message.contains("must declare a deterministic fallback")
        }));
    }

    #[test]
    fn discover_accepts_semantic_fallback_from_ancestor() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        write(root, INVARIANTS_FILE, &sample_predicate("root_fallback"));
        let nested = root.join("crates");
        write(
            &nested,
            INVARIANTS_FILE,
            r#"
@invariant
@semantic(fallback: root_fallback)
@archivist(evidence: ["https://x"], confidence: 0.5)
fn semantic_check(slice) -> bool { return true }
"#,
        );

        let files = discover_invariants(root, &nested);

        assert!(files
            .iter()
            .flat_map(|file| file.diagnostics.iter())
            .all(|diagnostic| diagnostic.severity != DiagnosticSeverity::Error));
        let resolved = resolve_predicates(&files);
        let semantic = resolved
            .iter()
            .find(|predicate| predicate.logical_name == "semantic_check")
            .unwrap();
        assert_eq!(
            semantic.fallback_hash,
            Some(files[0].predicates[0].source_hash.clone())
        );
    }

    #[test]
    fn discover_rejects_semantic_fallback_from_descendant_only() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        write(
            root,
            INVARIANTS_FILE,
            r#"
@invariant
@semantic(fallback: child_fallback)
@archivist(evidence: ["https://x"], confidence: 0.5)
fn semantic_check(slice) -> bool { return true }
"#,
        );
        let nested = root.join("crates");
        write(
            &nested,
            INVARIANTS_FILE,
            &sample_predicate("child_fallback"),
        );

        let files = discover_invariants(root, &nested);

        assert!(files[0].diagnostics.iter().any(|diagnostic| {
            diagnostic.severity == DiagnosticSeverity::Error
                && diagnostic
                    .message
                    .contains("same invariants.harn file or an ancestor file")
        }));
    }

    #[test]
    fn parse_skips_handler_ir_invariants() {
        // `@invariant("name", "glob")` is the harn-ir handler form; it
        // should never be treated as a Flow predicate.
        let source = r#"
@invariant("fs.writes", "src/**")
fn handler_check(slice) -> bool { return true }
"#;
        let parsed = parse_invariants_source(source);
        assert!(parsed.predicates.is_empty(), "{:?}", parsed.predicates);
    }

    #[test]
    fn resolve_predicates_keeps_ancestors_for_composition() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        write(root, INVARIANTS_FILE, &sample_predicate("shared"));
        let nested = root.join("crates");
        // Override `shared` and add `extra`.
        write(
            &nested,
            INVARIANTS_FILE,
            &format!(
                "{}{}",
                sample_predicate("shared"),
                sample_predicate("extra")
            ),
        );

        let files = discover_invariants(root, &nested);
        let resolved = resolve_predicates(&files);
        let qualified: Vec<_> = resolved.iter().map(|p| p.qualified_name.clone()).collect();
        // Composition needs both versions so child results can tighten but
        // cannot relax ancestor verdicts.
        assert!(qualified.contains(&"shared".to_string()));
        assert!(qualified.contains(&"crates::shared".to_string()));
        // `extra` only exists in the deeper file.
        assert!(qualified.contains(&"crates::extra".to_string()));
    }
}