arora-behavior-tree 8.2.0

The Arora behavior tree: Groot-compatible trees ticking Arora modules.
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
//! Engine-free tests. Tests that need a real engine moved to `arora-sdk`.
//!
//! The basic control nodes (seq, seq_star, fallback, parallel, succeed, fail,
//! run) are dispatched natively, so their execution can be exercised here with a
//! minimal registry-backed [`CallBridge`] — no wasm module, no engine.
use crate::arora_generated::behavior_tree::status::Status;
use crate::load_behavior_tree_yaml;
use crate::nodes;
use crate::tree_node::TreeNode;
use crate::{run_behavior_tree, BehaviorTree, BehaviorTreeRuntime, ModuleFunction};
use anyhow::Result;
use arora_types::call::{Call, CallBridge, CallError, CallResult, Callable, CallableId};
use arora_types::record::module::frozen::Function;
use arora_types::record::ty::{FrozenTy, PrimitiveKind};
use arora_types::value::Value;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use uuid::Uuid;

#[test]
pub fn load_parse_error() -> Result<()> {
    let tree_yaml = "I'm singing in the rain...";
    assert!(load_behavior_tree_yaml(tree_yaml).is_err());
    Ok(())
}

#[test]
pub fn load_simple_tree() -> Result<()> {
    let tree_yaml = &crate::schema::tests::SIMPLE_TREE_YAML;
    load_behavior_tree_yaml(tree_yaml)?;
    Ok(())
}

/// Two node parameters that reference the **same** variable id must resolve to a
/// single shared cell, so a write through one is visible through the other —
/// that is what makes `{var}` a shared blackboard entry across nodes.
///
/// Regression test for the variable-sharing bug: a freshly-referenced variable
/// was inserted into the variables map under a fresh `Uuid::new_v4()` instead of
/// its own `variable_id`, so the next lookup by `variable_id` missed and a second,
/// independent cell was created.
#[test]
fn shared_variable_id_resolves_to_one_cell() {
    use crate::schema::{Expression, NodeParameterId};
    use crate::variable::VariableCell;

    let var_id = Uuid::new_v4();
    let mut variables: HashMap<Uuid, VariableCell> = HashMap::new();
    let mut node_parameters: HashMap<NodeParameterId, VariableCell> = HashMap::new();

    let param_a = NodeParameterId {
        node: Uuid::new_v4(),
        parameter: Uuid::new_v4(),
    };
    let param_b = NodeParameterId {
        node: Uuid::new_v4(),
        parameter: Uuid::new_v4(),
    };

    let cell_a = crate::setup_node_parameter_variable(
        &param_a,
        &Expression::VariableId(var_id),
        &mut variables,
        &mut node_parameters,
        &|_| None,
        &HashMap::new(),
    )
    .unwrap();
    let cell_b = crate::setup_node_parameter_variable(
        &param_b,
        &Expression::VariableId(var_id),
        &mut variables,
        &mut node_parameters,
        &|_| None,
        &HashMap::new(),
    )
    .unwrap();

    cell_a.set(Value::Boolean(true));
    assert_eq!(
        cell_b.get_or_unit(),
        Value::Boolean(true),
        "two parameters bound to the same variable id must share one cell"
    );
}

/// A `{var}` whose name the resolver knows binds to the data store: the cell and
/// the store key are the same storage, both ways. This is the Direct convention
/// (variable name == store key) the runtime supplies — exercised here against a
/// real [`SimpleDataStore`] so the behavior-tree crate's `Slot` plumbing is
/// covered without an engine.
#[test]
fn resolved_variable_is_store_backed() {
    use crate::schema::{Expression, NodeParameterId};
    use crate::variable::VariableCell;
    use arora_simple_data_store::SimpleDataStore;
    use arora_types::data::{DataStore, Key, StateChange};

    let store = SimpleDataStore::new();
    let resolver = {
        let store = store.clone();
        // `DataStore::slot` already hands back a `Box<dyn Slot>`.
        move |name: &str| Some(store.slot(&Key::from(name)))
    };

    let var_id = Uuid::new_v4();
    let names = HashMap::from([(var_id, "battery.level".to_string())]);

    let mut variables: HashMap<Uuid, VariableCell> = HashMap::new();
    let mut node_parameters: HashMap<NodeParameterId, VariableCell> = HashMap::new();
    let param = NodeParameterId {
        node: Uuid::new_v4(),
        parameter: Uuid::new_v4(),
    };

    let cell = crate::setup_node_parameter_variable(
        &param,
        &Expression::VariableId(var_id),
        &mut variables,
        &mut node_parameters,
        &resolver,
        &names,
    )
    .unwrap();

    // Write through the cell, read through the store.
    cell.set(Value::from(1.0_f64));
    assert_eq!(
        store.read(&[Key::from("battery.level")]),
        vec![Some(Value::from(1.0_f64))],
        "a write through the resolved cell must reach the store key"
    );

    // Write through the store, read through the cell.
    store
        .write(StateChange::set("battery.level", Value::from(2.0_f64)))
        .unwrap();
    assert_eq!(
        cell.get(),
        Some(Value::from(2.0_f64)),
        "a write through the store key must be visible through the resolved cell"
    );
}

