promptforge-core 0.1.0

PromptForge runtime core: prompt parser, HTTP client, section execution
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
use std::num::NonZeroU32;

use super::arm::ArmFinalizer;
use super::proxies::ProxyObserver;
use super::*;
use crate::observe::detail;
use crate::parser::Block;

#[test]
fn resolve_sibling_finds_exact_match() {
    let sections = vec![
        Section {
            name: "Worker".to_string(),
            level: 3,
            blocks: vec![Block::Prose {
                text: String::new(),
                loop_capable: true,
            }],
            children: Vec::new(),
            items: Vec::new(),
        },
        Section {
            name: "Topics".to_string(),
            level: 3,
            blocks: vec![Block::Prose {
                text: String::new(),
                loop_capable: true,
            }],
            children: Vec::new(),
            items: vec!["a".to_string()],
        },
    ];
    let found = resolve_sibling("### Worker", &sections).expect("must resolve");
    assert_eq!(found.name, "Worker");
}

#[test]
fn resolve_sibling_missing_heading_lists_available() {
    let sections = vec![Section {
        name: "Worker".to_string(),
        level: 3,
        blocks: vec![Block::Prose {
            text: String::new(),
            loop_capable: true,
        }],
        children: Vec::new(),
        items: Vec::new(),
    }];
    let err = resolve_sibling("### Missing", &sections).expect_err("missing heading must error");
    assert!(err.to_string().contains("### Worker"), "error was: {err}");
}

#[test]
fn resolve_sibling_bare_name_errors() {
    let sections = vec![Section {
        name: "Worker".to_string(),
        level: 3,
        blocks: vec![Block::Prose {
            text: String::new(),
            loop_capable: true,
        }],
        children: Vec::new(),
        items: Vec::new(),
    }];
    let err = resolve_sibling("Worker", &sections).expect_err("bare name without ### must error");
    assert!(err.to_string().contains("### markers"), "error was: {err}");
}

fn sibling(name: &str, level: u8) -> Section {
    Section {
        name: name.to_string(),
        level,
        blocks: vec![Block::Prose {
            text: String::new(),
            loop_capable: true,
        }],
        children: Vec::new(),
        items: Vec::new(),
    }
}

#[test]
fn resolve_sibling_requires_whitespace_after_markers() {
    let sections = vec![sibling("Worker", 3)];
    let err = resolve_sibling("###Worker", &sections)
        .expect_err("no whitespace after markers must error");
    assert!(err.to_string().contains("whitespace"), "error was: {err}");
}

#[test]
fn resolve_sibling_requires_exact_level() {
    let sections = vec![sibling("Worker", 3)];
    // Same name, wrong marker level, must not resolve.
    let err = resolve_sibling("## Worker", &sections)
        .expect_err("a level mismatch must not resolve by name alone");
    assert!(err.to_string().contains("not found"), "error was: {err}");
    // The exact address resolves.
    let ok = resolve_sibling("### Worker", &sections).expect("exact address resolves");
    assert_eq!(ok.name, "Worker");
}

