aion-cli 0.31.0

The `aion` command line: operate Aion durable workflows over gRPC and run the Aion server.
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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
//! Local `generate` subcommand: types-first codec + activity codegen.
//!
//! The authored source of truth is the package's Gleam types module
//! `src/<package>_io.gleam` (ADR-014, resolved types-first 2026-07-02).
//! `aion generate` derives everything wire-shaped from it: the
//! `<package>_codecs` module (encoders/decoders/typed codecs), the emitted
//! `schemas/*.json` artifacts, and — when the package declares activities via
//! the `manifest()` its `src/<package>_activities.gleam` exports — the
//! `<package>_activity_wrappers` constructors, the per-tier worker module,
//! the remote wire-compat golden, the `workflow.toml` activities list, and a
//! write-once test scaffold. The pure generators live in `aion_package`; this
//! command orchestrates the phases and owns the steps the library cannot —
//! running the Gleam toolchain to export the package interface and to execute
//! `manifest()`.
//!
//! Both toolchain steps must build the package, but the generated modules the
//! build would need may not exist yet (fresh project, or the round-trip
//! deleted them). So each toolchain pass first renames aside (in place,
//! restored on completion or error) the target generated modules and every
//! source module that transitively imports them, runs the toolchain against
//! the surviving sources, then restores:
//!
//! - the **interface pass** sets aside `{<pkg>_codecs, <pkg>_activity_wrappers}`
//!   and their importers, leaving the types module (which imports neither) to
//!   compile standalone for `gleam export package-interface`;
//! - the **manifest pass** sets aside `{<pkg>_activity_wrappers}` and its
//!   importers — the freshly generated codecs module must remain, because the
//!   author's activities module references `codecs.<type>_codec()`.
//!
//! Nothing is written to a server; the whole command runs locally.
//!
//! `--check` compares every *generated* file against a fresh in-memory
//! regeneration and never writes one, but it is not side-effect-free: it still
//! drives the toolchain, so the same transient rename-aside/restore happens
//! during the builds.
//!
//! Each toolchain pass is **single-flight per project**: the
//! rename-aside/restore dance mutates the source tree in place, so two
//! concurrent `aion generate` runs on the same project would set aside the
//! same modules and collide. An exclusive `.aiongen.lock` file (created
//! atomically with `create_new`) is held for the whole of a pass; a second
//! concurrent run fails fast with a clear error rather than corrupting the
//! tree, and the lock is removed on every exit path — success, `bail!`, or
//! panic — by its RAII guard.

use std::collections::HashMap;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use aion_package::{
    ActivityDeclaration, BoundaryType, CodegenMode, boundary_types_from_interface, emit_schemas,
    generate_activities, generate_codecs, generate_test_scaffold, parse_declarations,
};
use aion_toolchain::gleam_failure::{GleamFailureLayer, classify_gleam_failure};
use anyhow::{Context, Result, bail};
use serde::Serialize;
use serde_json::Value;
use toml_edit::DocumentMut;

use crate::output::to_value;

/// Line the probe prints immediately before the manifest JSON, so the reader
/// is robust against any other stdout the toolchain emits.
const MANIFEST_MARKER: &str = "AION_MANIFEST_BEGIN";

/// Throwaway Gleam module the probe is written to. Chosen not to collide with a
/// plausible author module; created and deleted within one extraction.
const PROBE_MODULE: &str = "aion_generate_probe";

/// Suffix appended to a source file renamed aside for an extraction build.
/// Gleam ignores non-`.gleam` files, so the renamed module is excluded; the
/// suffix stays in the same directory (not moved to a temp tree) so a crash
/// leaves an obvious, recoverable file.
const ASIDE_SUFFIX: &str = ".aiongen-aside";

/// First line of the probe module, used to recognise a stale probe left by a
/// crashed prior run without risking a same-named author module.
const PROBE_DOC: &str =
    "//// Temporary manifest-extraction probe written by `aion generate`. Safe to delete.";

/// Advisory single-flight lock file, created exclusively at the project root for
/// the duration of one toolchain pass so two concurrent runs cannot set aside
/// the same modules and collide. Held by [`ExtractionLock`], removed on every
/// exit.
const LOCK_FILE: &str = ".aiongen.lock";

/// Where the interface pass has `gleam export package-interface` write its
/// JSON, relative to the project root. Lives under `build/` (toolchain-owned,
/// gitignored) and is removed after it is read.
const INTERFACE_OUT: &str = "build/.aiongen-interface.json";

/// JSON document printed on stdout after a successful `generate` run.
#[derive(Serialize)]
struct GenerateOutput {
    /// The authored types module the generation derives from, relative to the
    /// project root (never written by this command).
    types_module: String,
    /// Generated `src/<package>_codecs.gleam`, relative to the project root.
    codecs_module: String,
    /// Every emitted `schemas/*.json` artifact, in type-name order.
    schemas_emitted: Vec<String>,
    /// Stale emitted schemas removed by this run (types renamed away).
    schemas_removed: Vec<String>,
    /// Every generated activity file (wrappers, worker, golden), in order.
    /// Empty for a package without an activities module.
    activity_modules: Vec<String>,
    /// `test/<entry_module>_scaffold_test.gleam` (write-once; kept when the
    /// author has filled it in). `None` for a package without activities.
    test_scaffold: Option<String>,
    /// Number of activity declarations the package's `manifest()` returned.
    declarations: usize,
    /// `synced` when the workflow.toml activities list was rewritten,
    /// `unchanged` when it already matched, `checked` under `--check`,
    /// `skipped` for a package without an activities module.
    workflow_toml: &'static str,
    /// `written` for a generation run, `checked` for `--check`.
    action: &'static str,
}

/// The activity-phase results folded into [`GenerateOutput`].
struct ActivityPhase {
    activity_modules: Vec<String>,
    test_scaffold: Option<String>,
    declarations: usize,
    workflow_toml: &'static str,
}

