apoc 0.9.1

Agentic process control for LLMs
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
use std::collections::BTreeSet;
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU64, Ordering};

use serde_json::Value;
use tempfile::{TempDir, tempdir};

static TEST_IDEMPOTENCY_SEQUENCE: AtomicU64 = AtomicU64::new(1);

struct Fixture {
    binary: String,
    home: TempDir,
    runtime: TempDir,
}

impl Fixture {
    fn new() -> Self {
        Self {
            binary: env!("CARGO_BIN_EXE_apoc").to_string(),
            home: tempdir().unwrap(),
            runtime: tempdir().unwrap(),
        }
    }

    fn run(&self, args: &[&str]) -> Output {
        self.run_with_env(args, &[])
    }

    fn run_with_env(&self, args: &[&str], env: &[(&str, &str)]) -> Output {
        let mut argv = args
            .iter()
            .map(|arg| (*arg).to_string())
            .collect::<Vec<_>>();
        let mutating = match argv.as_slice() {
            [group, command, ..] if group == "execution" => matches!(
                command.as_str(),
                "start"
                    | "command"
                    | "batch"
                    | "pipeline"
                    | "input"
                    | "signal"
                    | "cancel"
                    | "remove"
            ),
            [group, action, target, ..] if group == "poll" => {
                matches!(action.as_str(), "run" | "start")
                    && matches!(target.as_str(), "command" | "apoc")
            }
            _ => false,
        };
        let already_keyed = argv
            .iter()
            .any(|arg| arg == "--idempotency-key" || arg.starts_with("--idempotency-key="));
        if mutating && !already_keyed {
            let boundary = argv
                .iter()
                .position(|arg| arg == "--")
                .unwrap_or(argv.len());
            argv.splice(
                boundary..boundary,
                [
                    "--idempotency-key".to_string(),
                    format!(
                        "execution-verbosity-auto-{}",
                        TEST_IDEMPOTENCY_SEQUENCE.fetch_add(1, Ordering::Relaxed)
                    ),
                ],
            );
        }
        let boundary = argv
            .iter()
            .position(|arg| arg == "--")
            .unwrap_or(argv.len());
        argv.splice(
            boundary..boundary,
            [
                "--purpose".to_string(),
                "Running the execution verbosity fixture.".to_string(),
            ],
        );
        let mut command = Command::new(&self.binary);
        command
            .args(argv)
            .env("APOC_HOME", self.home.path())
            .env("APOC_RUNTIME_DIR", self.runtime.path())
            .env("XDG_DATA_HOME", self.home.path().join("xdg-data"))
            .env_remove("APOC_VERBOSITY")
            .env_remove("APOC_VIEW");
        for (name, value) in env {
            command.env(name, value);
        }
        command.output().unwrap()
    }

    fn json(&self, args: &[&str]) -> Value {
        let output = self.run(args);
        assert!(
            output.status.success(),
            "command failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        serde_json::from_slice(&output.stdout).unwrap()
    }

    /// Runs a command that is expected to reach a verdict, whatever its exit status.
    fn verdict(&self, args: &[&str]) -> (Value, Option<i32>) {
        let output = self.run(args);
        let value = serde_json::from_slice(&output.stdout).unwrap_or_else(|error| {
            panic!(
                "unparsable response: {error}\nstdout: {}\nstderr: {}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            )
        });
        (value, output.status.code())
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        let _ = self.run(&[
            "daemon",
            "stop",
            "--idempotency-key",
            "execution-verbosity-fixture-stop",
            "--format",
            "json",
        ]);
    }
}

fn keys(value: &Value) -> BTreeSet<String> {
    value
        .as_object()
        .unwrap()
        .keys()
        .map(ToString::to_string)
        .collect()
}

fn set(values: &[&str]) -> BTreeSet<String> {
    values.iter().map(ToString::to_string).collect()
}

#[test]
fn every_call_returns_the_same_minimal_verdict() {
    let apoc = Fixture::new();
    let passed = apoc.run(&[
        "execution",
        "command",
        "/bin/echo",
        "--format",
        "json",
        "--",
        "quiet",
    ]);
    let failed = apoc.run(&[
        "execution",
        "command",
        "/bin/sh",
        "--format",
        "json",
        "--",
        "-c",
        "echo noisy failure output >&2; exit 3",
    ]);

    let passed_value: Value = serde_json::from_slice(&passed.stdout).unwrap();
    let failed_value: Value = serde_json::from_slice(&failed.stdout).unwrap();
    assert_eq!(
        keys(&passed_value),
        keys(&failed_value),
        "a failure must not return a different shape than a success\n{failed_value:#}"
    );
    assert_eq!(keys(&passed_value), set(&["id", "outcome"]));
    assert_eq!(passed_value["outcome"], "passed");
    assert_eq!(failed_value["outcome"], "failed");

    // The exit status is the only channel left for the code, so it must stay truthful.
    assert_eq!(passed.status.code(), Some(0));
    assert_eq!(failed.status.code(), Some(3));

    for response in [&passed.stdout, &failed.stdout] {
        assert!(
            response.len() < 80,
            "minimal response grew to {} bytes: {}",
            response.len(),
            String::from_utf8_lossy(response)
        );
    }
    let stdout = String::from_utf8_lossy(&failed.stdout);
    assert!(!stdout.contains("noisy failure output"), "{stdout}");
}

#[test]
fn the_verdict_separates_a_failed_assertion_from_a_fault() {
    let apoc = Fixture::new();

    let (met, code) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/echo",
        "--expect-stdout-regex",
        "All tests passed",
        "--format",
        "json",
        "--",
        "All tests passed",
    ]);
    assert_eq!(met["outcome"], "passed", "{met:#}");
    assert_eq!(code, Some(0));

