telltale-language 17.0.0

Shared choreography frontend for Telltale DSL parsing, projection, and macro code generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! Effect handler scaffolding and simulation metadata generation.

use crate::ast::{Choreography, EffectAuthorityClass};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GeneratedEffectBehavior {
    OneShot,
    Stream,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GeneratedSimulationMode {
    Deterministic,
    Adversarial,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GeneratedSimulationMetadata {
    pub behavior: GeneratedEffectBehavior,
    pub mode: GeneratedSimulationMode,
    pub latency_policy: String,
    pub timeout_policy: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GeneratedEffectOperation {
    pub interface_name: String,
    pub operation_name: String,
    pub rust_method_name: String,
    pub request_type_name: String,
    pub outcome_type_name: String,
    pub authority_class: EffectAuthorityClass,
    pub input_type: String,
    pub output_type: String,
    pub simulation: GeneratedSimulationMetadata,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GeneratedEffectFamily {
    pub interface_name: String,
    pub request_enum_name: String,
    pub outcome_enum_name: String,
    pub host_trait_name: String,
    pub simulator_trait_name: String,
    pub scenario_builder_name: String,
    pub operations: Vec<GeneratedEffectOperation>,
}

/// Derive canonical effect-interface families from a parsed choreography.
pub fn generated_effect_families(choreography: &Choreography) -> Vec<GeneratedEffectFamily> {
    choreography
        .effect_interface_declarations()
        .into_iter()
        .map(|effect| {
            let request_enum_name = format!("{}Request", effect.name);
            let outcome_enum_name = format!("{}Outcome", effect.name);
            let host_trait_name = format!("{}ExternalHandler", effect.name);
            let simulator_trait_name = format!("{}SimulatorHandler", effect.name);
            let scenario_builder_name = format!("{}ScenarioBuilder", effect.name);
            let operations = effect
                .operations
                .into_iter()
                .map(|op| {
                    let operation_type_name = to_upper_camel_case(&op.name);
                    GeneratedEffectOperation {
                        interface_name: effect.name.clone(),
                        operation_name: op.name.clone(),
                        rust_method_name: to_snake_case(&op.name),
                        request_type_name: format!("{}{}Request", effect.name, operation_type_name),
                        outcome_type_name: format!("{}{}Outcome", effect.name, operation_type_name),
                        authority_class: op.authority_class,
                        input_type: op.input_type,
                        output_type: op.output_type,
                        simulation: simulation_defaults(op.authority_class),
                    }
                })
                .collect();

            GeneratedEffectFamily {
                interface_name: effect.name,
                request_enum_name,
                outcome_enum_name,
                host_trait_name,
                simulator_trait_name,
                scenario_builder_name,
                operations,
            }
        })
        .collect()
}

/// Generate canonical Rust effect interfaces, manifests, and optional simulator
/// scaffolds from declared effect families.
pub fn generate_effect_interface_scaffold(
    out_dir: &Path,
    families: &[GeneratedEffectFamily],
    with_simulator: bool,
) -> Result<Vec<PathBuf>, String> {
    fs::create_dir_all(out_dir).map_err(|e| {
        format!(
            "failed to create output directory '{}': {e}",
            out_dir.display()
        )
    })?;

    let files = build_effect_family_files(families, with_simulator)?;
    preflight_absent_targets(out_dir, &files)?;
    write_files_transactionally(out_dir, &files)
}

#[derive(Debug, Clone)]
struct GeneratedFile {
    name: &'static str,
    kind: &'static str,
    content: String,
}

fn build_effect_family_files(
    families: &[GeneratedEffectFamily],
    with_simulator: bool,
) -> Result<Vec<GeneratedFile>, String> {
    let mut files = vec![
        GeneratedFile {
            name: "generated_effects.rs",
            kind: "generated effect interface scaffold",
            content: render_generated_effects(families),
        },
        GeneratedFile {
            name: "generated_effect_manifest.json",
            kind: "generated effect manifest",
            content: serde_json::to_string_pretty(families)
                .map_err(|e| format!("encode effect manifest: {e}"))?,
        },
        GeneratedFile {
            name: "README.md",
            kind: "generated effect README",
            content: render_generated_readme(families, with_simulator),
        },
    ];

    if with_simulator {
        files.push(GeneratedFile {
            name: "generated_simulator.rs",
            kind: "generated simulator scaffold",
            content: render_generated_simulator(families),
        });
    }

    Ok(files)
}

fn preflight_absent_targets(out_dir: &Path, files: &[GeneratedFile]) -> Result<(), String> {
    for file in files {
        let path = out_dir.join(file.name);
        if path.exists() {
            return Err(format!(
                "{} already exists at '{}'; use a new output directory or remove existing files",
                file.kind,
                path.display()
            ));
        }
    }
    Ok(())
}

fn write_files_transactionally(
    out_dir: &Path,
    files: &[GeneratedFile],
) -> Result<Vec<PathBuf>, String> {
    let stage_dir = out_dir.join(format!(
        ".effect_scaffold_stage_{}_{}",
        std::process::id(),
        now_nanos()
    ));
    fs::create_dir_all(&stage_dir).map_err(|e| {
        format!(
            "failed to create staging directory '{}': {e}",
            stage_dir.display()
        )
    })?;

    for file in files {
        let stage_path = stage_dir.join(file.name);
        if let Err(err) = fs::write(&stage_path, &file.content) {
            drop(fs::remove_dir_all(&stage_dir));
            return Err(format!(
                "failed to write staging file '{}': {err}",
                stage_path.display()
            ));
        }
    }

    let mut moved = Vec::new();
    for file in files {
        let stage_path = stage_dir.join(file.name);
        let target_path = out_dir.join(file.name);
        if let Err(err) = fs::rename(&stage_path, &target_path) {
            rollback_moved_files(&moved);
            drop(fs::remove_dir_all(&stage_dir));
            return Err(format!(
                "failed to finalize '{}' from staging '{}': {err}",
                target_path.display(),
                stage_path.display()
            ));
        }
        moved.push(target_path);
    }

    if let Err(err) = fs::remove_dir(&stage_dir) {
        return Err(format!(
            "generated files but failed to clean staging directory '{}': {err}",
            stage_dir.display()
        ));
    }

    Ok(moved)
}

fn rollback_moved_files(paths: &[PathBuf]) {
    for path in paths {
        drop(fs::remove_file(path));
    }
}

fn render_generated_effects(families: &[GeneratedEffectFamily]) -> String {
    let mut out = String::from(
        "// @generated by effect-scaffold from Telltale `effect` declarations.\n\
         // This file is the canonical Rust-facing effect boundary for the declared interfaces.\n\n\
         use serde::{Deserialize, Serialize};\n\
         use serde_json::Value;\n\n",
    );

    for family in families {
        out.push_str(&format!(
            "#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\
             pub enum {} {{\n",
            family.request_enum_name
        ));
        for op in &family.operations {
            let variant_name = operation_variant_name(op);
            out.push_str(&format!(
                "    {}({}),\n",
                variant_name, op.request_type_name
            ));
        }
        out.push_str("}\n\n");

        out.push_str(&format!(
            "#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\
             pub enum {} {{\n",
            family.outcome_enum_name
        ));
        for op in &family.operations {
            let variant_name = operation_variant_name(op);
            out.push_str(&format!(
                "    {}({}),\n",
                variant_name, op.outcome_type_name
            ));
        }
        out.push_str("}\n\n");

        for op in &family.operations {
            out.push_str(&render_request_struct(op));
            out.push('\n');
            out.push_str(&render_outcome_enum(op));
            out.push('\n');
        }

        out.push_str(&format!("pub trait {} {{\n", family.host_trait_name));
        for op in &family.operations {
            out.push_str(&format!(
                "    fn {}(&self, request: {}) -> {};\n",
                op.rust_method_name, op.request_type_name, op.outcome_type_name
            ));
        }
        out.push_str("}\n\n");
    }

    out
}

fn render_generated_simulator(families: &[GeneratedEffectFamily]) -> String {
    let mut out = String::from(
        "// @generated by effect-scaffold from Telltale `effect` declarations.\n\
         // This file provides first-class simulator helpers for generated effect families.\n\n\
         use std::collections::BTreeMap;\n\n\
         use serde_json::Value;\n\
         use telltale_simulator::generated::{GeneratedEffectScenario, GeneratedEffectScenarioBuilder, ScenarioEffectResult};\n\n",
    );

    for family in families {
        out.push_str(&format!(
            "#[derive(Debug, Clone, Default)]\n\
pub struct {}State {{\n\
    pub values: BTreeMap<String, Value>,\n\
    pub event_log: Vec<String>,\n\
}}\n\n",
            family.interface_name
        ));

        out.push_str(&format!(
            "#[derive(Debug, Clone, Default)]\n\
pub struct {} {{\n\
    builder: GeneratedEffectScenarioBuilder,\n\
}}\n\n\
impl {} {{\n\
    pub fn new() -> Self {{\n\
        Self::default()\n\
    }}\n\n",
            family.scenario_builder_name, family.scenario_builder_name
        ));
        for op in &family.operations {
            out.push_str(&render_scenario_builder_methods(family, op));
        }
        out.push_str(
            "    pub fn build(self) -> GeneratedEffectScenario {\n        self.builder.build()\n    }\n}\n\n",
        );

        out.push_str(&format!("pub trait {} {{\n", family.simulator_trait_name));
        for op in &family.operations {
            out.push_str(&format!(
                "    fn {}(&mut self, state: &mut {}State, request: Value) -> ScenarioEffectResult<Value>;\n",
                op.rust_method_name, family.interface_name
            ));
        }
        out.push_str("}\n\n");
    }

    out
}

fn render_generated_readme(families: &[GeneratedEffectFamily], with_simulator: bool) -> String {
    let mut out = String::from(
        "# Generated Effect Interfaces\n\n\
         This directory was generated from Telltale `effect` declarations. The DSL is the single\n\
         source of truth for the Rust host boundary, simulator scenario helpers, and exported\n\
         effect-family manifest.\n\n\
         ## Files\n\n\
         - `generated_effects.rs`: canonical request/outcome enums and host-handler traits.\n\
         - `generated_effect_manifest.json`: schema/export manifest for the same effect families.\n",
    );
    if with_simulator {
        out.push_str(
            "- `generated_simulator.rs`: first-class simulator state, traits, and scenario builders.\n",
        );
    }
    out.push_str("\n## Declared effect families\n\n");
    for family in families {
        out.push_str(&format!("- `{}`\n", family.interface_name));
        for op in &family.operations {
            out.push_str(&format!(
                "  - `{}.{}`: `{}` input, `{}` output, `{}` authority, `{}` simulation\n",
                family.interface_name,
                op.operation_name,
                op.input_type,
                op.output_type,
                authority_class_name(op.authority_class),
                simulation_mode_name(op.simulation.mode)
            ));
        }
    }

    out.push_str(
        "\n## Next steps\n\n\
         1. Implement the generated external-handler traits in the host runtime.\n\
         2. Keep simulator scenarios in CI for success, timeout, cancellation, stale late result,\n\
            blocked, and degraded cases.\n\
         3. Treat `generated_effect_manifest.json` as the exported schema surface for this guest runtime.\n",
    );
    out
}

fn render_request_struct(op: &GeneratedEffectOperation) -> String {
    format!(
        "#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\
pub struct {} {{\n\
    pub input: Value,\n\
}}\n\n\
impl {} {{\n\
    pub const INTERFACE_NAME: &'static str = \"{}\";\n\
    pub const OPERATION_NAME: &'static str = \"{}\";\n\
    pub const DSL_INPUT_TYPE: &'static str = \"{}\";\n\
    pub const AUTHORITY_CLASS: &'static str = \"{}\";\n\
}}\n",
        op.request_type_name,
        op.request_type_name,
        op.interface_name,
        op.operation_name,
        op.input_type,
        authority_class_name(op.authority_class),
    )
}

fn render_outcome_enum(op: &GeneratedEffectOperation) -> String {
    format!(
        "#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\
pub enum {} {{\n\
    Return {{ value: Value }},\n\
    Timeout,\n\
    Cancelled,\n\
    StaleLateResult,\n\
    Blocked,\n\
    Degraded {{ detail: String }},\n\
    Error {{ value: Value }},\n\
}}\n\n\
impl {} {{\n\
    pub const DSL_OUTPUT_TYPE: &'static str = \"{}\";\n\
    pub const SIMULATION_MODE: &'static str = \"{}\";\n\
}}\n",
        op.outcome_type_name,
        op.outcome_type_name,
        op.output_type,
        simulation_mode_name(op.simulation.mode),
    )
}

fn render_scenario_builder_methods(
    family: &GeneratedEffectFamily,
    op: &GeneratedEffectOperation,
) -> String {
    let interface = &family.interface_name;
    let operation = &op.operation_name;
    let method = &op.rust_method_name;
    format!(
        "    pub fn {method}_success(mut self, payload: Value) -> Self {{\n\
        self.builder = self.builder.record_return(\"{interface}\", \"{operation}\", payload);\n\
        self\n\
    }}\n\n\
    pub fn {method}_timeout(mut self) -> Self {{\n\
        self.builder = self.builder.record_timeout(\"{interface}\", \"{operation}\");\n\
        self\n\
    }}\n\n\
    pub fn {method}_cancelled(mut self) -> Self {{\n\
        self.builder = self.builder.record_cancelled(\"{interface}\", \"{operation}\");\n\
        self\n\
    }}\n\n\
    pub fn {method}_stale_late_result(mut self) -> Self {{\n\
        self.builder = self.builder.record_stale_late_result(\"{interface}\", \"{operation}\");\n\
        self\n\
    }}\n\n\
    pub fn {method}_blocked(mut self) -> Self {{\n\
        self.builder = self.builder.record_blocked(\"{interface}\", \"{operation}\");\n\
        self\n\
    }}\n\n\
    pub fn {method}_degraded(mut self, detail: impl Into<String>) -> Self {{\n\
        self.builder = self.builder.record_degraded(\"{interface}\", \"{operation}\", detail);\n\
        self\n\
    }}\n\n\
    pub fn {method}_with_delay_ms(mut self, delay_ms: u64) -> Self {{\n\
        self.builder = self.builder.with_delay_ms(delay_ms);\n\
        self\n\
    }}\n\n"
    )
}

fn simulation_defaults(authority_class: EffectAuthorityClass) -> GeneratedSimulationMetadata {
    match authority_class {
        EffectAuthorityClass::Observe => GeneratedSimulationMetadata {
            behavior: GeneratedEffectBehavior::Stream,
            mode: GeneratedSimulationMode::Deterministic,
            latency_policy: "best_effort".to_string(),
            timeout_policy: "not_authoritative".to_string(),
        },
        EffectAuthorityClass::Authoritative => GeneratedSimulationMetadata {
            behavior: GeneratedEffectBehavior::OneShot,
            mode: GeneratedSimulationMode::Deterministic,
            latency_policy: "bounded".to_string(),
            timeout_policy: "required".to_string(),
        },
        EffectAuthorityClass::Command => GeneratedSimulationMetadata {
            behavior: GeneratedEffectBehavior::OneShot,
            mode: GeneratedSimulationMode::Deterministic,
            latency_policy: "immediate".to_string(),
            timeout_policy: "optional".to_string(),
        },
    }
}

fn authority_class_name(class: EffectAuthorityClass) -> &'static str {
    match class {
        EffectAuthorityClass::Authoritative => "authoritative",
        EffectAuthorityClass::Command => "command",
        EffectAuthorityClass::Observe => "observe",
    }
}

fn operation_variant_name(op: &GeneratedEffectOperation) -> String {
    to_upper_camel_case(&op.operation_name)
}

fn simulation_mode_name(mode: GeneratedSimulationMode) -> &'static str {
    match mode {
        GeneratedSimulationMode::Deterministic => "deterministic",
        GeneratedSimulationMode::Adversarial => "adversarial",
    }
}

fn to_snake_case(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for (idx, ch) in input.chars().enumerate() {
        if ch.is_ascii_uppercase() {
            if idx > 0 {
                out.push('_');
            }
            out.push(ch.to_ascii_lowercase());
        } else {
            out.push(ch);
        }
    }
    out
}

fn to_upper_camel_case(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut uppercase_next = true;
    for ch in input.chars() {
        if ch == '_' || ch == '-' {
            uppercase_next = true;
            continue;
        }
        if uppercase_next {
            out.push(ch.to_ascii_uppercase());
            uppercase_next = false;
        } else {
            out.push(ch);
        }
    }
    out
}

fn now_nanos() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |duration| duration.as_nanos())
}