/// Runs the `generate` subcommand: derives every artifact from the package's
/// authored types module (and, when present, its activity declarations), or
/// verifies them with `--check`.
pub(crate) fn run(path: &Path, check: bool) -> Result<Value> {
    let mode = if check {
        CodegenMode::Check
    } else {
        CodegenMode::Write
    };
    let package_name = read_gleam_package_name(path)?;

    // Phase A: have the compiler export the package interface for the
    // authored types module (types-first front door, ADR-014).
    let interface_json = export_package_interface(path, &package_name)?;

    // Phase B: map the interface into the boundary-type model.
    let types =
        boundary_types_from_interface(&interface_json, &package_name).with_context(|| {
            format!("failed to read the boundary types of src/{package_name}_io.gleam")
        })?;

    // Phase C: the codecs module, which must exist on disk before the package
    // will build for declaration extraction.
    let codecs = generate_codecs(path, &types, mode).with_context(|| {
        format!(
            "failed to generate the codecs module for {}",
            path.display()
        )
    })?;

    // Phase D: the emitted schemas/*.json artifacts (packaging, `aion input`,
    // and external reference read these).
    let schemas = emit_schemas(path, &package_name, &types, mode)
        .with_context(|| format!("failed to emit the schema artifacts for {}", path.display()))?;

    // Phase E: the declaration-driven activity plumbing, for packages that
    // declare activities via `src/<package>_activities.gleam` `manifest()`.
    let activity = activity_phase(path, &package_name, &types, mode)?;

    to_value(GenerateOutput {
        types_module: format!("src/{package_name}_io.gleam"),
        codecs_module: codecs.module_relative,
        schemas_emitted: schemas.emitted,
        schemas_removed: schemas.removed,
        activity_modules: activity.activity_modules,
        test_scaffold: activity.test_scaffold,
        declarations: activity.declarations,
        workflow_toml: activity.workflow_toml,
        action: if check { "checked" } else { "written" },
    })
}

/// Runs the activity phases (manifest extraction, wrappers/worker/golden,
/// workflow.toml sync, test scaffold) when the package has an activities
/// module; a package without one — a pure-workflow project — skips them.
fn activity_phase(
    path: &Path,
    package_name: &str,
    types: &[BoundaryType],
    mode: CodegenMode,
) -> Result<ActivityPhase> {
    let activities_file = path
        .join("src")
        .join(format!("{package_name}_activities.gleam"));
    if !activities_file.is_file() {
        return Ok(ActivityPhase {
            activity_modules: Vec::new(),
            test_scaffold: None,
            declarations: 0,
            workflow_toml: "skipped",
        });
    }

    // Run the package's `manifest()` to read the declarations.
    let manifest_json = extract_declarations(path, package_name)?;
    let declarations = parse_declarations(&manifest_json).with_context(|| {
        format!(
            "failed to parse the activity manifest emitted by {package_name}_activities.manifest()"
        )
    })?;

    // The declaration-derived plumbing.
    let activities = generate_activities(path, &declarations, types, mode).with_context(|| {
        format!(
            "failed to generate the activity plumbing for {}",
            path.display()
        )
    })?;

    // Keep the workflow.toml activities list in step with the declared names.
    let workflow_toml = sync_workflow_activities(path, &declarations, mode)?;

    // The per-workflow `aion/testing` skeleton — write-once: an existing
    // (possibly author-filled) scaffold is kept.
    let entry_module = read_entry_module(path)?;
    let scaffold = generate_test_scaffold(path, &entry_module, &declarations, types, mode)
        .with_context(|| {
            format!(
                "failed to generate the test scaffold for {}",
                path.display()
            )
        })?;

    Ok(ActivityPhase {
        activity_modules: activities
            .artifacts
            .iter()
            .map(|artifact| artifact.relative.clone())
            .collect(),
        test_scaffold: Some(scaffold.module_relative),
        declarations: declarations.len(),
        workflow_toml,
    })
}

/// Reads the single `[[workflow]]` table's `entry_module` from `workflow.toml`.
///
/// The scaffold drives one workflow's typed entry; like the activities sync, it
/// supports a single-workflow package only and bails loudly otherwise rather
/// than guessing which workflow to scaffold.
fn read_entry_module(root: &Path) -> Result<String> {
    let toml_path = root.join("workflow.toml");
    let contents = fs::read_to_string(&toml_path)
        .with_context(|| format!("failed to read {}", toml_path.display()))?;
    let document = contents
        .parse::<DocumentMut>()
        .with_context(|| format!("{} is not valid TOML", toml_path.display()))?;
    let workflows = document
        .get("workflow")
        .and_then(|item| item.as_array_of_tables())
        .with_context(|| {
            format!(
                "{} declares no [[workflow]] entry to scaffold a test for",
                toml_path.display()
            )
        })?;
    if workflows.len() > 1 {
        bail!(
            "{} declares {} [[workflow]] entries; `aion generate` scaffolds a test for a \
             single-workflow package only",
            toml_path.display(),
            workflows.len()
        );
    }
    let entry = workflows
        .iter()
        .next()
        .and_then(|table| table.get("entry_module"))
        .and_then(|item| item.as_str())
        .with_context(|| {
            format!(
                "{} [[workflow]] entry has no `entry_module` to scaffold a test for",
                toml_path.display()
            )
        })?;
    Ok(entry.to_owned())
}

/// Reads the package name from the project's `gleam.toml`.
fn read_gleam_package_name(root: &Path) -> Result<String> {
    let gleam_toml = root.join("gleam.toml");
    let contents = fs::read_to_string(&gleam_toml)
        .with_context(|| format!("failed to read {}", gleam_toml.display()))?;
    let document = contents
        .parse::<DocumentMut>()
        .with_context(|| format!("{} is not valid TOML", gleam_toml.display()))?;
    document
        .get("name")
        .and_then(|name| name.as_str())
        .map(str::to_owned)
        .with_context(|| format!("{} has no `name` field", gleam_toml.display()))
}