// Native execution harness
//================================================================
/// A leaf whose status is supplied by a shared, mutable cell, so a test can
/// change what it returns between ticks. Modeled as a plain (non-control) node
/// so it dispatches through `arora_call` — the path real module leaves use.
type LeafStatuses = Rc<RefCell<HashMap<Uuid, Status>>>;

/// Records how many times each leaf function id was ticked.
type LeafTicks = Rc<RefCell<HashMap<Uuid, u32>>>;

/// A [`CallBridge`] that registers/invokes callables natively and answers
/// `arora_call` for the test's scripted leaf functions. Native behavior trees
/// never call into real modules.
struct TestBridge {
    registered: HashMap<u64, Rc<dyn Callable>>,
    next_id: u64,
    leaf_statuses: LeafStatuses,
    leaf_ticks: LeafTicks,
}

impl TestBridge {
    fn new(leaf_statuses: LeafStatuses, leaf_ticks: LeafTicks) -> Self {
        Self {
            registered: HashMap::new(),
            next_id: 0,
            leaf_statuses,
            leaf_ticks,
        }
    }

    fn empty() -> Self {
        Self::new(
            Rc::new(RefCell::new(HashMap::new())),
            Rc::new(RefCell::new(HashMap::new())),
        )
    }
}

impl CallBridge for TestBridge {
    fn arora_call(&mut self, call: Call) -> Result<CallResult, CallError> {
        *self.leaf_ticks.borrow_mut().entry(call.id).or_insert(0) += 1;
        let status = self
            .leaf_statuses
            .borrow()
            .get(&call.id)
            .cloned()
            .ok_or(CallError::FunctionNotFound { id: call.id })?;
        Ok(CallResult {
            ret: status.into(),
            mutated: Vec::new(),
        })
    }

    fn arora_register_callable(&mut self, callable: Rc<dyn Callable>) -> CallableId {
        let id = self.next_id;
        self.next_id += 1;
        self.registered.insert(id, callable);
        CallableId { id }
    }

    fn arora_unregister_callable(&mut self, callable_id: &CallableId) {
        self.registered.remove(&callable_id.id);
    }

    fn arora_call_indirect(&mut self, callable_id: &CallableId) -> Result<Value, CallError> {
        let callable = self
            .registered
            .get(&callable_id.id)
            .cloned()
            .ok_or(CallError::Generic {
                message: format!("unknown callable {}", callable_id.id),
            })?;
        callable.call(self)
    }
}

/// A scripted leaf node: a non-control node dispatched through `arora_call`,
/// whose status comes from the bridge's `leaf_statuses`.
fn scripted_leaf(function: Uuid) -> TreeNode {
    TreeNode {
        function,
        children: None,
        parameters: HashMap::new(),
    }
}

/// A minimal `ModuleFunction` for a scripted leaf, so the native tick path can
/// build the (empty) call. The leaf has no parameters and returns a status.
fn scripted_leaf_function(function: Uuid) -> ModuleFunction {
    ModuleFunction {
        module_id: Uuid::nil(),
        function_id: function,
        function_name: "scripted_leaf".to_string(),
        function: Function {
            parameters: HashMap::new(),
            parameter_ordering: Vec::new(),
            return_ty: FrozenTy::from(PrimitiveKind::U8),
        },
    }
}

pub(crate) fn build(node: TreeNode) -> BehaviorTree {
    node.try_into().expect("tree builds")
}

/// Tick a tree (with only native nodes) exactly once.
fn tick_once(tree: &BehaviorTree) -> Status {
    let mut bridge = TestBridge::empty();
    let mut runtime = BehaviorTreeRuntime::setup(tree, Rc::new(HashMap::new()), &mut bridge, false)
        .expect("runtime sets up");
    runtime.tick().expect("tick succeeds")
}

/// Run a tree (with only native nodes) to a terminal status.
fn run(tree: &BehaviorTree) -> Status {
    let mut bridge = TestBridge::empty();
    run_behavior_tree(tree, Rc::new(HashMap::new()), &mut bridge, false).expect("run succeeds")
}

// seq
//----------------------------------------------------------------
#[test]
fn seq_all_success_is_success() {
    let tree = build(nodes::seq(vec![nodes::succeed(), nodes::succeed()]));
    assert_eq!(run(&tree), Status::Success);
}

#[test]
fn seq_first_failure_is_failure() {
    // `fail()` is native, so it short-circuits before the later child can run.
    // Make the later child a leaf that has no scripted status, so reaching it
    // would surface as an error rather than a silent pass.
    let later = Uuid::from_u128(0xA1);
    let tree = build(nodes::seq(vec![nodes::fail(), scripted_leaf(later)]));
    assert_eq!(tick_once(&tree), Status::Failure);
}

#[test]
fn seq_running_child_is_running() {
    let tree = build(nodes::seq(vec![nodes::succeed(), nodes::run()]));
    assert_eq!(tick_once(&tree), Status::Running);
}

// fallback
//----------------------------------------------------------------
#[test]
fn fallback_first_success_is_success() {
    let tree = build(nodes::fallback(vec![nodes::succeed(), nodes::fail()]));
    assert_eq!(run(&tree), Status::Success);
}

#[test]
fn fallback_all_failure_is_failure() {
    let tree = build(nodes::fallback(vec![nodes::fail(), nodes::fail()]));
    assert_eq!(run(&tree), Status::Failure);
}

