aion-server 0.27.0

Aion workflow server library: HTTP, gRPC, WebSocket, and worker endpoints. Run it with the `aion` binary from the aion-cli crate.
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
//! Tests for the boot-side config heal.
//!
//! The enumeration test is the load-bearing one: it walks
//! [`BOOT_REQUIRED_FIELD_DEFAULTS`] — never a hand-kept copy — strips each
//! declared field (and all of them at once) from a complete config, proves
//! the probe refuses each stripped file with the exact message the table row
//! declares, and proves the heal makes the FILE whole again under the same
//! probe. A new required field added to the requirement functions without a
//! table row fails the all-at-once leg here (the heal stops on the unknown
//! refusal and the healed file still fails the probe) — and the census in
//! `state::boot_required` fails it by name.

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

use crate::config::ServerConfig;
use crate::state::{BOOT_REQUIRED_FIELD_DEFAULTS, boot_required_probe};

use super::{HealOutcome, heal_config_file, heal_discovered};

type TestResult = Result<(), Box<dyn std::error::Error>>;

/// The version the heal stamps into markers and backup names.
const HEAL_VERSION: &str = env!("CARGO_PKG_VERSION");

/// No environment overlay: the common test posture.
const NO_ENV: &[(String, String)] = &[];

/// A complete haematite config in the shipped teaching shape, with operator
/// comments and deliberate formatting quirks the heal must never disturb.
const COMPLETE_HAEMATITE: &str = "\
# the operator's own leading comment\n\
[server]\n\
listen_address   = \"127.0.0.1:18080\"    # odd spacing, kept on purpose\n\
\n\
[store]\n\
backend = \"haematite\"\n\
node_cache_budget = \"unlimited\"\n\
\n\
[observability]\n\
max_batch_events = 64\n\
max_batch_hold_ms = 200\n";

/// A tempdir with its path pre-canonicalized, so equality assertions against
/// the heal's resolved paths hold on platforms whose temp roots are symlinks
/// (macOS `/var` → `/private/var`).
fn canonical_tempdir() -> Result<(tempfile::TempDir, PathBuf), Box<dyn std::error::Error>> {
    let sandbox = crate::test_support::private_tempdir()?;
    let canonical = sandbox.path().canonicalize()?;
    Ok((sandbox, canonical))
}

fn write_config(dir: &Path, name: &str, text: &str) -> Result<PathBuf, std::io::Error> {
    let path = dir.join(name);
    std::fs::write(&path, text)?;
    Ok(path)
}

/// Remove one key from one `[section]` of a TOML text, failing loudly when
/// the section or key is not there to remove (a vacuous strip would turn the
/// enumeration test into a no-op).
fn strip_key(text: &str, section: &str, key: &str) -> Result<String, Box<dyn std::error::Error>> {
    let mut document: toml_edit::DocumentMut = text.parse()?;
    let table = document
        .get_mut(section)
        .and_then(toml_edit::Item::as_table_mut)
        .ok_or_else(|| format!("fixture has no [{section}] table"))?;
    table
        .remove(key)
        .ok_or_else(|| format!("fixture has no {section}.{key} to strip"))?;
    Ok(document.to_string())
}

fn parse(bytes: &[u8]) -> Result<ServerConfig, Box<dyn std::error::Error>> {
    Ok(ServerConfig::parse_unresolved(bytes)?)
}

fn probe_message(config: &ServerConfig) -> Result<String, Box<dyn std::error::Error>> {
    let error = boot_required_probe(config)
        .err()
        .ok_or("the stripped config must fail the boot-required probe")?;
    match error {
        crate::error::ServerError::Config { message } => Ok(message),
        other => Err(format!("expected a config refusal, got: {other}").into()),
    }
}

