vespera_macro 0.4.0

Procedural macros for Vespera - automatic route discovery and OpenAPI generation
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
use std::{collections::HashMap, path::Path};

use crate::{
    error::{MacroResult, err_call_site},
    metadata::CollectedMetadata,
    openapi_generator::{OpenApiSecurity, try_generate_openapi_doc_with_metadata},
    route_impl::StoredRouteInfo,
    router_codegen::ProcessedVesperaInput,
};
use proc_macro2::Span;
use syn::spanned::Spanned;

use super::{
    cache::{MergeSpecCache, MergeSpecRead, path_fingerprint},
    path_utils::{current_crate_tag, find_target_dir},
    schema_merge::SchemaMergeGuard,
};

fn display_merge_path(path: &syn::Path) -> String {
    path.segments
        .iter()
        .map(|segment| segment.ident.to_string())
        .collect::<Vec<_>>()
        .join("::")
}

/// OpenAPI write result consumed by router/doc codegen and incremental cache sidecars.
///
/// The docs/redoc URLs are intentionally **not** carried here: the sole
/// consumer (`vespera_impl::orchestrator`) reads them straight off
/// `ProcessedVesperaInput`, so mirroring them would be dead weight.
#[derive(Debug)]
pub struct OpenApiWriteResult {
    pub spec_json: Option<String>,
    pub spec_pretty: Option<String>,
}

pub(super) struct EmbeddedSpecWrite {
    pub(super) tokens: proc_macro2::TokenStream,
    pub(super) fingerprint: Option<u64>,
}

/// Whether `path` already holds exactly `content`.
///
/// A cheap `metadata().len()` pre-check skips the full `read_to_string`
/// whenever the byte length alone proves the content changed (the common
/// case when a regenerated spec differs) — only an exact length match
/// falls back to the full read + compare.  Missing or unreadable files
/// count as "changed", so the caller writes — exactly like the previous
/// `read_to_string(...).map_or(true, |e| e != content)` this replaces.
pub(super) fn content_unchanged(path: &Path, content: &str) -> bool {
    std::fs::metadata(path).is_ok_and(|m| m.len() == content.len() as u64)
        && std::fs::read_to_string(path).is_ok_and(|existing| existing == content)
}

pub(super) fn write_if_changed(path: &Path, content: &str) -> std::io::Result<Option<u64>> {
    if !content_unchanged(path, content) {
        std::fs::write(path, content)?;
    }
    Ok(path_fingerprint(path))
}