#[test]
fn fallback_empty_is_success() {
    let tree = build(nodes::fallback(vec![]));
    assert_eq!(run(&tree), Status::Success);
}

#[test]
fn fallback_running_child_is_running() {
    let tree = build(nodes::fallback(vec![nodes::run(), nodes::succeed()]));
    assert_eq!(tick_once(&tree), Status::Running);
}

// parallel
//----------------------------------------------------------------
#[test]
fn parallel_all_success_is_success() {
    let tree = build(nodes::parallel(vec![nodes::succeed(), nodes::succeed()]));
    assert_eq!(run(&tree), Status::Success);
}

#[test]
fn parallel_any_failure_is_failure() {
    let tree = build(nodes::parallel(vec![
        nodes::succeed(),
        nodes::fail(),
        nodes::succeed(),
    ]));
    assert_eq!(run(&tree), Status::Failure);
}

#[test]
fn parallel_mixed_running_is_running() {
    // A running child with no failing child yields Running.
    let tree = build(nodes::parallel(vec![nodes::succeed(), nodes::run()]));
    assert_eq!(tick_once(&tree), Status::Running);
}

/// Poll-on-tick with per-run identity: two long-running leaves run concurrently
/// under `parallel`, each carrying its own status. The tree is re-ticked while
/// either is `Running` (that re-tick *is* the poll-on-tick contract — see
/// docs/async-functions.md), and completing one leaves the other running: each
/// run advances on its own identity, not a shared slot. This is the state model a
/// spawned `say` action needs — here the two runs are distinct scripted leaves,
/// no module and no network. (`polly::say` keys its runs by content only because
/// the module ABI hands it no per-invocation id; a run spawned as a behavior gets
/// that identity from the node, per the reserved-parameter note in the doc.)
#[test]
fn concurrent_runs_advance_independently() {
    let a = Uuid::from_u128(0xA);
    let b = Uuid::from_u128(0xB);

    let statuses: LeafStatuses = Rc::new(RefCell::new(HashMap::from([
        (a, Status::Running),
        (b, Status::Running),
    ])));
    let ticks: LeafTicks = Rc::new(RefCell::new(HashMap::new()));
    let function_index = Rc::new(HashMap::from([
        (a, scripted_leaf_function(a)),
        (b, scripted_leaf_function(b)),
    ]));
    let tree = build(nodes::parallel(vec![scripted_leaf(a), scripted_leaf(b)]));
    let mut bridge = TestBridge::new(statuses.clone(), ticks.clone());

    // Both runs pending → the tree keeps being re-ticked (Running).
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Running);
    let _ = runtime;

    // Complete run A only. Its status is its own, so B is untouched and the tree
    // is still Running — the two runs never shared a slot.
    statuses.borrow_mut().insert(a, Status::Success);
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Running);
    let _ = runtime;

    // Complete run B. Both terminal → the tree succeeds.
    statuses.borrow_mut().insert(b, Status::Success);
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Success);
}

// seq_star
//----------------------------------------------------------------
#[test]
fn seq_star_resumes_and_resets() {
    // Three scripted leaves; the middle one starts as Running. seq_star should
    // tick the first (Success), hit the second (Running) and stop there,
    // remembering index 1. On the next tick it must resume at the second leaf
    // WITHOUT re-ticking the first. After a terminal result the index resets.
    let first = Uuid::from_u128(0x1);
    let second = Uuid::from_u128(0x2);
    let third = Uuid::from_u128(0x3);

    let statuses: LeafStatuses = Rc::new(RefCell::new(HashMap::from([
        (first, Status::Success),
        (second, Status::Running),
        (third, Status::Success),
    ])));
    let ticks: LeafTicks = Rc::new(RefCell::new(HashMap::new()));

    let function_index = Rc::new(HashMap::from([
        (first, scripted_leaf_function(first)),
        (second, scripted_leaf_function(second)),
        (third, scripted_leaf_function(third)),
    ]));

    let tree = build(nodes::seq_star(vec![
        scripted_leaf(first),
        scripted_leaf(second),
        scripted_leaf(third),
    ]));

    let mut bridge = TestBridge::new(statuses.clone(), ticks.clone());

    // First tick: first succeeds, second is Running -> tree Running, index = 1.
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Running);
    let _ = runtime;
    assert_eq!(*ticks.borrow().get(&first).unwrap_or(&0), 1);
    assert_eq!(*ticks.borrow().get(&second).unwrap_or(&0), 1);
    assert_eq!(*ticks.borrow().get(&third).unwrap_or(&0), 0);

    // The second leaf now succeeds.
    statuses.borrow_mut().insert(second, Status::Success);

    // Second tick: resumes at the second leaf (no re-tick of the first), both
    // remaining leaves succeed -> whole seq_star succeeds, index resets to 0.
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Success);
    let _ = runtime;
    assert_eq!(
        *ticks.borrow().get(&first).unwrap_or(&0),
        1,
        "first not re-ticked"
    );
    assert_eq!(*ticks.borrow().get(&second).unwrap_or(&0), 2);
    assert_eq!(*ticks.borrow().get(&third).unwrap_or(&0), 1);

    // Third tick: after the reset, it restarts from the first leaf.
    let mut runtime = BehaviorTreeRuntime::setup(&tree, function_index.clone(), &mut bridge, false)
        .expect("setup");
    assert_eq!(runtime.tick().expect("tick"), Status::Success);
    let _ = runtime;
    assert_eq!(
        *ticks.borrow().get(&first).unwrap_or(&0),
        2,
        "first re-ticked after reset"
    );
}