#[test]
fn every_declared_field_is_required_and_healed_one_at_a_time() -> TestResult {
    for entry in &BOOT_REQUIRED_FIELD_DEFAULTS {
        let (_sandbox, root) = canonical_tempdir()?;
        let stripped = strip_key(COMPLETE_HAEMATITE, entry.section, entry.key)?;
        let path = write_config(&root, "config.toml", &stripped)?;

        // The strip is discriminating: the boot probe refuses the file with
        // the EXACT message the table row declares, which is the lookup key
        // tying the requirement function to its declared default.
        let message = probe_message(&parse(stripped.as_bytes())?)?;
        assert_eq!(
            message, entry.requirement_message,
            "stripping {} must trip its own requirement message",
            entry.path
        );

        let outcome = heal_config_file(&path, NO_ENV)?;
        let inserted: Vec<&str> = outcome.inserted.iter().map(|field| field.path).collect();
        assert_eq!(
            inserted,
            vec![entry.path],
            "the heal must insert exactly the stripped field"
        );
        assert_eq!(outcome.config_path.as_deref(), Some(path.as_path()));

        // The healed FILE passes the same probe boot runs.
        let healed = std::fs::read(&path)?;
        boot_required_probe(&parse(&healed)?)?;

        // The inserted key carries its teaching comment and the version
        // marker, in place, in the file.
        let healed_text = String::from_utf8(healed)?;
        let first_teaching_line = entry
            .teaching_comment
            .first()
            .ok_or("every declared default carries a teaching comment")?;
        assert!(
            healed_text.contains(&format!("# {first_teaching_line}")),
            "healed file must carry the teaching comment for {}",
            entry.path
        );
        assert!(
            healed_text.contains(&format!("# added by aion {HEAL_VERSION} config heal")),
            "healed file must carry the heal marker for {}",
            entry.path
        );

        // The previous file is preserved beside it, byte-for-byte.
        let backup = outcome
            .backup_path
            .ok_or("a written heal must preserve the previous file")?;
        assert_eq!(
            backup,
            path.with_file_name(format!("config.toml.pre-{HEAL_VERSION}")),
            "the backup name must carry the version the file predates"
        );
        assert_eq!(
            std::fs::read(&backup)?,
            stripped.as_bytes(),
            "the backup must hold the pre-heal bytes"
        );
    }
    Ok(())
}

#[test]
fn stripping_every_declared_field_at_once_heals_the_file_whole() -> TestResult {
    let (_sandbox, root) = canonical_tempdir()?;
    let mut stripped = COMPLETE_HAEMATITE.to_owned();
    for entry in &BOOT_REQUIRED_FIELD_DEFAULTS {
        stripped = strip_key(&stripped, entry.section, entry.key)?;
    }
    let path = write_config(&root, "config.toml", &stripped)?;

    let outcome = heal_config_file(&path, NO_ENV)?;
    let mut inserted: Vec<&str> = outcome.inserted.iter().map(|field| field.path).collect();
    inserted.sort_unstable();
    let mut declared: Vec<&str> = BOOT_REQUIRED_FIELD_DEFAULTS
        .iter()
        .map(|entry| entry.path)
        .collect();
    declared.sort_unstable();
    assert_eq!(
        inserted, declared,
        "with every declared field stripped, the heal must insert every one"
    );

    // The healed file passes the boot probe, and each field carries the
    // declared default value — the (field, default) table, asserted at the
    // wire: "unlimited" / 64 / 200 are the shipped teaching configs' values.
    let healed = parse(&std::fs::read(&path)?)?;
    boot_required_probe(&healed)?;
    assert!(
        matches!(
            healed.store.node_cache_budget,
            Some(haematite::NodeCacheBudget::Unlimited)
        ),
        "store.node_cache_budget must heal to \"unlimited\""
    );
    assert_eq!(healed.observability.max_batch_events, Some(64));
    assert_eq!(healed.observability.max_batch_hold_ms, Some(200));
    Ok(())
}

#[test]
fn a_complete_config_passes_byte_untouched() -> TestResult {
    let (_sandbox, root) = canonical_tempdir()?;
    let path = write_config(&root, "config.toml", COMPLETE_HAEMATITE)?;

    let outcome = heal_config_file(&path, NO_ENV)?;
    assert!(outcome.inserted.is_empty(), "nothing to heal");
    assert!(outcome.config_path.is_none());
    assert!(outcome.backup_path.is_none());

    assert_eq!(
        std::fs::read(&path)?,
        COMPLETE_HAEMATITE.as_bytes(),
        "a complete config must pass through byte-untouched"
    );
    // No backup, no staging file — the config is the directory's only entry.
    let mut entries: Vec<String> = std::fs::read_dir(&root)?
        .map(|entry| Ok(entry?.file_name().to_string_lossy().into_owned()))
        .collect::<Result<_, std::io::Error>>()?;
    entries.sort();
    assert_eq!(entries, vec!["config.toml".to_owned()]);
    Ok(())
}

