hopper-cli 0.3.1

Command-line tooling for Hopper account inspection, schema export, and migration planning
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
use std::fs;
use std::path::PathBuf;
use std::process;

use hopper_schema::{InstructionDescriptor, ProgramManifest};

pub fn cmd_test_gen(args: &[String]) {
    match args.first().map(String::as_str) {
        Some("security") => run_generator(&args[1..], Generator::Security),
        // `write-containment` (aliases: `writes`, `containment`) emits the
        // declared-vs-actual write-containment property tests.
        Some("write-containment") | Some("writes") | Some("containment") => {
            run_generator(&args[1..], Generator::WriteContainment)
        }
        _ => usage_and_exit(),
    }
}

#[derive(Clone, Copy)]
enum Generator {
    Security,
    WriteContainment,
}

impl Generator {
    fn default_out(self) -> &'static str {
        match self {
            Generator::Security => "tests/hopper_security_matrix.rs",
            Generator::WriteContainment => "tests/hopper_write_containment.rs",
        }
    }

    fn render(self, manifest: &ProgramManifest) -> String {
        match self {
            Generator::Security => security_matrix(manifest),
            Generator::WriteContainment => write_containment_matrix(manifest),
        }
    }

    fn label(self) -> &'static str {
        match self {
            Generator::Security => "security test matrix",
            Generator::WriteContainment => "write-containment property tests",
        }
    }
}

fn run_generator(args: &[String], generator: Generator) {
    let mut program_arg = None;
    let mut out_path = PathBuf::from(generator.default_out());
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--program" => {
                i += 1;
                if i >= args.len() {
                    usage_and_exit();
                }
                program_arg = Some(args[i].clone());
            }
            "--out" => {
                i += 1;
                if i >= args.len() {
                    usage_and_exit();
                }
                out_path = PathBuf::from(&args[i]);
            }
            "--help" | "-h" => usage_and_exit(),
            other => {
                eprintln!("Unknown test-gen argument: {other}");
                usage_and_exit();
            }
        }
        i += 1;
    }
    let program_arg = program_arg.unwrap_or_else(|| usage_and_exit());
    let manifest = crate::load_program_manifest(&program_arg);
    if let Some(parent) = out_path.parent() {
        fs::create_dir_all(parent).unwrap_or_else(|err| {
            eprintln!("Failed to create {}: {err}", parent.display());
            process::exit(1);
        });
    }
    fs::write(&out_path, generator.render(&manifest)).unwrap_or_else(|err| {
        eprintln!("Failed to write {}: {err}", out_path.display());
        process::exit(1);
    });
    println!(
        "Generated {} for {} at {}",
        generator.label(),
        manifest.name,
        out_path.display()
    );
}

fn usage_and_exit() -> ! {
    eprintln!("Usage:");
    eprintln!(
        "  hopper test-gen security --program <manifest> [--out tests/hopper_security_matrix.rs]"
    );
    eprintln!("  hopper test-gen write-containment --program <manifest> [--out tests/hopper_write_containment.rs]");
    process::exit(1);
}

fn security_matrix(manifest: &ProgramManifest) -> String {
    let mut out = String::new();
    out.push_str("//! Generated by `hopper test-gen security`.\n");
    out.push_str("//! Fill the fixture builders with your local program-test harness.\n\n");
    out.push_str("#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n");
    out.push_str("enum SecurityCase { MissingSigner, WrongOwner, WrongPda, WrongLayout, NonWritableMut, WrongTokenExtension }\n\n");
    out.push_str("#[test]\nfn generated_security_matrix_is_not_empty() {\n");
    out.push_str("    let cases = security_cases();\n    assert!(!cases.is_empty());\n}\n\n");
    out.push_str("fn security_cases() -> &'static [(&'static str, SecurityCase)] {\n");
    out.push_str("    &[\n");
    for ix in manifest.instructions {
        let base = sanitize(ix.name);
        out.push_str(&format!(
            "        (\"{base}:missing-signer\", SecurityCase::MissingSigner),\n"
        ));
        out.push_str(&format!(
            "        (\"{base}:wrong-owner\", SecurityCase::WrongOwner),\n"
        ));
        out.push_str(&format!(
            "        (\"{base}:wrong-pda\", SecurityCase::WrongPda),\n"
        ));
        out.push_str(&format!(
            "        (\"{base}:wrong-layout\", SecurityCase::WrongLayout),\n"
        ));
        out.push_str(&format!(
            "        (\"{base}:non-writable-mut\", SecurityCase::NonWritableMut),\n"
        ));
        if ix
            .capabilities
            .iter()
            .any(|cap| cap.contains("token") || cap.contains("Token"))
        {
            out.push_str(&format!(
                "        (\"{base}:wrong-token-extension\", SecurityCase::WrongTokenExtension),\n"
            ));
        }
    }
    out.push_str("    ]\n}\n");
    out
}