/// A fresh interpreter hosts the runner scaffold from the start: it accepts
/// edits before anything is loaded, and with nothing grafted the runner ticks
/// no children — the interpreter idles, always `Running`.
#[test]
fn a_fresh_interpreter_accepts_edits_and_idles_while_empty() {
    use crate::behavior::BehaviorTreeInterpreter;
    use arora_behavior::graph::GraphDiff;
    use arora_behavior::{BehaviorContext, BehaviorInterpreter, BehaviorStatus};
    use arora_simple_data_store::SimpleDataStore;

    let mut interpreter = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

    // The scaffold is there before anything is loaded: one runner node.
    assert!(interpreter.graph().root.is_some(), "the runner is the root");
    assert_eq!(interpreter.graph().nodes.len(), 1, "just the runner");

    // The empty (no-op) edit is valid.
    interpreter
        .apply(GraphDiff::default())
        .expect("a fresh interpreter accepts a diff");

    // The re-lowering tick sees the bare runner: idle, stay installed.
    let store = SimpleDataStore::new();
    let (statuses, ticks) = (LeafStatuses::default(), LeafTicks::default());
    let mut bridge = TestBridge::new(statuses, ticks);
    let mut ctx = BehaviorContext {
        store: &store,
        call_bridge: &mut bridge,
    };
    let status = interpreter.tick(&mut ctx).expect("the bare scaffold idles");
    assert_eq!(status, BehaviorStatus::Running);
}

/// Task runs: `spawn`/`halt` on the interpreter, and how a run advances
/// alongside the main tree. Each run invokes a scripted leaf (through
/// [`TestBridge`]) whose returned status the test drives between ticks — a
/// stand-in for a real action-behavior whose status decorator publishes its
/// outcome to the run's status key.
mod task_runs {
    use super::{LeafStatuses, LeafTicks, TestBridge};
    use crate::arora_generated::behavior_tree::status::Status;
    use crate::behavior::BehaviorTreeInterpreter;
    use arora_behavior::{BehaviorContext, BehaviorInterpreter, BehaviorStatus, RunPolicy, TaskId};
    use arora_simple_data_store::SimpleDataStore;
    use arora_types::call::Call;
    use arora_types::data::DataStore;
    use arora_types::value::Value;
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::rc::Rc;
    use uuid::Uuid;

    /// A [`TestBridge`] whose one scripted leaf `leaf` returns `status`, plus the
    /// shared cells to drive it (`statuses`) and observe invocations (`ticks`).
    fn scripted(leaf: Uuid, status: Status) -> (TestBridge, LeafStatuses, LeafTicks) {
        let statuses: LeafStatuses = Rc::new(RefCell::new(HashMap::from([(leaf, status)])));
        let ticks: LeafTicks = Rc::new(RefCell::new(HashMap::new()));
        (
            TestBridge::new(statuses.clone(), ticks.clone()),
            statuses,
            ticks,
        )
    }

    /// A [`Call`] a run invokes: `module`/`leaf` identify the scripted leaf.
    fn call_to(module: u128, leaf: Uuid) -> Call {
        Call {
            module_id: Some(Uuid::from_u128(module)),
            id: leaf,
            args: Vec::new(),
        }
    }

    #[test]
    fn a_spawned_run_advances_and_writes_its_status_key() {
        let leaf = Uuid::from_u128(0xA1);
        let (mut bridge, statuses, ticks) = scripted(leaf, Status::Running);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

        // The default-reject is overridden: a handle comes back, its keys
        // namespaced under the run id.
        let handle = interp
            .spawn(call_to(0xB0, leaf), RunPolicy::Concurrent)
            .expect("the tree interpreter hosts runs");
        assert!(
            handle.status.path.starts_with("arora/tasks/"),
            "{}",
            handle.status.path
        );
        assert!(
            handle.status.path.ends_with("/status"),
            "{}",
            handle.status.path
        );

        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        // Spawn does not tick: nothing is written until the next tick.
        assert_eq!(store.read(std::slice::from_ref(&handle.status)), vec![None]);

        // First tick invokes the run once and publishes Running.
        assert_eq!(interp.tick(&mut ctx).unwrap(), BehaviorStatus::Running);
        let running: Value = Status::Running.into();
        assert_eq!(
            store.read(std::slice::from_ref(&handle.status)),
            vec![Some(running)],
            "the run's status key holds Running"
        );
        assert_eq!(*ticks.borrow().get(&leaf).unwrap(), 1);

        // The run reaches Success: the interpreter publishes it, drops the run,
        // and — no runs, no tree — idles rather than being dropped.
        statuses.borrow_mut().insert(leaf, Status::Success);
        assert_eq!(interp.tick(&mut ctx).unwrap(), BehaviorStatus::Running);
        let success: Value = Status::Success.into();
        assert_eq!(
            store.read(std::slice::from_ref(&handle.status)),
            vec![Some(success)]
        );

        // A finished run is not ticked again.
        let before = *ticks.borrow().get(&leaf).unwrap();
        interp.tick(&mut ctx).unwrap();
        assert_eq!(
            *ticks.borrow().get(&leaf).unwrap(),
            before,
            "a finished run is not re-ticked"
        );
    }

