spawningpool 0.3.0

Create hyper-specific, 0-waste agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
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
//! Tests for [`super`]. Extracted from `eval.rs` and included via
//! `#[path]` so they remain a child module with access to private items.

use super::*;
use crate::workflow::parse::parse;

/// A headless ask handler for tests that don't exercise `ask`: every question is
/// unanswerable. (A function item coerces to `&dyn Fn(&str) -> AskOutcome`.)
fn no_ask(_: &str) -> AskOutcome {
    AskOutcome::Unavailable
}

/// A log sink that discards every event, for tests that don't inspect logging.
fn no_log(_: serde_json::Value) {}

/// Evaluate `src` capturing every structured log event, returning the result
/// alongside the events in emission order.
async fn eval_capture(
    name: &str,
    src: &str,
    tools: Vec<ToolDef>,
    workflows: HashMap<String, Workflow>,
    ask: &AskHandler<'_>,
) -> (
    Result<serde_json::Value, WorkflowError>,
    Vec<serde_json::Value>,
) {
    let wf = parse(src).expect("parse failed");
    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();
    let inputs = HashMap::new();
    let events = std::cell::RefCell::new(Vec::new());
    // Scope the sink so its borrow of `events` ends before we take ownership.
    let result = {
        let sink = |e: serde_json::Value| events.borrow_mut().push(e);
        eval(
            name, &wf, &registry, &tools, &client, &keys, &inputs, &workflows, ask, &sink,
        )
        .await
    };
    (result, events.into_inner())
}

/// The `event` field of each captured event, in order.
fn event_names(events: &[serde_json::Value]) -> Vec<&str> {
    events
        .iter()
        .map(|e| e["event"].as_str().unwrap())
        .collect()
}

async fn eval_src(src: &str) -> Result<serde_json::Value, WorkflowError> {
    let wf = parse(src).expect("parse failed");
    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();
    let inputs = HashMap::new();
    let workflows = HashMap::new();
    eval(
        "test",
        &wf,
        &registry,
        &[],
        &client,
        &keys,
        &inputs,
        &workflows,
        &no_ask,
        &no_log,
    )
    .await
}