#[test]
fn a_missing_observability_section_is_created_whole() -> TestResult {
    let (_sandbox, root) = canonical_tempdir()?;
    let text = "\
[store]\n\
backend = \"haematite\"\n\
node_cache_budget = \"unlimited\"\n";
    let path = write_config(&root, "config.toml", text)?;

    let outcome = heal_config_file(&path, NO_ENV)?;
    assert_eq!(outcome.inserted.len(), 2, "both flush-policy fields insert");
    let healed_bytes = std::fs::read(&path)?;
    boot_required_probe(&parse(&healed_bytes)?)?;
    let healed_text = String::from_utf8(healed_bytes)?;
    assert!(
        healed_text.contains("[observability]"),
        "the absent section must be created: {healed_text}"
    );
    Ok(())
}

#[test]
fn a_memory_backend_is_not_asked_for_a_node_cache_budget() -> TestResult {
    let (_sandbox, root) = canonical_tempdir()?;
    let text = "\
[store]\n\
backend = \"memory\"\n";
    let path = write_config(&root, "config.toml", text)?;

    let outcome = heal_config_file(&path, NO_ENV)?;
    let inserted: Vec<&str> = outcome.inserted.iter().map(|field| field.path).collect();
    assert_eq!(
        inserted,
        vec![
            "observability.max_batch_events",
            "observability.max_batch_hold_ms"
        ],
        "a memory backend needs only the transcript flush policy"
    );
    let healed = std::fs::read_to_string(&path)?;
    assert!(
        !healed.contains("node_cache_budget"),
        "a memory deployment is not asked to rule on a cache it does not have"
    );
    boot_required_probe(&parse(healed.as_bytes())?)?;
    Ok(())
}

/// B2: WHICH requirements apply follows the RESOLVED backend, not the file's
/// word. `AION_STORE_BACKEND=haematite` over a `memory` file makes the
/// node-cache budget required — and healed — because that is the backend the
/// server will run; the inverse overlay drops the requirement the same way.
#[test]
fn the_environments_backend_governs_which_requirements_apply() -> TestResult {
    // memory file + haematite environment: all three fields heal, and the
    // healed file satisfies the probe AS THE SERVER WILL RUN IT.
    let (_sandbox, root) = canonical_tempdir()?;
    let path = write_config(&root, "config.toml", "[store]\nbackend = \"memory\"\n")?;
    let env = vec![("AION_STORE_BACKEND".to_owned(), "haematite".to_owned())];
    let outcome = heal_config_file(&path, &env)?;
    let mut inserted: Vec<&str> = outcome.inserted.iter().map(|field| field.path).collect();
    inserted.sort_unstable();
    assert_eq!(
        inserted,
        vec![
            "observability.max_batch_events",
            "observability.max_batch_hold_ms",
            "store.node_cache_budget",
        ],
        "the environment-selected haematite backend requires the budget"
    );
    let mut healed = parse(&std::fs::read(&path)?)?;
    healed.store.backend = crate::config::StoreBackend::Haematite;
    boot_required_probe(&healed)?;

    // haematite file + memory environment: the budget requirement follows
    // the resolved backend OFF, so only the flush policy heals.
    let (_sandbox, root) = canonical_tempdir()?;
    let path = write_config(&root, "config.toml", "[store]\nbackend = \"haematite\"\n")?;
    let env = vec![("AION_STORE_BACKEND".to_owned(), "memory".to_owned())];
    let outcome = heal_config_file(&path, &env)?;
    let inserted: Vec<&str> = outcome.inserted.iter().map(|field| field.path).collect();
    assert_eq!(
        inserted,
        vec![
            "observability.max_batch_events",
            "observability.max_batch_hold_ms"
        ],
        "a memory-resolved boot is not asked for a node cache budget"
    );
    assert!(!std::fs::read_to_string(&path)?.contains("node_cache_budget"));
    Ok(())
}