/// Generate `OpenAPI` JSON and write to files, returning docs info
pub fn generate_and_write_openapi(
    input: &ProcessedVesperaInput,
    metadata: &CollectedMetadata,
    file_asts: HashMap<String, syn::File>,
    route_storage: &[StoredRouteInfo],
    merge_specs: &mut MergeSpecCache,
) -> MacroResult<OpenApiWriteResult> {
    if input.openapi_file_names.is_empty() && input.docs_url.is_none() && input.redoc_url.is_none()
    {
        return Ok(OpenApiWriteResult {
            spec_json: None,
            spec_pretty: None,
        });
    }

    let mut openapi_doc = try_generate_openapi_doc_with_metadata(
        input.title.clone(),
        input.version.clone(),
        input.servers.clone(),
        Some(OpenApiSecurity {
            security_schemes: input.security_schemes.clone(),
            security: input.security.clone(),
            tag_descriptions: input.tag_descriptions.clone(),
        }),
        metadata,
        Some(file_asts),
        route_storage,
    )?;

    // Merge specs from child apps at compile time. This is the one point where
    // the parent and every exported child definition are all available, so
    // schema-name conflicts are checked here before OpenApi's first-wins merge
    // can discard a later definition.
    if !input.merge.is_empty() {
        let mut schema_guard = SchemaMergeGuard::new(&openapi_doc)?;
        for merge_path in &input.merge {
            // Extract the struct name (last segment, e.g., "ThirdApp" from "third::ThirdApp")
            if let Some((struct_name, spec_file)) = merge_specs.spec_file_for(merge_path) {
                let spec_content = match merge_specs.read(&spec_file) {
                    MergeSpecRead::Present(content) => content,
                    MergeSpecRead::Error(e) => {
                        return Err(err_call_site(format!(
                            "OpenAPI merge: failed to read child spec for `{struct_name}` at '{}'. Error: {e}. Ensure the child crate containing `export_app!({struct_name})` is built before the parent app.",
                            spec_file.display()
                        )));
                    }
                };
                let child_spec = serde_json::from_str::<vespera_core::openapi::OpenApi>(spec_content).map_err(|e| err_call_site(format!("OpenAPI merge: failed to parse child spec for `{struct_name}` at '{}'. Error: {e}.", spec_file.display())))?;
                let child_origin = format!("merged app `{}`", display_merge_path(merge_path));
                schema_guard.check_child(&child_spec, &child_origin, merge_path.span())?;
                openapi_doc.merge(child_spec);
            }
        }
    }

    // NOTE on F-01: an earlier audit suggested serialising the
    // `OpenApi` document once into `serde_json::Value` and emitting
    // pretty + compact from the cached `Value`.  We deliberately do
    // **not** do that here.  Going through `Value` re-orders every
    // object's keys alphabetically (because the default
    // `serde_json::Map` is `BTreeMap`-backed), which silently changes
    // the field order in every user-visible `openapi.json` file.  The
    // marginal build-time saving is not worth churning the output of a
    // file users diff in CI.  Keep two direct serialisations.
    //
    // Pretty-print for user-visible files.
    let spec_pretty = if input.openapi_file_names.is_empty() {
        None
    } else {
        let json_pretty = serde_json::to_string_pretty(&openapi_doc).map_err(|e| err_call_site(format!("OpenAPI generation: failed to serialize document to JSON. Error: {e}. Check that all schema types are serializable.")))?;
        for openapi_file_name in &input.openapi_file_names {
            let file_path = Path::new(openapi_file_name);
            if let Some(parent) = file_path.parent() {
                std::fs::create_dir_all(parent).map_err(|e| err_call_site(format!("OpenAPI output: failed to create directory '{}'. Error: {}. Ensure the path is valid and writable.", parent.display(), e)))?;
            }
            let should_write = !content_unchanged(file_path, &json_pretty);
            if should_write {
                std::fs::write(file_path, &json_pretty).map_err(|e| err_call_site(format!("OpenAPI output: failed to write file '{openapi_file_name}'. Error: {e}. Ensure the file path is writable.")))?;
            }
        }
        Some(json_pretty)
    };

    // Compact JSON for embedding (smaller binary, faster downstream compilation).
    let spec_json = if input.docs_url.is_some() || input.redoc_url.is_some() {
        Some(serde_json::to_string(&openapi_doc).map_err(|e| err_call_site(format!("OpenAPI generation: failed to serialize document to JSON. Error: {e}. Check that all schema types are serializable.")))?)
    } else {
        None
    };

    Ok(OpenApiWriteResult {
        spec_json,
        spec_pretty,
    })
}

/// Write cached OpenAPI spec to output files if they are stale or missing.
pub fn ensure_openapi_files_from_cache(
    openapi_file_names: &[String],
    spec_pretty: Option<&str>,
) -> syn::Result<()> {
    let Some(pretty) = spec_pretty else {
        return Ok(());
    };
    for openapi_file_name in openapi_file_names {
        let file_path = Path::new(openapi_file_name);
        let should_write = !content_unchanged(file_path, pretty);
        if should_write {
            if let Some(parent) = file_path.parent() {
                std::fs::create_dir_all(parent).map_err(|e| {
                    syn::Error::new(
                        Span::call_site(),
                        format!(
                            "OpenAPI output: failed to create directory '{}': {}",
                            parent.display(),
                            e
                        ),
                    )
                })?;
            }
            std::fs::write(file_path, pretty).map_err(|e| {
                syn::Error::new(
                    Span::call_site(),
                    format!("OpenAPI output: failed to write file '{openapi_file_name}': {e}"),
                )
            })?;
        }
    }
    Ok(())
}

