morphir-workspace 0.2.0

Portable, root-confined Morphir workspace discovery
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
use std::collections::BTreeMap;

use serde_json::json;

use super::{
    EffectiveConfigCollector, discover_internal,
    layers::{MemberConfigLayers, member_effective_config, without_project_or_workspace},
};
use crate::{
    DiscoveryPurpose, DiscoveryRequest, FileEntry, FileTree, ProjectOrigin, ProjectSource,
    RelativePath, SourceSelection, WORKSPACE_CONFIG_INVALID, WORKSPACE_LANGUAGE_ID_EMPTY,
    WORKSPACE_PROJECT_NAME_EMPTY, WORKSPACE_SELECTION_DUPLICATE, WORKSPACE_SELECTION_EMPTY,
    WORKSPACE_SELECTION_INVALID, WORKSPACE_SELECTION_NAME_REQUIRED,
    WORKSPACE_SELECTION_OUTSIDE_ROOT, WORKSPACE_SYMLINK_UNSUPPORTED, discover,
    discover_with_details,
};

#[derive(Default)]
struct CountingCollector {
    roots: usize,
    projects: Vec<RelativePath>,
}

impl EffectiveConfigCollector for CountingCollector {
    fn root(&mut self, _effective: &serde_json::Value) {
        self.roots += 1;
    }

    fn project(&mut self, path: &RelativePath, _effective: &serde_json::Value) {
        self.projects.push(path.clone());
    }
}

fn collection_request() -> DiscoveryRequest {
    DiscoveryRequest {
        protocol_version: crate::workspace_discovery_protocol(),
        development_root: FileTree {
            entries: BTreeMap::from([
                (RelativePath::root(), FileEntry::Directory),
                (
                    RelativePath::parse("morphir.toml").unwrap(),
                    FileEntry::File {
                        text:
                            "[workspace]\nmembers = ['packages/*']\n[project]\nname = 'acme/root'\n"
                                .to_owned(),
                    },
                ),
                (
                    RelativePath::parse("packages/orders").unwrap(),
                    FileEntry::Directory,
                ),
                (
                    RelativePath::parse("packages/orders/morphir.toml").unwrap(),
                    FileEntry::File {
                        text: "[project]\nname = 'acme/orders'\n".to_owned(),
                    },
                ),
            ]),
        },
        morphir_home: None,
        system_config: None,
        environment: BTreeMap::new(),
        cli_overlay: json!({}),
        purpose: Default::default(),
    }
}

#[test]
fn effective_configs_are_collected_only_when_a_sink_is_supplied() {
    let request = collection_request();
    let ordinary = discover_internal(request.clone(), None).unwrap();
    let mut collector = CountingCollector::default();
    let detailed = discover_internal(request, Some(&mut collector)).unwrap();

    assert_eq!(ordinary, detailed);
    assert_eq!(collector.roots, 1);
    assert_eq!(
        collector.projects,
        [
            RelativePath::root(),
            RelativePath::parse("packages/orders").unwrap(),
        ]
    );
}

#[test]
fn portable_discovery_rejects_unmaterialized_symlinks_in_every_mount() {
    enum Mount {
        DevelopmentRoot,
        MorphirHome,
        SystemConfig,
    }

    for (mount, context) in [
        (Mount::DevelopmentRoot, "development root"),
        (Mount::MorphirHome, "Morphir Home"),
        (Mount::SystemConfig, "system configuration"),
    ] {
        let first = RelativePath::parse("a-link").unwrap();
        let first_target = RelativePath::parse("targets/first").unwrap();
        let links = FileTree {
            entries: BTreeMap::from([
                (RelativePath::root(), FileEntry::Directory),
                (
                    RelativePath::parse("z-link").unwrap(),
                    FileEntry::Symlink {
                        target: RelativePath::parse("targets/last").unwrap(),
                    },
                ),
                (
                    first.clone(),
                    FileEntry::Symlink {
                        target: first_target.clone(),
                    },
                ),
            ]),
        };
        let mut request = collection_request();
        match mount {
            Mount::DevelopmentRoot => request.development_root = links,
            Mount::MorphirHome => request.morphir_home = Some(links),
            Mount::SystemConfig => request.system_config = Some(links),
        }

        let failure = discover_internal(request, None).unwrap_err();

        assert_eq!(failure.code, WORKSPACE_SYMLINK_UNSUPPORTED);
        assert_eq!(failure.path, Some(first.clone()));
        assert!(failure.message.contains(context));
        assert!(failure.message.contains(first.as_str()));
        assert!(failure.message.contains(first_target.as_str()));
        assert!(!failure.message.contains("z-link"));
    }
}