/// Exports the package interface with the generated modules set aside,
/// returning the raw interface JSON. The authored types module imports
/// neither generated module, so it survives the aside and compiles standalone.
fn export_package_interface(root: &Path, package_name: &str) -> Result<Vec<u8>> {
    let types_file = root.join("src").join(format!("{package_name}_io.gleam"));
    if !types_file.is_file() {
        bail!(
            "expected {} to exist and declare the workflow's boundary types; it is the authored \
             source of truth `aion generate` derives every codec and schema from (ADR-014)",
            types_file.display()
        );
    }
    let codecs_module = format!("{package_name}_codecs");
    let wrappers_module = format!("{package_name}_activity_wrappers");
    let golden_module = format!("{package_name}_wire_compat_test");
    let (_lock, _scratch) = begin_toolchain_pass(
        root,
        &[&codecs_module, &wrappers_module, &golden_module],
        None,
    )?;

    // Absolute, because the child process resolves a relative `--out` against
    // ITS working directory (the project root), not ours.
    let out_path = std::path::absolute(root.join(INTERFACE_OUT))
        .with_context(|| format!("failed to resolve {INTERFACE_OUT} under {}", root.display()))?;
    if let Some(parent) = out_path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }
    let output = Command::new("gleam")
        .args(["export", "package-interface", "--out"])
        .arg(&out_path)
        .current_dir(root)
        .output()
        .with_context(|| {
            format!(
                "failed to run `gleam export package-interface` in {} (is a gleam toolchain \
                 with `export package-interface` on PATH?)",
                root.display()
            )
        })?;
    // `_scratch` restores the renamed modules when it drops at the end of this
    // function, including on the bail! paths below.
    if !output.status.success() {
        // 🔴 A non-zero exit is not evidence about the author's source (#125).
        // `gleam export package-interface` resolves and fetches dependencies
        // before it reads a line of Gleam, so a registry outage fails here
        // having never reached the compiler. This message used to assert that
        // the author's types module "must compile standalone" in EVERY case,
        // which on an outage sends them to rewrite working code over a network
        // fault they cannot fix. Classification is shared with the toolchain;
        // the WORDING is not, because a diagnostic's safe default belongs to
        // whoever receives it — and this one is read by an author.
        let combined = format!(
            "{}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        if classify_gleam_failure(&combined) == GleamFailureLayer::DependencyLayer {
            bail!(
                "`gleam export package-interface` could not reach its package registry in {}, so \
                 your workflow was never compiled — this is a network or registry failure, NOT a \
                 problem with your code. Nothing has been generated; try again when the registry \
                 is reachable.\n{combined}",
                root.display()
            );
        }
        bail!(
            "interface export failed: `gleam export package-interface` exited with {} in {}. \
             `gleam`'s own output follows; the most common cause is that the types module \
             src/{package_name}_io.gleam (or another module not reaching the generated \
             codecs/wrappers) does not compile standalone.\n{combined}",
            output.status,
            root.display()
        );
    }
    let json = fs::read(&out_path)
        .with_context(|| format!("failed to read the exported {}", out_path.display()))?;
    // Best-effort cleanup: the file lives under the gitignored build/ tree.
    let _ = fs::remove_file(&out_path);
    Ok(json)
}

/// Builds and runs a probe that prints `manifest()` as JSON, returning the raw
/// JSON bytes. The generated wrappers module and every source module that
/// transitively imports it are renamed aside for the build so the package
/// compiles without them, and restored before this returns (or on error). The
/// freshly generated codecs module stays: the author's activities module
/// references `codecs.<type>_codec()`.
fn extract_declarations(root: &Path, package_name: &str) -> Result<Vec<u8>> {
    let activities_module = format!("{package_name}_activities");
    let wrappers_module = format!("{package_name}_activity_wrappers");
    // The golden is regenerated by this run too: a stale one references the
    // OLD codecs surface and would break the probe build.
    let golden_module = format!("{package_name}_wire_compat_test");
    let (_lock, _scratch) = begin_toolchain_pass(
        root,
        &[&wrappers_module, &golden_module],
        Some(&activities_module),
    )?;

    let output = Command::new("gleam")
        .args(["run", "-m", PROBE_MODULE])
        .current_dir(root)
        .output()
        .with_context(|| {
            format!(
                "failed to run `gleam run -m {PROBE_MODULE}` in {}",
                root.display()
            )
        })?;
    // `_scratch` restores the renamed modules and removes the probe when it
    // drops at the end of this function, including on the bail! paths below.
    if !output.status.success() {
        bail!(
            "manifest extraction failed: `gleam run -m {PROBE_MODULE}` exited with {} in {}\n{}",
            output.status,
            root.display(),
            String::from_utf8_lossy(&output.stderr)
        );
    }
    extract_marked_json(&output.stdout)
}

/// Shared preamble of both toolchain passes: recover crash leftovers, take the
/// single-flight lock, rename aside the target generated modules and every
/// module that transitively imports one, and (for the manifest pass) write the
/// probe module. Returns the RAII guards; dropping them restores the tree and
/// releases the lock on every exit path — success, `bail!`, or panic.
fn begin_toolchain_pass(
    root: &Path,
    aside_targets: &[&str],
    probe_activities_module: Option<&str>,
) -> Result<(ExtractionLock, ExtractionScratch)> {
    let src = root.join("src");
    // A prior pass killed mid-flight (SIGKILL / power loss, which no `Drop`
    // can cover) can leave renamed-aside modules and a stale probe in the
    // tree. Recover them before touching anything, so the build sees the real
    // sources.
    recover_leftover_scratch(&src)?;

    // Take the single-flight lock before mutating the tree: a second
    // concurrent `aion generate` on this project fails fast here rather than
    // colliding on the rename-aside step.
    let lock = ExtractionLock::acquire(root)?;

    // Set aside the target generated modules themselves (a stale one may no
    // longer compile against the edited types module — this includes the
    // generated wire-compat golden in `test/`) and every module that
    // transitively imports one — in `src/` and in `test/`. The generated test
    // scaffold lives in `test/` and imports the workflow module (which
    // reaches the wrappers), so a prior run's scaffold would otherwise break
    // the build. Test module reachability is resolved through the `src/`
    // import graph, so both trees are scanned into one map.
    let blocking = modules_reaching(root, aside_targets)?;
    let mut scratch = ExtractionScratch::default();
    for module_file in blocking {
        scratch.rename_aside(&module_file)?;
    }
    if let Some(activities_module) = probe_activities_module {
        scratch.write_probe(&src, activities_module)?;
    }
    Ok((lock, scratch))
}