#[cfg(test)]
mod tests {
    use super::{
        generate_effect_interface_scaffold, generated_effect_families, now_nanos,
        render_generated_effects, render_generated_simulator, GeneratedEffectBehavior,
    };
    use crate::compiler::parser::parse_choreography_str;
    use std::env;
    use std::fs;
    use std::path::PathBuf;

    fn sample_dsl() -> &'static str {
        r#"
effect Runtime
  authoritative readChannel : ChannelRef -> Result ReadError ChannelSnapshot
  {
    class : authoritative
    progress : may_block
    region : fragment
    agreement_use : required
    reentrancy : reject_same_fragment
  }
  command acceptInvite : InviteRef -> Result AcceptError MaterializedChannel
  {
    class : best_effort
    progress : immediate
    region : session
    agreement_use : none
    reentrancy : allow
  }
  observe watchPresence : ChannelId -> PresenceView
  {
    class : observational
    progress : immediate
    region : session
    agreement_use : forbidden
    reentrancy : allow
  }

protocol Flow uses Runtime =
  roles Coordinator
  Coordinator -> Coordinator : Ping
"#
    }

    #[test]
    fn generated_effect_families_follow_declared_effect_interfaces() {
        let choreography = parse_choreography_str(sample_dsl()).expect("parse effect surface");
        let families = generated_effect_families(&choreography);
        assert_eq!(families.len(), 1);
        let runtime = &families[0];
        assert_eq!(runtime.interface_name, "Runtime");
        assert_eq!(runtime.host_trait_name, "RuntimeExternalHandler");
        assert_eq!(runtime.simulator_trait_name, "RuntimeSimulatorHandler");
        assert_eq!(runtime.operations.len(), 3);
        assert_eq!(runtime.operations[0].rust_method_name, "read_channel");
        assert_eq!(
            runtime.operations[2].simulation.behavior,
            GeneratedEffectBehavior::Stream
        );
    }

    #[test]
    fn generated_effect_rendering_emits_host_and_simulator_surfaces() {
        let choreography = parse_choreography_str(sample_dsl()).expect("parse choreography");
        let families = generated_effect_families(&choreography);

        let effects = render_generated_effects(&families);
        assert!(effects.contains("pub enum RuntimeRequest"));
        assert!(effects.contains("pub trait RuntimeExternalHandler"));
        assert!(effects.contains("pub struct RuntimeReadChannelRequest"));
        assert!(effects.contains("pub enum RuntimeWatchPresenceOutcome"));

        let simulator = render_generated_simulator(&families);
        assert!(simulator.contains("pub struct RuntimeScenarioBuilder"));
        assert!(simulator.contains("pub trait RuntimeSimulatorHandler"));
        assert!(simulator.contains("read_channel_success"));
    }

    #[test]
    fn scaffold_generation_writes_expected_files() {
        let out_dir = unique_temp_dir("effect_scaffold_ok");
        let choreography = parse_choreography_str(sample_dsl()).expect("parse choreography");
        let generated = generate_effect_interface_scaffold(
            &out_dir,
            &generated_effect_families(&choreography),
            true,
        )
        .expect("generation succeeds");

        assert_eq!(generated.len(), 4);
        assert!(out_dir.join("generated_effects.rs").exists());
        assert!(out_dir.join("generated_effect_manifest.json").exists());
        assert!(out_dir.join("generated_simulator.rs").exists());
        assert!(out_dir.join("README.md").exists());
        let effects = fs::read_to_string(out_dir.join("generated_effects.rs")).expect("read");
        assert!(effects.contains("RuntimeExternalHandler"));
        let simulator =
            fs::read_to_string(out_dir.join("generated_simulator.rs")).expect("read sim");
        assert!(simulator.contains("RuntimeScenarioBuilder"));

        drop(fs::remove_dir_all(out_dir));
    }

    #[test]
    fn preflight_rejects_existing_files_without_partial_writes() {
        let out_dir = unique_temp_dir("effect_scaffold_preflight");
        fs::create_dir_all(&out_dir).expect("create out dir");
        fs::write(
            out_dir.join("generated_effect_manifest.json"),
            "already here",
        )
        .expect("seed existing file");
        let choreography = parse_choreography_str(sample_dsl()).expect("parse choreography");

        let error = generate_effect_interface_scaffold(
            &out_dir,
            &generated_effect_families(&choreography),
            true,
        )
        .expect_err("preflight should fail");
        assert!(error.contains("generated_effect_manifest.json"));
        assert!(!out_dir.join("generated_effects.rs").exists());
        assert!(!out_dir.join("generated_simulator.rs").exists());
        assert!(!out_dir.join("README.md").exists());

        drop(fs::remove_dir_all(out_dir));
    }

    fn unique_temp_dir(prefix: &str) -> PathBuf {
        let mut path = env::temp_dir();
        path.push(format!("{prefix}_{}_{}", std::process::id(), now_nanos()));
        path
    }
}