#[test]
fn member_merge_inherits_only_shared_root_user_sections() {
    let empty = json!({});
    let root_user = json!({
        "workspace": { "name": "root-user-workspace" },
        "project": {
            "name": "root/user",
            "version": "2.0.0",
            "source_directory": "root-user-src"
        },
        "ir": { "strict_mode": true, "mode": "root-user" }
    });
    let shared_root_user = without_project_or_workspace(&root_user);
    let member_primary = json!({
        "project": {
            "name": "member/primary",
            "version": "1.0.0",
            "source_directory": "member-src"
        },
        "ir": { "format_version": 3, "mode": "member-primary" }
    });
    let member_user = json!({
        "project": { "version": "3.0.0" },
        "ir": { "mode": "member-user" }
    });

    let effective = member_effective_config(MemberConfigLayers {
        system: &empty,
        global: &empty,
        shared_workspace: &empty,
        member_primary: &member_primary,
        shared_workspace_user: &shared_root_user,
        member_user: Some(&member_user),
        environment: &empty,
        cli_overlay: &empty,
    });

    assert_eq!(effective["project"]["name"], "member/primary");
    assert_eq!(effective["project"]["version"], "3.0.0");
    assert_eq!(effective["project"]["source_directory"], "member-src");
    assert!(effective.get("workspace").is_none());
    assert_eq!(effective["ir"]["strict_mode"], true);
    assert_eq!(effective["ir"]["format_version"], 3);
    assert_eq!(effective["ir"]["mode"], "member-user");
}

fn gleam_source(path: &str) -> (RelativePath, FileEntry) {
    (
        RelativePath::parse(path).unwrap(),
        FileEntry::File {
            text: "pub type Customer {\n  Customer(id: String)\n}\n".to_owned(),
        },
    )
}

fn ad_hoc_request_with_entries(
    entries: BTreeMap<RelativePath, FileEntry>,
    project: ProjectSource,
    sources: SourceSelection,
) -> DiscoveryRequest {
    DiscoveryRequest {
        protocol_version: crate::workspace_discovery_protocol(),
        development_root: FileTree { entries },
        morphir_home: None,
        system_config: None,
        environment: BTreeMap::new(),
        cli_overlay: json!({}),
        purpose: DiscoveryPurpose::AdHocSources {
            project,
            sources,
            language_id: "gleam".to_owned(),
        },
    }
}

fn ad_hoc_request(paths: Vec<RelativePath>, root: RelativePath) -> DiscoveryRequest {
    let (source, entry) = gleam_source("models/domain/customer.gleam");
    ad_hoc_request_with_entries(
        BTreeMap::from([
            (RelativePath::root(), FileEntry::Directory),
            (source, entry),
        ]),
        ProjectSource::Synthesized,
        SourceSelection { root, paths },
    )
}

/// A selection with no manifest yields one synthesized project, and the root
/// the request carried is the one reported. Nested on purpose: a root-level
/// fixture cannot tell a correct root from a recomputed one.
///
/// Two paths, in two different directories, sharing a basename: this is the
/// plan's own motivating collision example. Recomputing the root from the
/// files (rather than carrying `sources.root` verbatim) would name both
/// modules `customer`. The selection root stays `models` and `inputs`
/// preserves the order the request gave, proving both never happen here.
///
/// Multi-source, so this now requires an explicit overlay name (see the
/// single-source cardinality rule below); the asserted name is exactly the
/// overlay value, never anything derived from the paths.
#[test]
fn ad_hoc_sources_without_a_manifest_yield_a_synthesized_project() {
    let domain = gleam_source("models/domain/customer.gleam");
    let party = gleam_source("models/party/customer.gleam");
    let paths = vec![domain.0.clone(), party.0.clone()];
    let root = RelativePath::parse("models").unwrap();
    let entries = BTreeMap::from([(RelativePath::root(), FileEntry::Directory), domain, party]);
    let mut request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: root.clone(),
            paths: paths.clone(),
        },
    );
    request.cli_overlay = json!({ "project": { "name": "acme/models" } });

    let snapshot = discover(request)
        .into_result()
        .expect("an ad-hoc selection with no manifest should synthesize a project");

    assert_eq!(snapshot.projects.len(), 1);
    let project = &snapshot.projects[0];
    assert_eq!(project.origin, ProjectOrigin::Synthesized { inputs: paths });
    assert_eq!(project.relative_path, root);
    assert_eq!(project.source_directory, RelativePath::root());
    // The exposed modules are intermediate data, not a final contract:
    // deriving them means parsing source, which is the provider's job. A
    // later provider-synthesis step fills these in; this task must not.
    assert_eq!(project.name, "acme/models");
    assert_eq!(project.exposed_modules, None);
    assert_eq!(project.config_anchor, None);
    assert_eq!(project.version, None);
    assert_eq!(project.state, crate::ProjectState::Unloaded);
    assert_eq!(snapshot.config_anchor, None);
}