#[test]
fn an_explicit_zero_is_the_operators_value_and_stays_refused() -> TestResult {
    let (_sandbox, root) = canonical_tempdir()?;
    let text = "\
[store]\n\
backend = \"haematite\"\n\
node_cache_budget = \"unlimited\"\n\
\n\
[observability]\n\
max_batch_events = 0\n";
    let path = write_config(&root, "config.toml", text)?;

    let outcome = heal_config_file(&path, NO_ENV)?;
    let inserted: Vec<&str> = outcome.inserted.iter().map(|field| field.path).collect();
    assert_eq!(
        inserted,
        vec!["observability.max_batch_hold_ms"],
        "only the ABSENT field is healed; the zero is the operator's value"
    );
    let healed = std::fs::read_to_string(&path)?;
    assert!(
        healed.contains("max_batch_events = 0"),
        "the operator's explicit zero must survive the heal untouched"
    );
    // The boot still refuses the zero with the requirement's own message.
    let message = probe_message(&parse(healed.as_bytes())?)?;
    assert_eq!(
        message,
        crate::config::OBSERVABILITY_MAX_BATCH_EVENTS_REQUIRED
    );
    Ok(())
}

#[test]
fn a_second_heal_never_clobbers_the_first_backup() -> TestResult {
    let (_sandbox, root) = canonical_tempdir()?;
    let first_original = strip_key(COMPLETE_HAEMATITE, "observability", "max_batch_hold_ms")?;
    let path = write_config(&root, "config.toml", &first_original)?;

    let first = heal_config_file(&path, NO_ENV)?;
    let first_backup = first
        .backup_path
        .ok_or("the first heal must mint a backup")?;
    assert_eq!(std::fs::read(&first_backup)?, first_original.as_bytes());

    // The operator (or an older tool) strips a field again after the heal.
    let healed_once = std::fs::read_to_string(&path)?;
    let second_original = strip_key(&healed_once, "observability", "max_batch_events")?;
    std::fs::write(&path, &second_original)?;

    let second = heal_config_file(&path, NO_ENV)?;
    let second_backup = second
        .backup_path
        .ok_or("the second heal must mint a backup")?;
    assert_eq!(
        second_backup,
        path.with_file_name(format!("config.toml.pre-{HEAL_VERSION}.2")),
        "the second backup claims the next free name"
    );
    assert_eq!(
        std::fs::read(&first_backup)?,
        first_original.as_bytes(),
        "the first backup's bytes must be untouched by the second heal"
    );
    assert_eq!(std::fs::read(&second_backup)?, second_original.as_bytes());
    Ok(())
}

#[cfg(unix)]
#[test]
fn the_heal_preserves_the_config_files_mode() -> TestResult {
    use std::os::unix::fs::PermissionsExt;

    let (_sandbox, root) = canonical_tempdir()?;
    let stripped = strip_key(COMPLETE_HAEMATITE, "observability", "max_batch_hold_ms")?;
    let path = write_config(&root, "config.toml", &stripped)?;
    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;

    let outcome = heal_config_file(&path, NO_ENV)?;
    let backup = outcome.backup_path.ok_or("a heal must mint a backup")?;
    assert_eq!(
        std::fs::metadata(&path)?.permissions().mode() & 0o777,
        0o600,
        "the healed file keeps the original's owner-only mode"
    );
    assert_eq!(
        std::fs::metadata(&backup)?.permissions().mode() & 0o777,
        0o600,
        "the backup keeps the original's owner-only mode"
    );
    Ok(())
}