// ─────────────────────────────────────────────────────────────────────────
// Write-containment property tests.
//
// For each instruction that declares `strict_writes`, emit a hopper-svm
// property test that drives the handler under the `touch-map` feature and
// asserts that every recorded write touch `(account, offset, size)` is
// contained in the instruction's invocation-resolved `WritePolicy`, the same
// static envelopes and parametric cell rules the `strict_writes` macro
// compiles and installs. The manifest publishes both surfaces in
// `write_ranges` and `parametric_write_ranges`; the runtime binds selectors
// from the real invocation. The
// touch-map ledger is the "actual" footprint; the installed policy is the
// "declared" set. No competitor can generate this test because none carries
// the ledger.
//
// A partial touch map (`touch_map_overflowed`) is surfaced as INCONCLUSIVE,
// never silently passed. Containment is judged per BYTE against the UNION of
// the declared ranges; not per-declaration, because the ledger coalesces
// adjacent touch records under capacity pressure: one record may be the
// exact union of several individually-gated acquires and so may span two
// adjacent declarations. Instructions that do NOT declare `strict_writes`
// get no such test, and are enumerated in a trailing comment for the record.
// ─────────────────────────────────────────────────────────────────────────

/// Reusable oracle + assertion helpers emitted verbatim into every generated
/// write-containment file. Byte-union and exact-cell resolution live in the
/// shipped Context API; `containment_verdict` independently mirrors that
/// algorithm in this crate's tests.
const CONTAINMENT_HELPERS: &str = r#"use hopper::context::Context;
use hopper::hopper_runtime::segment_borrow::AccessKind;

/// Outcome of folding an instruction's touch-map ledger against its installed
/// (declared) write policy.
#[derive(Debug, PartialEq, Eq)]
enum Containment {
    /// Every byte of every recorded write touch is covered by the union of
    /// the declared ranges.
    Contained,
    /// A write touch put at least one byte outside every declared range.
    Violation { account_index: u8, offset: u32, size: u32 },
    /// The touch map overflowed: the footprint is partial, so containment is
    /// inconclusive and MUST NOT be treated as a pass.
    Inconclusive,
    /// `strict_writes` was expected but no policy was installed on the ctx.
    NoPolicy,
}

/// Declared-vs-actual oracle. Reuses the shipped `WritePolicy` (declared) and
/// the touch-map ledger (actual), zero instrumentation in the program. The
/// Context folds static ranges together with the invocation-selected exact
/// cells using the selector values bound by the runtime gate.
fn evaluate_containment(ctx: &Context<'_>) -> Containment {
    // Overflow first: a partial ledger can never certify containment.
    if ctx.touch_map_overflowed() {
        return Containment::Inconclusive;
    }
    if ctx.write_policy().is_none() {
        return Containment::NoPolicy;
    }
    let accounts = ctx.accounts();
    let mut verdict = Containment::Contained;
    ctx.for_each_touch(|t| {
        // Reads are never write-policy-gated.
        if t.kind != AccessKind::Write {
            return;
        }
        // Report the first violation; later touches don't override it.
        if verdict != Containment::Contained {
            return;
        }
        let touched = t.key.to_bytes();
        let idx = accounts
            .iter()
            .position(|a| a.address().to_bytes() == touched);
        match idx {
            Some(i) if i <= u8::MAX as usize => {
                if ctx
                    .first_unauthorized_write_byte(i, t.offset, t.size)
                    .is_some()
                {
                    verdict = Containment::Violation {
                        account_index: i as u8,
                        offset: t.offset,
                        size: t.size,
                    };
                }
            }
            // A write on an account the ctx can't resolve, or beyond the u8
            // index space, can never be a declared range: it is a violation.
            _ => {
                verdict = Containment::Violation {
                    account_index: u8::MAX,
                    offset: t.offset,
                    size: t.size,
                };
            }
        }
    });
    verdict
}