/// Returns the source files of every module under the project's `src/` and
/// `test/` trees that is one of the `targets` (a generated module being
/// regenerated) or transitively imports one, so they can be set aside while
/// the package is built for a toolchain pass.
///
/// Both trees are collected into one import map, each module named relative to
/// its own tree root (the Gleam module-name convention), so a `test/` module's
/// reachability resolves through the `src/` import graph. `test/` is optional —
/// a project without one is collected from `src/` alone.
fn modules_reaching(root: &Path, targets: &[&str]) -> Result<Vec<PathBuf>> {
    let mut imports: HashMap<String, (PathBuf, Vec<String>)> = HashMap::new();
    let src = root.join("src");
    collect_modules(&src, &src, &mut imports)?;
    let test = root.join("test");
    if test.is_dir() {
        collect_modules(&test, &test, &mut imports)?;
    }

    let mut blocking = Vec::new();
    for (module, (file, _)) in &imports {
        let is_target = targets.iter().any(|target| target == module);
        let reaches_target = targets
            .iter()
            .any(|target| reaches(module, target, &imports, &mut Vec::new()));
        if is_target || reaches_target {
            blocking.push(file.clone());
        }
    }
    // Deterministic order so the rename/restore sequence is reproducible.
    blocking.sort();
    Ok(blocking)
}

/// Walks `dir` recursively, recording each `*.gleam` module's name and the
/// modules it imports.
fn collect_modules(
    src_root: &Path,
    dir: &Path,
    imports: &mut HashMap<String, (PathBuf, Vec<String>)>,
) -> Result<()> {
    let entries = fs::read_dir(dir)
        .with_context(|| format!("failed to list source directory {}", dir.display()))?;
    for entry in entries {
        let entry =
            entry.with_context(|| format!("failed to read an entry in {}", dir.display()))?;
        let path = entry.path();
        if path.is_dir() {
            collect_modules(src_root, &path, imports)?;
        } else if path.extension().is_some_and(|ext| ext == "gleam") {
            let module = module_name(src_root, &path);
            let contents = fs::read_to_string(&path)
                .with_context(|| format!("failed to read {}", path.display()))?;
            imports.insert(module, (path, parse_imports(&contents)));
        }
    }
    Ok(())
}

/// Derives a Gleam module name from a source file path: the path relative to
/// `src`, without the `.gleam` extension, with directory separators as `/`.
fn module_name(src_root: &Path, file: &Path) -> String {
    let relative = file.strip_prefix(src_root).unwrap_or(file);
    let without_ext = relative.with_extension("");
    without_ext
        .components()
        .map(|component| component.as_os_str().to_string_lossy())
        .collect::<Vec<_>>()
        .join("/")
}

/// Extracts the imported module names from Gleam source: the token after
/// `import`, up to the first `.` (the `.{..}` unqualified list) or whitespace
/// (an `as` alias or a trailing `// comment`).
///
/// A line whose first non-whitespace token is a `//` comment (including a
/// `////` module-doc) is never treated as an import, even when the comment text
/// happens to contain the word `import`. A real import with a trailing inline
/// comment (`import foo // note`) still resolves to `foo`, because the bare
/// module name is taken from the first whitespace-delimited token after the
/// keyword. Missing a genuine import would break extraction (the importer would
/// not be set aside), so the heuristic errs toward detection, never suppression.
fn parse_imports(contents: &str) -> Vec<String> {
    contents
        .lines()
        .filter_map(|line| {
            let trimmed = line.trim_start();
            // Skip comment lines (`//`, `///`, `////`) so a comment that
            // mentions `import` is never mistaken for one.
            if trimmed.starts_with("//") {
                return None;
            }
            let rest = trimmed.strip_prefix("import ")?;
            let token = rest
                .split_whitespace()
                .next()?
                .split('.')
                .next()
                .unwrap_or_default();
            (!token.is_empty()).then(|| token.to_owned())
        })
        .collect()
}

/// Whether `module` reaches `target` by following local imports, guarding
/// against import cycles.
fn reaches(
    module: &str,
    target: &str,
    imports: &HashMap<String, (PathBuf, Vec<String>)>,
    stack: &mut Vec<String>,
) -> bool {
    let Some((_, module_imports)) = imports.get(module) else {
        return false;
    };
    if module_imports.iter().any(|import| import == target) {
        return true;
    }
    if stack.iter().any(|seen| seen == module) {
        return false;
    }
    stack.push(module.to_owned());
    let found = module_imports
        .iter()
        .any(|import| reaches(import, target, imports, stack));
    stack.pop();
    found
}

/// Pulls the manifest JSON line that follows the marker out of the probe's
/// stdout.
fn extract_marked_json(stdout: &[u8]) -> Result<Vec<u8>> {
    let text = String::from_utf8_lossy(stdout);
    let mut lines = text.lines();
    while let Some(line) = lines.next() {
        if line.trim() == MANIFEST_MARKER {
            let json = lines.next().with_context(|| {
                "manifest probe printed its marker but no JSON line followed".to_owned()
            })?;
            return Ok(json.trim().as_bytes().to_vec());
        }
    }
    bail!("manifest probe did not print the `{MANIFEST_MARKER}` marker; stdout was:\n{text}")
}