/// An explicit `cli_overlay.project.name` reaches the synthesized snapshot
/// unchanged. Without this, discovery writes an empty name unconditionally
/// and a provider cannot tell "no name was given" from "a name was given and
/// lost on the way here".
#[test]
fn an_explicit_package_name_reaches_the_synthesized_snapshot() {
    let (path, entry) = gleam_source("models/domain/customer.gleam");
    let root = RelativePath::parse("models").unwrap();
    let entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (path.clone(), entry),
    ]);
    let mut request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: root.clone(),
            paths: vec![path],
        },
    );
    request.cli_overlay = json!({ "project": { "name": "acme/orders" } });

    let snapshot = discover(request)
        .into_result()
        .expect("an explicit overlay name should synthesize successfully");

    assert_eq!(snapshot.projects.len(), 1);
    assert_eq!(snapshot.projects[0].name, "acme/orders");
}

/// Surrounding whitespace on an explicit `cli_overlay.project.name` is
/// stripped before the name is stored, so `"  acme/widgets  "` and
/// `"acme/widgets"` name one package rather than two. The overlay's origin is
/// a command line, where a leading or trailing space is a shell artefact
/// rather than something an author wrote and can see; the CLI trims today, so
/// storing the raw string here would lose trimming that shipped behaviour
/// already has once the flag is routed through discovery. This pins the
/// stored value, not just the emptiness check, which reads the trimmed form
/// either way.
#[test]
fn an_explicit_package_name_is_stored_trimmed() {
    let (path, entry) = gleam_source("models/domain/customer.gleam");
    let root = RelativePath::parse("models").unwrap();
    let entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (path.clone(), entry),
    ]);
    let mut request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: root.clone(),
            paths: vec![path],
        },
    );
    request.cli_overlay = json!({ "project": { "name": "  acme/widgets  " } });

    let snapshot = discover(request)
        .into_result()
        .expect("an explicit overlay name should synthesize successfully");

    assert_eq!(snapshot.projects.len(), 1);
    assert_eq!(snapshot.projects[0].name, "acme/widgets");
}

/// Portable discovery no longer measures cardinality: how many *distinct*
/// sources a selection holds depends on the language, so an unnamed
/// multi-source selection passes through with an empty name for the provider
/// to judge (`discover_with_identity`).
#[test]
fn an_unnamed_multi_source_selection_is_left_for_the_provider_to_judge() {
    let domain = gleam_source("models/domain/customer.gleam");
    let party = gleam_source("models/party/customer.gleam");
    let paths = vec![domain.0.clone(), party.0.clone()];
    let root = RelativePath::parse("models").unwrap();
    let entries = BTreeMap::from([(RelativePath::root(), FileEntry::Directory), domain, party]);
    let request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection { root, paths },
    );

    let snapshot = discover(request)
        .into_result()
        .expect("portable discovery leaves cardinality to the provider");

    assert_eq!(snapshot.projects[0].name, "");
}

