aion-package 0.31.0

Archive validation, content hashing, and namespacing for Aion workflow packages.
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
//! The render's own rules, exercised on inputs this module constructs.

use std::collections::BTreeMap;

use serde_json::json;

use super::{
    ArgumentValue, ArgvSlot, CommandLineContract, CommandParameterContract,
    DeclaredCommandContract, EnvBindingContract, FillPiece, FillTemplate, RenderError,
};

/// What a test returns. Every fallible step is carried rather than unwrapped,
/// because the workspace denies panicking accessors in test code as firmly as
/// in library code.
type TestResult = Result<(), Box<dyn std::error::Error>>;

fn hole(parameter: &str) -> FillTemplate {
    FillTemplate {
        pieces: vec![FillPiece::Hole {
            parameter: parameter.to_owned(),
        }],
    }
}

fn mixed(prefix: &str, parameter: &str, suffix: &str) -> FillTemplate {
    FillTemplate {
        pieces: vec![
            FillPiece::Literal {
                text: prefix.to_owned(),
            },
            FillPiece::Hole {
                parameter: parameter.to_owned(),
            },
            FillPiece::Literal {
                text: suffix.to_owned(),
            },
        ],
    }
}

fn slot(fill: FillTemplate, label: &str, admits_leading_dash: bool) -> ArgvSlot {
    ArgvSlot {
        fill,
        label: label.to_owned(),
        admits_leading_dash,
    }
}

fn parameter(name: &str, default: Option<&str>) -> CommandParameterContract {
    CommandParameterContract {
        name: name.to_owned(),
        default: default.map(str::to_owned),
    }
}

/// One-line contract: the program words become literal slots, then the given
/// slots follow — the shape the AWL emitter produces for one body line.
fn contract(
    parameters: Vec<CommandParameterContract>,
    program: &[&str],
    args: Vec<ArgvSlot>,
) -> DeclaredCommandContract {
    let mut slots: Vec<ArgvSlot> = program
        .iter()
        .map(|word| slot(FillTemplate::literal((*word).to_owned()), word, true))
        .collect();
    slots.extend(args);
    DeclaredCommandContract {
        name: "probe".to_owned(),
        parameters,
        lines: vec![CommandLineContract { slots }],
        env: Vec::new(),
        cwd: None,
        prior_form_refusal: None,
    }
}

fn supplied(pairs: &[(&str, ArgumentValue)]) -> BTreeMap<String, ArgumentValue> {
    pairs
        .iter()
        .map(|(name, value)| ((*name).to_owned(), value.clone()))
        .collect()
}

#[test]
fn a_value_carrying_shell_metacharacters_arrives_as_one_argv_element() -> TestResult {
    let command = contract(
        vec![parameter("value", None)],
        &["echo"],
        vec![slot(hole("value"), "value", true)],
    );
    let rendered = command.render(&supplied(&[(
        "value",
        ArgumentValue::scalar("$(boom); rm -rf /"),
    )]))?;
    assert_eq!(
        rendered.argv_lines,
        vec![vec!["echo".to_owned(), "$(boom); rm -rf /".to_owned()]],
        "a hostile value must be one inert element, never re-split"
    );
    Ok(())
}

/// A fill is ONE argv element always — the named divergence from just. A
/// value containing a space stays one argument.
#[test]
fn a_value_containing_a_space_stays_one_element() -> TestResult {
    let command = contract(
        vec![parameter("value", None)],
        &["echo"],
        vec![slot(hole("value"), "value", true)],
    );
    let rendered = command.render(&supplied(&[("value", ArgumentValue::scalar("a b c"))]))?;
    assert_eq!(
        rendered.argv_lines,
        vec![vec!["echo".to_owned(), "a b c".to_owned()]]
    );
    Ok(())
}