/// The Gleam source of the manifest-extraction probe.
fn probe_source(activities_module: &str) -> String {
    format!(
        "{PROBE_DOC}\n\n\
         import aion/manifest\n\
         import gleam/io\n\
         import {activities_module} as activities\n\n\
         pub fn main() {{\n  \
         io.println(\"{MANIFEST_MARKER}\")\n  \
         io.println(manifest.to_json(activities.manifest()))\n}}\n"
    )
}

/// Recovers the on-disk leftovers of a prior extraction that was killed before
/// its [`ExtractionScratch`] could restore them: renames every `*.aiongen-aside`
/// module back (or removes it when the original already exists), and removes a
/// stale probe module. Idempotent and safe on a clean tree.
fn recover_leftover_scratch(src: &Path) -> Result<()> {
    recover_asides(src)?;
    let probe = src.join(format!("{PROBE_MODULE}.gleam"));
    match fs::read_to_string(&probe) {
        Ok(contents) if contents.starts_with(PROBE_DOC) => fs::remove_file(&probe)
            .with_context(|| format!("failed to remove a stale probe {}", probe.display()))?,
        _ => {}
    }
    Ok(())
}

/// Walks `dir` for files renamed aside by a crashed extraction and restores
/// each: rename back when the original is gone, or drop the stale copy when the
/// original is present (the original is authoritative).
fn recover_asides(dir: &Path) -> Result<()> {
    for entry in fs::read_dir(dir).with_context(|| format!("failed to list {}", dir.display()))? {
        let path = entry
            .with_context(|| format!("failed to read an entry in {}", dir.display()))?
            .path();
        if path.is_dir() {
            recover_asides(&path)?;
        } else if let Some(original) = aside_original(&path) {
            if original.exists() {
                fs::remove_file(&path)
                    .with_context(|| format!("failed to remove stale aside {}", path.display()))?;
            } else {
                fs::rename(&path, &original).with_context(|| {
                    format!(
                        "failed to restore {} from a crashed extraction",
                        original.display()
                    )
                })?;
            }
        }
    }
    Ok(())
}

/// If `path` ends in the aside suffix, returns the original path it was renamed
/// from.
fn aside_original(path: &Path) -> Option<PathBuf> {
    let name = path.to_str()?;
    name.strip_suffix(ASIDE_SUFFIX).map(PathBuf::from)
}

/// Single-flight advisory lock for one project's extraction. Created
/// exclusively (`create_new`, an atomic create-if-absent) at the project root;
/// a second concurrent run finds it present and fails fast instead of colliding
/// on the rename-aside step. The lock is removed when this guard drops, on every
/// exit path of [`extract_declarations`].
struct ExtractionLock {
    path: PathBuf,
}

impl ExtractionLock {
    /// Acquires the lock at `<root>/.aiongen.lock`, failing if another run holds
    /// it.
    fn acquire(root: &Path) -> Result<Self> {
        let path = root.join(LOCK_FILE);
        match fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&path)
        {
            Ok(_) => Ok(Self { path }),
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => bail!(
                "another `aion generate` is already extracting declarations for this project \
                 (lock file {} exists). Wait for it to finish; if you are sure no other run is \
                 in progress, delete {} and retry.",
                path.display(),
                path.display()
            ),
            Err(error) => Err(error).with_context(|| {
                format!(
                    "failed to acquire the manifest-extraction lock {}",
                    path.display()
                )
            }),
        }
    }
}

impl Drop for ExtractionLock {
    fn drop(&mut self) {
        if let Err(error) = fs::remove_file(&self.path)
            && self.path.exists()
        {
            eprintln!(
                "warning: failed to remove the manifest-extraction lock {}: {error}; \
                 delete it manually before the next `aion generate`",
                self.path.display()
            );
        }
    }
}

/// Tracks the temporary on-disk changes one extraction makes — the probe module
/// it writes and the source modules it renames aside — and undoes them when it
/// drops, so a build failure or panic never leaves the project mangled.
#[derive(Default)]
struct ExtractionScratch {
    probe: Option<PathBuf>,
    /// `(aside_path, original_path)` pairs to rename back.
    renamed: Vec<(PathBuf, PathBuf)>,
}

impl ExtractionScratch {
    /// Renames `original` aside (appending `.aiongen-aside`, which Gleam
    /// ignores) so the build excludes it.
    fn rename_aside(&mut self, original: &Path) -> Result<()> {
        let mut aside_name: OsString = original.as_os_str().to_owned();
        aside_name.push(ASIDE_SUFFIX);
        let aside = PathBuf::from(aside_name);
        fs::rename(original, &aside).with_context(|| {
            format!(
                "failed to set aside {} for manifest extraction",
                original.display()
            )
        })?;
        self.renamed.push((aside, original.to_path_buf()));
        Ok(())
    }

    /// Writes the probe module into `src`.
    fn write_probe(&mut self, src: &Path, activities_module: &str) -> Result<()> {
        let probe = src.join(format!("{PROBE_MODULE}.gleam"));
        fs::write(&probe, probe_source(activities_module))
            .with_context(|| format!("failed to write the probe module {}", probe.display()))?;
        self.probe = Some(probe);
        Ok(())
    }
}

impl Drop for ExtractionScratch {
    fn drop(&mut self) {
        if let Some(probe) = self.probe.take()
            && let Err(error) = fs::remove_file(&probe)
            && probe.exists()
        {
            eprintln!(
                "warning: failed to remove manifest probe {}: {error}",
                probe.display()
            );
        }
        for (aside, original) in self.renamed.drain(..) {
            if let Err(error) = fs::rename(&aside, &original) {
                eprintln!(
                    "error: failed to restore {} from {} after manifest extraction: {error}; \
                     rename it back manually",
                    original.display(),
                    aside.display()
                );
            }
        }
    }
}