    // Exited cleanly, but the caller's assertion did not hold.
    let (unmet, code) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/echo",
        "--expect-stdout-regex",
        "All tests passed",
        "--format",
        "json",
        "--",
        "1 test failed",
    ]);
    assert_eq!(unmet["outcome"], "failed", "{unmet:#}");
    assert_eq!(
        code,
        Some(1),
        "an unmet assertion must exit nonzero, or the exit status contradicts the verdict"
    );

    let (nonzero, code) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/sh",
        "--format",
        "json",
        "--",
        "-c",
        "exit 4",
    ]);
    assert_eq!(nonzero["outcome"], "failed", "{nonzero:#}");
    assert_eq!(code, Some(4));

    // A program that never ran reached no verdict at all.
    let (fault, _) = apoc.verdict(&[
        "execution",
        "command",
        "/nonexistent/program",
        "--format",
        "json",
    ]);
    assert_eq!(
        fault["outcome"], "error",
        "a launch failure is a fault, not a failed assertion\n{fault:#}"
    );
}

#[test]
fn an_unlaunched_batch_child_is_skipped() {
    let apoc = Fixture::new();
    let parent = apoc.verdict(&[
        "execution",
        "batch",
        "--commands",
        r#"[{"id":"first","argv":["/bin/sh","-c","exit 9"]},{"id":"second","argv":["/bin/echo","never"]}]"#,
        "--max-parallel",
        "1",
        "--fail-fast",
        "--format",
        "json",
    ])
    .0;
    let parent_id = parent["id"].as_str().unwrap().to_string();

    // A group has no exit code of its own. Judging it by one reported every failing batch as an
    // apoc fault, sending the caller to look for a broken harness instead of a broken command.
    assert_eq!(
        parent["outcome"], "failed",
        "a group whose command failed did not fault; it failed\n{parent:#}"
    );

    let children = apoc.json(&[
        "execution",
        "list",
        "--parent",
        &parent_id,
        "--format",
        "json",
    ]);
    let verdicts = children["executions"]
        .as_array()
        .unwrap()
        .iter()
        .map(|child| {
            let id = child["id"].as_str().unwrap();
            apoc.verdict(&["execution", "get", id, "--format", "json"])
                .0["outcome"]
                .as_str()
                .unwrap()
                .to_string()
        })
        .collect::<BTreeSet<_>>();
    assert!(
        verdicts.contains("skipped"),
        "a declared command that never launched must be skipped, not failed: {verdicts:?}"
    );
}