/// A body is LINES: each renders its own argv, in order — the execution
/// contract every executor shares.
#[test]
fn a_multi_line_body_renders_one_argv_per_line_in_order() -> TestResult {
    let command = DeclaredCommandContract {
        name: "probe".to_owned(),
        parameters: vec![parameter("tag", None)],
        lines: vec![
            CommandLineContract {
                slots: vec![
                    slot(FillTemplate::literal("git"), "git", true),
                    slot(FillTemplate::literal("fetch"), "fetch", true),
                ],
            },
            CommandLineContract {
                slots: vec![
                    slot(FillTemplate::literal("git"), "git", true),
                    slot(FillTemplate::literal("tag"), "tag", true),
                    slot(FillTemplate::literal("--"), "--", true),
                    slot(hole("tag"), "tag", true),
                ],
            },
        ],
        env: Vec::new(),
        cwd: None,
        prior_form_refusal: None,
    };
    let rendered = command.render(&supplied(&[("tag", ArgumentValue::scalar("v1.0"))]))?;
    assert_eq!(
        rendered.argv_lines,
        vec![
            vec!["git".to_owned(), "fetch".to_owned()],
            vec![
                "git".to_owned(),
                "tag".to_owned(),
                "--".to_owned(),
                "v1.0".to_owned()
            ],
        ]
    );
    Ok(())
}

#[test]
fn a_default_is_literal_text() -> TestResult {
    let command = contract(
        vec![parameter("range", Some("main..HEAD"))],
        &["git", "log"],
        vec![slot(hole("range"), "range", true)],
    );
    let rendered = command.render(&BTreeMap::new())?;
    assert_eq!(
        rendered.argv_lines,
        vec![vec![
            "git".to_owned(),
            "log".to_owned(),
            "main..HEAD".to_owned()
        ]]
    );
    Ok(())
}

#[test]
fn a_supplied_value_beats_the_declared_default() -> TestResult {
    let command = contract(
        vec![parameter("who", Some("nobody"))],
        &["echo"],
        vec![slot(hole("who"), "who", true)],
    );
    let rendered = command.render(&supplied(&[("who", ArgumentValue::scalar("world"))]))?;
    assert_eq!(
        rendered.argv_lines,
        vec![vec!["echo".to_owned(), "world".to_owned()]]
    );
    Ok(())
}

#[test]
fn a_parameter_with_no_value_and_no_default_refuses_by_name() {
    let command = contract(
        vec![parameter("who", None)],
        &["echo"],
        vec![slot(hole("who"), "who", true)],
    );
    assert_eq!(
        command.render(&BTreeMap::new()),
        Err(RenderError::ArgumentMissing {
            command: "probe".to_owned(),
            parameter: "who".to_owned(),
        })
    );
}

#[test]
fn a_value_the_command_does_not_declare_refuses_by_name() {
    let command = contract(Vec::new(), &["echo"], Vec::new());
    assert_eq!(
        command.render(&supplied(&[("stray", ArgumentValue::scalar("x"))])),
        Err(RenderError::ArgumentUndeclared {
            command: "probe".to_owned(),
            parameter: "stray".to_owned(),
        })
    );
}

/// A command parameter is one command-line word; a list has no rendering
/// (a fill is one element, never several) and refuses naming both shapes.
#[test]
fn a_list_value_refuses_naming_both_shapes() {
    let command = contract(
        vec![parameter("paths", None)],
        &["git"],
        vec![slot(hole("paths"), "paths", true)],
    );
    assert_eq!(
        command.render(&supplied(&[(
            "paths",
            ArgumentValue::list(["a.rs", "b.rs"])
        )])),
        Err(RenderError::ArgumentTypeMismatch {
            command: "probe".to_owned(),
            parameter: "paths".to_owned(),
            observed: "[a.rs, b.rs]".to_owned(),
            declared: "single value",
            supplied: "list",
        })
    );
}