/// Panic with a precise message unless every actual write is contained.
fn assert_writes_contained(instruction: &str, ctx: &Context<'_>) {
    match evaluate_containment(ctx) {
        Containment::Contained => {}
        Containment::Inconclusive => panic!(
            "{instruction}: touch map overflowed, the instruction touched more than \
             MAX_TOUCH_RECORDS pairwise-unmergeable byte ranges (contiguous ranges \
             coalesce automatically, so this means genuinely scattered access), the \
             write footprint is PARTIAL, and containment is INCONCLUSIVE; split the \
             instruction rather than accept a false pass"
        ),
        Containment::NoPolicy => panic!(
            "{instruction}: no write policy installed; this test was generated for a \
             `strict_writes` instruction but the bound context installed no policy"
        ),
        Containment::Violation {
            account_index,
            offset,
            size,
        } => panic!(
            "{instruction}: write [{offset}, {offset}+{size}) on account {account_index} \
             ESCAPES the declared strict_writes WritePolicy (declared-vs-actual mismatch)"
        ),
    }
}
"#;

fn write_containment_matrix(manifest: &ProgramManifest) -> String {
    let mut out = String::new();
    out.push_str("//! Generated by `hopper test-gen write-containment`.\n");
    out.push_str("//!\n");
    out.push_str(
        "//! Write-containment property tests: every actual write touch recorded by the\n",
    );
    out.push_str("//! `touch-map` ledger must be contained in the instruction's declared\n");
    out.push_str("//! `strict_writes` `WritePolicy`. The installed policy is the SAME static\n");
    out.push_str(
        "//! envelopes plus invocation-selected exact cells the macro compiles from the\n",
    );
    out.push_str("//! context declarations (published in `write_ranges` and\n");
    out.push_str(
        "//! `parametric_write_ranges`), so this is a true declared-vs-actual guarantee.\n",
    );
    out.push_str("//!\n");
    out.push_str(
        "//! Requires the `touch-map` feature. For each instruction below, implement the\n",
    );
    out.push_str("//! `drive_*` fixture hook to build account fixtures, bind the\n");
    out.push_str(
        "//! `#[hopper::context(strict_writes)]` context, run the handler, and hand the\n",
    );
    out.push_str(
        "//! resulting raw `hopper::context::Context` to `check`. Tests are `#[ignore]`d\n",
    );
    out.push_str("//! until their fixture is wired.\n");
    out.push_str("#![cfg(feature = \"touch-map\")]\n");
    out.push_str("#![allow(dead_code)]\n\n");
    out.push_str(CONTAINMENT_HELPERS);
    out.push('\n');

    let mut emitted = 0usize;
    let mut skipped: Vec<&str> = Vec::new();
    for ix in manifest.instructions {
        if !instruction_declares_strict_writes(ix) {
            skipped.push(ix.name);
            continue;
        }
        emitted += 1;
        out.push_str(&emit_instruction_test(ix));
    }

    if emitted == 0 {
        out.push_str(
            "// No instruction in this manifest declares `strict_writes`, so no\n\
             // write-containment tests were generated. This is expected: the guarantee\n\
             // only applies to instructions that opt into byte-range write policies.\n",
        );
        out.push_str("#[test]\nfn no_strict_writes_instructions() {\n");
        out.push_str("    // Placeholder so the generated file has at least one item.\n");
        out.push_str("}\n\n");
    }

    // Document the contract: instructions WITHOUT strict_writes get no test.
    if !skipped.is_empty() {
        out.push_str("// Instructions WITHOUT `strict_writes` (no containment test emitted):\n");
        for name in skipped {
            out.push_str(&format!("//   - {name}\n"));
        }
    }
    out
}