/// A non-string `cli_overlay.project.name` is a structurally invalid
/// override, not an absent one: it must not be silently treated as "no name
/// was given" and fall through to the cardinality rule.
#[test]
fn ad_hoc_overlay_project_name_must_be_a_string() {
    let (path, entry) = gleam_source("models/domain/customer.gleam");
    let root = RelativePath::parse("models").unwrap();
    let entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (path.clone(), entry),
    ]);
    let mut request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: root.clone(),
            paths: vec![path],
        },
    );
    request.cli_overlay = json!({ "project": { "name": 42 } });

    let error = discover(request).into_result().unwrap_err();

    assert_eq!(error.code, WORKSPACE_CONFIG_INVALID);
    assert!(error.message.contains("project.name"));
}

/// A whitespace-only `cli_overlay.project.name` is rejected outright rather
/// than treated as "no name was given": an override this visibly broken
/// deserves a loud diagnostic, not a silent fallback to the single-source
/// cardinality rule.
#[test]
fn ad_hoc_overlay_project_name_whitespace_only_is_rejected() {
    let (path, entry) = gleam_source("models/domain/customer.gleam");
    let root = RelativePath::parse("models").unwrap();
    let entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (path.clone(), entry),
    ]);
    let mut request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: root.clone(),
            paths: vec![path],
        },
    );
    request.cli_overlay = json!({ "project": { "name": "   " } });

    let error = discover(request).into_result().unwrap_err();

    assert_eq!(error.code, WORKSPACE_PROJECT_NAME_EMPTY);
}

#[test]
fn ad_hoc_empty_selection_is_rejected() {
    let root = RelativePath::parse("models").unwrap();
    let request = ad_hoc_request(Vec::new(), root);

    let error = discover(request).into_result().unwrap_err();

    assert_eq!(error.code, WORKSPACE_SELECTION_EMPTY);
    assert!(error.message.contains("models"));
}

#[test]
fn ad_hoc_selected_path_naming_a_directory_is_rejected() {
    let directory = RelativePath::parse("models/domain").unwrap();
    let entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (directory.clone(), FileEntry::Directory),
    ]);
    let request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: RelativePath::parse("models").unwrap(),
            paths: vec![directory.clone()],
        },
    );

    let error = discover(request).into_result().unwrap_err();

    assert_eq!(error.code, WORKSPACE_SELECTION_INVALID);
    assert!(error.message.contains(directory.as_str()));
}

#[test]
fn ad_hoc_selected_path_naming_nothing_is_rejected() {
    let missing = RelativePath::parse("models/domain/missing.gleam").unwrap();
    let entries = BTreeMap::from([(RelativePath::root(), FileEntry::Directory)]);
    let request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: RelativePath::parse("models").unwrap(),
            paths: vec![missing.clone()],
        },
    );

    let error = discover(request).into_result().unwrap_err();

    assert_eq!(error.code, WORKSPACE_SELECTION_INVALID);
    assert!(error.message.contains(missing.as_str()));
}

/// Decision: duplicate paths in a selection are rejected. The inputs are the
/// synthesized project's identity, so a repeat is a caller mistake that would
/// otherwise produce a duplicate module silently.
#[test]
fn ad_hoc_duplicate_selected_path_is_rejected() {
    let (path, entry) = gleam_source("models/domain/customer.gleam");
    let entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (path.clone(), entry),
    ]);
    let request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: RelativePath::parse("models").unwrap(),
            paths: vec![path.clone(), path.clone()],
        },
    );

    let error = discover(request).into_result().unwrap_err();

    assert_eq!(error.code, WORKSPACE_SELECTION_DUPLICATE);
    assert!(error.message.contains(path.as_str()));
}

/// A naive string-prefix confinement check would wave this through: the path
/// shares the text prefix `models` with the root, but `models-other` is a
/// sibling directory, not a child of `models`.
#[test]
fn ad_hoc_selected_path_sharing_a_string_prefix_with_root_is_rejected() {
    let (path, entry) = gleam_source("models-other/file.gleam");
    let entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (path.clone(), entry),
    ]);
    let request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: RelativePath::parse("models").unwrap(),
            paths: vec![path.clone()],
        },
    );

    let error = discover(request).into_result().unwrap_err();

    assert_eq!(error.code, WORKSPACE_SELECTION_OUTSIDE_ROOT);
    assert!(error.message.contains(path.as_str()));
}