#[test]
fn a_leading_dash_operand_refuses_where_the_program_still_reads_options() {
    let command = contract(
        vec![parameter("name", None)],
        &["git", "tag"],
        vec![slot(hole("name"), "name", false)],
    );
    let Err(error) = command.render(&supplied(&[("name", ArgumentValue::scalar("-n"))])) else {
        panic_free_failure("a leading-dash operand must refuse");
        return;
    };
    assert_eq!(
        error,
        RenderError::LeadingDashOperand {
            command: "probe".to_owned(),
            argument: "name".to_owned(),
            element: "-n".to_owned(),
            marker: "--",
        }
    );
}

/// An element the author OPENED LITERALLY admits a dash wherever the dash
/// came from: `--max-count={{n}}` with a negative `n` is the flag the author
/// wrote, and the slot travels as admitting.
#[test]
fn a_literally_opened_element_is_not_dash_guarded() -> TestResult {
    let command = contract(
        vec![parameter("count", None)],
        &["grep"],
        vec![
            slot(FillTemplate::literal("--max-count"), "--max-count", true),
            slot(hole("count"), "count", true),
        ],
    );
    let rendered = command.render(&supplied(&[("count", ArgumentValue::scalar("-3"))]))?;
    assert_eq!(
        rendered.argv_lines,
        vec![vec![
            "grep".to_owned(),
            "--max-count".to_owned(),
            "-3".to_owned()
        ]]
    );
    Ok(())
}

#[test]
fn the_same_bytes_pass_once_the_end_of_options_marker_stands_before_them() -> TestResult {
    let command = contract(
        vec![parameter("name", None)],
        &["git", "tag"],
        vec![
            slot(FillTemplate::literal("--"), "--", true),
            slot(hole("name"), "name", true),
        ],
    );
    let rendered = command.render(&supplied(&[("name", ArgumentValue::scalar("-n"))]))?;
    assert_eq!(
        rendered.argv_lines,
        vec![vec![
            "git".to_owned(),
            "tag".to_owned(),
            "--".to_owned(),
            "-n".to_owned()
        ]]
    );
    Ok(())
}

/// Environment bindings are the document's `export` lines: literal name and
/// value, carried through the render untouched.
#[test]
fn env_bindings_carry_their_literal_values() -> TestResult {
    let mut command = contract(Vec::new(), &["true"], Vec::new());
    command.env = vec![EnvBindingContract {
        name: "GIT_PAGER".to_owned(),
        value: "cat".to_owned(),
    }];
    command.cwd = Some("{workspace_root}".to_owned());
    let rendered = command.render(&BTreeMap::new())?;
    assert_eq!(
        rendered.env,
        vec![("GIT_PAGER".to_owned(), "cat".to_owned())]
    );
    assert_eq!(rendered.cwd, Some("{workspace_root}".to_owned()));
    Ok(())
}

#[test]
fn json_values_take_their_one_obvious_argument_form() -> TestResult {
    assert_eq!(
        ArgumentValue::from_json("p", &json!("text"))?,
        ArgumentValue::scalar("text")
    );
    assert_eq!(
        ArgumentValue::from_json("p", &json!(7))?,
        ArgumentValue::scalar("7")
    );
    assert_eq!(
        ArgumentValue::from_json("p", &json!(true))?,
        ArgumentValue::scalar("true")
    );
    assert_eq!(
        ArgumentValue::from_json("p", &json!(["a", 2]))?,
        ArgumentValue::list(["a", "2"])
    );
    Ok(())
}

#[test]
fn json_values_with_no_argument_form_refuse_by_name() {
    for (value, kind) in [
        (json!(null), "null"),
        (json!({ "a": 1 }), "an object"),
        (json!([[1]]), "a nested array"),
    ] {
        assert_eq!(
            ArgumentValue::from_json("p", &value),
            Err(RenderError::UnrepresentableValue {
                parameter: "p".to_owned(),
                kind,
            })
        );
    }
    assert_eq!(
        ArgumentValue::from_json("p", &json!("has\0nul")),
        Err(RenderError::InteriorNul {
            parameter: "p".to_owned(),
        })
    );
}