#[cfg(unix)]
#[test]
fn an_unwritable_directory_refuses_the_boot_naming_the_missing_fields() -> TestResult {
    use std::os::unix::fs::PermissionsExt;

    let (_sandbox, root) = canonical_tempdir()?;
    let stripped = strip_key(COMPLETE_HAEMATITE, "observability", "max_batch_hold_ms")?;
    let path = write_config(&root, "config.toml", &stripped)?;

    std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o500))?;
    let result = heal_config_file(&path, NO_ENV);
    std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700))?;

    let error = result
        .err()
        .ok_or("a heal that cannot write must refuse the boot")?;
    let message = error.to_string();
    assert!(
        message.contains("config heal failed"),
        "the refusal must name the heal: {message}"
    );
    assert!(
        message.contains("observability.max_batch_hold_ms"),
        "the refusal must name the missing field: {message}"
    );
    assert!(
        message.contains("config.toml"),
        "the refusal must name the file: {message}"
    );
    assert_eq!(
        std::fs::read(&path)?,
        stripped.as_bytes(),
        "a refused heal must leave the config untouched"
    );
    Ok(())
}

/// B1: a symlinked config is healed at its TARGET — the link survives, the
/// backup lands beside the target, and the link's directory gains nothing.
#[cfg(unix)]
#[test]
fn a_symlinked_config_is_healed_at_its_target() -> TestResult {
    use std::os::unix::fs::symlink;

    let (_sandbox, root) = canonical_tempdir()?;
    let source_dir = root.join("managed-source");
    let home = root.join("home");
    std::fs::create_dir(&source_dir)?;
    std::fs::create_dir(&home)?;
    let stripped = strip_key(COMPLETE_HAEMATITE, "observability", "max_batch_hold_ms")?;
    let target = write_config(&source_dir, "real.toml", &stripped)?;
    let link = home.join("config.toml");
    symlink(&target, &link)?;

    let outcome = heal_config_file(&link, NO_ENV)?;
    assert_eq!(
        outcome.config_path.as_deref(),
        Some(target.as_path()),
        "the heal must act on the resolved target"
    );

    // The link survives, still a link, still pointing where it pointed.
    let link_metadata = std::fs::symlink_metadata(&link)?;
    assert!(
        link_metadata.file_type().is_symlink(),
        "the operator's link must survive the heal"
    );
    assert_eq!(std::fs::read_link(&link)?, target);

    // The target is healed; the backup lands BESIDE THE TARGET.
    boot_required_probe(&parse(&std::fs::read(&target)?)?)?;
    assert_eq!(
        outcome.backup_path.as_deref(),
        Some(
            target
                .with_file_name(format!("real.toml.pre-{HEAL_VERSION}"))
                .as_path()
        )
    );
    assert_eq!(
        std::fs::read(target.with_file_name(format!("real.toml.pre-{HEAL_VERSION}")))?,
        stripped.as_bytes()
    );
    // The link's directory gained nothing: the link is its only entry.
    let mut home_entries: Vec<String> = std::fs::read_dir(&home)?
        .map(|entry| Ok(entry?.file_name().to_string_lossy().into_owned()))
        .collect::<Result<_, std::io::Error>>()?;
    home_entries.sort();
    assert_eq!(home_entries, vec!["config.toml".to_owned()]);
    Ok(())
}

/// B1: a link whose target is gone refuses the boot naming both ends —
/// neither the heal nor the load can act on it, and silence would strand the
/// operator staring at a link that looks like a config.
#[cfg(unix)]
#[test]
fn a_dangling_config_link_refuses_naming_both_ends() -> TestResult {
    use std::os::unix::fs::symlink;

    let (_sandbox, root) = canonical_tempdir()?;
    let link = root.join("config.toml");
    let missing_target = root.join("gone-away.toml");
    symlink(&missing_target, &link)?;

    let error = heal_config_file(&link, NO_ENV)
        .err()
        .ok_or("a dangling config link must refuse the boot")?;
    let message = error.to_string();
    assert!(
        message.contains("config.toml"),
        "the refusal must name the link: {message}"
    );
    assert!(
        message.contains("gone-away.toml"),
        "the refusal must name the target: {message}"
    );
    Ok(())
}