    #[test]
    fn halting_a_run_terminates_it_next_tick() {
        let leaf = Uuid::from_u128(0xC2);
        let (mut bridge, _statuses, ticks) = scripted(leaf, Status::Running);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

        let handle = interp
            .spawn(call_to(0xB0, leaf), RunPolicy::Concurrent)
            .unwrap();
        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };

        // Runs indefinitely: after a tick it is still Running.
        assert_eq!(interp.tick(&mut ctx).unwrap(), BehaviorStatus::Running);
        let running: Value = Status::Running.into();
        assert_eq!(
            store.read(std::slice::from_ref(&handle.status)),
            vec![Some(running)]
        );

        // Halt: the next tick ends the run (Failure) without invoking it again.
        interp.halt(handle.id).unwrap();
        let ticks_before = *ticks.borrow().get(&leaf).unwrap();
        assert_eq!(interp.tick(&mut ctx).unwrap(), BehaviorStatus::Running);
        let failure: Value = Status::Failure.into();
        assert_eq!(
            store.read(std::slice::from_ref(&handle.status)),
            vec![Some(failure)],
            "a halted run ends Failure"
        );
        assert_eq!(
            *ticks.borrow().get(&leaf).unwrap(),
            ticks_before,
            "a halted run is not invoked"
        );

        // Idempotent: halting the finished run, or an unknown run, is a clean
        // no-op.
        interp
            .halt(handle.id)
            .expect("halting a finished run is a no-op");
        interp
            .halt(TaskId(Uuid::from_u128(0xDEAD)))
            .expect("halting an unknown run is a no-op");
    }

    /// A loaded behavior and a spawned run coexist under the runner and both
    /// advance each tick — the main behavior reactively re-evaluated, the run
    /// invoked once per tick — and the interpreter is a standing policy: it
    /// reports `Running` every tick, never `Done`.
    #[test]
    fn a_loaded_behavior_and_a_run_tick_together() {
        use arora_behavior::graph::{Graph, Node as GraphNode};

        let main_leaf = Uuid::from_u128(0xE3);
        let run_leaf = Uuid::from_u128(0xE4);
        let statuses: LeafStatuses = Rc::new(RefCell::new(HashMap::from([
            (main_leaf, Status::Success),
            (run_leaf, Status::Running),
        ])));
        let ticks: LeafTicks = Rc::new(RefCell::new(HashMap::new()));
        let mut bridge = TestBridge::new(statuses.clone(), ticks.clone());
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

        // The main behavior: a single run-call leaf graph invoking the
        // scripted main_leaf (dispatched through arora_call, like a module
        // action node would be).
        let main_node = Uuid::from_u128(0x111);
        let mut main = Graph::empty();
        main.root = Some(main_node);
        main.nodes.insert(
            main_node,
            GraphNode {
                id: main_node,
                function: crate::nodes::RUN_CALL_FUNCTION_ID,
                inputs: vec![arora_behavior::graph::Io::new(
                    crate::nodes::RUN_CALL_PARAM_ID,
                )],
                ..GraphNode::default()
            },
        );
        main.links.push(arora_behavior::graph::Link::new(
            arora_behavior::graph::Port::new(main_node, crate::nodes::RUN_CALL_PARAM_ID),
            arora_behavior::graph::LinkSource::Literal(
                arora_types::value_serde::to_value(&call_to(0xB0, main_leaf)).unwrap(),
            ),
        ));
        interp.load(main).expect("the behavior loads");
        interp
            .spawn(call_to(0xB0, run_leaf), RunPolicy::Concurrent)
            .unwrap();

        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        for round in 1..=3u32 {
            assert_eq!(
                interp.tick(&mut ctx).unwrap(),
                BehaviorStatus::Running,
                "the interpreter is a standing policy (never Done)"
            );
            assert_eq!(
                *ticks.borrow().get(&main_leaf).unwrap(),
                round,
                "the main behavior re-evaluates every tick"
            );
            assert_eq!(
                *ticks.borrow().get(&run_leaf).unwrap(),
                round,
                "the run advances every tick"
            );
        }
    }

    /// The scaffold is introspectable the behavior tree's way: a spawned run is
    /// two graph nodes under the runner (a run-status decorator, its status key
    /// predetermined, over a run-call leaf carrying the call as literal data) —
    /// and a halted run's fragment is pruned again.
    #[test]
    fn a_spawned_run_is_visible_in_the_graph_until_halted() {
        let leaf = Uuid::from_u128(0xE5);
        let (mut bridge, _statuses, _ticks) = scripted(leaf, Status::Running);
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

        let handle = interp
            .spawn(call_to(0xB0, leaf), RunPolicy::Concurrent)
            .unwrap();
        let graph = interp.graph();
        let decorator = graph
            .nodes
            .values()
            .find(|n| n.function == crate::nodes::RUN_STATUS_FUNCTION_ID)
            .expect("the run's status decorator is in the graph");
        assert_eq!(
            decorator.outputs[0].predetermined_key.as_deref(),
            Some(handle.status.path.as_str()),
            "the decorator's status output is predetermined to the run's key"
        );
        let call_node = decorator.children.as_ref().unwrap()[0];
        assert_eq!(
            graph.nodes[&call_node].function,
            crate::nodes::RUN_CALL_FUNCTION_ID,
            "the decorator wraps the run-call leaf"
        );
        let root = graph.root.expect("the runner roots the scaffold");
        assert!(
            graph.nodes[&root]
                .children
                .as_ref()
                .unwrap()
                .contains(&decorator.id),
            "the fragment hangs off the runner"
        );

        // Halt: the next tick prunes the fragment from the graph.
        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        interp.tick(&mut ctx).unwrap();
        interp.halt(handle.id).unwrap();
        interp.tick(&mut ctx).unwrap();
        assert_eq!(
            interp.graph().nodes.len(),
            1,
            "only the runner remains after the halt pruned the fragment"
        );
    }

    #[test]
    fn concurrent_runs_get_independent_status_keys() {
        let a = Uuid::from_u128(0xAA);
        let b = Uuid::from_u128(0xBB);
        let statuses: LeafStatuses = Rc::new(RefCell::new(HashMap::from([
            (a, Status::Running),
            (b, Status::Running),
        ])));
        let ticks: LeafTicks = Rc::new(RefCell::new(HashMap::new()));
        let mut bridge = TestBridge::new(statuses.clone(), ticks.clone());
        let store = SimpleDataStore::new();
        let mut interp = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));

        let ha = interp
            .spawn(call_to(0xB0, a), RunPolicy::Concurrent)
            .unwrap();
        let hb = interp
            .spawn(call_to(0xB0, b), RunPolicy::Concurrent)
            .unwrap();
        assert_ne!(
            ha.status.path, hb.status.path,
            "each run gets its own status key"
        );

        let mut ctx = BehaviorContext {
            store: &store,
            call_bridge: &mut bridge,
        };
        interp.tick(&mut ctx).unwrap();
        let running: Value = Status::Running.into();
        assert_eq!(
            store.read(std::slice::from_ref(&ha.status)),
            vec![Some(running.clone())]
        );
        assert_eq!(
            store.read(std::slice::from_ref(&hb.status)),
            vec![Some(running.clone())]
        );

        // Halt A only; B keeps running independently.
        interp.halt(ha.id).unwrap();
        interp.tick(&mut ctx).unwrap();
        let failure: Value = Status::Failure.into();
        assert_eq!(
            store.read(std::slice::from_ref(&ha.status)),
            vec![Some(failure)],
            "the halted run ended"
        );
        assert_eq!(
            store.read(std::slice::from_ref(&hb.status)),
            vec![Some(running)],
            "the other run is unaffected"
        );
    }
}