#[test]
fn the_contract_round_trips_through_json() -> TestResult {
    let mut command = contract(
        vec![parameter("who", Some("world"))],
        &["echo"],
        vec![slot(mixed("hello ", "who", "!"), "who", false)],
    );
    command.cwd = Some("{workspace_root}".to_owned());
    command.env = vec![EnvBindingContract {
        name: "GIT_PAGER".to_owned(),
        value: "cat".to_owned(),
    }];
    let encoded = serde_json::to_string(&command)?;
    let decoded: DeclaredCommandContract = serde_json::from_str(&encoded)?;
    assert_eq!(decoded, command);
    Ok(())
}

/// Every field of the emitted form is executable authority, so no two
/// distinct commands may hash alike — and the CAPTURE is authority too: the
/// same argvs returning a decoded record and returning a string are two
/// different promises to a caller.
#[test]
fn every_distinguishing_edit_moves_the_identity_bytes() -> TestResult {
    use crate::contract::CommandBodyCapture;

    let base = contract(
        vec![parameter("who", None)],
        &["echo"],
        vec![slot(hole("who"), "who", true)],
    );

    let mut seen = std::collections::BTreeSet::new();
    let mut record = |capture: CommandBodyCapture,
                      command: &DeclaredCommandContract|
     -> Result<(), Box<dyn std::error::Error>> {
        let mut bytes = Vec::new();
        crate::declared_command::encode_identity(&mut bytes, command);
        bytes.push(u8::from(matches!(capture, CommandBodyCapture::Json)));
        assert!(seen.insert(bytes), "two distinct commands hashed alike");
        Ok(())
    };

    record(CommandBodyCapture::Text, &base)?;
    // The capture alone.
    record(CommandBodyCapture::Json, &base)?;
    // The program word.
    let mut edited = base.clone();
    edited.lines[0].slots[0].fill = FillTemplate::literal("printf");
    record(CommandBodyCapture::Text, &edited)?;
    // The argument list.
    let mut edited = base.clone();
    edited.lines[0]
        .slots
        .push(slot(FillTemplate::literal("--"), "--", true));
    record(CommandBodyCapture::Text, &edited)?;
    // The order of the argument list: `--` before an operand and after it
    // are different commands.
    let mut edited = base.clone();
    edited.lines[0]
        .slots
        .insert(1, slot(FillTemplate::literal("--"), "--", true));
    record(CommandBodyCapture::Text, &edited)?;
    // The dash-guard fact.
    let mut edited = base.clone();
    edited.lines[0].slots[1].admits_leading_dash = false;
    record(CommandBodyCapture::Text, &edited)?;
    // A second line, and line ORDER: the same lines in a different order run
    // different work.
    let extra = CommandLineContract {
        slots: vec![slot(FillTemplate::literal("true"), "true", true)],
    };
    let mut edited = base.clone();
    edited.lines.push(extra.clone());
    record(CommandBodyCapture::Text, &edited)?;
    let mut edited = base.clone();
    edited.lines.insert(0, extra);
    record(CommandBodyCapture::Text, &edited)?;
    // The environment.
    let mut edited = base.clone();
    edited.env = vec![EnvBindingContract {
        name: "A".to_owned(),
        value: "1".to_owned(),
    }];
    record(CommandBodyCapture::Text, &edited)?;
    // The working directory.
    let mut edited = base.clone();
    edited.cwd = Some("/srv".to_owned());
    record(CommandBodyCapture::Text, &edited)?;
    // A parameter's default.
    let mut edited = base;
    edited.parameters[0].default = Some("world".to_owned());
    record(CommandBodyCapture::Text, &edited)?;
    Ok(())
}