/// B3: a symlink planted at a staging name is refused by `create_new` and
/// merely advances the attempt — the victim it points at is never written.
#[cfg(unix)]
#[test]
fn a_planted_staging_symlink_is_not_followed() -> TestResult {
    use std::os::unix::fs::symlink;

    let (_sandbox, root) = canonical_tempdir()?;
    let stripped = strip_key(COMPLETE_HAEMATITE, "observability", "max_batch_hold_ms")?;
    let path = write_config(&root, "config.toml", &stripped)?;
    let victim = write_config(&root, "victim.txt", "must never be overwritten")?;
    let planted = root.join(format!("config.toml.heal-staging-{}.1", std::process::id()));
    symlink(&victim, &planted)?;

    let outcome = heal_config_file(&path, NO_ENV)?;
    assert_eq!(outcome.inserted.len(), 1, "the heal must still complete");
    boot_required_probe(&parse(&std::fs::read(&path)?)?)?;
    assert_eq!(
        std::fs::read_to_string(&victim)?,
        "must never be overwritten",
        "a planted staging symlink must never route the healed bytes"
    );
    assert!(
        std::fs::symlink_metadata(&planted)?
            .file_type()
            .is_symlink(),
        "the planted name is not the heal's to remove"
    );
    Ok(())
}

/// M2: a CRLF document stays CRLF — inserted lines included — instead of
/// being silently rewritten to LF end to end.
#[test]
fn a_crlf_config_stays_crlf() -> TestResult {
    let (_sandbox, root) = canonical_tempdir()?;
    let stripped = strip_key(COMPLETE_HAEMATITE, "observability", "max_batch_hold_ms")?;
    let crlf_original = stripped.replace('\n', "\r\n");
    let path = write_config(&root, "config.toml", &crlf_original)?;

    let outcome = heal_config_file(&path, NO_ENV)?;
    assert_eq!(outcome.inserted.len(), 1);
    let healed = std::fs::read_to_string(&path)?;
    let bare_lf = healed
        .as_bytes()
        .iter()
        .enumerate()
        .filter(|(index, byte)| {
            **byte == b'\n' && (*index == 0 || healed.as_bytes()[index - 1] != b'\r')
        })
        .count();
    assert_eq!(
        bare_lf, 0,
        "every line of a CRLF document must stay CRLF: {healed:?}"
    );
    // Untouched regions are byte-identical: stripping the healed file back
    // down must reproduce the original exactly.
    boot_required_probe(&parse(healed.as_bytes())?)?;
    assert!(
        healed.contains("max_batch_hold_ms = 200\r\n"),
        "the inserted line itself carries the document's ending: {healed:?}"
    );
    for line in crlf_original.lines() {
        assert!(
            healed.contains(line),
            "an original line went missing from the healed CRLF file: {line:?}"
        );
    }
    Ok(())
}

#[test]
fn an_inline_observability_table_is_healed_without_comments() -> TestResult {
    let (_sandbox, root) = canonical_tempdir()?;
    let text = "\
observability = { max_event_bytes = 262144 }\n\
\n\
[store]\n\
backend = \"haematite\"\n\
node_cache_budget = \"unlimited\"\n";
    let path = write_config(&root, "config.toml", text)?;

    let outcome = heal_config_file(&path, NO_ENV)?;
    assert_eq!(outcome.inserted.len(), 2);
    let healed_text = std::fs::read_to_string(&path)?;
    let healed = parse(healed_text.as_bytes())?;
    boot_required_probe(&healed)?;
    assert_eq!(healed.observability.max_batch_events, Some(64));
    assert_eq!(healed.observability.max_batch_hold_ms, Some(200));
    assert_eq!(healed.observability.max_event_bytes, 262_144);
    // L2: the inserted entries space like their neighbours — no stray
    // ` ,` where the old last entry's closing space used to sit.
    assert!(
        !healed_text.contains(" ,"),
        "inline-table insertion must not leave a space before a comma: {healed_text:?}"
    );
    assert!(
        healed_text.contains("max_event_bytes = 262144, max_batch_events = 64"),
        "inline entries must read `key = value, key = value`: {healed_text:?}"
    );
    Ok(())
}