#[test]
fn raising_verbosity_adds_without_replacing() {
    let apoc = Fixture::new();
    let mut previous: Option<BTreeSet<String>> = None;
    for level in ["error", "warn", "info", "debug"] {
        let (value, _) = apoc.verdict(&[
            "execution",
            "command",
            "/bin/sh",
            "--verbosity",
            level,
            "--format",
            "json",
            "--",
            "-c",
            "echo out; echo err >&2; exit 5",
        ]);
        let current = keys(&value);
        assert_eq!(value["outcome"], "failed", "{level}: {value:#}");
        if let Some(previous) = &previous {
            assert!(
                previous.is_subset(&current),
                "{level} dropped keys that a lower level returned: {previous:?} -> {current:?}"
            );
        }
        previous = Some(current);
    }
    let debug = previous.unwrap();
    assert!(
        debug.contains("logs"),
        "debug must carry log tails: {debug:?}"
    );
    assert!(debug.contains("inspect"), "{debug:?}");

    // Trace is the one level that is not additive: it answers with the durable record itself
    // rather than the verdict envelope, because its consumers address that record by pointer.
    // What it must never drop is the verdict, which is asserted in `trace_carries_the_verdict_
    // beside_the_complete_record`. Pinning the break here keeps it a stated exception rather
    // than something this test avoids by stopping a rung early.
    let (traced, _) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/sh",
        "--verbosity",
        "trace",
        "--format",
        "json",
        "--",
        "-c",
        "echo out; echo err >&2; exit 5",
    ]);
    let traced = keys(&traced);
    assert!(traced.contains("outcome"), "{traced:?}");
    assert!(
        traced.contains("execution"),
        "trace must answer with the durable record: {traced:?}"
    );
    assert!(
        !debug.is_subset(&traced),
        "trace has become additive; make the ladder claim unconditional instead of noting an \
         exception here"
    );

    // Off returns no payload at all.
    let (silent, code) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/echo",
        "--verbosity",
        "off",
        "--format",
        "json",
        "--",
        "quiet",
    ]);
    assert_eq!(keys_or_empty(&silent), BTreeSet::new(), "{silent:#}");
    assert_eq!(code, Some(0));
}

fn keys_or_empty(value: &Value) -> BTreeSet<String> {
    value
        .as_object()
        .map(|object| object.keys().map(ToString::to_string).collect())
        .unwrap_or_default()
}

#[test]
fn progressive_disclosure_reveals_one_line_then_its_neighbours() {
    let apoc = Fixture::new();
    let (started, _) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/sh",
        "--format",
        "json",
        "--",
        "-c",
        "i=1; while [ $i -le 400 ]; do echo \"line $i\"; i=$((i+1)); done; \
         echo 'FATAL: disk unavailable' >&2; exit 2",
    ]);
    let id = started["id"].as_str().unwrap().to_string();

    let found = apoc.json(&[
        "execution",
        "logs",
        &id,
        "--grep",
        "FATAL",
        "--context",
        "0",
        "--format",
        "json",
    ]);
    assert_eq!(found["total_matches"], 1, "{found:#}");
    assert_eq!(found["stdout_lines"], 400, "{found:#}");
    let hit = &found["lines"].as_array().unwrap()[0];
    assert_eq!(hit["stream"], "stderr", "{found:#}");
    assert!(
        hit["text"].as_str().unwrap().contains("disk unavailable"),
        "{found:#}"
    );

    // The 400 stdout lines never entered the response until a range asked for three of them.
    let expanded = apoc.json(&[
        "execution",
        "logs",
        &id,
        "--lines",
        "200-202",
        "--format",
        "json",
    ]);
    let lines = expanded["lines"].as_array().unwrap();
    assert_eq!(lines.len(), 3, "{expanded:#}");
    assert_eq!(lines[0]["number"], 200, "{expanded:#}");
    assert_eq!(lines[2]["text"], "line 202", "{expanded:#}");
    assert_eq!(expanded["stdout_lines"], 400, "{expanded:#}");
}

#[test]
fn grep_finds_a_failure_that_only_wrote_to_stdout() {
    let apoc = Fixture::new();
    let (started, _) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/sh",
        "--format",
        "json",
        "--",
        "-c",
        "echo 'AssertionError: expected 2 to equal 3'; exit 1",
    ]);
    let id = started["id"].as_str().unwrap().to_string();

    let found = apoc.json(&[
        "execution",
        "logs",
        &id,
        "--grep",
        "AssertionError",
        "--format",
        "json",
    ]);
    assert_eq!(found["total_matches"], 1, "{found:#}");
    let hit = &found["lines"].as_array().unwrap()[0];
    assert_eq!(
        hit["stream"], "stdout",
        "diagnostics on stdout must be findable\n{found:#}"
    );
}