#[test]
fn resolve_sibling_rejects_more_than_one_match() {
    let sections = vec![sibling("Worker", 3), sibling("Worker", 3)];
    let err = resolve_sibling("### Worker", &sections)
        .expect_err("two identical siblings must be rejected as ambiguous");
    assert!(err.to_string().contains("ambiguous"), "error was: {err}");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fanout_arm_join_failure_preserves_the_join_error_source() {
    // A panicked/aborted arm surfaces as `Error::FanoutArmJoin` that keeps
    // the structured `JoinError` as its `#[source]`, rather than being
    // flattened into an `Error::Lua` string that loses the cause.
    use std::error::Error as _;

    let join_error = tokio::spawn(async { panic!("arm blew up") })
        .await
        .expect_err("a panicking task must produce a JoinError");
    let error = Error::FanoutArmJoin(join_error);
    assert!(
        error.source().is_some(),
        "the JoinError must be preserved as the error source"
    );
    assert!(
        !error.to_string().contains("arm blew up"),
        "the panic payload is not stringified into the outer message"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pre_cancelled_fanout_returns_interrupted() {
    use crate::Error;
    use crate::cancel::{self, CancelHandle};
    use crate::client::GatewayClient;
    use crate::lua::LuaProgram;
    use crate::model::ModelBindings;
    use crate::observe::NullObserver;
    use crate::parser::Section;
    use crate::store::StoreRef;

    let prologue = LuaProgram::compile(
        "return item",
        "test prologue",
        NonZeroU32::new(1).expect("compile source line is non-zero"),
        "fanout-cancel-test",
        &NullObserver,
        "Worker",
    )
    .expect("test Lua must compile");
    let worker = Section {
        name: "Worker".to_string(),
        level: 3,
        blocks: vec![Block::Lua(prologue)],
        children: Vec::new(),
        items: Vec::new(),
    };
    let items = vec!["alpha".to_string(), "beta".to_string()];
    let store = StoreRef::memory();
    let bindings = ToolBindings::default();
    let models = ModelBindings::default();
    let analysis = crate::execute::ToolAnalysis::default();
    let shared_tools = SharedTools::default();
    let client: Option<GatewayClient> = None;
    let observer = NullObserver;
    let ctx = FanoutContext {
        args: "",
        store: &store,
        execution: "fanout-cancel-test",
        observer: &observer,
        client: &client,
        debug: None,
        shared: None,
        bindings: &bindings,
        models: &models,
        analysis: &analysis,
        shared_tools: &shared_tools,
        max_tool_iterations: 24,
        fanout_concurrency: NonZeroUsize::new(8).expect("8 is non-zero"),
        max_fanout_items: NonZeroUsize::new(1024).expect("1024 is non-zero"),
        lua_memory_bytes: 64 * 1024 * 1024,
        lua_log_events: 1024,
        last_reply: None,
        when: "2026-08-08",
        parent_id: 1,
        section_count: 1,
    };

    let cancel = CancelHandle::new();
    cancel.cancel();
    let error = cancel::scope(cancel, run_fanout_arms(&worker, &items, &ctx))
        .await
        .expect_err("pre-cancelled fanout must fail");
    assert!(
        matches!(error, Error::Interrupted),
        "expected Interrupted, got {error}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fatal_arm_aborts_and_drops_blocked_siblings() {
    // FANOUT-003: drive `run_fanout_arms` for real. A fatal arm error returns
    // from the run level (not Interrupted, not a synthetic JoinError), and the
    // queued/blocked siblings are dropped without running - proven by a store
    // side-channel that only the fatal arm ever wrote to.
    use crate::cancel::{self, CancelHandle};
    use crate::client::GatewayClient;
    use crate::model::ModelBindings;
    use crate::observe::NullObserver;
    use crate::parser::Section;
    use crate::store::StoreRef;

    let prologue = LuaProgram::compile(
        "store.append('log.txt', item)\nif item == 'boom' then error('fatal arm error') end\nreturn item",
        "worker prologue",
        NonZeroU32::new(1).expect("compile source line is non-zero"),
        "fanout-fatal-test",
        &NullObserver,
        "Worker",
    )
    .expect("test Lua must compile");
    let worker = Section {
        name: "Worker".to_string(),
        level: 3,
        blocks: vec![Block::Lua(prologue)],
        children: Vec::new(),
        items: Vec::new(),
    };
    // The fatal item is dispatched first; with concurrency 1 the siblings stay
    // queued and must never be spawned once the first arm fails.
    let items = vec!["boom".to_string(), "beta".to_string(), "gamma".to_string()];
    let store = StoreRef::memory();
    let bindings = ToolBindings::default();
    let models = ModelBindings::default();
    let analysis = crate::execute::ToolAnalysis::default();
    let shared_tools = SharedTools::default();
    let client: Option<GatewayClient> = None;
    let observer = NullObserver;
    let ctx = FanoutContext {
        args: "",
        store: &store,
        execution: "fanout-fatal-test",
        observer: &observer,
        client: &client,
        debug: None,
        shared: None,
        bindings: &bindings,
        models: &models,
        analysis: &analysis,
        shared_tools: &shared_tools,
        max_tool_iterations: 24,
        fanout_concurrency: NonZeroUsize::new(1).expect("1 is non-zero"),
        max_fanout_items: NonZeroUsize::new(1024).expect("1024 is non-zero"),
        lua_memory_bytes: 64 * 1024 * 1024,
        lua_log_events: 1024,
        last_reply: None,
        when: "2026-08-08",
        parent_id: 1,
        section_count: 1,
    };

    let error = cancel::scope(CancelHandle::new(), run_fanout_arms(&worker, &items, &ctx))
        .await
        .expect_err("a fatal arm must fail the whole fanout");
    // A genuine arm failure, not cancellation or a synthetic join failure.
    assert!(
        !matches!(error, Error::Interrupted | Error::FanoutArmJoin(_)),
        "expected a fatal arm error, got {error}"
    );
    // Only the fatal arm ran; the blocked siblings were dropped and never
    // executed their prologue.
    let log = store.read("log.txt").expect("the fatal arm wrote its item");
    assert!(log.contains("boom"), "the fatal arm ran: {log:?}");
    assert!(
        !log.contains("beta") && !log.contains("gamma"),
        "blocked siblings must not run after a fatal arm: {log:?}"
    );
}

#[test]
fn arm_window_never_exceeds_the_concurrency_limit() {
    // Drive the pure scheduler through every completion order for a few
    // sizes and prove the invariant that gates real arms: outstanding never
    // exceeds the limit, and each index is dispatched exactly once.
    for &limit in &[1usize, 2, 3, 5] {
        for &count in &[0usize, 1, 4, 9, 20] {
            let concurrency = NonZeroUsize::new(limit).expect("limit is non-zero");
            let mut window = ArmWindow::new(count, concurrency);
            let mut in_flight: Vec<usize> = Vec::new();
            let mut dispatched: Vec<usize> = Vec::new();
            let mut max_outstanding = 0usize;

            while let Some(index) = window.take_next() {
                in_flight.push(index);
                dispatched.push(index);
            }
            assert!(
                in_flight.len() <= limit,
                "initial window {} exceeded limit {limit}",
                in_flight.len()
            );
            let mut toggle = false;
            while !in_flight.is_empty() {
                assert!(
                    in_flight.len() <= limit,
                    "outstanding {} exceeded limit {limit}",
                    in_flight.len()
                );
                max_outstanding = max_outstanding.max(in_flight.len());
                // Complete arms from alternating ends to vary the order.
                let done = if toggle {
                    in_flight.remove(0)
                } else {
                    in_flight.pop().expect("non-empty")
                };
                toggle = !toggle;
                let _ = done;
                window.complete_one();
                while let Some(index) = window.take_next() {
                    in_flight.push(index);
                    dispatched.push(index);
                }
            }

            assert!(max_outstanding <= limit);
            dispatched.sort_unstable();
            assert_eq!(
                dispatched,
                (0..count).collect::<Vec<_>>(),
                "every item index must be dispatched exactly once"
            );
        }
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fanout_rejects_a_list_over_the_item_cap() {
    use crate::client::GatewayClient;
    use crate::model::ModelBindings;
    use crate::observe::NullObserver;
    use crate::parser::Section;
    use crate::store::StoreRef;

    let worker = Section {
        name: "Worker".to_string(),
        level: 3,
        blocks: vec![Block::Prose {
            text: "irrelevant".to_string(),
            loop_capable: true,
        }],
        children: Vec::new(),
        items: Vec::new(),
    };
    let items: Vec<String> = (0..5).map(|i| i.to_string()).collect();
    let store = StoreRef::memory();
    let bindings = ToolBindings::default();
    let models = ModelBindings::default();
    let analysis = crate::execute::ToolAnalysis::default();
    let shared_tools = SharedTools::default();
    let client: Option<GatewayClient> = None;
    let observer = NullObserver;
    let ctx = FanoutContext {
        args: "",
        store: &store,
        execution: "fanout-cap-test",
        observer: &observer,
        client: &client,
        debug: None,
        shared: None,
        bindings: &bindings,
        models: &models,
        analysis: &analysis,
        shared_tools: &shared_tools,
        max_tool_iterations: 24,
        fanout_concurrency: NonZeroUsize::new(8).expect("8 is non-zero"),
        max_fanout_items: NonZeroUsize::new(3).expect("3 is non-zero"),
        lua_memory_bytes: 64 * 1024 * 1024,
        lua_log_events: 1024,
        last_reply: None,
        when: "2026-08-08",
        parent_id: 1,
        section_count: 1,
    };

    let error = run_fanout_arms(&worker, &items, &ctx)
        .await
        .expect_err("a list longer than max_fanout_items must be rejected");
    assert!(
        error.to_string().contains("exceeding the maximum of 3"),
        "error must explain the item cap: {error}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn model_required_when_arm_prose_has_no_binding() {
    use crate::Error;
    use crate::client::GatewayClient;
    use crate::model::ModelBindings;
    use crate::observe::NullObserver;
    use crate::parser::Section;
    use crate::store::StoreRef;

    let worker = Section {
        name: "Worker".to_string(),
        level: 3,
        blocks: vec![Block::Prose {
            text: "Ask the model about {{ item }}.".to_string(),
            loop_capable: true,
        }],
        children: Vec::new(),
        items: Vec::new(),
    };
    let items = vec!["alpha".to_string()];
    let store = StoreRef::memory();
    let bindings = ToolBindings::default();
    let models = ModelBindings::default();
    let analysis = crate::execute::ToolAnalysis::default();
    let shared_tools = SharedTools::default();
    let client: Option<GatewayClient> = None;
    let observer = NullObserver;
    let ctx = FanoutContext {
        args: "",
        store: &store,
        execution: "fanout-test",
        observer: &observer,
        client: &client,
        debug: None,
        shared: None,
        bindings: &bindings,
        models: &models,
        analysis: &analysis,
        shared_tools: &shared_tools,
        max_tool_iterations: 24,
        fanout_concurrency: NonZeroUsize::new(8).expect("8 is non-zero"),
        max_fanout_items: NonZeroUsize::new(1024).expect("1024 is non-zero"),
        lua_memory_bytes: 64 * 1024 * 1024,
        lua_log_events: 1024,
        last_reply: None,
        when: "2026-08-08",
        parent_id: 1,
        section_count: 1,
    };

    let error = run_fanout_arms(&worker, &items, &ctx)
        .await
        .expect_err("non-empty arm prose without a model binding must fail");
    assert!(
        matches!(error, Error::ModelRequired { .. }),
        "expected ModelRequired, got {error}"
    );
    assert!(
        error
            .to_string()
            .contains("model binding required for section Worker"),
        "error must name the worker section: {error}"
    );
}

/// Records every observation's Display string, in order.
#[derive(Default)]
struct EventRecorder(std::sync::Mutex<Vec<String>>);

impl Observer for EventRecorder {
    fn observe(&self, _execution: &str, _section: &str, event: Observation) {
        self.0
            .lock()
            .expect("recorder mutex is not poisoned")
            .push(event.to_string());
    }
}

impl EventRecorder {
    fn snapshot(&self) -> Vec<String> {
        self.0
            .lock()
            .expect("recorder mutex is not poisoned")
            .clone()
    }

    fn count(&self, label: &str) -> usize {
        self.snapshot()
            .iter()
            .filter(|e| e.as_str() == label)
            .count()
    }
}

fn lua_worker(source: &str) -> Section {
    let program = LuaProgram::compile(
        source,
        "test prologue",
        NonZeroU32::new(1).expect("compile source line is non-zero"),
        "fanout-terminal-test",
        &crate::observe::NullObserver,
        "Worker",
    )
    .expect("test Lua must compile");
    Section {
        name: "Worker".to_string(),
        level: 3,
        blocks: vec![Block::Lua(program)],
        children: Vec::new(),
        items: Vec::new(),
    }
}

#[expect(
    clippy::ref_option,
    reason = "FanoutContext.client borrows an Option<GatewayClient>, so the helper must too"
)]
fn terminal_ctx<'a>(
    observer: &'a dyn Observer,
    store: &'a StoreRef,
    bindings: &'a ToolBindings,
    models: &'a ModelBindings,
    analysis: &'a crate::execute::ToolAnalysis,
    shared_tools: &'a SharedTools,
    client: &'a Option<GatewayClient>,
) -> FanoutContext<'a> {
    FanoutContext {
        args: "",
        store,
        execution: "fanout-terminal-test",
        observer,
        client,
        debug: None,
        shared: None,
        bindings,
        models,
        analysis,
        shared_tools,
        max_tool_iterations: 24,
        fanout_concurrency: NonZeroUsize::new(4).expect("4 is non-zero"),
        max_fanout_items: NonZeroUsize::new(1024).expect("1024 is non-zero"),
        lua_memory_bytes: 64 * 1024 * 1024,
        lua_log_events: 1024,
        last_reply: None,
        when: "2026-08-08",
        parent_id: 1,
        section_count: 1,
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn each_arm_emits_a_distinct_succeeded_terminal_event() {
    // FANOUT-004: every arm is finalized exactly once with a distinct
    // terminal event. Two arms whose prologue returns a value each emit one
    // `started` and one `succeeded`, and nothing else.
    let worker = lua_worker("return item");
    let items = vec!["a".to_string(), "b".to_string()];
    let store = StoreRef::memory();
    let bindings = ToolBindings::default();
    let models = ModelBindings::default();
    let analysis = crate::execute::ToolAnalysis::default();
    let shared_tools = SharedTools::default();
    let client: Option<GatewayClient> = None;
    let recorder = EventRecorder::default();
    let ctx = terminal_ctx(
        &recorder,
        &store,
        &bindings,
        &models,
        &analysis,
        &shared_tools,
        &client,
    );

    let results = run_fanout_arms(&worker, &items, &ctx)
        .await
        .expect("both arms must succeed");
    assert_eq!(results.len(), 2);
    assert_eq!(recorder.count("Fanout arm started"), 2);
    assert_eq!(
        recorder.count("Fanout arm succeeded"),
        2,
        "each arm emits one distinct succeeded event: {:?}",
        recorder.snapshot()
    );
    assert_eq!(recorder.count("Fanout arm failed"), 0);
    assert_eq!(recorder.count("Fanout arm cancelled"), 0);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_hard_failing_arm_emits_a_failed_terminal_event() {
    // FANOUT-004: a hard arm error emits a distinct `failed` terminal event,
    // never `succeeded`.
    let worker = lua_worker("error('boom')");
    let items = vec!["a".to_string()];
    let store = StoreRef::memory();
    let bindings = ToolBindings::default();
    let models = ModelBindings::default();
    let analysis = crate::execute::ToolAnalysis::default();
    let shared_tools = SharedTools::default();
    let client: Option<GatewayClient> = None;
    let recorder = EventRecorder::default();
    let ctx = terminal_ctx(
        &recorder,
        &store,
        &bindings,
        &models,
        &analysis,
        &shared_tools,
        &client,
    );

    run_fanout_arms(&worker, &items, &ctx)
        .await
        .expect_err("a hard arm error must fail the fanout");
    assert_eq!(
        recorder.count("Fanout arm failed"),
        1,
        "the failing arm emits one failed event: {:?}",
        recorder.snapshot()
    );
    assert_eq!(recorder.count("Fanout arm succeeded"), 0);
}

/// Signals a oneshot the first time it observes a Lua `log` event, so a test
/// can learn deterministically that an arm has started running.
struct SignalOnLog {
    tx: std::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
}

impl Observer for SignalOnLog {
    fn observe(&self, _execution: &str, _section: &str, event: Observation) {
        if matches!(event, Observation::Lua(_))
            && let Some(tx) = self.tx.lock().expect("signal mutex").take()
        {
            let _ = tx.send(());
        }
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_in_flight_fanout_arm_is_cancelled_cooperatively() {
    // PF-CANCEL-002 / FANOUT-003 (in-flight): a spawned arm carries an
    // explicit CancelHandle, so an arm spinning in synchronous Lua stops via
    // its OWN instruction hook when cancelled mid-flight. Without the
    // per-arm handle the arm could not be aborted (synchronous Lua cannot be
    // preempted) and the join drain would hang - so the timeout below is the
    // regression guard. Readiness is signaled explicitly (no sleeps).
    use crate::cancel::{self, CancelHandle};

    let worker = lua_worker("log('running')\nwhile true do end\nreturn item");
    let items = vec!["only".to_string()];
    let store = StoreRef::memory();
    let bindings = ToolBindings::default();
    let models = ModelBindings::default();
    let analysis = crate::execute::ToolAnalysis::default();
    let shared_tools = SharedTools::default();
    let client: Option<GatewayClient> = None;

    let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
    let observer = SignalOnLog {
        tx: std::sync::Mutex::new(Some(ready_tx)),
    };
    let ctx = terminal_ctx(
        &observer,
        &store,
        &bindings,
        &models,
        &analysis,
        &shared_tools,
        &client,
    );

    let cancel = CancelHandle::new();
    let canceller = {
        let handle = cancel.clone();
        tokio::spawn(async move {
            // Cancel only once the arm has actually started spinning.
            let _ = ready_rx.await;
            handle.cancel();
        })
    };

    let result = tokio::time::timeout(
        std::time::Duration::from_secs(10),
        cancel::scope(cancel, run_fanout_arms(&worker, &items, &ctx)),
    )
    .await
    .expect("the in-flight arm must cooperatively cancel, not hang the join drain");
    let error = result.expect_err("a cancelled fanout returns an error");
    assert!(
        matches!(error, crate::Error::Interrupted),
        "expected Interrupted, got {error}"
    );
    canceller.await.expect("the canceller task joins");
}

#[test]
fn arm_finalizer_emits_cancelled_on_drop_unless_finished() {
    // FANOUT-004/006: the guard emits exactly one terminal event. Dropped
    // without finishing => cancelled; finished => only that event.
    let (tx, mut rx) = mpsc::channel::<(String, Observation)>(8);
    let proxy = Arc::new(ProxyObserver { tx });

    drop(ArmFinalizer::new(
        Arc::clone(&proxy),
        "exec".to_string(),
        "S".to_string(),
    ));
    let (_, event) = rx.try_recv().expect("a dropped finalizer emits an event");
    assert_eq!(event.to_string(), "Fanout arm cancelled");
    assert!(rx.try_recv().is_err(), "exactly one terminal event on drop");

    let mut finalizer = ArmFinalizer::new(Arc::clone(&proxy), "exec".to_string(), "S".to_string());
    finalizer.finish(detail::FANOUT_ARM_SUCCEEDED);
    drop(finalizer);
    let (_, event) = rx.try_recv().expect("finish emits its event");
    assert_eq!(event.to_string(), "Fanout arm succeeded");
    assert!(
        rx.try_recv().is_err(),
        "a finished finalizer does not also emit cancelled on drop"
    );
}