/// Fails the calling test without a panicking accessor.
fn panic_free_failure(reason: &str) {
    assert!(reason.is_empty(), "{reason}");
}

// ---------------------------------------------------------------------------
// The prior archive form (`super::compat`): archives deployed before the
// body-lines reshape must READ everywhere and render the same argv, and each
// construct with no faithful translation — an interpolating environment
// binding, an interpolating hardened `PATH`, a list parameter, an
// interpolating default — must be carried by name and refuse at RENDER, never
// at read.
// ---------------------------------------------------------------------------

/// A prior-form contract as the pre-v0.27 emitter wrote it, shaped like the
/// release-ceremony archive that is durable in the real store: a `program`
/// word, `args` whose fills mix literal text and holes, and a `timeout` the
/// current surface deleted.
fn prior_form_specimen() -> serde_json::Value {
    json!({
        "name": "probe_release_tree_sh",
        "parameters": [
            {"name": "tree", "list": false},
            {"name": "version", "list": false}
        ],
        "program": ["sh"],
        "args": [
            {
                "fill": {"pieces": [
                    {"kind": "hole", "parameter": "tree"},
                    {"kind": "literal", "text": "/workflows/release_ceremony/probe-release-tree.sh"}
                ]},
                "label": "script",
                "admits_leading_dash": true
            },
            {
                "fill": {"pieces": [{"kind": "hole", "parameter": "tree"}]},
                "label": "release_tree",
                "admits_leading_dash": true
            },
            {
                "fill": {"pieces": [{"kind": "hole", "parameter": "version"}]},
                "label": "release_version",
                "admits_leading_dash": true
            }
        ],
        "timeout_ms": 300_000,
        "timeout_owner": "release"
    })
}

/// THE READ-PATH PROMISE: the prior form deserializes, and renders exactly
/// the argv the prior executor built — program words first, then each arg
/// slot resolved against the command's parameters, in declared order.
#[test]
fn the_prior_archive_form_reads_and_renders_the_same_argv() -> TestResult {
    let command: DeclaredCommandContract = serde_json::from_value(prior_form_specimen())?;
    assert_eq!(command.name, "probe_release_tree_sh");
    assert_eq!(command.prior_form_refusal, None);
    let rendered = command.render(&supplied(&[
        ("tree", ArgumentValue::scalar("/srv/release")),
        ("version", ArgumentValue::scalar("0.27.0")),
    ]))?;
    assert_eq!(
        rendered.argv_lines,
        vec![vec![
            "sh".to_owned(),
            "/srv/release/workflows/release_ceremony/probe-release-tree.sh".to_owned(),
            "/srv/release".to_owned(),
            "0.27.0".to_owned(),
        ]]
    );
    assert!(rendered.env.is_empty());
    assert_eq!(rendered.cwd, None);
    Ok(())
}

/// The prior `hardening path` value becomes a literal `PATH` binding — the
/// same child-environment fact it enforced, spelled the way the current
/// executor honours it.
#[test]
fn a_prior_hardened_path_becomes_a_literal_path_binding() -> TestResult {
    let mut specimen = prior_form_specimen();
    specimen["hardened_path"] = json!({
        "pieces": [{"kind": "literal", "text": "/usr/bin:/bin"}]
    });
    let command: DeclaredCommandContract = serde_json::from_value(specimen)?;
    let rendered = command.render(&supplied(&[
        ("tree", ArgumentValue::scalar("/srv/release")),
        ("version", ArgumentValue::scalar("0.27.0")),
    ]))?;
    assert_eq!(
        rendered.env,
        vec![("PATH".to_owned(), "/usr/bin:/bin".to_owned())]
    );
    Ok(())
}