/// Path of the compact-spec embed sidecar (`include_str!` target).
///
/// The file name is **namespaced per crate**: two workspace members
/// both using `vespera!` compile in parallel under the same shared
/// `target/vespera/` directory — with a single shared file name, crate
/// A's `include_str!` could read the spec crate B just wrote.
pub(super) fn embed_spec_path() -> std::path::PathBuf {
    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default();
    find_target_dir(Path::new(&manifest_dir))
        .join("vespera")
        .join(format!("vespera_spec-{}.json", current_crate_tag()))
}

/// Path of the pretty-spec sidecar (warm-rebuild source for
/// `openapi.json` recovery — see `ensure_openapi_files_from_cache`).
pub(super) fn pretty_sidecar_path() -> std::path::PathBuf {
    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default();
    find_target_dir(Path::new(&manifest_dir))
        .join("vespera")
        .join(format!("openapi_pretty-{}.json", current_crate_tag()))
}

/// Build the `include_str!` tokens pointing at the embed sidecar.
fn embed_tokens(spec_file: &Path) -> proc_macro2::TokenStream {
    let path_str = crate::file_utils::path_to_include_str_literal(spec_file);
    quote::quote! { include_str!(#path_str) }
}

/// Hash-validated sidecar specs loaded on a warm cache hit.
pub(super) struct SidecarSpecs {
    /// Pretty spec content (for `openapi.json` recovery); `None` when
    /// no openapi file is configured.
    pub(super) pretty: Option<String>,
    /// `include_str!` tokens for the embed sidecar; `None` when docs
    /// are disabled.
    pub(super) spec_tokens: Option<proc_macro2::TokenStream>,
}

/// Load and hash-validate the sidecar spec files on a warm cache hit.
///
/// Returns `None` when any expected sidecar is missing or fails its
/// content-hash check — the caller must then treat the cache as a miss
/// (a full regeneration rewrites both sidecars, so corruption
/// self-heals on the next build).
pub(super) fn load_validated_sidecar_specs(
    spec_json_hash: Option<u64>,
    spec_pretty_hash: Option<u64>,
    spec_json_fingerprint: Option<u64>,
    spec_pretty_fingerprint: Option<u64>,
) -> Option<SidecarSpecs> {
    let spec_tokens = match (spec_json_hash, spec_json_fingerprint) {
        (None, _) => None,
        (Some(expected_hash), Some(expected_fingerprint)) => {
            let path = embed_spec_path();
            if !super::cache::sidecar_matches(
                &path,
                Some(expected_hash),
                Some(expected_fingerprint),
            ) {
                return None;
            }
            Some(embed_tokens(&path))
        }
        (Some(_), None) => return None,
    };
    let pretty = match (spec_pretty_hash, spec_pretty_fingerprint) {
        (None, _) => None,
        (Some(expected_hash), Some(expected_fingerprint)) => {
            let path = pretty_sidecar_path();
            let content = std::fs::read_to_string(&path).ok()?;
            if super::cache::path_fingerprint(&path) != Some(expected_fingerprint)
                && super::cache::hash_str(&content) != expected_hash
            {
                return None;
            }
            Some(content)
        }
        (Some(_), None) => return None,
    };
    Some(SidecarSpecs {
        pretty,
        spec_tokens,
    })
}

/// Write the pretty-spec sidecar (write-if-differs).  Best-effort like
/// the cache itself: failures only cost a future cache miss.
pub(super) fn write_pretty_sidecar(spec_pretty: Option<&str>) -> Option<u64> {
    let pretty = spec_pretty?;
    let path = pretty_sidecar_path();
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    write_if_changed(&path, pretty).ok().flatten()
}

/// Write compact spec JSON to target dir for `include_str!` embedding.
pub(super) fn write_spec_for_embedding(
    spec_json: Option<String>,
) -> syn::Result<Option<EmbeddedSpecWrite>> {
    let Some(json) = spec_json else {
        return Ok(None);
    };
    let spec_file = embed_spec_path();
    if let Some(parent) = spec_file.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            syn::Error::new(
                Span::call_site(),
                format!(
                    "vespera! macro: failed to create directory '{}': {}",
                    parent.display(),
                    e
                ),
            )
        })?;
    }
    let fingerprint = write_if_changed(&spec_file, &json).map_err(|e| {
        syn::Error::new(
            Span::call_site(),
            format!(
                "vespera! macro: failed to write spec file '{}': {}",
                spec_file.display(),
                e
            ),
        )
    })?;
    Ok(Some(EmbeddedSpecWrite {
        tokens: embed_tokens(&spec_file),
        fingerprint,
    }))
}

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

    use tempfile::TempDir;

    use super::*;
    use crate::vespera_impl::cache::hash_str;

    #[test]
    fn test_generate_and_write_openapi_no_output() {
        let processed = ProcessedVesperaInput {
            folder_name: "routes".to_string(),
            openapi_file_names: vec![],
            title: None,
            version: None,
            docs_url: None,
            redoc_url: None,
            servers: None,
            security_schemes: None,
            security: None,
            tag_descriptions: None,
            merge: vec![],
        };
        let metadata = CollectedMetadata::new();
        let result = generate_and_write_openapi(
            &processed,
            &metadata,
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        );
        assert!(result.is_ok());
        let result = result.unwrap();
        assert!(result.spec_json.is_none());
        assert!(result.spec_pretty.is_none());
    }

    #[test]
    fn test_generate_and_write_openapi_docs_only() {
        let processed = ProcessedVesperaInput {
            folder_name: "routes".to_string(),
            openapi_file_names: vec![],
            title: Some("Test API".to_string()),
            version: Some("1.0.0".to_string()),
            docs_url: Some("/docs".to_string()),
            redoc_url: None,
            servers: None,
            security_schemes: None,
            security: None,
            tag_descriptions: None,
            merge: vec![],
        };
        let metadata = CollectedMetadata::new();
        let result = generate_and_write_openapi(
            &processed,
            &metadata,
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        );
        assert!(result.is_ok());
        let result = result.unwrap();
        assert!(result.spec_pretty.is_none());
        assert!(result.spec_json.is_some());
        let json = result.spec_json.unwrap();
        assert!(json.contains("\"openapi\""));
        assert!(json.contains("Test API"));
    }

    #[test]
    fn test_generate_and_write_openapi_redoc_only() {
        let processed = ProcessedVesperaInput {
            folder_name: "routes".to_string(),
            openapi_file_names: vec![],
            title: None,
            version: None,
            docs_url: None,
            redoc_url: Some("/redoc".to_string()),
            servers: None,
            security_schemes: None,
            security: None,
            tag_descriptions: None,
            merge: vec![],
        };
        let metadata = CollectedMetadata::new();
        let result = generate_and_write_openapi(
            &processed,
            &metadata,
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        );
        assert!(result.is_ok());
        let result = result.unwrap();
        assert!(result.spec_json.is_some());
        assert!(result.spec_pretty.is_none());
    }

    #[test]
    fn test_generate_and_write_openapi_both_docs() {
        let processed = ProcessedVesperaInput {
            folder_name: "routes".to_string(),
            openapi_file_names: vec![],
            title: None,
            version: None,
            docs_url: Some("/docs".to_string()),
            redoc_url: Some("/redoc".to_string()),
            servers: None,
            security_schemes: None,
            security: None,
            tag_descriptions: None,
            merge: vec![],
        };
        let metadata = CollectedMetadata::new();
        let result = generate_and_write_openapi(
            &processed,
            &metadata,
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        );
        assert!(result.is_ok());
        let result = result.unwrap();
        assert!(result.spec_json.is_some());
        assert!(result.spec_pretty.is_none());
    }

    #[test]
    fn test_generate_and_write_openapi_file_output() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let output_path = temp_dir.path().join("test-openapi.json");

        let processed = ProcessedVesperaInput {
            folder_name: "routes".to_string(),
            openapi_file_names: vec![output_path.to_string_lossy().to_string()],
            title: Some("File Test".to_string()),
            version: Some("2.0.0".to_string()),
            docs_url: None,
            redoc_url: None,
            servers: None,
            security_schemes: None,
            security: None,
            tag_descriptions: None,
            merge: vec![],
        };
        let metadata = CollectedMetadata::new();
        let result = generate_and_write_openapi(
            &processed,
            &metadata,
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        );
        assert!(result.is_ok());

        // Verify file was written
        assert!(output_path.exists());
        let content = fs::read_to_string(&output_path).unwrap();
        assert!(content.contains("\"openapi\""));
        assert!(content.contains("File Test"));
        assert!(content.contains("2.0.0"));
    }

    #[test]
    fn test_generate_and_write_openapi_creates_directories() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let output_path = temp_dir.path().join("nested/dir/openapi.json");

        let processed = ProcessedVesperaInput {
            folder_name: "routes".to_string(),
            openapi_file_names: vec![output_path.to_string_lossy().to_string()],
            title: None,
            version: None,
            docs_url: None,
            redoc_url: None,
            servers: None,
            security_schemes: None,
            security: None,
            tag_descriptions: None,
            merge: vec![],
        };
        let metadata = CollectedMetadata::new();
        let result = generate_and_write_openapi(
            &processed,
            &metadata,
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        );
        assert!(result.is_ok());

        // Verify nested directories and file were created
        assert!(output_path.exists());
    }

    #[serial_test::serial]
    #[test]
    fn test_generate_and_write_openapi_with_merge_no_manifest_dir() {
        // When CARGO_MANIFEST_DIR is not set or merge is empty, it should work normally
        let old_manifest_dir = std::env::var("CARGO_MANIFEST_DIR").ok();
        // SAFETY: This serial test temporarily removes process environment to
        // exercise the no-manifest fallback branch.
        unsafe { std::env::remove_var("CARGO_MANIFEST_DIR") };

        let processed = ProcessedVesperaInput {
            folder_name: "routes".to_string(),
            openapi_file_names: vec![],
            title: Some("Test".to_string()),
            version: None,
            docs_url: Some("/docs".to_string()),
            redoc_url: None,
            servers: None,
            security_schemes: None,
            security: None,
            tag_descriptions: None,
            merge: vec![syn::parse_quote!(app::TestApp)], // Has merge but no valid manifest dir
        };
        let metadata = CollectedMetadata::new();
        // This should still work - merge logic is skipped when CARGO_MANIFEST_DIR lookup fails
        let result = generate_and_write_openapi(
            &processed,
            &metadata,
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        );
        if let Some(value) = old_manifest_dir {
            // SAFETY: This serial test restores the process environment it changed.
            unsafe { std::env::set_var("CARGO_MANIFEST_DIR", value) };
        }
        assert!(result.is_ok());
    }

    #[serial_test::serial]
    #[test]
    fn test_generate_and_write_openapi_with_merge_and_valid_spec() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Create the vespera directory with a spec file
        let target_dir = temp_dir.path().join("target").join("vespera");
        fs::create_dir_all(&target_dir).expect("Failed to create target/vespera dir");

        // Write a valid OpenAPI spec file
        let spec_content =
            r#"{"openapi":"3.1.0","info":{"title":"Child API","version":"1.0.0"},"paths":{}}"#;
        fs::write(target_dir.join("ChildApp.openapi.json"), spec_content)
            .expect("Failed to write spec file");

        // Save and set CARGO_MANIFEST_DIR
        let old_manifest_dir = std::env::var("CARGO_MANIFEST_DIR").ok();
        // SAFETY: We're in a single-threaded test context
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };

        let processed = ProcessedVesperaInput {
            folder_name: "routes".to_string(),
            openapi_file_names: vec![],
            title: Some("Parent API".to_string()),
            version: Some("2.0.0".to_string()),
            docs_url: Some("/docs".to_string()),
            redoc_url: None,
            servers: None,
            security_schemes: None,
            security: None,
            tag_descriptions: None,
            merge: vec![syn::parse_quote!(child::ChildApp)],
        };
        let metadata = CollectedMetadata::new();

        let result = generate_and_write_openapi(
            &processed,
            &metadata,
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        );

        // Restore CARGO_MANIFEST_DIR
        if let Some(old_value) = old_manifest_dir {
            // SAFETY: We're in a single-threaded test context
            unsafe { std::env::set_var("CARGO_MANIFEST_DIR", old_value) };
        }

        assert!(result.is_ok());
    }

    #[serial_test::serial]
    #[test]
    fn merged_child_schema_conflict_is_a_spanned_compile_error() {
        let temp_dir = TempDir::new().unwrap();
        let target_dir = temp_dir.path().join("target/vespera");
        fs::create_dir_all(&target_dir).unwrap();
        let spec = |property: &str, schema_type: &str| {
            serde_json::json!({
                "openapi": "3.1.0",
                "info": { "title": "child", "version": "1.0.0" },
                "paths": {},
                "components": {
                    "schemas": {
                        "ExampleItem": {
                            "type": "object",
                            "properties": { (property): { "type": schema_type } }
                        }
                    }
                }
            })
            .to_string()
        };
        fs::write(
            target_dir.join("PluginA.openapi.json"),
            spec("id", "string"),
        )
        .unwrap();
        fs::write(
            target_dir.join("PluginB.openapi.json"),
            spec("collisionMarker", "boolean"),
        )
        .unwrap();

        let _restore = RestoreManifest(std::env::var("CARGO_MANIFEST_DIR").ok());
        // SAFETY: this serialized test restores the process environment through RAII.
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp_dir.path()) };
        let mut processed = merge_input(syn::parse_quote!(plugin_a::PluginA));
        processed.merge.push(syn::parse_quote!(plugin_b::PluginB));
        let error = generate_and_write_openapi(
            &processed,
            &CollectedMetadata::new(),
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        )
        .expect_err("different same-named child schemas must fail the build");
        let message = error.to_string();
        assert!(message.contains("Duplicate OpenAPI schema name 'ExampleItem'"));
        assert!(message.contains("plugin_a::PluginA"));
        assert!(message.contains("plugin_b::PluginB"));
    }

    #[test]
    fn test_generate_and_write_openapi_file_write_error() {
        // Line 95: fs::write failure when output path is a directory
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Create a directory where the output file should be
        let output_path = temp_dir.path().join("openapi.json");
        fs::create_dir(&output_path).expect("Failed to create directory");

        let processed = ProcessedVesperaInput {
            folder_name: "routes".to_string(),
            openapi_file_names: vec![output_path.to_string_lossy().to_string()],
            title: Some("Test API".to_string()),
            version: Some("1.0.0".to_string()),
            docs_url: None,
            redoc_url: None,
            servers: None,
            security_schemes: None,
            security: None,
            tag_descriptions: None,
            merge: vec![],
        };
        let metadata = CollectedMetadata::new();

        let result = generate_and_write_openapi(
            &processed,
            &metadata,
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        );
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("failed to write file"));
    }

    #[test]
    fn test_ensure_openapi_files_from_cache_none_spec() {
        // Exercises lines 266-267: early return when spec_pretty is None
        let result = ensure_openapi_files_from_cache(&["dummy.json".to_string()], None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_ensure_openapi_files_from_cache_writes_file() {
        // Exercises lines 269-276: write new file
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let output_path = temp_dir.path().join("api.json");
        let spec = r#"{"openapi":"3.1.0"}"#;

        let result = ensure_openapi_files_from_cache(
            &[output_path.to_string_lossy().to_string()],
            Some(spec),
        );
        assert!(result.is_ok());
        assert_eq!(fs::read_to_string(&output_path).unwrap(), spec);
    }

    #[test]
    fn test_ensure_openapi_files_from_cache_skip_unchanged() {
        // Exercises line 271-272: should_write is false when content matches
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let output_path = temp_dir.path().join("api.json");
        let spec = r#"{"openapi":"3.1.0"}"#;

        // Write file first with same content
        fs::write(&output_path, spec).unwrap();

        let result = ensure_openapi_files_from_cache(
            &[output_path.to_string_lossy().to_string()],
            Some(spec),
        );
        assert!(result.is_ok());
        // File should still contain same content (no unnecessary write)
        assert_eq!(fs::read_to_string(&output_path).unwrap(), spec);
    }

    #[test]
    fn test_ensure_openapi_files_from_cache_creates_parent_dirs() {
        // Exercises lines 273-274: create parent directories
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let output_path = temp_dir.path().join("nested").join("dir").join("api.json");
        let spec = r#"{"openapi":"3.1.0"}"#;

        let result = ensure_openapi_files_from_cache(
            &[output_path.to_string_lossy().to_string()],
            Some(spec),
        );
        assert!(result.is_ok());
        assert!(output_path.exists());
        assert_eq!(fs::read_to_string(&output_path).unwrap(), spec);
    }

    #[test]
    fn test_ensure_openapi_files_from_cache_write_error() {
        // Exercises line 276: write failure
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let output_path = temp_dir.path().join("api.json");

        // Create a directory where the file should be -> write will fail
        fs::create_dir(&output_path).unwrap();

        let result = ensure_openapi_files_from_cache(
            &[output_path.to_string_lossy().to_string()],
            Some("spec"),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_ensure_openapi_files_from_cache_multiple_files() {
        // Exercises the loop with multiple file names (line 269)
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let path1 = temp_dir.path().join("api1.json");
        let path2 = temp_dir.path().join("api2.json");
        let spec = r#"{"openapi":"3.1.0"}"#;

        let result = ensure_openapi_files_from_cache(
            &[
                path1.to_string_lossy().to_string(),
                path2.to_string_lossy().to_string(),
            ],
            Some(spec),
        );
        assert!(result.is_ok());
        assert_eq!(fs::read_to_string(&path1).unwrap(), spec);
        assert_eq!(fs::read_to_string(&path2).unwrap(), spec);
    }

    struct RestoreManifest(Option<String>);

    impl Drop for RestoreManifest {
        fn drop(&mut self) {
            // SAFETY: environment-mutating tests are serialized and restore their prior value.
            unsafe {
                match self.0.take() {
                    Some(value) => std::env::set_var("CARGO_MANIFEST_DIR", value),
                    None => std::env::remove_var("CARGO_MANIFEST_DIR"),
                }
            }
        }
    }

    fn merge_input(path: syn::Path) -> ProcessedVesperaInput {
        ProcessedVesperaInput {
            folder_name: "routes".to_string(),
            openapi_file_names: Vec::new(),
            title: None,
            version: None,
            docs_url: Some("/docs".to_string()),
            redoc_url: None,
            servers: None,
            security_schemes: None,
            security: None,
            tag_descriptions: None,
            merge: vec![path],
        }
    }

    #[test]
    #[serial_test::serial]
    fn merge_reports_missing_and_malformed_child_specs() {
        let temp = TempDir::new().unwrap();
        let vespera_dir = temp.path().join("target/vespera");
        fs::create_dir_all(&vespera_dir).unwrap();
        let _restore = RestoreManifest(std::env::var("CARGO_MANIFEST_DIR").ok());
        // SAFETY: this serialized test restores the process environment through RAII.
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp.path()) };

        let missing = generate_and_write_openapi(
            &merge_input(syn::parse_quote!(child::MissingChild)),
            &CollectedMetadata::new(),
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        )
        .expect_err("missing child sidecar must fail");
        assert!(missing.to_string().contains("failed to read child spec"));

        fs::write(vespera_dir.join("BrokenChild.openapi.json"), "not-json").unwrap();
        let malformed = generate_and_write_openapi(
            &merge_input(syn::parse_quote!(child::BrokenChild)),
            &CollectedMetadata::new(),
            HashMap::new(),
            &[],
            &mut MergeSpecCache::new(),
        )
        .expect_err("malformed child sidecar must fail");
        assert!(malformed.to_string().contains("failed to parse child spec"));
    }

    #[test]
    fn ensure_cached_openapi_reports_parent_creation_error() {
        let temp = TempDir::new().unwrap();
        let blocking_parent = temp.path().join("blocking");
        fs::write(&blocking_parent, "file").unwrap();
        let output = blocking_parent.join("openapi.json");

        let error =
            ensure_openapi_files_from_cache(&[output.to_string_lossy().into_owned()], Some("{}"))
                .expect_err("a file cannot be created as a directory");
        assert!(error.to_string().contains("failed to create directory"));
    }

    #[test]
    #[serial_test::serial]
    fn sidecar_validation_covers_missing_fingerprints_corruption_and_success() {
        let temp = TempDir::new().unwrap();
        let _restore = RestoreManifest(std::env::var("CARGO_MANIFEST_DIR").ok());
        // SAFETY: this serialized test restores the process environment through RAII.
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", temp.path()) };
        let vespera_dir = temp.path().join("target/vespera");
        fs::create_dir_all(&vespera_dir).unwrap();
        let compact = embed_spec_path();
        let pretty = pretty_sidecar_path();
        fs::write(&compact, "compact").unwrap();
        fs::write(&pretty, "pretty").unwrap();
        let compact_fp = path_fingerprint(&compact).unwrap();
        let pretty_fp = path_fingerprint(&pretty).unwrap();

        assert!(
            load_validated_sidecar_specs(Some(hash_str("compact")), None, None, None).is_none()
        );
        assert!(load_validated_sidecar_specs(None, Some(hash_str("pretty")), None, None).is_none());
        assert!(
            load_validated_sidecar_specs(
                Some(hash_str("wrong")),
                None,
                Some(compact_fp.wrapping_add(1)),
                None,
            )
            .is_none()
        );
        assert!(
            load_validated_sidecar_specs(
                None,
                Some(hash_str("wrong")),
                None,
                Some(pretty_fp.wrapping_add(1)),
            )
            .is_none()
        );

        let loaded = load_validated_sidecar_specs(
            Some(hash_str("compact")),
            Some(hash_str("pretty")),
            Some(compact_fp),
            Some(pretty_fp),
        )
        .expect("matching sidecars load");
        assert_eq!(loaded.pretty.as_deref(), Some("pretty"));
        assert!(loaded.spec_tokens.is_some());
    }

    #[test]
    fn sidecar_validation_accepts_cache_without_generated_specs() {
        let loaded = load_validated_sidecar_specs(None, None, None, None)
            .expect("a cache without configured specs needs no sidecar validation");

        assert!(loaded.pretty.is_none());
        assert!(loaded.spec_tokens.is_none());
    }

    #[test]
    #[serial_test::serial]
    fn embedding_reports_directory_creation_and_spec_write_errors() {
        let create_temp = TempDir::new().unwrap();
        let _restore = RestoreManifest(std::env::var("CARGO_MANIFEST_DIR").ok());
        // SAFETY: this serialized test restores the process environment through RAII.
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", create_temp.path()) };
        fs::create_dir_all(create_temp.path().join("target")).unwrap();
        fs::write(create_temp.path().join("target/vespera"), "blocking file").unwrap();
        let Err(create_error) = write_spec_for_embedding(Some("{}".to_string())) else {
            panic!("blocking parent must fail directory creation");
        };
        assert!(
            create_error
                .to_string()
                .contains("failed to create directory")
        );

        let write_temp = TempDir::new().unwrap();
        // SAFETY: this serialized test restores the process environment through RAII.
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", write_temp.path()) };
        let spec_path = embed_spec_path();
        fs::create_dir_all(&spec_path).unwrap();
        let Err(write_error) = write_spec_for_embedding(Some("{}".to_string())) else {
            panic!("a directory cannot be overwritten as a spec file");
        };
        assert!(
            write_error
                .to_string()
                .contains("failed to write spec file")
        );
    }
}