/// Emit the fixture hook + `#[test]` for one `strict_writes` instruction,
/// including a doc comment enumerating its declared write ranges (the
/// manifest's published `WritePolicy`, for the reader's reference, the test
/// itself checks against the runtime-installed policy).
fn emit_instruction_test(ix: &InstructionDescriptor) -> String {
    let base = sanitize(ix.name);
    let name = ix.name;
    let mut out = String::new();

    out.push_str(&format!(
        "/// Drive `{name}` through its bound `strict_writes` context and hand the raw\n"
    ));
    out.push_str("/// context (touch map + installed write policy) to `check`.\n");
    out.push_str("///\n/// Declared write ranges (from the manifest `WritePolicy`):\n");
    if ix.write_ranges.is_empty() {
        out.push_str(
            "///   (none; an empty policy denies every Context-mediated write,\n\
             ///    i.e. a machine-checked read-only instruction)\n",
        );
    } else {
        for r in ix.write_ranges {
            out.push_str(&format!(
                "///   - account {}: [{}, {}+{})\n",
                r.account_index, r.offset, r.offset, r.size
            ));
        }
    }
    if !ix.parametric_write_ranges.is_empty() {
        out.push_str("///\n/// Invocation-parametric exact-cell rules:\n");
        for rule in ix.parametric_write_ranges {
            out.push_str(&format!(
                "///   - account {} segment `{}`: base={}, stride={}, size={}, count={}, selector `{}`[{}]\n",
                rule.account_index,
                rule.segment_name,
                rule.base_offset,
                rule.stride,
                rule.cell_size,
                rule.count,
                rule.argument_name,
                rule.argument_index,
            ));
        }
    }
    out.push_str(&format!(
        "///\n/// TODO(fixture): build fixtures, bind the strict_writes context, run the\n\
         /// `{name}` handler, then call `check(bound.raw())`.\n"
    ));
    out.push_str(&format!(
        "fn drive_{base}(check: impl FnOnce(&Context<'_>)) {{\n"
    ));
    out.push_str("    let _ = check;\n");
    out.push_str(&format!(
        "    unimplemented!(\"wire the `{name}` strict_writes fixture\");\n"
    ));
    out.push_str("}\n\n");
    out.push_str(&format!(
        "#[test]\n#[ignore = \"implement drive_{base}(): bind strict_writes ctx, run handler\"]\n"
    ));
    out.push_str(&format!("fn write_containment_{base}() {{\n"));
    out.push_str(&format!(
        "    drive_{base}(|ctx| assert_writes_contained(\"{name}\", ctx));\n"
    ));
    out.push_str("}\n\n");
    out
}

/// Whether `ix` opts into byte-range write policies (`strict_writes`).
///
/// Reads the manifest's first-class `strict_writes` flag, which the
/// `#[hopper::context(strict_writes)]` macro sets alongside the published
/// `write_ranges`. Instructions without it are provably outside the
/// containment guarantee and get no generated test.
fn instruction_declares_strict_writes(ix: &InstructionDescriptor) -> bool {
    ix.strict_writes
}

fn sanitize(value: &str) -> String {
    value
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || ch == '_' {
                ch
            } else {
                '-'
            }
        })
        .collect()
}

// ── Tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use hopper_schema::{InstructionDescriptor, ParametricWriteRange, ProgramManifest, WriteRange};

    const fn ix(
        name: &'static str,
        strict_writes: bool,
        write_ranges: &'static [WriteRange],
    ) -> InstructionDescriptor {
        ix_with_parametric(name, strict_writes, write_ranges, &[])
    }

    const fn ix_with_parametric(
        name: &'static str,
        strict_writes: bool,
        write_ranges: &'static [WriteRange],
        parametric_write_ranges: &'static [ParametricWriteRange],
    ) -> InstructionDescriptor {
        InstructionDescriptor {
            name,
            tag: 0,
            discriminator: &[0],
            args: &[],
            accounts: &[],
            remaining_accounts: None,
            capabilities: &[],
            policy_pack: "",
            receipt_expected: false,
            strict_writes,
            write_ranges,
            parametric_write_ranges,
            mutation_complete: false,
            lamport_accounts: &[],
            cu_estimate: 0,
        }
    }

    const fn manifest(instructions: &'static [InstructionDescriptor]) -> ProgramManifest {
        ProgramManifest {
            name: "demo",
            version: "0.0.0",
            description: "",
            layouts: &[],
            layout_metadata: &[],
            instructions,
            events: &[],
            policies: &[],
            compatibility_pairs: &[],
            tooling_hints: &[],
            contexts: &[],
        }
    }

    // ---- gating: strict_writes detection ---------------------------------

    #[test]
    fn strict_writes_flag_gates_generation() {
        let strict = ix("deposit", true, &[]);
        let plain = ix("peek", false, &[]);
        assert!(instruction_declares_strict_writes(&strict));
        assert!(!instruction_declares_strict_writes(&plain));
    }

    // ---- emitted source shape --------------------------------------------

    #[test]
    fn emitted_source_has_containment_assertions_for_strict_writes_ix() {
        static RANGES: &[WriteRange] = &[WriteRange::new(1, 16, 8), WriteRange::new(1, 24, 8)];
        static IXS: &[InstructionDescriptor] =
            &[ix("deposit", true, RANGES), ix("peek", false, &[])];
        static M: ProgramManifest = manifest(IXS);
        let src = write_containment_matrix(&M);

        // The oracle + assertion helpers are present. Coverage is judged per
        // byte against the union of declared ranges (coalesced touch records
        // may legitimately span adjacent declarations).
        assert!(src.contains("fn evaluate_containment(ctx: &Context<'_>) -> Containment"));
        assert!(src.contains("fn assert_writes_contained(instruction: &str, ctx: &Context<'_>)"));
        assert!(src.contains("first_unauthorized_write_byte(i, t.offset, t.size)"));
        // Overflow is surfaced as inconclusive, never a silent pass.
        assert!(src.contains("touch_map_overflowed()"));
        assert!(src.contains("INCONCLUSIVE"));

        // A per-instruction test + fixture hook exists for the strict_writes ix.
        assert!(src.contains("fn write_containment_deposit()"));
        assert!(src.contains("fn drive_deposit(check: impl FnOnce(&Context<'_>))"));
        assert!(src.contains("assert_writes_contained(\"deposit\", ctx)"));

        // The declared ranges are documented in the emitted source.
        assert!(src.contains("account 1: [16, 16+8)"));
        assert!(src.contains("account 1: [24, 24+8)"));

        // The non-strict_writes instruction gets NO test, and is documented.
        assert!(!src.contains("fn write_containment_peek()"));
        assert!(src.contains("Instructions WITHOUT `strict_writes`"));
        assert!(src.contains("//   - peek"));
    }

    #[test]
    fn emitted_oracle_uses_bound_parametric_selectors() {
        static RANGES: &[WriteRange] = &[WriteRange::new(1, 100, 20 * 8)];
        static PARAMETRIC: &[ParametricWriteRange] = &[ParametricWriteRange::new(
            1, 100, 8, 8, 20, 0, "slot", "balances",
        )];
        static IXS: &[InstructionDescriptor] =
            &[ix_with_parametric("claim", true, RANGES, PARAMETRIC)];
        static M: ProgramManifest = manifest(IXS);
        let src = write_containment_matrix(&M);

        assert!(src.contains("first_unauthorized_write_byte(i, t.offset, t.size)"));
        assert!(!src.contains("first_uncovered_byte(policy.allows"));
        assert!(src.contains("segment `balances`: base=100, stride=8, size=8, count=20"));
        assert!(src.contains("selector `slot`[0]"));
    }

    #[test]
    fn empty_policy_strict_writes_ix_documents_read_only_contract() {
        static IXS: &[InstructionDescriptor] = &[ix("freeze", true, &[])];
        static M: ProgramManifest = manifest(IXS);
        let src = write_containment_matrix(&M);
        assert!(src.contains("fn write_containment_freeze()"));
        assert!(src.contains("machine-checked read-only instruction"));
    }

    #[test]
    fn emitted_source_documents_when_no_strict_writes_instructions() {
        static IXS: &[InstructionDescriptor] = &[ix("peek", false, &[])];
        static M: ProgramManifest = manifest(IXS);
        let src = write_containment_matrix(&M);
        assert!(src.contains("No instruction in this manifest declares `strict_writes`"));
        assert!(src.contains("fn no_strict_writes_instructions()"));
        assert!(!src.contains("fn write_containment_"));
    }

    #[test]
    fn emitted_source_is_gated_on_touch_map_feature() {
        static IXS: &[InstructionDescriptor] = &[ix("deposit", true, &[])];
        static M: ProgramManifest = manifest(IXS);
        let src = write_containment_matrix(&M);
        assert!(src.contains("#![cfg(feature = \"touch-map\")]"));
    }

    // ---- assertion-logic proof (synthesized touch-vs-policy mismatch) ----
    //
    // `containment_verdict` is the textual twin of the emitted
    // `evaluate_containment`: same overflow-first ordering, same per-byte
    // union-coverage judgement ("first write touch with an uncovered byte =>
    // Violation"), same read-skip. Testing it here proves the emitted
    // assertion actually catches a violation, without standing up a full
    // on-chain fixture. Coverage is against the UNION of the declared
    // ranges, not per-declaration containment, because the touch ledger
    // coalesces adjacent records under capacity pressure: one record may be
    // the exact union of several individually-gated acquires.

    #[derive(Debug, PartialEq, Eq)]
    enum Verdict {
        Contained,
        Violation {
            account_index: u8,
            offset: u32,
            size: u32,
        },
        Inconclusive,
        NoPolicy,
    }

    /// Independent twin of the runtime's invocation-resolved containment
    /// walk, over the same range/rule shapes the manifest publishes.
    fn first_uncovered_byte(
        ranges: &[WriteRange],
        parametric: &[ParametricWriteRange],
        args: &[u32],
        account_index: u8,
        start: u64,
        end: u64,
    ) -> Option<u64> {
        let mut cursor = start;
        while cursor < end {
            let mut governing_rule = None;
            for rule in parametric {
                if rule.account_index != account_index {
                    continue;
                }
                let envelope_start = rule.base_offset as u64;
                let envelope_end = envelope_start
                    + rule.stride as u64 * rule.count.saturating_sub(1) as u64
                    + rule.cell_size as u64;
                if envelope_start <= cursor && cursor < envelope_end {
                    governing_rule = Some(rule);
                    break;
                }
            }
            if let Some(rule) = governing_rule {
                let Some(selected) = args.get(rule.argument_index as usize).copied() else {
                    return Some(cursor);
                };
                if selected >= rule.count {
                    return Some(cursor);
                }
                let selected_start = rule.base_offset as u64 + rule.stride as u64 * selected as u64;
                let selected_end = selected_start + rule.cell_size as u64;
                if selected_start <= cursor && cursor < selected_end {
                    cursor = selected_end.min(end);
                    continue;
                }
                return Some(cursor);
            }

            let mut covered_until = cursor;
            for r in ranges {
                if r.account_index != account_index {
                    continue;
                }
                let r_start = r.offset as u64;
                let r_end = r.offset as u64 + r.size as u64;
                if r_start <= cursor && cursor < r_end {
                    covered_until = covered_until.max(r_end);
                }
            }
            if covered_until == cursor {
                return Some(cursor);
            }
            for rule in parametric {
                let envelope_start = rule.base_offset as u64;
                if rule.account_index == account_index
                    && cursor < envelope_start
                    && envelope_start < covered_until
                {
                    covered_until = envelope_start;
                }
            }
            cursor = covered_until.min(end);
        }
        None
    }

    /// A recorded touch: (account_index, offset, size, is_write).
    fn containment_verdict(
        overflowed: bool,
        policy: Option<&[WriteRange]>,
        touches: &[(u8, u32, u32, bool)],
    ) -> Verdict {
        containment_verdict_with_args(overflowed, policy, &[], &[], touches)
    }

    fn containment_verdict_with_args(
        overflowed: bool,
        policy: Option<&[WriteRange]>,
        parametric: &[ParametricWriteRange],
        args: &[u32],
        touches: &[(u8, u32, u32, bool)],
    ) -> Verdict {
        if overflowed {
            return Verdict::Inconclusive;
        }
        let ranges = match policy {
            Some(r) => r,
            None => return Verdict::NoPolicy,
        };
        for &(idx, offset, size, is_write) in touches {
            if !is_write {
                continue;
            }
            let start = offset as u64;
            let end = offset as u64 + size as u64;
            if first_uncovered_byte(ranges, parametric, args, idx, start, end).is_some() {
                return Verdict::Violation {
                    account_index: idx,
                    offset,
                    size,
                };
            }
        }
        Verdict::Contained
    }

    static POLICY: &[WriteRange] = &[WriteRange::new(1, 16, 8), WriteRange::new(1, 24, 8)];

    static PARAMETRIC_POLICY: &[WriteRange] = &[WriteRange::new(1, 100, 20 * 8)];
    static PARAMETRIC_RULES: &[ParametricWriteRange] = &[ParametricWriteRange::new(
        1, 100, 8, 8, 20, 0, "slot", "balances",
    )];

    #[test]
    fn invocation_selected_cell_is_contained_but_its_neighbor_is_not() {
        let selected = [(1u8, 100 + 7 * 8, 8u32, true)];
        assert_eq!(
            containment_verdict_with_args(
                false,
                Some(PARAMETRIC_POLICY),
                PARAMETRIC_RULES,
                &[7],
                &selected,
            ),
            Verdict::Contained
        );

        let neighbor = [(1u8, 100 + 8 * 8, 8u32, true)];
        assert_eq!(
            containment_verdict_with_args(
                false,
                Some(PARAMETRIC_POLICY),
                PARAMETRIC_RULES,
                &[7],
                &neighbor,
            ),
            Verdict::Violation {
                account_index: 1,
                offset: 100 + 8 * 8,
                size: 8,
            }
        );

        assert_eq!(
            containment_verdict_with_args(
                false,
                Some(PARAMETRIC_POLICY),
                PARAMETRIC_RULES,
                &[],
                &selected,
            ),
            Verdict::Violation {
                account_index: 1,
                offset: 100 + 7 * 8,
                size: 8,
            }
        );
    }

    #[test]
    fn all_declared_writes_are_contained() {
        let touches = [(1u8, 16u32, 8u32, true), (1, 24, 8, true), (1, 18, 4, true)];
        assert_eq!(
            containment_verdict(false, Some(POLICY), &touches),
            Verdict::Contained
        );
    }

    #[test]
    fn write_outside_declared_ranges_is_caught_as_violation() {
        // Writes balance [16,24), allowed, then a stray write at [0,8).
        let touches = [(1u8, 16u32, 8u32, true), (1, 0, 8, true)];
        assert_eq!(
            containment_verdict(false, Some(POLICY), &touches),
            Verdict::Violation {
                account_index: 1,
                offset: 0,
                size: 8
            }
        );
    }

    #[test]
    fn write_straddling_two_adjacent_ranges_is_covered_by_their_union() {
        // [16,32) is covered by the UNION of the two adjacent declarations.
        // The runtime gate still refuses a straddling ACQUIRE (per-range
        // `check_write`), but a straddling touch RECORD is legitimate: the
        // ledger coalesces adjacent records under pressure, so this record
        // may be the exact union of two individually-gated acquires. The
        // oracle audits bytes, and every byte here is declared.
        let touches = [(1u8, 16u32, 16u32, true)];
        assert_eq!(
            containment_verdict(false, Some(POLICY), &touches),
            Verdict::Contained
        );
    }

    #[test]
    fn write_spanning_a_gap_between_declarations_is_a_violation() {
        // The declarations leave [32, 40) undeclared; a touch running from
        // inside the declared span across that gap has uncovered bytes,
        // union coverage still catches every genuine escape.
        static GAPPED: &[WriteRange] = &[WriteRange::new(1, 16, 16), WriteRange::new(1, 40, 8)];
        let touches = [(1u8, 24u32, 20u32, true)];
        assert_eq!(
            containment_verdict(false, Some(GAPPED), &touches),
            Verdict::Violation {
                account_index: 1,
                offset: 24,
                size: 20
            }
        );
    }

    #[test]
    fn read_touches_are_never_policy_violations() {
        // A read outside every declared range is fine; only writes are gated.
        let touches = [(1u8, 0u32, 8u32, false), (1, 16, 8, true)];
        assert_eq!(
            containment_verdict(false, Some(POLICY), &touches),
            Verdict::Contained
        );
    }

    #[test]
    fn overflow_is_inconclusive_even_when_a_violation_is_present() {
        // A partial ledger must never certify containment, nor mask a violation
        // as a pass: it is reported as INCONCLUSIVE regardless of touches.
        let touches = [(1u8, 0u32, 8u32, true)];
        assert_eq!(
            containment_verdict(true, Some(POLICY), &touches),
            Verdict::Inconclusive
        );
    }

    #[test]
    fn missing_policy_is_surfaced_not_treated_as_pass() {
        let touches = [(1u8, 16u32, 8u32, true)];
        assert_eq!(
            containment_verdict(false, None, &touches),
            Verdict::NoPolicy
        );
    }

    #[test]
    fn wrong_account_write_is_a_violation() {
        // A write on account 2 with no declared range on account 2.
        let touches = [(2u8, 16u32, 8u32, true)];
        assert_eq!(
            containment_verdict(false, Some(POLICY), &touches),
            Verdict::Violation {
                account_index: 2,
                offset: 16,
                size: 8
            }
        );
    }
}