/// An environment binding whose value interpolates a parameter has no
/// faithful translation. The archive still READS — the contract
/// deserializes and carries the construct by name — and only RENDER refuses,
/// naming the command, the construct, and the cure.
#[test]
fn a_prior_interpolating_env_binding_reads_but_refuses_to_render() -> TestResult {
    let mut specimen = prior_form_specimen();
    specimen["env"] = json!([{
        "name": "DECLARED_WHO",
        "value": {"pieces": [{"kind": "hole", "parameter": "version"}]}
    }]);
    let command: DeclaredCommandContract = serde_json::from_value(specimen)?;
    let Some(construct) = &command.prior_form_refusal else {
        panic_free_failure("the untranslatable binding must be carried by name");
        return Ok(());
    };
    assert!(construct.contains("DECLARED_WHO"), "{construct}");
    let Err(error) = command.render(&supplied(&[
        ("tree", ArgumentValue::scalar("/srv/release")),
        ("version", ArgumentValue::scalar("0.27.0")),
    ])) else {
        panic_free_failure("a prior-form construct with no translation must not execute");
        return Ok(());
    };
    let RenderError::PriorFormUnrenderable { command, construct } = &error else {
        panic_free_failure(&format!(
            "the refusal must name the prior form, got {error:?}"
        ));
        return Ok(());
    };
    assert_eq!(command, "probe_release_tree_sh");
    assert!(construct.contains("DECLARED_WHO"), "{construct}");
    assert!(error.to_string().contains("redeploy"), "{error}");
    Ok(())
}

/// A prior parameter default that interpolated other parameters has no
/// current spelling — a default is literal text now — so it is carried by
/// NAME and refuses at render. Reading it as "no default" would have told the
/// operator the archive declares no default, which is false about the archive
/// and names no cure.
#[test]
fn a_prior_interpolating_parameter_default_reads_but_refuses_to_render() -> TestResult {
    let mut specimen = prior_form_specimen();
    specimen["parameters"] = json!([
        {"name": "tree", "list": false},
        {
            "name": "version",
            "list": false,
            "default": {"pieces": [
                {"kind": "hole", "parameter": "tree"},
                {"kind": "literal", "text": "..HEAD"}
            ]}
        }
    ]);
    let command: DeclaredCommandContract = serde_json::from_value(specimen)?;
    let Some(construct) = &command.prior_form_refusal else {
        panic_free_failure("the untranslatable default must be carried by name");
        return Ok(());
    };
    assert_eq!(construct, "the default of parameter `version`");
    // Even a dispatch that supplies every parameter refuses: the archive
    // carries something the current form cannot express, and the cure is the
    // redeploy, not a luckier parameter set.
    let outcome = command.render(&supplied(&[
        ("tree", ArgumentValue::scalar("/srv/release")),
        ("version", ArgumentValue::scalar("0.27.0")),
    ]));
    assert_eq!(
        outcome,
        Err(RenderError::PriorFormUnrenderable {
            command: "probe_release_tree_sh".to_owned(),
            construct: "the default of parameter `version`".to_owned(),
        })
    );
    Ok(())
}

/// A prior LIST parameter has no current rendering at all: the prior executor
/// splatted such a value into one argv element per item, and a fill is
/// exactly one element now. It is carried by NAME and refuses at render —
/// never by blaming the caller's supplied value for a shape mismatch the
/// caller did not cause.
#[test]
fn a_prior_list_parameter_reads_but_refuses_to_render() -> TestResult {
    let mut specimen = prior_form_specimen();
    specimen["parameters"] = json!([
        {"name": "tree", "list": false},
        {"name": "version", "list": true}
    ]);
    let command: DeclaredCommandContract = serde_json::from_value(specimen)?;
    let Some(construct) = &command.prior_form_refusal else {
        panic_free_failure("the list parameter must be carried by name");
        return Ok(());
    };
    assert_eq!(construct, "the list parameter `version`");

    let expected = Err(RenderError::PriorFormUnrenderable {
        command: "probe_release_tree_sh".to_owned(),
        construct: "the list parameter `version`".to_owned(),
    });
    // Whatever the caller supplies — a list, as the prior form took, or the
    // single value the current form would take — the refusal names the
    // ARCHIVE's construct and the cure, not the caller's value.
    assert_eq!(
        command.render(&supplied(&[
            ("tree", ArgumentValue::scalar("/srv/release")),
            ("version", ArgumentValue::list(["0.27.0", "0.27.1"])),
        ])),
        expected
    );
    assert_eq!(
        command.render(&supplied(&[
            ("tree", ArgumentValue::scalar("/srv/release")),
            ("version", ArgumentValue::scalar("0.27.0")),
        ])),
        expected
    );
    Ok(())
}