/// The mount root `.` legitimately contains every confined path. A
/// naive check that required a non-empty root prefix would reject the
/// whole tree; segment comparison must not.
#[test]
fn ad_hoc_selection_root_of_dot_contains_every_path() {
    let (path, entry) = gleam_source("models/domain/customer.gleam");
    let entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (path.clone(), entry),
    ]);
    let request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: RelativePath::root(),
            paths: vec![path.clone()],
        },
    );

    let snapshot = discover(request)
        .into_result()
        .expect("a `.` selection root should confine, not reject, every selected path");

    assert_eq!(snapshot.projects.len(), 1);
    assert_eq!(snapshot.projects[0].relative_path, RelativePath::root());
}

fn manifest_request(with_manifest: bool, name: Option<&str>) -> DiscoveryRequest {
    let manifest_path = RelativePath::parse("morphir.toml").unwrap();
    let (path, entry) = gleam_source("models/domain/customer.gleam");
    let mut entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (path.clone(), entry),
    ]);
    if with_manifest {
        entries.insert(
            manifest_path.clone(),
            FileEntry::File {
                text: "[project]\nname = 'acme/declared'\n".to_owned(),
            },
        );
    }
    let mut request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Manifest {
            path: manifest_path,
        },
        SourceSelection {
            root: RelativePath::parse("models").unwrap(),
            paths: vec![path],
        },
    );
    if let Some(name) = name {
        request.cli_overlay = json!({ "project": { "name": name } });
    }
    request
}

/// A selection borrowing a manifest's identity takes its name from the
/// overlay, where the host states what it resolved from that manifest, and
/// records the manifest as the project's origin and anchor. The manifest's own
/// text is not read: `acme/declared` never reaches the snapshot.
#[test]
fn a_manifest_origin_selection_borrows_the_host_resolved_identity() {
    let snapshot = discover(manifest_request(true, Some("acme/widgets")))
        .into_result()
        .expect("a manifest-origin selection should discover");

    let project = &snapshot.projects[0];
    let manifest = RelativePath::parse("morphir.toml").unwrap();
    assert_eq!(project.name, "acme/widgets");
    assert_eq!(
        project.origin,
        ProjectOrigin::Manifest {
            path: manifest.clone()
        }
    );
    assert_eq!(project.config_anchor, Some(manifest));
    assert_eq!(
        project.relative_path,
        RelativePath::parse("models").unwrap()
    );
    assert_eq!(project.exposed_modules, None);
}

/// Without a name the host has not stated the manifest's identity, and
/// discovery will not read one from the manifest itself.
#[test]
fn a_manifest_origin_selection_requires_a_host_stated_name() {
    let error = discover(manifest_request(true, None))
        .into_result()
        .unwrap_err();

    assert_eq!(error.code, WORKSPACE_SELECTION_NAME_REQUIRED);
    assert!(error.message.contains("morphir.toml"));
}

#[test]
fn a_manifest_origin_selection_requires_the_manifest_to_exist() {
    let error = discover(manifest_request(false, Some("acme/widgets")))
        .into_result()
        .unwrap_err();

    assert_eq!(error.code, WORKSPACE_SELECTION_INVALID);
    assert!(error.message.contains("morphir.toml"));
}

/// `discover_with_details` must not panic on the ad-hoc path: the collector
/// needs a root effective config, which the ad-hoc case now supplies by
/// collecting defaults, environment and the CLI overlay directly, since
/// there is no workspace layer to collect instead.
#[test]
fn ad_hoc_discover_with_details_collects_defaults_and_overlay_without_panicking() {
    let path = RelativePath::parse("models/domain/customer.gleam").unwrap();
    let root = RelativePath::parse("models").unwrap();
    let mut request = ad_hoc_request(vec![path.clone()], root.clone());
    request.cli_overlay = json!({ "ir": { "mode": "cli-overlay" } });

    let details = discover_with_details(request)
        .expect("the ad-hoc path must collect a root config, not panic in `finish`");

    assert_eq!(details.root_effective["ir"]["mode"], "cli-overlay");
    assert_eq!(
        details.project_effective[&root]["ir"]["mode"],
        "cli-overlay"
    );
    assert_eq!(details.snapshot.projects.len(), 1);
}