/// Keeps every `[[workflow]]` table's `activities` list in step with the
/// declared activity names. Returns the action taken for the printed report.
///
/// The comparison is by name and order, not bytes: a workflow.toml whose list
/// already matches is left untouched (its formatting and comments are
/// preserved), so only an actually-stale list is a `--check` failure or a
/// rewrite.
fn sync_workflow_activities(
    root: &Path,
    declarations: &[ActivityDeclaration],
    mode: CodegenMode,
) -> Result<&'static str> {
    let toml_path = root.join("workflow.toml");
    let original = fs::read_to_string(&toml_path)
        .with_context(|| format!("failed to read {}", toml_path.display()))?;
    let mut document = original
        .parse::<DocumentMut>()
        .with_context(|| format!("{} is not valid TOML", toml_path.display()))?;

    let desired: Vec<&str> = declarations
        .iter()
        .map(|declaration| declaration.name.as_str())
        .collect();

    let workflows = document
        .get_mut("workflow")
        .and_then(|item| item.as_array_of_tables_mut())
        .with_context(|| {
            format!(
                "{} declares no [[workflow]] entry to attach activities to",
                toml_path.display()
            )
        })?;

    // A package-level `manifest()` cannot attribute its activities across more
    // than one workflow, so syncing the same list into every `[[workflow]]`
    // would be a guess. Refuse rather than guess; per-workflow attribution is
    // out of scope for WA-001 (the `.aion` format is single-workflow today).
    if workflows.len() > 1 {
        bail!(
            "{} declares {} [[workflow]] entries; `aion generate` syncs the activities \
             list for a single-workflow package only",
            toml_path.display(),
            workflows.len()
        );
    }

    let mut changed = false;
    for table in workflows.iter_mut() {
        if workflow_activities(table) == desired {
            continue;
        }
        if mode == CodegenMode::Check {
            bail!(
                "--check failed: {} activities list is out of date; run `aion generate`",
                toml_path.display()
            );
        }
        let mut array = toml_edit::Array::new();
        for name in &desired {
            array.push(*name);
        }
        table["activities"] = toml_edit::value(array);
        changed = true;
    }

    if mode == CodegenMode::Check {
        return Ok("checked");
    }
    if changed {
        fs::write(&toml_path, document.to_string())
            .with_context(|| format!("failed to write {}", toml_path.display()))?;
        Ok("synced")
    } else {
        Ok("unchanged")
    }
}