/// The core string nodes run natively in a Groot tree over a data store, with
/// no module loaded: their ports bind to store keys that need not exist yet.
mod core_string_nodes {
    use super::{LeafStatuses, LeafTicks, TestBridge};
    use crate::arora_generated::behavior_tree::status::Status;
    use crate::behavior::BehaviorTreeInterpreter;
    use crate::nodes;
    use crate::schema::Expression;
    use crate::variable::VariableCell;
    use crate::BehaviorTreeRuntime;
    use arora_behavior::{BehaviorContext, BehaviorInterpreter};
    use arora_simple_data_store::SimpleDataStore;
    use arora_types::data::{DataStore, Key, StateChange};
    use arora_types::value::Value;
    use std::collections::HashMap;
    use std::rc::Rc;

    fn groot(body: &str) -> String {
        format!(
            r#"<root main_tree_to_execute="MainTree"><BehaviorTree ID="MainTree">{body}</BehaviorTree></root>"#
        )
    }

    /// An interpreter with no module (an empty function index) running `body`.
    fn interpreter(body: &str) -> BehaviorTreeInterpreter {
        let mut interpreter = BehaviorTreeInterpreter::new(Rc::new(HashMap::new()));
        interpreter
            .load_groot(&groot(body))
            .expect("the core nodes need no module");
        interpreter
    }

    /// A loaded tree and the bridge its node ticks are registered on.
    struct Device {
        tree: BehaviorTreeInterpreter,
        bridge: TestBridge,
    }

    fn device(body: &str) -> Device {
        Device {
            tree: interpreter(body),
            bridge: TestBridge::new(LeafStatuses::default(), LeafTicks::default()),
        }
    }

    fn tick(device: &mut Device, store: &SimpleDataStore) {
        let mut ctx = BehaviorContext {
            store,
            call_bridge: &mut device.bridge,
        };
        device.tree.tick(&mut ctx).expect("the tree ticks");
    }

    fn read(store: &SimpleDataStore, key: &str) -> Option<Value> {
        store.read(&[Key::from(key)]).remove(0)
    }

    fn string(value: &str) -> Option<Value> {
        Some(Value::String(value.to_string()))
    }

    fn unset(key: &str) -> StateChange {
        StateChange {
            set: HashMap::new(),
            unset: std::collections::HashSet::from([Key::from(key)]),
        }
    }