#[test]
fn the_heal_edits_exactly_the_file_discovery_will_load() -> TestResult {
    let (_sandbox, root) = canonical_tempdir()?;
    let home = root.join("home");
    let working = root.join("working");
    std::fs::create_dir(&home)?;
    std::fs::create_dir(&working)?;
    let stripped = strip_key(COMPLETE_HAEMATITE, "observability", "max_batch_hold_ms")?;
    let home_config = write_config(&home, "config.toml", &stripped)?;
    let project_config = write_config(&working, "aion.toml", &stripped)?;

    // Project-local wins over home: only the project file is healed.
    let outcome = heal_discovered(None, &home, &working, NO_ENV)?;
    assert_eq!(
        outcome.config_path.as_deref(),
        Some(project_config.as_path())
    );
    assert_eq!(
        std::fs::read(&home_config)?,
        stripped.as_bytes(),
        "the home config must stay untouched while a project config wins"
    );
    boot_required_probe(&parse(&std::fs::read(&project_config)?)?)?;

    // An explicit --config wins over both: only the named file is healed.
    let explicit = write_config(&root, "explicit.toml", &stripped)?;
    let outcome = heal_discovered(Some(&explicit), &home, &working, NO_ENV)?;
    assert_eq!(outcome.config_path.as_deref(), Some(explicit.as_path()));
    boot_required_probe(&parse(&std::fs::read(&explicit)?)?)?;
    assert_eq!(
        std::fs::read(&home_config)?,
        stripped.as_bytes(),
        "the home config must stay untouched while an explicit config wins"
    );

    // No file anywhere: nothing to heal, nothing created.
    let empty_home = root.join("empty-home");
    let empty_working = root.join("empty-working");
    std::fs::create_dir(&empty_home)?;
    std::fs::create_dir(&empty_working)?;
    let outcome = heal_discovered(None, &empty_home, &empty_working, NO_ENV)?;
    assert!(outcome.inserted.is_empty());
    assert!(std::fs::read_dir(&empty_home)?.next().is_none());
    Ok(())
}

#[test]
fn the_boot_log_names_each_minted_field_and_the_count() -> TestResult {
    let (_sandbox, root) = canonical_tempdir()?;
    let home = root.join("home");
    let working = root.join("working");
    std::fs::create_dir(&home)?;
    std::fs::create_dir(&working)?;
    let mut stripped = COMPLETE_HAEMATITE.to_owned();
    for entry in &BOOT_REQUIRED_FIELD_DEFAULTS {
        stripped = strip_key(&stripped, entry.section, entry.key)?;
    }
    write_config(&home, "config.toml", &stripped)?;

    let (captured, outcome) = crate::test_support::CapturedLogs::capture(|| {
        heal_discovered(None, &home, &working, NO_ENV)
    });
    let outcome = outcome?;
    assert_eq!(outcome.inserted.len(), BOOT_REQUIRED_FIELD_DEFAULTS.len());

    let logged = captured.text()?;
    for field in &outcome.inserted {
        assert!(
            logged.contains(field.path),
            "the boot log must name {}: {logged}",
            field.path
        );
        // A TOML string literal logs with its quotes escaped by the fmt
        // layer, so the assertion holds the literal's content.
        assert!(
            logged.contains(field.value.trim_matches('"')),
            "the boot log must carry {}'s inserted value: {logged}",
            field.path
        );
    }
    assert!(
        logged.contains(&format!(
            "inserted_field_count={}",
            BOOT_REQUIRED_FIELD_DEFAULTS.len()
        )),
        "the boot summary must name the count: {logged}"
    );
    assert!(
        logged.contains(&format!("config.toml.pre-{HEAL_VERSION}")),
        "the boot summary must name the preserved backup: {logged}"
    );
    Ok(())
}