#[tokio::test]
async fn evaluates_string_literal() {
    let v = eval_src(r#"x = "hello""#).await.unwrap();
    assert_eq!(v, serde_json::json!("hello"));
}

#[tokio::test]
async fn evaluates_number_literal() {
    let v = eval_src("x = 42").await.unwrap();
    assert_eq!(v, serde_json::json!(42.0));
}

#[tokio::test]
async fn evaluates_bool_literal() {
    let v = eval_src("x = true").await.unwrap();
    assert_eq!(v, serde_json::json!(true));
}

#[tokio::test]
async fn seeds_declared_inputs_into_scope() {
    let wf = parse("# inputs: CITY:string\n\ngreeting = \"hi \" + CITY").unwrap();
    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();
    let mut inputs = HashMap::new();
    inputs.insert("CITY".to_string(), serde_json::json!("Portland"));
    let workflows = HashMap::new();
    let v = eval(
        "test",
        &wf,
        &registry,
        &[],
        &client,
        &keys,
        &inputs,
        &workflows,
        &no_ask,
        &no_log,
    )
    .await
    .unwrap();
    assert_eq!(v, serde_json::json!("hi Portland"));
}

#[tokio::test]
async fn evaluates_string_concatenation() {
    let v = eval_src(r#"x = "hello" + " " + "world""#).await.unwrap();
    assert_eq!(v, serde_json::json!("hello world"));
}

#[tokio::test]
async fn evaluates_equality_and_comparison() {
    let cases = [
        ("x = 1 == 1", true),
        ("x = 1 == 2", false),
        ("x = 1 != 2", true),
        (r#"x = "a" == "a""#, true),
        (r#"x = "a" != "a""#, false),
        ("x = true == true", true),
        ("x = 1 < 2", true),
        ("x = 2 < 1", false),
        ("x = 2 <= 2", true),
        ("x = 3 > 2", true),
        ("x = 2 >= 3", false),
        (r#"x = "a" < "b""#, true),
        (r#"x = "b" < "a""#, false),
    ];
    for (src, expected) in cases {
        let v = eval_src(src)
            .await
            .unwrap_or_else(|e| panic!("eval failed for `{src}`: {e}"));
        assert_eq!(v, serde_json::json!(expected), "for source `{src}`");
    }
}

#[tokio::test]
async fn equality_treats_integer_and_float_as_equal() {
    // A `# inputs:` number arrives as a JSON integer, while the `1` literal is an
    // f64; equality must see through the representation difference.
    let wf = parse("# inputs: N:number\n\nx = N == 1").unwrap();
    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();
    let mut inputs = HashMap::new();
    inputs.insert("N".to_string(), serde_json::json!(1)); // integer representation
    let workflows = HashMap::new();
    let v = eval(
        "test",
        &wf,
        &registry,
        &[],
        &client,
        &keys,
        &inputs,
        &workflows,
        &no_ask,
        &no_log,
    )
    .await
    .unwrap();
    assert_eq!(v, serde_json::json!(true));
}

#[tokio::test]
async fn evaluates_arithmetic() {
    let v = eval_src("x = 2 + 3 * 4").await.unwrap();
    // Left-to-right: (2+3)*4 = 20
    assert_eq!(v, serde_json::json!(20.0));
}

#[tokio::test]
async fn evaluates_power() {
    let v = eval_src("x = 2 ^ 10").await.unwrap();
    assert_eq!(v, serde_json::json!(1024.0));
}

#[tokio::test]
async fn evaluates_logical_ops() {
    let v = eval_src("x = true && false").await.unwrap();
    assert_eq!(v, serde_json::json!(false));
    let v = eval_src("x = false || true").await.unwrap();
    assert_eq!(v, serde_json::json!(true));
}

#[tokio::test]
async fn evaluates_not() {
    let v = eval_src("x = !true").await.unwrap();
    assert_eq!(v, serde_json::json!(false));
}

#[tokio::test]
async fn evaluates_object_literal() {
    let v = eval_src(r#"x = { "a": 1, "b": "hi" }"#).await.unwrap();
    assert_eq!(v, serde_json::json!({"a": 1.0, "b": "hi"}));
}

#[tokio::test]
async fn evaluates_variable_reference() {
    let v = eval_src("city = \"Portland\"\n\nname = city")
        .await
        .unwrap();
    assert_eq!(v, serde_json::json!("Portland"));
}

#[tokio::test]
async fn last_statement_value_is_returned() {
    let v = eval_src("a = 1\n\nb = 2\n\nc = 3").await.unwrap();
    assert_eq!(v, serde_json::json!(3.0));
}

#[tokio::test]
async fn evaluates_member_access() {
    let v = eval_src("obj = { \"x\": 42 }\n\nv = obj.x").await.unwrap();
    assert_eq!(v, serde_json::json!(42.0));
}

#[tokio::test]
async fn evaluates_array_index_access() {
    // Build an array via a for-loop over a literal... actually we don't
    // have array literals. Use object field containing a computed value.
    // Simpler: just verify indexed access works on a known JSON value by
    // testing eval_access directly.
    let arr = serde_json::json!([10, 20, 30]);
    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();
    let workflows = HashMap::new();
    let ctx = EvalCtx {
        registry: &registry,
        tools: &[],
        client: &client,
        keys: &keys,
        workflows: &workflows,
        ask: &no_ask,
        log: &no_log,
    };
    let frame = Frame {
        wf: "test",
        stmt: "val",
    };
    let val = eval_access(
        arr,
        &AccessKey::Index(1),
        Env::new(),
        &ctx,
        Vec::new(),
        frame,
    )
    .await
    .unwrap();
    assert_eq!(val, serde_json::json!(20));
}

#[tokio::test]
async fn computed_index_accepts_float_backed_whole_number() {
    // DSL numbers are f64, so an arithmetic-derived index (here `1 - 1`) is a
    // float-backed JSON number `0.0`. It must index like the integer `0`.
    let arr = serde_json::json!([10, 20, 30]);
    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();
    let workflows = HashMap::new();
    let ctx = EvalCtx {
        registry: &registry,
        tools: &[],
        client: &client,
        keys: &keys,
        workflows: &workflows,
        ask: &no_ask,
        log: &no_log,
    };
    let frame = Frame {
        wf: "test",
        stmt: "val",
    };
    let index = Expr::BinOp {
        op: crate::workflow::BinOp::Sub,
        lhs: Box::new(Expr::Num(1.0)),
        rhs: Box::new(Expr::Num(1.0)),
    };
    let val = eval_access(
        arr,
        &AccessKey::Computed(Box::new(index)),
        Env::new(),
        &ctx,
        Vec::new(),
        frame,
    )
    .await
    .unwrap();
    assert_eq!(val, serde_json::json!(10));
}

#[tokio::test]
async fn evaluates_if_true_branch() {
    let v = eval_src(r#"v = if (true) "yes", (_) "no""#).await.unwrap();
    assert_eq!(v, serde_json::json!("yes"));
}

#[tokio::test]
async fn evaluates_if_default_branch() {
    let v = eval_src(r#"v = if (false) "yes", (_) "no""#).await.unwrap();
    assert_eq!(v, serde_json::json!("no"));
}

#[tokio::test]
async fn evaluates_for_as_map() {
    // We can't create arrays via literals, so build from an Object field
    // holding a pre-known array-typed variable. Actually, the simplest
    // test: for over an empty array.
    // Use a script-backed tool to produce an array, or test via direct
    // eval with a seeded env.
    let wf = parse("doubled = for [x: nums] (x)").unwrap();
    let mut env = Env::new();
    env.insert("nums".to_string(), serde_json::json!([1, 2, 3]));
    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();
    let workflows = HashMap::new();
    let ctx = EvalCtx {
        registry: &registry,
        tools: &[],
        client: &client,
        keys: &keys,
        workflows: &workflows,
        ask: &no_ask,
        log: &no_log,
    };

    let mut last = serde_json::Value::Null;
    for stmt in &wf.statements {
        let frame = Frame {
            wf: "test",
            stmt: &stmt.name,
        };
        let val = eval_expr(&stmt.expr, env.clone(), &ctx, Vec::new(), frame)
            .await
            .unwrap();
        last = val.clone();
        env.insert(stmt.name.clone(), val);
    }
    assert_eq!(last, serde_json::json!([1, 2, 3]));
}

#[tokio::test]
async fn do_runs_once_then_stops_when_while_is_false() {
    // The body runs at least once; the condition reads the bound value (`answer`)
    // and is false here, so the loop stops and yields the body value.
    let v = eval_src("answer = do (false) while (answer) max (5)")
        .await
        .unwrap();
    assert_eq!(v, serde_json::json!(false));
}

#[tokio::test]
async fn do_rejects_max_below_one() {
    let err = eval_src("answer = do (true) while (false) max (0)")
        .await
        .unwrap_err();
    assert!(err.0.contains("at least 1"));
}

/// A `poll` tool whose script bumps a persisted counter on each call and reports
/// `{ "done": <count >= 3>, "count": <count> }`, so a `do` loop's progress comes
/// from the tool's side effect rather than from an accumulator. Returns the tool
/// and the temp paths (script, counter) for cleanup.
fn polling_tool() -> (ToolDef, std::path::PathBuf, std::path::PathBuf) {
    use std::os::unix::fs::PermissionsExt;

    let nonce = format!(
        "{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );
    let counter_path = std::env::temp_dir().join(format!("sp_wf_do_cnt_{nonce}"));
    let script_path = std::env::temp_dir().join(format!("sp_wf_do_{nonce}.sh"));
    std::fs::write(
        &script_path,
        format!(
            "#!/bin/sh\nn=$(cat {cnt} 2>/dev/null || echo 0)\nn=$((n+1))\necho $n > {cnt}\n\
             if [ $n -ge 3 ]; then d=true; else d=false; fi\n\
             printf '{{\"done\":%s,\"count\":%s}}' $d $n > \"$SP_OUTPUT_PATH\"\n",
            cnt = counter_path.display()
        ),
    )
    .unwrap();
    std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).unwrap();

    let tool = ToolDef {
        name: "poll".to_string(),
        script: script_path.clone(),
        description: String::new(),
        params: vec![],
        output: Some(crate::types::Type::Object(vec![
            ("done".to_string(), crate::types::Type::Bool),
            ("count".to_string(), crate::types::Type::Number),
        ])),
        exits: vec![],
    };
    (tool, script_path, counter_path)
}

#[tokio::test]
async fn do_loops_until_while_reads_done_via_assigned_var() {
    let (tool, script_path, counter_path) = polling_tool();
    // `while (!result.done)` inspects the bound value; the cap is high enough that
    // the tool's own `done` flag is what stops the loop, at the 3rd call.
    let val = eval_with_tool(
        "result = do (run tool poll {}) while (!result.done) max (10)",
        tool,
    )
    .await
    .unwrap();
    std::fs::remove_file(&script_path).ok();
    std::fs::remove_file(&counter_path).ok();
    assert_eq!(val, serde_json::json!({ "done": true, "count": 3 }));
}

#[tokio::test]
async fn do_caps_iterations_at_max() {
    let (tool, script_path, counter_path) = polling_tool();
    // The cap of 2 interrupts before the tool would report `done` (at 3), so the
    // loop yields the 2nd call's value.
    let val = eval_with_tool(
        "result = do (run tool poll {}) while (!result.done) max (2)",
        tool,
    )
    .await
    .unwrap();
    std::fs::remove_file(&script_path).ok();
    std::fs::remove_file(&counter_path).ok();
    assert_eq!(val, serde_json::json!({ "done": false, "count": 2 }));
}

#[tokio::test]
async fn run_tool_runs_script_and_reads_output() {
    use std::os::unix::fs::PermissionsExt;

    let script_path = std::env::temp_dir().join(format!(
        "sp_wf_tool_{}_{}.sh",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::write(
        &script_path,
        "#!/bin/sh\nprintf '{\"greeting\":\"hello %s\"}' \"$NAME\" > \"$SP_OUTPUT_PATH\"\n",
    )
    .unwrap();
    std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).unwrap();

    let tool_def = ToolDef {
        name: "greet".to_string(),
        script: script_path.clone(),
        description: String::new(),
        params: vec![crate::types::Param {
            name: "NAME".to_string(),
            ty: crate::types::Type::String,
        }],
        output: Some(crate::types::Type::Object(vec![(
            "greeting".to_string(),
            crate::types::Type::String,
        )])),
        exits: vec![],
    };

    let wf = parse(r#"result = run tool greet { NAME: "world" }"#).unwrap();
    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();

    let inputs = HashMap::new();
    let workflows = HashMap::new();
    let val = eval(
        "test",
        &wf,
        &registry,
        &[tool_def],
        &client,
        &keys,
        &inputs,
        &workflows,
        &no_ask,
        &no_log,
    )
    .await
    .unwrap();
    std::fs::remove_file(&script_path).ok();

    assert_eq!(val, serde_json::json!({"greeting": "hello world"}));
}

#[tokio::test]
async fn run_tool_errors_when_sp_output_path_omitted() {
    use std::os::unix::fs::PermissionsExt;

    let script_path = std::env::temp_dir().join(format!(
        "sp_wf_noout_{}_{}.sh",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::write(&script_path, "#!/bin/sh\necho ok\n").unwrap();
    std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).unwrap();

    let tool_def = ToolDef {
        name: "silent".to_string(),
        script: script_path.clone(),
        description: String::new(),
        params: vec![],
        output: Some(crate::types::Type::String),
        exits: vec![],
    };

    let wf = parse("result = run tool silent {}").unwrap();
    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();

    let inputs = HashMap::new();
    let workflows = HashMap::new();
    let err = eval(
        "test",
        &wf,
        &registry,
        &[tool_def],
        &client,
        &keys,
        &inputs,
        &workflows,
        &no_ask,
        &no_log,
    )
    .await
    .unwrap_err();
    std::fs::remove_file(&script_path).ok();

    assert!(err.0.contains("SP_OUTPUT_PATH"));
}

/// A `ping` tool whose script exits with `code` (writing no output), declaring
/// `# exits:` `1 unreachable` / `2 badArgs` and output `{ "ms": number }`.
#[cfg(test)]
fn exiting_tool(code: i32) -> (ToolDef, std::path::PathBuf) {
    use std::os::unix::fs::PermissionsExt;
    let script_path = std::env::temp_dir().join(format!(
        "sp_wf_exit_{}_{}.sh",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::write(&script_path, format!("#!/bin/sh\nexit {code}\n")).unwrap();
    std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).unwrap();
    let tool = ToolDef {
        name: "ping".to_string(),
        script: script_path.clone(),
        description: String::new(),
        params: vec![],
        output: Some(crate::types::Type::Object(vec![(
            "ms".to_string(),
            crate::types::Type::Number,
        )])),
        exits: vec![
            crate::types::ExitCode {
                code: 1,
                name: "unreachable".to_string(),
                desc: None,
            },
            crate::types::ExitCode {
                code: 2,
                name: "badArgs".to_string(),
                desc: None,
            },
        ],
    };
    (tool, script_path)
}

#[cfg(test)]
async fn eval_with_tool(src: &str, tool: ToolDef) -> Result<serde_json::Value, WorkflowError> {
    let wf = parse(src).expect("parse failed");
    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();
    let inputs = HashMap::new();
    let workflows = HashMap::new();
    eval(
        "test",
        &wf,
        &registry,
        &[tool],
        &client,
        &keys,
        &inputs,
        &workflows,
        &no_ask,
        &no_log,
    )
    .await
}

#[tokio::test]
async fn run_tool_recovers_via_named_else_arm() {
    let (tool, script_path) = exiting_tool(1); // -> "unreachable"
    let val = eval_with_tool(
        r#"r = run tool ping {} else { unreachable: { "ms": 0 }, badArgs: { "ms": 1 } }"#,
        tool,
    )
    .await
    .unwrap();
    std::fs::remove_file(&script_path).ok();
    assert_eq!(val, serde_json::json!({ "ms": 0.0 }));
}

#[tokio::test]
async fn run_tool_recovers_undeclared_exit_via_default_arm() {
    let (tool, script_path) = exiting_tool(7); // not in `# exits:`
    let val = eval_with_tool(r#"r = run tool ping {} else { _: { "ms": 99 } }"#, tool)
        .await
        .unwrap();
    std::fs::remove_file(&script_path).ok();
    assert_eq!(val, serde_json::json!({ "ms": 99.0 }));
}

#[tokio::test]
async fn run_tool_aborts_on_unhandled_nonzero_exit() {
    let (tool, script_path) = exiting_tool(1);
    let err = eval_with_tool("r = run tool ping {}", tool)
        .await
        .unwrap_err();
    std::fs::remove_file(&script_path).ok();
    assert!(err.0.contains("no `else` arm handles it"));
}

/// A tiny tool that echoes `NAME` into a structured `{ "v": string }`.
#[cfg(test)]
fn echo_tool() -> (ToolDef, std::path::PathBuf) {
    use std::os::unix::fs::PermissionsExt;
    let script_path = std::env::temp_dir().join(format!(
        "sp_wf_echo_{}_{}.sh",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::write(
        &script_path,
        "#!/bin/sh\nprintf '{\"v\":\"%s\"}' \"$NAME\" > \"$SP_OUTPUT_PATH\"\n",
    )
    .unwrap();
    std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).unwrap();
    let tool = ToolDef {
        name: "echo".to_string(),
        script: script_path.clone(),
        description: String::new(),
        params: vec![crate::types::Param {
            name: "NAME".to_string(),
            ty: crate::types::Type::String,
        }],
        output: Some(crate::types::Type::Object(vec![(
            "v".to_string(),
            crate::types::Type::String,
        )])),
        exits: vec![],
    };
    (tool, script_path)
}

#[tokio::test]
async fn run_nests_a_workflow_passing_inputs() {
    // The outer workflow runs `inner`, which calls a tool with the input it
    // was handed, and reads a field off the nested result.
    let (tool, script_path) = echo_tool();
    let inner = parse("# inputs: WHO:string\n\nout = run tool echo { NAME: WHO }").unwrap();
    let outer = parse(r#"r = run workflow inner { WHO: "world" }"#).unwrap();

    let mut workflows = HashMap::new();
    workflows.insert("inner".to_string(), inner);

    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();
    let inputs = HashMap::new();
    let val = eval(
        "test",
        &outer,
        &registry,
        &[tool],
        &client,
        &keys,
        &inputs,
        &workflows,
        &no_ask,
        &no_log,
    )
    .await
    .unwrap();
    std::fs::remove_file(&script_path).ok();

    // `run inner` yields inner's last statement — the tool's structured output.
    assert_eq!(val, serde_json::json!({"v": "world"}));
}

#[tokio::test]
async fn run_detects_a_cycle() {
    // `a` runs `b`, `b` runs `a` — evaluation must stop with a cycle error.
    let a = parse("x = run workflow b {}").unwrap();
    let b = parse("y = run workflow a {}").unwrap();
    let mut workflows = HashMap::new();
    workflows.insert("a".to_string(), a.clone());
    workflows.insert("b".to_string(), b);

    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();
    let inputs = HashMap::new();
    let err = eval(
        "test",
        &a,
        &registry,
        &[],
        &client,
        &keys,
        &inputs,
        &workflows,
        &no_ask,
        &no_log,
    )
    .await
    .unwrap_err();
    assert!(err.0.contains("cycle"), "{}", err.0);
}

/// Evaluate `src` with a specific `ask` handler (the workflows-only `ask` path).
async fn eval_src_with_ask(
    src: &str,
    ask: &AskHandler<'_>,
) -> Result<serde_json::Value, WorkflowError> {
    let wf = parse(src).expect("parse failed");
    let registry = Registry::default();
    let client = crate::ai::Client::new();
    let keys = HashMap::new();
    let inputs = HashMap::new();
    let workflows = HashMap::new();
    eval(
        "test",
        &wf,
        &registry,
        &[],
        &client,
        &keys,
        &inputs,
        &workflows,
        ask,
        &no_log,
    )
    .await
}

#[tokio::test]
async fn ask_returns_the_user_answer() {
    let answer = |_: &str| AskOutcome::Answered("Boston".to_string());
    let v = eval_src_with_ask(r#"c = ask "Which city?""#, &answer)
        .await
        .unwrap();
    assert_eq!(v, serde_json::json!("Boston"));
}

#[tokio::test]
async fn ask_empty_answer_is_the_empty_string() {
    // A bare enter is in-band data: a successful empty-string answer, not an
    // "unavailable" (docs/ask.md §3).
    let answer = |_: &str| AskOutcome::Answered(String::new());
    let v = eval_src_with_ask(r#"c = ask "Which city?""#, &answer)
        .await
        .unwrap();
    assert_eq!(v, serde_json::json!(""));
}

#[tokio::test]
async fn ask_evaluates_its_prompt_and_passes_it_to_the_handler() {
    // Echo the prompt back so we can see it was evaluated (concatenation) and
    // handed to the handler.
    let echo = |p: &str| AskOutcome::Answered(format!("got:{p}"));
    let v = eval_src_with_ask(r#"c = ask ("Which " + "city?")"#, &echo)
        .await
        .unwrap();
    assert_eq!(v, serde_json::json!("got:Which city?"));
}

#[tokio::test]
async fn ask_unavailable_falls_back_to_else() {
    let v = eval_src_with_ask(r#"c = ask "Which city?" else "Portland""#, &no_ask)
        .await
        .unwrap();
    assert_eq!(v, serde_json::json!("Portland"));
}

#[tokio::test]
async fn ask_unavailable_without_else_aborts() {
    let err = eval_src_with_ask(r#"c = ask "Which city?""#, &no_ask)
        .await
        .unwrap_err();
    assert!(err.0.contains("ask couldn't be answered"), "{}", err.0);
}

#[tokio::test]
async fn logs_workflow_and_tool_lifecycle() {
    let (tool, script_path) = echo_tool();
    let (result, events) = eval_capture(
        "greet",
        r#"out = run tool echo { NAME: "world" }"#,
        vec![tool],
        HashMap::new(),
        &no_ask,
    )
    .await;
    std::fs::remove_file(&script_path).ok();
    result.unwrap();

    assert_eq!(
        event_names(&events),
        ["workflow.start", "tool.call", "tool.done", "workflow.done"]
    );
    assert_eq!(events[0]["wf"], "greet");
    assert_eq!(events[0]["inputs"], serde_json::json!({}));

    // A workflow `call tool`: no specialist, statement name, typed args.
    let call = &events[1];
    assert_eq!(call["wf"], "greet");
    assert_eq!(call["stmt"], "out");
    assert!(call["specialist"].is_null());
    assert_eq!(call["tool"], "echo");
    assert_eq!(call["args"], serde_json::json!({ "NAME": "world" }));

    let done = &events[2];
    assert_eq!(done["success"], true);
    assert_eq!(done["exit_code"], 0);
    assert!(done["elapsed_ms"].is_number());
}

#[tokio::test]
async fn logs_workflow_error_with_tool_exit_code() {
    let (tool, script_path) = exiting_tool(1); // unhandled non-zero exit -> abort
    let (result, events) = eval_capture(
        "pinger",
        "r = run tool ping {}",
        vec![tool],
        HashMap::new(),
        &no_ask,
    )
    .await;
    std::fs::remove_file(&script_path).ok();
    result.unwrap_err();

    // The frame opens and closes with an error; the tool's exit is still logged.
    assert_eq!(
        event_names(&events),
        ["workflow.start", "tool.call", "tool.done", "workflow.error"]
    );
    let done = &events[2];
    assert_eq!(done["success"], false);
    assert_eq!(done["exit_code"], 1);
    assert_eq!(events[3]["wf"], "pinger");
    assert!(events[3]["error"].as_str().unwrap().contains("else"));
}

#[tokio::test]
async fn logs_sub_workflow_sharing_the_run_with_a_distinct_wf() {
    let (tool, script_path) = echo_tool();
    let inner = parse("# inputs: WHO:string\n\nout = run tool echo { NAME: WHO }").unwrap();
    let mut workflows = HashMap::new();
    workflows.insert("inner".to_string(), inner);

    let (result, events) = eval_capture(
        "outer",
        r#"r = run workflow inner { WHO: "world" }"#,
        vec![tool],
        workflows,
        &no_ask,
    )
    .await;
    std::fs::remove_file(&script_path).ok();
    result.unwrap();

    // The sub-workflow nests its own start/done; the tool call is tagged `inner`.
    assert_eq!(
        event_names(&events),
        [
            "workflow.start", // outer
            "workflow.start", // inner
            "tool.call",
            "tool.done",
            "workflow.done", // inner
            "workflow.done", // outer
        ]
    );
    assert_eq!(events[0]["wf"], "outer");
    assert_eq!(events[1]["wf"], "inner");
    assert_eq!(events[1]["inputs"], serde_json::json!({ "WHO": "world" }));
    assert_eq!(events[2]["wf"], "inner");
}

#[tokio::test]
async fn logs_ask_prompt_and_answer() {
    let answer = |_: &str| AskOutcome::Answered("Boston".to_string());
    let (result, events) = eval_capture(
        "asker",
        r#"c = ask "Which city?""#,
        vec![],
        HashMap::new(),
        &answer,
    )
    .await;
    result.unwrap();

    assert_eq!(
        event_names(&events),
        [
            "workflow.start",
            "ask.prompt",
            "ask.answer",
            "workflow.done"
        ]
    );
    assert_eq!(events[1]["prompt"], "Which city?");
    assert_eq!(events[1]["stmt"], "c");
    assert_eq!(events[2]["answered"], true);
}

#[tokio::test]
async fn logs_ask_answer_false_when_unavailable() {
    let (result, events) = eval_capture(
        "asker",
        r#"c = ask "Which city?" else "Portland""#,
        vec![],
        HashMap::new(),
        &no_ask,
    )
    .await;
    result.unwrap();
    let answer = events.iter().find(|e| e["event"] == "ask.answer").unwrap();
    assert_eq!(answer["answered"], false);
}