/// The spec's standalone rule: a manifest present in the tree has no effect
/// on an ad-hoc synthesized request. This is the rule a later change is most
/// likely to erode, so it is pinned directly.
#[test]
fn ad_hoc_ignores_a_manifest_present_in_the_tree() {
    let (path, entry) = gleam_source("models/domain/customer.gleam");
    let entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (path.clone(), entry),
        (
            RelativePath::parse("morphir.toml").unwrap(),
            FileEntry::File {
                text: "[workspace]\nmembers = [\"packages/*\"]\n[project]\nname = \"acme/root\"\nsource_directory = \"src\"\n"
                    .to_owned(),
            },
        ),
    ]);
    let root = RelativePath::parse("models").unwrap();
    let request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: root.clone(),
            paths: vec![path.clone()],
        },
    );

    let snapshot = discover(request)
        .into_result()
        .expect("an ad-hoc request should succeed even with a manifest present in the tree");

    assert_eq!(snapshot.projects.len(), 1);
    let project = &snapshot.projects[0];
    assert_eq!(
        project.origin,
        ProjectOrigin::Synthesized { inputs: vec![path] }
    );
    assert_eq!(project.relative_path, root);
    assert_eq!(project.name, "");
    assert_eq!(snapshot.config_anchor, None);
}

/// `discover_with_details` at `sources.root == "."` combines two invariants
/// each existing test only covers half of: it must not panic collecting a
/// root config, and `DetailsCollector::finish` must re-insert `"."` into
/// `project_effective`. That re-insertion matters beyond this crate:
/// `morphir-daemon`'s `Workspace::from_discovery` calls
/// `project_configs.remove(&project.relative_path).expect(...)` and panics if
/// the entry is missing, so a project whose `relative_path` is the mount root
/// must still have an effective config recorded for it.
#[test]
fn ad_hoc_discover_with_details_at_root_reinserts_root_into_project_effective() {
    let path = RelativePath::parse("models/domain/customer.gleam").unwrap();
    let root = RelativePath::root();
    let request = ad_hoc_request(vec![path], root.clone());

    let details = discover_with_details(request)
        .expect("the ad-hoc path at `.` must collect a root config, not panic in `finish`");

    assert_eq!(details.snapshot.projects.len(), 1);
    assert_eq!(details.snapshot.projects[0].relative_path, root);
    assert_eq!(
        details.project_effective.get(&root),
        Some(&details.root_effective)
    );
}

/// A caller sending `root: "models", paths: ["models"]` is reachable: the
/// path names the root itself. `path_is_under_root` rejects it because it
/// requires the path to be strictly deeper than the root, so this never
/// reaches the file-existence check — the path is a directory, not a file,
/// and would fail differently there. That ordering is what makes this safe;
/// pin the diagnostic so a later refactor that reorders the checks is caught.
#[test]
fn ad_hoc_selected_path_equal_to_root_is_rejected_by_confinement_not_file_existence() {
    let root = RelativePath::parse("models").unwrap();
    let entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (root.clone(), FileEntry::Directory),
    ]);
    let request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: root.clone(),
            paths: vec![root.clone()],
        },
    );

    let error = discover(request).into_result().unwrap_err();

    assert_eq!(error.code, WORKSPACE_SELECTION_OUTSIDE_ROOT);
    assert!(error.message.contains(root.as_str()));
}

/// An empty language id is a caller mistake distinct from an unconfined or
/// missing path, and gets its own diagnostic rather than surfacing as a
/// confusing downstream failure.
#[test]
fn ad_hoc_empty_language_id_is_rejected() {
    let (path, entry) = gleam_source("models/domain/customer.gleam");
    let entries = BTreeMap::from([
        (RelativePath::root(), FileEntry::Directory),
        (path.clone(), entry),
    ]);
    let mut request = ad_hoc_request_with_entries(
        entries,
        ProjectSource::Synthesized,
        SourceSelection {
            root: RelativePath::parse("models").unwrap(),
            paths: vec![path],
        },
    );
    let DiscoveryPurpose::AdHocSources {
        language_id: purpose_language_id,
        ..
    } = &mut request.purpose
    else {
        unreachable!("ad_hoc_request_with_entries always builds an AdHocSources purpose")
    };
    purpose_language_id.clear();

    let error = discover(request).into_result().unwrap_err();

    assert_eq!(error.code, WORKSPACE_LANGUAGE_ID_EMPTY);
    assert!(error.message.contains("models"));
}