/// H1: a field minted while its `AION_*` override is set still lands in the
/// file — the file must stand alone — but the boot WARNS that the running
/// value is the override's, so the log never asserts the file value as fact.
#[test]
fn an_env_supplied_value_is_still_minted_with_a_warning() -> TestResult {
    let (_sandbox, root) = canonical_tempdir()?;
    let home = root.join("home");
    let working = root.join("working");
    std::fs::create_dir(&home)?;
    std::fs::create_dir(&working)?;
    let stripped = strip_key(
        &strip_key(COMPLETE_HAEMATITE, "observability", "max_batch_events")?,
        "observability",
        "max_batch_hold_ms",
    )?;
    let path = write_config(&home, "config.toml", &stripped)?;

    let env = vec![(
        "AION_OBSERVABILITY_MAX_BATCH_EVENTS".to_owned(),
        "512".to_owned(),
    )];
    let (captured, outcome) =
        crate::test_support::CapturedLogs::capture(|| heal_discovered(None, &home, &working, &env));
    let outcome = outcome?;
    assert_eq!(
        outcome.inserted.len(),
        2,
        "both absent fields mint regardless of the override"
    );
    // The FILE carries the declared default, not the override's value.
    let healed = parse(&std::fs::read(&path)?)?;
    assert_eq!(healed.observability.max_batch_events, Some(64));

    let logged = captured.text()?;
    let warning_line = logged
        .lines()
        .find(|line| line.contains("WARN") && line.contains("AION_OBSERVABILITY_MAX_BATCH_EVENTS"))
        .ok_or_else(|| format!("no override warning in the boot log: {logged}"))?;
    assert!(
        warning_line.contains("512"),
        "the warning must carry the effective runtime value: {warning_line}"
    );
    assert!(
        warning_line.contains("64"),
        "the warning must carry the minted file value: {warning_line}"
    );
    assert!(
        !logged.contains("AION_OBSERVABILITY_MAX_BATCH_HOLD_MS"),
        "no warning for a minted field with no override set: {logged}"
    );
    Ok(())
}

/// N1: the heal never voices the retired-variable warning — that line belongs
/// to the loader's authoritative overlay, once per boot. Two postures pinned:
/// a byte-untouched complete-config boot, where the heal must add NOTHING to
/// the log at all (the invariant the module doc states), and a healing boot,
/// where the heal logs its insertions but still not the retired line.
#[test]
fn the_heal_never_emits_the_retired_variable_warning() -> TestResult {
    let env = vec![(
        "AION_STORE_LOCK_ACQUISITION_PATIENCE_MS".to_owned(),
        "60000".to_owned(),
    )];

    // Byte-untouched posture: a complete config with the retired variable
    // set. The heal's shadow overlay sees the variable; the boot log must
    // gain not one line from this pass.
    let (_sandbox, root) = canonical_tempdir()?;
    let home = root.join("home");
    let working = root.join("working");
    std::fs::create_dir(&home)?;
    std::fs::create_dir(&working)?;
    write_config(&home, "config.toml", COMPLETE_HAEMATITE)?;
    let (captured, outcome) =
        crate::test_support::CapturedLogs::capture(|| heal_discovered(None, &home, &working, &env));
    assert!(
        outcome?.inserted.is_empty(),
        "the complete config must pass byte-untouched"
    );
    let logged = captured.text()?;
    assert!(
        logged.is_empty(),
        "a byte-untouched boot's log must gain nothing from the heal path: {logged}"
    );

    // Healing posture: the heal logs its insertions, and still not the
    // retired-variable line — that warning is the loader's, exactly once.
    let (_sandbox, root) = canonical_tempdir()?;
    let home = root.join("home");
    let working = root.join("working");
    std::fs::create_dir(&home)?;
    std::fs::create_dir(&working)?;
    let stripped = strip_key(COMPLETE_HAEMATITE, "observability", "max_batch_hold_ms")?;
    write_config(&home, "config.toml", &stripped)?;
    let (captured, outcome) =
        crate::test_support::CapturedLogs::capture(|| heal_discovered(None, &home, &working, &env));
    assert_eq!(
        outcome?.inserted.len(),
        1,
        "the healing posture must actually heal"
    );
    let logged = captured.text()?;
    assert!(
        logged.contains("observability.max_batch_hold_ms"),
        "the healing boot still logs its insertion: {logged}"
    );
    assert!(
        !logged.contains("retired and ignored"),
        "the retired-variable warning is the loader's line, never the heal's: {logged}"
    );
    Ok(())
}

/// Silence-proofing for [`HealOutcome::default`]: the untouched outcome is
/// what every non-boot load path carries, so it must be visibly empty.
#[test]
fn the_default_outcome_is_visibly_untouched() {
    let outcome = HealOutcome::default();
    assert!(outcome.config_path.is_none());
    assert!(outcome.backup_path.is_none());
    assert!(outcome.inserted.is_empty());
}