#[test]
fn an_addressed_read_refuses_a_log_pending_redaction() {
    let apoc = Fixture::new();
    let (started, _) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/echo",
        "--format",
        "json",
        "--",
        "secret-bearing",
    ]);
    let id = started["id"].as_str().unwrap().to_string();

    // Recreate the state a pending secret redaction leaves behind.
    let directory = apoc.home.path().join("runs").join(&id);
    assert!(directory.is_dir(), "missing run directory {directory:?}");
    std::fs::write(directory.join("redaction.required"), []).unwrap();

    for query in [["--grep", "secret"], ["--lines", "1-2"]] {
        let refused = apoc.run(&[
            "execution",
            "logs",
            &id,
            query[0],
            query[1],
            "--format",
            "json",
        ]);
        let message = format!(
            "{}{}",
            String::from_utf8_lossy(&refused.stdout),
            String::from_utf8_lossy(&refused.stderr)
        );
        assert!(
            !refused.status.success() && message.contains("redaction"),
            "{query:?} read a log whose redaction had not completed: {message}"
        );
    }
}

#[test]
fn the_deprecated_view_alias_still_resolves() {
    let apoc = Fixture::new();
    let (aliased, _) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/echo",
        "--view",
        "full",
        "--format",
        "json",
        "--",
        "aliased",
    ]);
    assert!(
        aliased.get("execution").is_some() && aliased.get("logs").is_some(),
        "--view full must still reach the complete record\n{aliased:#}"
    );

    let env = apoc.run_with_env(
        &[
            "execution",
            "command",
            "/bin/echo",
            "--format",
            "json",
            "--",
            "aliased",
        ],
        &[("APOC_VIEW", "outcome")],
    );
    let value: Value = serde_json::from_slice(&env.stdout).unwrap();
    assert_eq!(
        keys(&value),
        set(&["id", "outcome"]),
        "APOC_VIEW=outcome asked for the collapsed verdict and must not widen past it\n{value:#}"
    );

    let preferred = apoc.run_with_env(
        &[
            "execution",
            "command",
            "/bin/echo",
            "--format",
            "json",
            "--",
            "preferred",
        ],
        &[("APOC_VERBOSITY", "debug"), ("APOC_VIEW", "outcome")],
    );
    let preferred: Value = serde_json::from_slice(&preferred.stdout).unwrap();
    assert!(
        preferred.get("logs").is_some(),
        "APOC_VERBOSITY must take precedence over APOC_VIEW\n{preferred:#}"
    );

    let blank = apoc.run_with_env(
        &[
            "execution",
            "command",
            "/bin/echo",
            "--format",
            "json",
            "--",
            "blank",
        ],
        &[("APOC_VERBOSITY", ""), ("APOC_VIEW", "outcome")],
    );
    let blank: Value = serde_json::from_slice(&blank.stdout).unwrap();
    assert_eq!(
        keys(&blank),
        set(&["id", "outcome"]),
        "a blank APOC_VERBOSITY must fall back to APOC_VIEW\n{blank:#}"
    );
}

#[test]
fn trace_carries_the_verdict_beside_the_complete_record() {
    let apoc = Fixture::new();
    let (traced, _) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/sh",
        "--verbosity",
        "trace",
        "--format",
        "json",
        "--",
        "-c",
        "echo out; exit 6",
    ]);

    // Trace replaces the verdict envelope with the durable record so typed consumers keep the
    // pointers they already address. The verdict travels with it, so raising verbosity never
    // costs a caller the one field every level below reports.
    assert_eq!(traced["outcome"], "failed", "{traced:#}");
    assert_eq!(traced["execution"]["status"], "failed", "{traced:#}");
    assert!(traced.get("logs").is_some(), "{traced:#}");
    assert!(traced.get("replayed").is_some(), "{traced:#}");
}