/// Reads a `[[workflow]]` table's `activities` list as owned strings, treating a
/// missing or malformed list as empty.
fn workflow_activities(table: &toml_edit::Table) -> Vec<String> {
    table
        .get("activities")
        .and_then(|item| item.as_array())
        .map(|array| {
            array
                .iter()
                .filter_map(|value| value.as_str().map(str::to_owned))
                .collect()
        })
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::{
        ExtractionLock, LOCK_FILE, extract_marked_json, module_name, parse_imports, reaches,
        sync_workflow_activities,
    };
    use aion_package::{ActivityDeclaration, CodegenMode, Tier};
    use std::collections::HashMap;
    use std::path::{Path, PathBuf};

    #[test]
    fn module_names_use_forward_slashes_under_src() {
        let src = Path::new("/p/src");
        assert_eq!(
            module_name(src, Path::new("/p/src/order_saga.gleam")),
            "order_saga"
        );
        assert_eq!(
            module_name(src, Path::new("/p/src/order_saga/locals.gleam")),
            "order_saga/locals"
        );
    }

    #[test]
    fn imports_are_parsed_to_bare_module_names() {
        let source = "import aion/manifest\nimport gleam/io.{println}\n\
                      import order_saga_codecs as codecs\nlet x = 1\n  import nested/mod\n";
        assert_eq!(
            parse_imports(source),
            vec![
                "aion/manifest".to_owned(),
                "gleam/io".to_owned(),
                "order_saga_codecs".to_owned(),
                "nested/mod".to_owned(),
            ]
        );
    }

    #[test]
    fn comment_lines_are_never_treated_as_imports() {
        // A `//` line comment, a `////` module-doc, and an indented comment that
        // each contain the word `import` must all be skipped.
        let source = "// import should_not_count\n\
                      //// import also/not/counted\n   \
                      // import indented_comment\n";
        assert!(parse_imports(source).is_empty());
    }

    #[test]
    fn indented_real_import_is_found() {
        assert_eq!(
            parse_imports("  import real/mod\n"),
            vec!["real/mod".to_owned()]
        );
    }

    #[test]
    fn aliased_and_unqualified_imports_yield_bare_name() {
        // Unqualified-with-alias and a nested path both reduce to the bare name.
        assert_eq!(
            parse_imports("import foo.{X} as y\n"),
            vec!["foo".to_owned()]
        );
        assert_eq!(parse_imports("import a/b/c\n"), vec!["a/b/c".to_owned()]);
        assert_eq!(parse_imports("import foo as bar\n"), vec!["foo".to_owned()]);
    }

    #[test]
    fn trailing_comment_after_import_is_ignored_but_module_kept() {
        // The trailing `// note` must not suppress the import, and must not
        // become part of the module name.
        assert_eq!(
            parse_imports("import foo // note\n"),
            vec!["foo".to_owned()]
        );
        assert_eq!(
            parse_imports("import a/b/c // a trailing import comment\n"),
            vec!["a/b/c".to_owned()]
        );
    }

    #[test]
    fn transitive_importers_of_the_target_are_found() {
        // workflow -> wrappers (direct); mid -> workflow (transitive);
        // activities -> codecs (never reaches wrappers).
        let mut imports: HashMap<String, (PathBuf, Vec<String>)> = HashMap::new();
        imports.insert(
            "workflow".to_owned(),
            (PathBuf::from("workflow.gleam"), vec!["wrappers".to_owned()]),
        );
        imports.insert(
            "mid".to_owned(),
            (PathBuf::from("mid.gleam"), vec!["workflow".to_owned()]),
        );
        imports.insert(
            "activities".to_owned(),
            (PathBuf::from("activities.gleam"), vec!["codecs".to_owned()]),
        );

        assert!(reaches("workflow", "wrappers", &imports, &mut Vec::new()));
        assert!(reaches("mid", "wrappers", &imports, &mut Vec::new()));
        assert!(!reaches(
            "activities",
            "wrappers",
            &imports,
            &mut Vec::new()
        ));
    }

    #[test]
    fn cyclic_imports_do_not_loop() {
        let mut imports: HashMap<String, (PathBuf, Vec<String>)> = HashMap::new();
        imports.insert(
            "a".to_owned(),
            (PathBuf::from("a.gleam"), vec!["b".to_owned()]),
        );
        imports.insert(
            "b".to_owned(),
            (PathBuf::from("b.gleam"), vec!["a".to_owned()]),
        );
        // Neither reaches the target; the cycle must terminate.
        assert!(!reaches("a", "wrappers", &imports, &mut Vec::new()));
    }

    #[test]
    fn marked_json_is_extracted_from_noisy_stdout() -> Result<(), Box<dyn std::error::Error>> {
        let stdout =
            b"  Compiling demo\n   Compiled in 0.3s\nAION_MANIFEST_BEGIN\n[{\"name\":\"a\"}]\n";
        assert_eq!(extract_marked_json(stdout)?, b"[{\"name\":\"a\"}]");
        Ok(())
    }

    #[test]
    fn missing_marker_is_an_error() {
        let stdout = b"some unrelated output\n";
        assert!(extract_marked_json(stdout).is_err());
    }

    #[test]
    fn modules_reaching_sets_aside_targets_and_their_importers()
    -> Result<(), Box<dyn std::error::Error>> {
        use super::modules_reaching;

        // A realistic tree: the two generated modules exist on disk (stale
        // copies being regenerated), the activities module imports the codecs,
        // the workflow imports the wrappers, and one module reaches neither.
        let temp = tempfile::tempdir()?;
        let src = temp.path().join("src");
        std::fs::create_dir(&src)?;
        std::fs::write(src.join("demo_io.gleam"), "pub type Input { Input }\n")?;
        std::fs::write(src.join("demo_codecs.gleam"), "import demo_io\n")?;
        std::fs::write(
            src.join("demo_activity_wrappers.gleam"),
            "import demo_activities\nimport demo_codecs\nimport demo_io\n",
        )?;
        std::fs::write(src.join("demo_activities.gleam"), "import demo_codecs\n")?;
        std::fs::write(
            src.join("workflow.gleam"),
            "import demo_activity_wrappers\n",
        )?;
        std::fs::write(src.join("standalone.gleam"), "import demo_io\n")?;

        // The interface pass targets {codecs, wrappers}: both target files and
        // everything reaching either are set aside; the types module and the
        // standalone module survive.
        let mut aside = modules_reaching(temp.path(), &["demo_codecs", "demo_activity_wrappers"])?;
        aside.sort();
        let names: Vec<String> = aside
            .iter()
            .filter_map(|path| path.file_name().map(|n| n.to_string_lossy().into_owned()))
            .collect();
        assert_eq!(
            names,
            vec![
                "demo_activities.gleam",
                "demo_activity_wrappers.gleam",
                "demo_codecs.gleam",
                "workflow.gleam",
            ]
        );

        // The manifest pass targets {wrappers} only: the codecs module and the
        // activities module (which imports only codecs) survive.
        let aside = modules_reaching(temp.path(), &["demo_activity_wrappers"])?;
        let names: Vec<String> = aside
            .iter()
            .filter_map(|path| path.file_name().map(|n| n.to_string_lossy().into_owned()))
            .collect();
        assert_eq!(
            names,
            vec!["demo_activity_wrappers.gleam", "workflow.gleam"]
        );
        Ok(())
    }

    #[test]
    fn crash_leftovers_are_recovered() -> Result<(), Box<dyn std::error::Error>> {
        use super::{PROBE_MODULE, recover_leftover_scratch};

        let temp = tempfile::tempdir()?;
        let src = temp.path();
        std::fs::create_dir(src.join("nested"))?;
        // A module renamed aside with its original gone → restored.
        std::fs::write(src.join("order_saga.gleam.aiongen-aside"), b"workflow")?;
        // A renamed-aside copy whose original survived → the stale copy dropped.
        std::fs::write(src.join("nested/helper.gleam"), b"current")?;
        std::fs::write(src.join("nested/helper.gleam.aiongen-aside"), b"stale")?;
        // A stale probe (recognised by its header) → removed; a same-named
        // author module would be left alone.
        std::fs::write(
            src.join(format!("{PROBE_MODULE}.gleam")),
            super::probe_source("demo_activities"),
        )?;

        recover_leftover_scratch(src)?;

        assert!(src.join("order_saga.gleam").is_file());
        assert!(!src.join("order_saga.gleam.aiongen-aside").exists());
        assert_eq!(std::fs::read(src.join("nested/helper.gleam"))?, b"current");
        assert!(!src.join("nested/helper.gleam.aiongen-aside").exists());
        assert!(!src.join(format!("{PROBE_MODULE}.gleam")).exists());

        // Idempotent on a clean tree.
        recover_leftover_scratch(src)?;
        Ok(())
    }

    /// Builds an [`ActivityDeclaration`] with the given name; the other fields
    /// are irrelevant to workflow.toml syncing, which compares by name only.
    fn declaration(name: &str) -> ActivityDeclaration {
        ActivityDeclaration {
            name: name.to_owned(),
            tier: Tier::InVm,
            input_type: "Input".to_owned(),
            output_type: "Output".to_owned(),
        }
    }

    /// Reads back the `[[workflow]]` `activities` array from a written
    /// workflow.toml as owned strings, in order.
    fn read_workflow_activities(path: &Path) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        let document = std::fs::read_to_string(path)?.parse::<toml_edit::DocumentMut>()?;
        let Some(array) = document
            .get("workflow")
            .and_then(|item| item.as_array_of_tables())
            .and_then(|tables| tables.iter().next())
            .and_then(|table| table.get("activities"))
            .and_then(|item| item.as_array())
        else {
            return Err("workflow.toml has no [[workflow]] activities array".into());
        };
        Ok(array
            .iter()
            .filter_map(|value| value.as_str().map(str::to_owned))
            .collect())
    }

    #[test]
    fn sync_clean_match_write_is_unchanged_and_preserves_bytes()
    -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let toml = temp.path().join("workflow.toml");
        // Deliberate formatting + a comment that must survive an unchanged sync.
        let original =
            "# keep me\n[[workflow]]\nname = \"saga\"\nactivities = [\"charge\", \"ship\"]\n";
        std::fs::write(&toml, original)?;

        let declarations = [declaration("charge"), declaration("ship")];
        let action = sync_workflow_activities(temp.path(), &declarations, CodegenMode::Write)?;

        assert_eq!(action, "unchanged");
        // Byte-for-byte untouched: formatting and the comment are preserved.
        assert_eq!(std::fs::read_to_string(&toml)?, original);
        Ok(())
    }

    #[test]
    fn sync_clean_match_check_is_checked() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let toml = temp.path().join("workflow.toml");
        std::fs::write(&toml, "[[workflow]]\nactivities = [\"charge\", \"ship\"]\n")?;

        let declarations = [declaration("charge"), declaration("ship")];
        let action = sync_workflow_activities(temp.path(), &declarations, CodegenMode::Check)?;

        assert_eq!(action, "checked");
        Ok(())
    }

    #[test]
    fn sync_stale_list_write_rewrites_in_declared_order() -> Result<(), Box<dyn std::error::Error>>
    {
        let temp = tempfile::tempdir()?;
        let toml = temp.path().join("workflow.toml");
        // Stale: wrong order and a missing name.
        std::fs::write(&toml, "[[workflow]]\nactivities = [\"ship\"]\n")?;

        let declarations = [
            declaration("charge"),
            declaration("ship"),
            declaration("refund"),
        ];
        let action = sync_workflow_activities(temp.path(), &declarations, CodegenMode::Write)?;

        assert_eq!(action, "synced");
        // The rewritten array equals the declared names, in declaration order.
        assert_eq!(
            read_workflow_activities(&toml)?,
            vec!["charge".to_owned(), "ship".to_owned(), "refund".to_owned()]
        );
        Ok(())
    }

    #[test]
    fn sync_stale_list_check_bails_with_path_and_reason() -> Result<(), Box<dyn std::error::Error>>
    {
        let temp = tempfile::tempdir()?;
        let toml = temp.path().join("workflow.toml");
        std::fs::write(&toml, "[[workflow]]\nactivities = [\"ship\"]\n")?;

        let declarations = [declaration("charge"), declaration("ship")];
        let result = sync_workflow_activities(temp.path(), &declarations, CodegenMode::Check);

        let Err(error) = result else {
            return Err("a stale list under --check must be an error".into());
        };
        let message = format!("{error}");
        assert!(
            message.contains("workflow.toml") && message.contains("out of date"),
            "error must name the toml and say it is out of date: {message}"
        );
        Ok(())
    }

    #[test]
    fn sync_multiple_workflow_tables_bails_naming_the_count()
    -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let toml = temp.path().join("workflow.toml");
        let two_tables = "[[workflow]]\nname = \"a\"\n[[workflow]]\nname = \"b\"\n";
        std::fs::write(&toml, two_tables)?;

        let declarations = [declaration("charge")];
        let result = sync_workflow_activities(temp.path(), &declarations, CodegenMode::Write);

        let Err(error) = result else {
            return Err("more than one [[workflow]] table must be an error".into());
        };
        let message = format!("{error}");
        assert!(
            message.contains('2'),
            "error must name the [[workflow]] count: {message}"
        );
        Ok(())
    }

    #[test]
    fn sync_no_workflow_table_bails() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let toml = temp.path().join("workflow.toml");
        std::fs::write(&toml, "name = \"no-workflow-table\"\n")?;

        let declarations = [declaration("charge")];
        let result = sync_workflow_activities(temp.path(), &declarations, CodegenMode::Write);

        assert!(
            result.is_err(),
            "a workflow.toml with no [[workflow]] table must be an error"
        );
        Ok(())
    }

    #[test]
    fn sync_missing_activities_key_is_created_on_write() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let toml = temp.path().join("workflow.toml");
        // No `activities` key at all → treated as empty, so a non-empty desired
        // list is stale and the key is created.
        std::fs::write(&toml, "[[workflow]]\nname = \"saga\"\n")?;

        let declarations = [declaration("charge"), declaration("ship")];
        let action = sync_workflow_activities(temp.path(), &declarations, CodegenMode::Write)?;

        assert_eq!(action, "synced");
        assert_eq!(
            read_workflow_activities(&toml)?,
            vec!["charge".to_owned(), "ship".to_owned()]
        );
        Ok(())
    }

    #[test]
    fn extraction_lock_is_exclusive_then_reacquirable() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let root = temp.path();

        let guard = ExtractionLock::acquire(root)?;
        assert!(root.join(LOCK_FILE).is_file(), "lock file must exist");

        // A second acquisition while the first is held must fail fast.
        assert!(
            ExtractionLock::acquire(root).is_err(),
            "a second concurrent lock acquisition must fail"
        );

        // Dropping the guard removes the lock and allows re-acquisition.
        drop(guard);
        assert!(
            !root.join(LOCK_FILE).exists(),
            "the lock file must be removed when the guard drops"
        );
        let _again = ExtractionLock::acquire(root)?;
        assert!(
            root.join(LOCK_FILE).is_file(),
            "the lock must be re-acquirable once released"
        );
        Ok(())
    }
}