    /// `IsStringSet → SetString → UnsetString` on a key written from outside
    /// the tree runs its branch once per write: the key is absent at first
    /// (the condition fails, nothing errors), each write runs the branch once,
    /// and the branch consuming the key keeps it from running again.
    #[test]
    fn a_branch_runs_once_per_write_of_a_key() {
        let store = SimpleDataStore::new();
        let mut tree = device(
            r#"<Sequence>
                 <IsStringSet value="{message}"/>
                 <SetString variable="{heard}" value="{message}"/>
                 <UnsetString variable="{message}"/>
               </Sequence>"#,
        );

        tick(&mut tree, &store);
        assert_eq!(read(&store, "heard"), None, "no message yet: no branch");

        store
            .write(StateChange::set("message", Value::String("hi".into())))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "heard"), string("hi"), "the branch ran");
        assert_eq!(read(&store, "message"), None, "and consumed the message");

        // Clear the trace: a tick without a new write does not run the branch.
        store.write(unset("heard")).unwrap();
        tick(&mut tree, &store);
        tick(&mut tree, &store);
        assert_eq!(read(&store, "heard"), None, "no write, no run");

        store
            .write(StateChange::set("message", Value::String("again".into())))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "heard"), string("again"));
        assert_eq!(read(&store, "message"), None);

        // An empty string is not set.
        store.write(unset("heard")).unwrap();
        store
            .write(StateChange::set("message", Value::String(String::new())))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "heard"), None, "an empty string is not set");
    }

    /// `SetString` creates a key that does not exist yet, from a literal.
    #[test]
    fn set_string_creates_a_missing_key() {
        let store = SimpleDataStore::new();
        let mut tree = device(r#"<SetString variable="{greeting}" value="hello"/>"#);
        assert_eq!(read(&store, "greeting"), None);
        tick(&mut tree, &store);
        assert_eq!(read(&store, "greeting"), string("hello"));
    }

    /// `WaitStringSet` holds its sequence `Running` while its key is absent,
    /// then lets it through once the key is written.
    #[test]
    fn wait_string_set_waits_for_its_key() {
        let store = SimpleDataStore::new();
        let mut tree = device(
            r#"<Sequence>
                 <WaitStringSet value="{reply}"/>
                 <SetString variable="{done}" value="yes"/>
               </Sequence>"#,
        );
        tick(&mut tree, &store);
        tick(&mut tree, &store);
        assert_eq!(read(&store, "done"), None, "waiting for the reply");
        store
            .write(StateChange::set("reply", Value::String("ok".into())))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "done"), string("yes"));
    }

    /// `WaitStringSet`'s own status: `Running` on an absent value, `Success`
    /// once set.
    #[test]
    fn wait_string_set_is_running_then_success() {
        let reply = VariableCell::local();
        let tree = crate::tests::build(nodes::wait_str_set(Expression::Variable(reply.clone())));
        let mut bridge = TestBridge::empty();
        let mut runtime =
            BehaviorTreeRuntime::setup(&tree, Rc::new(HashMap::new()), &mut bridge, false)
                .expect("runtime sets up");
        assert_eq!(runtime.tick().unwrap(), Status::Running);
        assert_eq!(runtime.tick().unwrap(), Status::Running);
        reply.set(Value::String("ok".into()));
        assert_eq!(runtime.tick().unwrap(), Status::Success);
    }

    /// `RegexMatch` writes the matched text to its output key, creating it,
    /// and fails — leaving the output alone — when nothing matches or the
    /// input is absent.
    #[test]
    fn regex_match_writes_the_match() {
        let store = SimpleDataStore::new();
        let mut tree = device(
            r#"<RegexMatch value="{input}" matcher="(Ross|Brad|Victor)" first_match="{name}"/>"#,
        );
        tick(&mut tree, &store);
        assert_eq!(read(&store, "name"), None, "no input: no match");
        store
            .write(StateChange::set(
                "input",
                Value::String("I am Victor".into()),
            ))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "name"), string("Victor"));
        store
            .write(StateChange::set("input", Value::String("nobody".into())))
            .unwrap();
        tick(&mut tree, &store);
        assert_eq!(read(&store, "name"), string("Victor"), "a miss leaves it");
    }

    /// A port bound to a value that is not a string fails the tick, as the
    /// module's argument decoding did, rather than reading as unset.
    #[test]
    fn a_non_string_value_fails_the_tick() {
        let value = VariableCell::local_with(Value::F32(1.0));
        let tree = crate::tests::build(nodes::is_str_set(Expression::Variable(value)));
        let mut bridge = TestBridge::empty();
        let mut runtime =
            BehaviorTreeRuntime::setup(&tree, Rc::new(HashMap::new()), &mut bridge, false)
                .expect("runtime sets up");
        assert!(runtime.tick().is_err());
    }
}

/// Module functions with optional parameters, bound to store keys that may be
/// absent: an absent key passes `None`, an optional out-parameter writes
/// `Some` as the key's value and `None` as unsetting it.
mod optional_parameters {
    use crate::behavior::BehaviorTreeInterpreter;
    use crate::ModuleFunction;
    use arora_behavior::{BehaviorContext, BehaviorInterpreter};
    use arora_simple_data_store::SimpleDataStore;
    use arora_types::call::{Call, CallBridge, CallError, CallResult, Callable, CallableId};
    use arora_types::data::{DataStore, Key, StateChange};
    use arora_types::record::module::frozen::{Function, Parameter};
    use arora_types::record::ty::{FrozenOption, FrozenTy, PrimitiveKind};
    use arora_types::value::{StructureField, Value};
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::rc::Rc;
    use uuid::Uuid;