#[test]
fn a_timeout_reaches_no_verdict() {
    let apoc = Fixture::new();
    let (timed_out, _) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/sh",
        "--timeout-ms",
        "200",
        "--verbosity",
        "trace",
        "--format",
        "json",
        "--",
        "-c",
        "sleep 30",
    ]);
    assert_eq!(
        timed_out["outcome"], "error",
        "a command apoc stopped never answered its assertion\n{timed_out:#}"
    );
    assert_eq!(
        timed_out["execution"]["status"], "canceled",
        "{timed_out:#}"
    );
    assert_eq!(
        timed_out["execution"]["result"]["error_code"], "EXECUTION_TIMEOUT",
        "{timed_out:#}"
    );
    let id = timed_out["execution"]["id"].as_str().unwrap();

    let executions = apoc.json(&[
        "execution",
        "list",
        "--error-code",
        "EXECUTION_TIMEOUT",
        "--format",
        "json",
    ]);
    assert_eq!(executions["executions"][0]["id"], id, "{executions:#}");

    let history = apoc.json(&[
        "history",
        "list",
        "--error-code",
        "EXECUTION_TIMEOUT",
        "--format",
        "json",
    ]);
    assert_eq!(history["invocations"][0]["execution_id"], id, "{history:#}");
}

#[test]
fn a_wait_boundary_returns_pending_without_failing_or_canceling_the_execution() {
    let apoc = Fixture::new();
    let started = apoc.json(&[
        "execution",
        "start",
        "/bin/sleep",
        "--format",
        "json",
        "--",
        "2",
    ]);
    let id = started["id"].as_str().unwrap();

    let (pending, code) = apoc.verdict(&[
        "execution",
        "wait",
        id,
        "--timeout-ms",
        "10",
        "--format",
        "json",
    ]);

    assert_eq!(pending, serde_json::json!({"id": id, "outcome": "pending"}));
    assert_eq!(
        code,
        Some(0),
        "an observation boundary is not a command failure"
    );

    let (finished, code) = apoc.verdict(&[
        "execution",
        "wait",
        id,
        "--timeout-ms",
        "5000",
        "--format",
        "json",
    ]);
    assert_eq!(finished["outcome"], "passed", "{finished:#}");
    assert_eq!(code, Some(0));
}

#[test]
fn a_terminal_wait_mirrors_the_verdict_exit_status() {
    let apoc = Fixture::new();
    let started = apoc.json(&["execution", "start", "/usr/bin/false", "--format", "json"]);
    let id = started["id"].as_str().unwrap();

    let (failed, code) = apoc.verdict(&[
        "execution",
        "wait",
        id,
        "--timeout-ms",
        "2000",
        "--format",
        "json",
    ]);
    assert_eq!(failed["outcome"], "failed", "{failed:#}");
    assert_ne!(code, Some(0), "{failed:#}");
}

#[test]
fn every_declared_command_carries_its_own_assertion() {
    let apoc = Fixture::new();
    // The second command exits zero but contradicts what its caller asserted.
    let (parent, code) = apoc.verdict(&[
        "execution",
        "batch",
        "--commands",
        r#"[{"id":"first","argv":["/bin/echo","ready"],"expect":{"kind":"stdout_regex","pattern":"ready"}},
            {"id":"second","argv":["/bin/echo","degraded"],"expect":{"kind":"stdout_regex","pattern":"ready"}}]"#,
        "--max-parallel",
        "2",
        "--format",
        "json",
    ]);
    assert_eq!(
        parent["outcome"], "failed",
        "a child's unmet assertion must reach its parent\n{parent:#}"
    );
    assert_ne!(code, Some(0), "the exit status must not contradict failed");

    let parent_id = parent["id"].as_str().unwrap().to_string();
    let children = apoc.json(&[
        "execution",
        "list",
        "--parent",
        &parent_id,
        "--format",
        "json",
    ]);
    let verdicts = children["executions"]
        .as_array()
        .unwrap()
        .iter()
        .map(|child| {
            let id = child["id"].as_str().unwrap();
            apoc.verdict(&["execution", "get", id, "--format", "json"])
                .0["outcome"]
                .as_str()
                .unwrap()
                .to_string()
        })
        .collect::<BTreeSet<_>>();
    assert_eq!(
        verdicts,
        set(&["passed", "failed"]),
        "each declared command is judged against its own expectation: {verdicts:?}"
    );
}