/// THE MISROUTE GUARD. `program` names the prior form and `lines` names the
/// current one; an entry carrying BOTH cannot be read either way without
/// silently discarding half of what it says, so it is refused at the wire
/// naming both keys.
#[test]
fn an_entry_carrying_both_archive_forms_refuses_rather_than_choosing() {
    let mut specimen = prior_form_specimen();
    specimen["lines"] = json!([{
        "slots": [{
            "fill": {"pieces": [{"kind": "literal", "text": "true"}]},
            "label": "true",
            "admits_leading_dash": true
        }]
    }]);
    let outcome: Result<DeclaredCommandContract, _> = serde_json::from_value(specimen);
    let Err(error) = outcome else {
        panic_free_failure("an entry carrying both forms must not read as either one");
        return;
    };
    let reported = error.to_string();
    assert!(reported.contains("program"), "{reported}");
    assert!(reported.contains("lines"), "{reported}");
}

/// A current-form entry carrying a key the current form never emits is
/// refused rather than read as something narrower: the stray key is the only
/// evidence that the entry is not what it claims to be.
#[test]
fn a_current_form_entry_with_a_stray_prior_key_refuses() -> TestResult {
    let command = contract(
        vec![parameter("name", None)],
        &["printf"],
        vec![slot(hole("name"), "name", true)],
    );
    let mut wire = serde_json::to_value(&command)?;
    let Some(object) = wire.as_object_mut() else {
        panic_free_failure("a serialized contract is a JSON object");
        return Ok(());
    };
    object.insert("hardened_path".to_owned(), json!({"pieces": []}));
    let outcome: Result<DeclaredCommandContract, _> = serde_json::from_value(wire);
    let Err(error) = outcome else {
        panic_free_failure("a stray key must not be read past in silence");
        return Ok(());
    };
    assert!(error.to_string().contains("hardened_path"), "{error}");
    Ok(())
}

/// A body that reads a parameter the command does not declare has no argv at
/// all. Rendering the hole as empty text would put a DIFFERENT command in
/// front of the program with nothing said, so it refuses, naming the command
/// and the parameter.
#[test]
fn a_body_reading_an_undeclared_parameter_refuses_by_name() {
    let command = contract(
        Vec::new(),
        &["echo"],
        vec![slot(mixed("prefix-", "ghost", "-suffix"), "ghost", true)],
    );
    assert_eq!(
        command.render(&BTreeMap::new()),
        Err(RenderError::UnboundHole {
            command: "probe".to_owned(),
            parameter: "ghost".to_owned(),
        })
    );
}

/// The CURRENT form is untouched by the compat reader: a serialized contract
/// deserializes back equal, and the prior-form marker never appears on the
/// wire for an emitted contract.
#[test]
fn the_current_form_round_trips_unchanged() -> TestResult {
    let command = contract(
        vec![parameter("name", None)],
        &["printf", "--", "%s"],
        vec![slot(hole("name"), "name", true)],
    );
    let wire = serde_json::to_value(&command)?;
    assert!(
        wire.get("prior_form_refusal").is_none(),
        "an emitted contract must not carry the reader's marker on the wire"
    );
    let read: DeclaredCommandContract = serde_json::from_value(wire)?;
    assert_eq!(read, command);
    Ok(())
}