    const ECHO: Uuid = Uuid::from_u128(0xEC40);
    const INPUT: Uuid = Uuid::from_u128(0xEC41);
    const OUTPUT: Uuid = Uuid::from_u128(0xEC42);

    fn unset(key: &str) -> StateChange {
        StateChange {
            set: HashMap::new(),
            unset: std::collections::HashSet::from([Key::from(key)]),
        }
    }

    fn optional_string() -> FrozenTy {
        FrozenTy::FrozenOption(FrozenOption {
            element: Box::new(FrozenTy::from(PrimitiveKind::String)),
        })
    }

    /// `echo(input: Option<String>, output: &mut Option<String>)`.
    fn echo_index() -> HashMap<Uuid, ModuleFunction> {
        HashMap::from([(
            ECHO,
            ModuleFunction {
                module_id: Uuid::from_u128(0xEC00),
                function_id: ECHO,
                function_name: "echo".to_string(),
                function: Function {
                    parameters: HashMap::from([
                        (
                            INPUT,
                            Parameter {
                                name: "input".to_string(),
                                ty: optional_string(),
                                mutable: false,
                            },
                        ),
                        (
                            OUTPUT,
                            Parameter {
                                name: "output".to_string(),
                                ty: optional_string(),
                                mutable: true,
                            },
                        ),
                    ]),
                    parameter_ordering: vec![INPUT, OUTPUT],
                    return_ty: FrozenTy::from(PrimitiveKind::U8),
                },
            },
        )])
    }

    /// Serves `echo` the way a module decoding `Option<String>` would: it
    /// refuses `()` for its optional input, and returns its output framed as
    /// an optional. Records the inputs it received.
    #[derive(Default)]
    struct EchoBridge {
        registered: HashMap<u64, Rc<dyn Callable>>,
        next_id: u64,
        inputs: Rc<RefCell<Vec<Value>>>,
    }

    impl CallBridge for EchoBridge {
        fn arora_call(&mut self, call: Call) -> Result<CallResult, CallError> {
            let input = call
                .args
                .iter()
                .find(|arg| arg.id == INPUT)
                .map(|arg| (*arg.value).clone())
                .ok_or(CallError::Generic {
                    message: "no input".into(),
                })?;
            self.inputs.borrow_mut().push(input.clone());
            let output = match input {
                Value::Option(None) => Value::Option(None),
                Value::Option(Some(s)) if matches!(*s, Value::String(_)) => Value::Option(Some(s)),
                other => {
                    return Err(CallError::Generic {
                        message: format!("input: unexpected value {other}"),
                    })
                }
            };
            Ok(CallResult {
                ret: Value::Unit,
                mutated: vec![StructureField {
                    id: OUTPUT,
                    value: Box::new(output),
                }],
            })
        }
        fn arora_register_callable(&mut self, callable: Rc<dyn Callable>) -> CallableId {
            let id = self.next_id;
            self.next_id += 1;
            self.registered.insert(id, callable);
            CallableId { id }
        }
        fn arora_unregister_callable(&mut self, callable_id: &CallableId) {
            self.registered.remove(&callable_id.id);
        }
        fn arora_call_indirect(&mut self, callable_id: &CallableId) -> Result<Value, CallError> {
            let callable = self.registered[&callable_id.id].clone();
            callable.call(self)
        }
    }

    #[test]
    fn an_absent_key_binds_none_and_an_optional_output_maps_to_the_key() {
        let store = SimpleDataStore::new();
        let mut tree = BehaviorTreeInterpreter::new(Rc::new(echo_index()));
        tree.load_groot(
            r#"<root main_tree_to_execute="MainTree"><BehaviorTree ID="MainTree">
                 <Echo input="{in}" output="{out}"/>
               </BehaviorTree></root>"#,
        )
        .expect("echo resolves by its PascalCase name");
        let mut bridge = EchoBridge::default();
        let inputs = bridge.inputs.clone();
        let read = |key: &str| store.read(&[Key::from(key)]).remove(0);
        let mut tick = |bridge: &mut EchoBridge| {
            let mut ctx = BehaviorContext {
                store: &store,
                call_bridge: bridge,
            };
            tree.tick(&mut ctx).expect("the tree ticks");
        };

        // `in` is not set: the module receives `None`, not `()`, and writes
        // `None`, which leaves `out` absent.
        tick(&mut bridge);
        assert_eq!(inputs.borrow().last(), Some(&Value::Option(None)));
        assert_eq!(read("out"), None);

        // `in` is set: the module receives `Some("x")`, and its `Some`
        // creates `out`, holding the bare string.
        store
            .write(StateChange::set("in", Value::String("x".into())))
            .unwrap();
        tick(&mut bridge);
        assert_eq!(
            inputs.borrow().last(),
            Some(&Value::Option(Some(Box::new(Value::String("x".into())))))
        );
        assert_eq!(read("out"), Some(Value::String("x".into())));

        // `in` is unset again: `None` unsets `out`.
        store.write(unset("in")).unwrap();
        tick(&mut bridge);
        assert_eq!(inputs.borrow().last(), Some(&Value::Option(None)));
        assert_eq!(read("out"), None);
    }
}