#[test]
fn command_groups_accept_declared_nonzero_exits() {
    for options in [
        vec!["batch", "--max-parallel", "1", "--fail-fast"],
        vec!["pipeline", "--pipefail", "true"],
        vec!["pipeline", "--pipefail", "false"],
    ] {
        let apoc = Fixture::new();
        let mut args = vec!["execution"];
        args.extend(options);
        args.extend([
            "--commands",
            r#"[{"id":"first","argv":["/usr/bin/false"],"expect":{"kind":"exit_code","codes":[1]}},
                {"id":"second","argv":["/usr/bin/false"],"expect":{"kind":"exit_code","codes":[1]}}]"#,
            "--idempotency-key", "accepted-group", "--verbosity", "trace", "--format", "json",
        ]);
        let (parent, code) = apoc.verdict(&args);
        assert_eq!(parent["outcome"], "passed", "{args:?}: {parent:#}");
        assert_eq!(code, Some(0), "{parent:#}");
        assert_eq!(
            parent["execution"]["result"]["counts"],
            serde_json::json!({
                "total": 2, "completed": 2, "failed": 0, "canceled": 0, "skipped": 0
            })
        );
        let id = parent["execution"]["id"].as_str().unwrap();
        let children = apoc.json(&["execution", "list", "--parent", id, "--format", "json"]);
        assert_eq!(children["executions"].as_array().unwrap().len(), 2);
        for child in children["executions"].as_array().unwrap() {
            let child_id = child["id"].as_str().unwrap();
            let (record, code) = apoc.verdict(&[
                "execution",
                "get",
                child_id,
                "--verbosity",
                "trace",
                "--format",
                "json",
            ]);
            assert_eq!(record["outcome"], "passed", "{record:#}");
            assert_eq!(code, Some(0));
            assert_eq!(
                record["status"], "failed",
                "raw process status is preserved"
            );
            assert_eq!(record["result"]["exit_code"], 1);
            let lease = apoc.json(&[
                "lease",
                "get",
                &format!("execution/{child_id}"),
                "--format",
                "json",
            ]);
            assert_eq!(lease["released"], true, "{lease:#}");
        }
        let (replay, code) = apoc.verdict(&args);
        assert_eq!(code, Some(0));
        assert_eq!(replay["execution"]["id"], id);
        assert_eq!(replay["replayed"], true);
        assert_eq!(replay["execution"]["result"], parent["execution"]["result"]);
        assert_eq!(
            apoc.json(&["execution", "list", "--parent", id, "--format", "json"]),
            children
        );
    }
}

#[test]
fn unmet_pipeline_assertions_fail_the_parent_regardless_of_pipefail() {
    for (pipefail, failed_stage, passes) in [
        (true, 0, false),
        (true, 1, false),
        (false, 0, false),
        (false, 1, false),
    ] {
        let apoc = Fixture::new();
        let commands = serde_json::to_string(&(0..2).map(|index| serde_json::json!({
            "id": format!("stage-{index}"), "argv": ["/usr/bin/true"],
            "expect": {"kind": "exit_code", "codes": [if index == failed_stage {1} else {0}]}
        })).collect::<Vec<_>>()).unwrap();
        let (parent, code) = apoc.verdict(&[
            "execution",
            "pipeline",
            "--commands",
            &commands,
            "--pipefail",
            if pipefail { "true" } else { "false" },
            "--verbosity",
            "trace",
            "--format",
            "json",
        ]);
        assert_eq!(
            parent["outcome"],
            if passes { "passed" } else { "failed" },
            "pipefail={pipefail}, stage={failed_stage}: {parent:#}"
        );
        assert_eq!(code == Some(0), passes);
        assert_eq!(parent["execution"]["result"]["counts"]["failed"], 1);
        assert_eq!(parent["execution"]["result"]["counts"]["completed"], 1);
    }
}

#[test]
fn poll_conditions_keep_the_full_record_under_the_minimal_default() {
    let apoc = Fixture::new();
    let (started, _) = apoc.verdict(&[
        "execution",
        "command",
        "/bin/echo",
        "--format",
        "json",
        "--",
        "polled",
    ]);
    let id = started["id"].as_str().unwrap().to_string();

    // `/attempts/0/exit_code` exists only in the complete record. If the minimal default
    // reached poll targets, this condition could never match and the poll would exhaust.
    let arguments = serde_json::json!({
        "id": id,
        "purpose": "Reading a durable execution inside a poll condition."
    })
    .to_string();
    let (poll, _) = apoc.verdict(&[
        "poll",
        "run",
        "apoc",
        "execution.get",
        "--arguments",
        &arguments,
        "--until-json-pointer",
        "/attempts/0/exit_code",
        "--until-json-equals",
        "0",
        "--interval-ms",
        "200",
        "--max-iterations",
        "3",
        "--format",
        "json",
    ]);
    assert_eq!(poll["outcome"], "passed", "{poll:#}");
}