aver-cert 0.1.7

Independent artifact certificate engine and verifier for Aver WebAssembly
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
//! Stable, compiler-independent certificate format declarations.
//!
//! The producer imports this module from `aver-cert`; there is intentionally
//! no separate format crate. The verifier is the authority for this surface,
//! and the compiler depends on it in the non-trust-bearing direction.

/// Public certificate-package layout understood by this verifier.
pub const FORMAT_VERSION: u32 = 1;

/// Raw wasm-gc module artifact target admitted since schema 6.
pub const TARGET_WASM_GC: &str = "wasm-gc";

/// WASI 0.2 Component Model artifact target admitted since schema 6 through a
/// declared component envelope.
pub const TARGET_WASIP2: &str = "wasip2";

/// Only emitted-fragment profile admitted since schema 6.
pub const PROFILE_ID: &str = "AverUserProfile/v1";

/// Runtime ABI admitted for the wasm-gc artifact target since schema 6.
pub const RUNTIME_ABI_WASM_GC: &str = "aver-wasm-gc/0";

/// Runtime ABI admitted for wasip2 component certificates since schema 6.
pub const RUNTIME_ABI_WASIP2: &str = "aver-wasip2/0";

/// Top-level manifest field for a wasip2 component envelope declaration.
/// It is intentionally target-specific and is rejected for wasm-gc artifacts.
pub const WASIP2_COMPONENT_ENVELOPE_FIELD: &str = "wasip2ComponentEnvelope";

/// Field names inside the wasip2 component-envelope object.
pub const WASIP2_COMPONENT_ENVELOPE_KIND_FIELD: &str = "kind";
pub const WASIP2_COMPONENT_ENVELOPE_PREFIX_LEN_FIELD: &str = "prefix_len";
pub const WASIP2_COMPONENT_ENVELOPE_CORE_LEN_FIELD: &str = "embedded_core_module_len";
pub const WASIP2_COMPONENT_ENVELOPE_SUFFIX_LEN_FIELD: &str = "suffix_len";

/// Version tag for the declared `prefix ++ embedded_core_module ++ suffix`
/// component split.
pub const WASIP2_COMPONENT_ENVELOPE_KIND: &str = "prefix-core-suffix/v1";

/// Manifest-facing declaration of the wasip2 component envelope.
///
/// The declaration carries byte counts only. A verifier that consumes it must
/// slice the delivered component by these declared lengths and confirm equality
/// against the separately supplied declared bytes; it must not rediscover the
/// embedded core by parsing or navigating the delivered component.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Wasip2ComponentEnvelopeDeclaration {
    /// Bytes before the embedded Aver user-core module payload.
    pub prefix_len: u64,
    /// Bytes in the embedded Aver user-core module payload.
    pub embedded_core_module_len: u64,
    /// Bytes after the embedded Aver user-core module payload.
    pub suffix_len: u64,
}

impl Wasip2ComponentEnvelopeDeclaration {
    pub const fn from_lengths(
        prefix_len: u64,
        embedded_core_module_len: u64,
        suffix_len: u64,
    ) -> Self {
        Self {
            prefix_len,
            embedded_core_module_len,
            suffix_len,
        }
    }

    pub const fn kind(&self) -> &'static str {
        WASIP2_COMPONENT_ENVELOPE_KIND
    }

    pub fn component_len(&self) -> Option<u64> {
        self.prefix_len
            .checked_add(self.embedded_core_module_len)?
            .checked_add(self.suffix_len)
    }

    pub fn embedded_core_module_range(&self) -> Option<std::ops::Range<u64>> {
        let start = self.prefix_len;
        let end = start.checked_add(self.embedded_core_module_len)?;
        Some(start..end)
    }

    /// Split component bytes by declared lengths only. This helper does not
    /// inspect the bytes and is therefore suitable for the future trusted path,
    /// provided the caller also checks the returned slices against the declared
    /// byte sequences.
    pub fn split_component<'a>(
        &self,
        component: &'a [u8],
    ) -> Option<(&'a [u8], &'a [u8], &'a [u8])> {
        if self.embedded_core_module_len == 0 {
            return None;
        }
        let prefix_len = usize::try_from(self.prefix_len).ok()?;
        let core_len = usize::try_from(self.embedded_core_module_len).ok()?;
        let suffix_len = usize::try_from(self.suffix_len).ok()?;
        let core_end = prefix_len.checked_add(core_len)?;
        let declared_len = core_end.checked_add(suffix_len)?;
        if declared_len != component.len() {
            return None;
        }
        Some((
            &component[..prefix_len],
            &component[prefix_len..core_end],
            &component[core_end..],
        ))
    }
}

/// Manifest schema accepted by the standalone verifier. Version 2 made the
/// subject's `hostRoleTable` optional: modules without the Int box helper
/// declare `null`, pinned against a byte-derived proof of the helper's
/// absence, while modules with the helper pin the exact decoded table. A
/// module whose role scan the decoder cannot complete matches no manifest
/// value. The declared arith helper indices (carrier, limb, and the
/// decompose/normalize/strip/umagCmp sub-routines) are proof-term data in the
/// generated Lean certificate, not public JSON, so the acceptance pin can
/// confirm each declared helper body byte-for-byte — box and toIndex included,
/// alongside add/sub/mul — without moving the public schema. Version 3 added
/// the required `toIndex` key to the object form of `hostRoleTable`: the fused
/// vector-read face binds the `__aint_to_index` helper by its named function
/// export, exactly like `box`, and the exact-object manifest matching means a
/// version-2 table would reject every module carrying the helper. Version 4
/// added the required `cmp` and `eq` keys for the same reason: the two Int
/// value-comparison faces bind `__aint_cmp` and `__aint_eq` by their named
/// function exports, and because those two helpers declare the same function
/// type, the export name is the only thing that tells one role from the other.
/// Version 5 added the required top-level `target` field and moved the
/// target/profile/ABI identifiers into the checker-owned statement schema.
/// Version 6 added the wasip2 component-envelope byte binding used by the
/// producer's `--target wasip2 --certify` path. Version 7 added the required
/// top-level `laws` array — the certificate's law-claims surface: each entry
/// names a universal law theorem of the model modules together with its
/// verbatim statement and its `Laws.lean` corollary, and the checker-owned
/// witness re-elaborates every corollary at exactly the declared statement
/// and audits its axioms against the kernel whitelist. Version 8 added the
/// required top-level `sourceBridges` array and the required `bridges` key on
/// every `laws` entry — the plan-equals-source surface: one entry per export
/// whose obligation model is the declared plan, naming the theorem that
/// identifies that plan with the transpiled source function, the STRUCTURE the
/// checker renders that theorem's statement from (the export, the source
/// function, and one closed-form encoder per parameter and result), and the
/// corollary conjoining it with `Holds`, pinned and axiom-audited exactly the
/// way a law-claim is. A bridge entry carries no statement TEXT: a declared
/// statement need only pass the syntactic gates to be credited, and a
/// tautology passes all of them, so the checker writes the statement instead.
/// A law-claim listing bridges carries a second corollary conjoining them,
/// pinned apart from its own so an unfinished bridge cannot cost the law its
/// credit.
///
/// Schema 9 states every obligation over the one plan grammar: the manifest
/// carries one `fnPlans` list (each planned function's optimized MIR body,
/// printed 1:1), the declared type layout, and obligations the wall derives
/// from the plans. Every certified export reports the one class
/// [`PLAN_CLASS`] with facets derived in the wall. Schema 9 declares no
/// law-claims and no source bridges yet; a package declaring either is
/// refused.
pub const CERT_SCHEMA_VERSION: u32 = 9;

/// The one report class of a certified export (schema 9).
pub const PLAN_CLASS: &str = "source-plan-v1";

/// Longest a transported display string may be. Every declared-only candidate
/// the manifest carries — export names, class and domain labels, runtime
/// contracts, capability names, and the declared-uncertified reasons — is
/// gated on this length and on the printable ASCII subset before a verdict
/// prints it. The engine that WRITES a decline reason shares the constant with
/// the verifier that gates it, so a reason can never grow past the point where
/// the package stops checking.
pub const MAX_CANDIDATE_LEN: usize = 200;

/// Named theorem audited by the checker-owned witness.
pub const ARTIFACT_CERTIFICATE_ROOT: &str = "AverCert.Artifact.certificate";

/// The discharge theorem every certified export names (informational; the
/// acceptance consumes the single artifact root).
pub const FN_CLAIM_DISCHARGE_THEOREM: &str = "AcceptanceSoundness.fn_claim_discharges";

/// Identity of the exact checker-owned Lean wall shipped by this release.
pub const CURRENT_WALL_ID: &str =
    "sha256:7d577458dae255e1d07d57f7c70e51aabc376f7a5221ae9f661bf2d254eafb75";

/// Complete host-import surface admitted by the wasm-gc certificate format.
///
/// This list is verifier-owned. `aver-lang` tests its `EffectName` lowering and
/// its `aver:work/v1` job-scheduling imports against it, so adding a compiler
/// import cannot silently broaden what the independent verifier accepts.
pub const WASM_GC_CAPABILITIES: &[(&str, &str)] = &[
    ("aver", "console_print"),
    ("aver", "console_error"),
    ("aver", "console_warn"),
    ("aver", "time_unix_ms"),
    ("aver", "process_stop_requested"),
    ("aver", "provider_contract_violation"),
    ("aver", "request_method"),
    ("aver", "request_url"),
    ("aver", "request_query"),
    ("aver", "request_body"),
    ("aver", "request_headers_load"),
    ("aver", "response_text"),
    ("aver", "response_set_header"),
    ("aver", "http_send"),
    ("aver", "http_add_request_header"),
    ("aver", "http_clear_request_headers"),
    ("aver", "env_get"),
    ("aver", "env_set"),
    ("aver", "console_read_line"),
    ("aver", "args_len"),
    ("aver", "args_get"),
    ("aver", "random_float"),
    ("aver", "random_int"),
    ("aver", "time_sleep"),
    ("aver", "time_now"),
    ("aver", "float_sin"),
    ("aver", "float_cos"),
    ("aver", "float_atan2"),
    ("aver", "float_pow"),
    ("aver", "terminal_enable_raw_mode"),
    ("aver", "terminal_disable_raw_mode"),
    ("aver", "terminal_clear"),
    ("aver", "terminal_move_to"),
    ("aver", "terminal_print"),
    ("aver", "terminal_set_color"),
    ("aver", "terminal_reset_color"),
    ("aver", "terminal_read_key"),
    ("aver", "terminal_size"),
    ("aver", "terminal_hide_cursor"),
    ("aver", "terminal_show_cursor"),
    ("aver", "terminal_flush"),
    ("aver", "disk_read_text"),
    ("aver", "disk_write_text"),
    ("aver", "disk_append_text"),
    ("aver", "disk_read_bytes"),
    ("aver", "disk_read_bytes_at"),
    ("aver", "disk_write_bytes"),
    ("aver", "disk_append_bytes"),
    ("aver", "disk_size"),
    ("aver", "disk_exists"),
    ("aver", "disk_delete"),
    ("aver", "disk_delete_dir"),
    ("aver", "disk_list_dir"),
    ("aver", "disk_make_dir"),
    ("aver", "disk_sync"),
    ("aver", "tcp_connect"),
    ("aver", "tcp_begin_connect"),
    ("aver", "tcp_dialled"),
    ("aver", "tcp_listen"),
    ("aver", "tcp_accept"),
    ("aver", "tcp_peer_address"),
    ("aver", "tcp_write_line"),
    ("aver", "tcp_write_bytes"),
    ("aver", "tcp_write_now"),
    ("aver", "tcp_read_line"),
    ("aver", "tcp_read_bytes"),
    ("aver", "tcp_read_some"),
    ("aver", "tcp_read_now"),
    ("aver", "tcp_poll"),
    ("aver", "tcp_close"),
    ("aver", "tcp_close_dial"),
    ("aver", "tcp_close_listener"),
    ("aver", "tcp_send"),
    ("aver", "tcp_send_bytes"),
    ("aver", "tcp_ping"),
    ("aver", "http_get"),
    ("aver", "http_head"),
    ("aver", "http_delete"),
    ("aver", "http_post"),
    ("aver", "http_put"),
    ("aver", "http_patch"),
    ("aver", "record_enter_group"),
    ("aver", "record_set_branch"),
    ("aver", "record_exit_group"),
    ("aver", "wait_poll"),
    ("aver", "work_cancel"),
    ("aver", "work_begin"),
    ("aver", "work_take"),
    ("aver", "run_fail"),
    ("aver", "run_failure"),
    ("aver", "run_wait_starts"),
    ("aver", "run_wait_ends"),
    ("aver", "run_last_turn"),
    ("aver:work/v1", "submit"),
    ("aver:work/v1", "take"),
    ("aver:work/v1", "task"),
    ("aver:work/v1", "complete"),
];

/// Complete standard host-import surface admitted for a wasip2 embedded core.
///
/// The list mirrors the compiler's exhaustive `Wasip2ImportSlot` enum. Exact
/// interface versions and canonical-ABI operation names are part of the
/// certificate boundary; no broad `wasi:*` prefix is accepted.
pub const WASIP2_CAPABILITIES: &[(&str, &str)] = &[
    ("wasi:cli/stdout@0.2.4", "get-stdout"),
    ("wasi:cli/stderr@0.2.4", "get-stderr"),
    (
        "wasi:io/streams@0.2.4",
        "[method]output-stream.blocking-write-and-flush",
    ),
    ("wasi:clocks/wall-clock@0.2.4", "now"),
    ("wasi:random/random@0.2.4", "get-random-u64"),
    ("wasi:cli/environment@0.2.4", "get-arguments"),
    ("wasi:cli/environment@0.2.4", "get-environment"),
    ("wasi:cli/stdin@0.2.4", "get-stdin"),
    (
        "wasi:io/streams@0.2.4",
        "[method]input-stream.blocking-read",
    ),
    ("wasi:io/streams@0.2.4", "[method]input-stream.subscribe"),
    ("wasi:io/streams@0.2.4", "[method]input-stream.read"),
    ("wasi:io/streams@0.2.4", "[method]output-stream.check-write"),
    ("wasi:io/streams@0.2.4", "[method]output-stream.write"),
    ("wasi:io/streams@0.2.4", "[method]output-stream.flush"),
    ("wasi:io/streams@0.2.4", "[method]output-stream.subscribe"),
    ("wasi:clocks/monotonic-clock@0.2.4", "subscribe-duration"),
    ("wasi:io/poll@0.2.4", "poll"),
    ("wasi:io/poll@0.2.4", "[resource-drop]pollable"),
    ("wasi:filesystem/preopens@0.2.4", "get-directories"),
    ("wasi:filesystem/types@0.2.4", "[method]descriptor.stat-at"),
    ("wasi:filesystem/types@0.2.4", "[method]descriptor.open-at"),
    (
        "wasi:filesystem/types@0.2.4",
        "[method]descriptor.read-via-stream",
    ),
    ("wasi:filesystem/types@0.2.4", "[resource-drop]descriptor"),
    ("wasi:io/streams@0.2.4", "[resource-drop]input-stream"),
    (
        "wasi:filesystem/types@0.2.4",
        "[method]descriptor.write-via-stream",
    ),
    ("wasi:io/streams@0.2.4", "[resource-drop]output-stream"),
    (
        "wasi:filesystem/types@0.2.4",
        "[method]descriptor.unlink-file-at",
    ),
    (
        "wasi:filesystem/types@0.2.4",
        "[method]descriptor.remove-directory-at",
    ),
    (
        "wasi:filesystem/types@0.2.4",
        "[method]descriptor.create-directory-at",
    ),
    ("wasi:filesystem/types@0.2.4", "[method]descriptor.sync"),
    (
        "wasi:filesystem/types@0.2.4",
        "[method]descriptor.append-via-stream",
    ),
    (
        "wasi:filesystem/types@0.2.4",
        "[method]descriptor.read-directory",
    ),
    (
        "wasi:filesystem/types@0.2.4",
        "[method]directory-entry-stream.read-directory-entry",
    ),
    (
        "wasi:filesystem/types@0.2.4",
        "[resource-drop]directory-entry-stream",
    ),
    ("wasi:http/types@0.2.4", "[constructor]fields"),
    ("wasi:http/types@0.2.4", "[constructor]outgoing-request"),
    (
        "wasi:http/types@0.2.4",
        "[method]outgoing-request.set-scheme",
    ),
    (
        "wasi:http/types@0.2.4",
        "[method]outgoing-request.set-authority",
    ),
    (
        "wasi:http/types@0.2.4",
        "[method]outgoing-request.set-path-with-query",
    ),
    ("wasi:http/outgoing-handler@0.2.4", "handle"),
    (
        "wasi:http/types@0.2.4",
        "[method]future-incoming-response.subscribe",
    ),
    (
        "wasi:http/types@0.2.4",
        "[method]future-incoming-response.get",
    ),
    ("wasi:http/types@0.2.4", "[method]incoming-response.status"),
    ("wasi:http/types@0.2.4", "[method]incoming-response.consume"),
    ("wasi:http/types@0.2.4", "[method]incoming-body.stream"),
    ("wasi:http/types@0.2.4", "[static]incoming-body.finish"),
    ("wasi:http/types@0.2.4", "[resource-drop]outgoing-request"),
    (
        "wasi:http/types@0.2.4",
        "[resource-drop]future-incoming-response",
    ),
    ("wasi:http/types@0.2.4", "[resource-drop]incoming-response"),
    ("wasi:http/types@0.2.4", "[resource-drop]future-trailers"),
    ("wasi:http/types@0.2.4", "[resource-drop]incoming-body"),
    ("wasi:http/types@0.2.4", "[method]incoming-response.headers"),
    ("wasi:http/types@0.2.4", "[method]fields.entries"),
    ("wasi:http/types@0.2.4", "[resource-drop]fields"),
    (
        "wasi:http/types@0.2.4",
        "[method]outgoing-request.set-method",
    ),
    ("wasi:http/types@0.2.4", "[method]outgoing-request.body"),
    ("wasi:http/types@0.2.4", "[method]outgoing-body.write"),
    ("wasi:http/types@0.2.4", "[static]outgoing-body.finish"),
    ("wasi:http/types@0.2.4", "[method]fields.append"),
    ("wasi:http/types@0.2.4", "[resource-drop]outgoing-body"),
    ("wasi:http/types@0.2.4", "[method]incoming-request.method"),
    (
        "wasi:http/types@0.2.4",
        "[method]incoming-request.path-with-query",
    ),
    ("wasi:http/types@0.2.4", "[method]incoming-request.headers"),
    ("wasi:http/types@0.2.4", "[method]incoming-request.consume"),
    ("wasi:http/types@0.2.4", "[resource-drop]incoming-request"),
    ("wasi:http/types@0.2.4", "[constructor]outgoing-response"),
    (
        "wasi:http/types@0.2.4",
        "[method]outgoing-response.set-status-code",
    ),
    ("wasi:http/types@0.2.4", "[method]outgoing-response.body"),
    ("wasi:http/types@0.2.4", "[static]response-outparam.set"),
    ("wasi:sockets/instance-network@0.2.4", "instance-network"),
    ("wasi:sockets/ip-name-lookup@0.2.4", "resolve-addresses"),
    (
        "wasi:sockets/ip-name-lookup@0.2.4",
        "[method]resolve-address-stream.resolve-next-address",
    ),
    (
        "wasi:sockets/ip-name-lookup@0.2.4",
        "[method]resolve-address-stream.subscribe",
    ),
    (
        "wasi:sockets/ip-name-lookup@0.2.4",
        "[resource-drop]resolve-address-stream",
    ),
    ("wasi:sockets/tcp-create-socket@0.2.4", "create-tcp-socket"),
    ("wasi:sockets/tcp@0.2.4", "[method]tcp-socket.start-connect"),
    (
        "wasi:sockets/tcp@0.2.4",
        "[method]tcp-socket.finish-connect",
    ),
    ("wasi:sockets/tcp@0.2.4", "[method]tcp-socket.subscribe"),
    ("wasi:sockets/tcp@0.2.4", "[method]tcp-socket.shutdown"),
    ("wasi:sockets/tcp@0.2.4", "[resource-drop]tcp-socket"),
];

/// Whether an import belongs to the exact standard/custom capability surface
/// admitted for the manifest target.
pub fn is_capability_import_for_target(target: &str, module: &str, field: &str) -> bool {
    let standard = match target {
        TARGET_WASM_GC => WASM_GC_CAPABILITIES.contains(&(module, field)),
        TARGET_WASIP2 => WASIP2_CAPABILITIES.contains(&(module, field)),
        _ => return false,
    };
    standard || is_custom_capability_import(module, field)
}

/// Whether a raw wasm-gc import is part of the certificate's admitted host
/// surface. Compiler-shipped effects use the finite table above. Program-
/// defined capabilities use a deterministic contract-derived namespace:
/// `aver:user/cap-n<module-utf8-hex>-c<sha256>` and
/// `op-n<operation-utf8-hex>`.
pub fn is_wasm_gc_capability_import(module: &str, field: &str) -> bool {
    is_capability_import_for_target(TARGET_WASM_GC, module, field)
}

/// Whether an import belongs to the exact wasip2 capability surface.
pub fn is_wasip2_capability_import(module: &str, field: &str) -> bool {
    is_capability_import_for_target(TARGET_WASIP2, module, field)
}

fn is_custom_capability_import(module: &str, field: &str) -> bool {
    const MODULE_PREFIX: &str = "aver:user/cap-n";
    const OP_PREFIX: &str = "op-n";

    let Some(module_tail) = module.strip_prefix(MODULE_PREFIX) else {
        return false;
    };
    let Some((module_hex, contract_hash)) = module_tail.split_once("-c") else {
        return false;
    };
    let Some(operation_hex) = field.strip_prefix(OP_PREFIX) else {
        return false;
    };

    is_nonempty_even_lower_hex(module_hex)
        && contract_hash.len() == 64
        && is_lower_hex(contract_hash)
        && is_nonempty_even_lower_hex(operation_hex)
}

fn is_nonempty_even_lower_hex(value: &str) -> bool {
    !value.is_empty() && value.len().is_multiple_of(2) && is_lower_hex(value)
}

fn is_lower_hex(value: &str) -> bool {
    value
        .bytes()
        .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn wasip2_envelope_surface_names_component_binding() {
        assert_eq!(TARGET_WASM_GC, "wasm-gc");
        assert_eq!(TARGET_WASIP2, "wasip2");
        assert_eq!(RUNTIME_ABI_WASM_GC, "aver-wasm-gc/0");
        assert_eq!(RUNTIME_ABI_WASIP2, "aver-wasip2/0");
        assert_eq!(WASIP2_COMPONENT_ENVELOPE_FIELD, "wasip2ComponentEnvelope");
        assert_eq!(WASIP2_COMPONENT_ENVELOPE_KIND_FIELD, "kind");
        assert_eq!(WASIP2_COMPONENT_ENVELOPE_PREFIX_LEN_FIELD, "prefix_len");
        assert_eq!(
            WASIP2_COMPONENT_ENVELOPE_CORE_LEN_FIELD,
            "embedded_core_module_len"
        );
        assert_eq!(WASIP2_COMPONENT_ENVELOPE_SUFFIX_LEN_FIELD, "suffix_len");
        assert_eq!(WASIP2_COMPONENT_ENVELOPE_KIND, "prefix-core-suffix/v1");
        assert_eq!(CERT_SCHEMA_VERSION, 9);
    }

    #[test]
    fn wasip2_component_envelope_declaration_splits_by_declared_lengths_only() {
        let declaration = Wasip2ComponentEnvelopeDeclaration::from_lengths(2, 3, 1);
        assert_eq!(declaration.kind(), WASIP2_COMPONENT_ENVELOPE_KIND);
        assert_eq!(declaration.component_len(), Some(6));
        assert_eq!(declaration.embedded_core_module_range(), Some(2..5));

        let (prefix, core, suffix) = declaration
            .split_component(b"abcdef")
            .expect("declared lengths match the component");
        assert_eq!(prefix, b"ab");
        assert_eq!(core, b"cde");
        assert_eq!(suffix, b"f");

        assert!(
            Wasip2ComponentEnvelopeDeclaration::from_lengths(2, 0, 1)
                .split_component(b"abc")
                .is_none(),
            "an empty embedded core declaration is not meaningful"
        );
        assert!(
            Wasip2ComponentEnvelopeDeclaration::from_lengths(2, 2, 0)
                .split_component(b"abc")
                .is_none(),
            "the declaration must account for the whole delivered component"
        );
        assert_eq!(
            Wasip2ComponentEnvelopeDeclaration::from_lengths(u64::MAX, 1, 0).component_len(),
            None,
            "length overflow must fail closed"
        );
    }

    #[test]
    fn capability_pairs_are_unique() {
        assert_eq!(WASIP2_CAPABILITIES.len(), 80);
        for registry in [WASM_GC_CAPABILITIES, WASIP2_CAPABILITIES] {
            let unique = registry
                .iter()
                .copied()
                .collect::<std::collections::BTreeSet<_>>();
            assert_eq!(unique.len(), registry.len());
        }
    }

    #[test]
    fn standard_capability_imports_are_target_specific_and_version_exact() {
        let wasi_pair = ("wasi:cli/stdout@0.2.4", "get-stdout");
        assert!(is_wasip2_capability_import(wasi_pair.0, wasi_pair.1));
        assert!(!is_wasm_gc_capability_import(wasi_pair.0, wasi_pair.1));
        assert!(!is_wasip2_capability_import(
            "wasi:cli/stdout@0.2.5",
            wasi_pair.1
        ));
        assert!(!is_wasip2_capability_import(
            "wasi:cli/unknown@0.2.4",
            wasi_pair.1
        ));
        assert!(!is_wasip2_capability_import(
            wasi_pair.0,
            "unknown-operation"
        ));

        let wasm_gc_pair = ("aver", "console_print");
        assert!(is_wasm_gc_capability_import(wasm_gc_pair.0, wasm_gc_pair.1));
        assert!(!is_wasip2_capability_import(wasm_gc_pair.0, wasm_gc_pair.1));
    }

    #[test]
    fn custom_capability_import_syntax_is_exact() {
        let hash = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
        assert!(is_wasm_gc_capability_import(
            &format!("aver:user/cap-n436c6f636b-c{hash}"),
            "op-n6e6f77"
        ));
        assert!(is_wasip2_capability_import(
            &format!("aver:user/cap-n436c6f636b-c{hash}"),
            "op-n6e6f77"
        ));
        for (module, field) in [
            (format!("aver:user/cap-n-c{hash}"), "op-n6e6f77"),
            (format!("aver:user/cap-n436c6f636b-c{hash}0"), "op-n6e6f77"),
            (format!("aver:user/cap-n436C6f636b-c{hash}"), "op-n6e6f77"),
            (format!("aver:user/cap-n436c6f636b-c{hash}"), "op-n"),
            (format!("aver:user/cap-n436c6f636b-c{hash}"), "op-nxyz"),
        ] {
            assert!(!is_wasm_gc_capability_import(&module, field));
        }
    }

    /// The format specification (`docs/certificate-format.md`) prints the wall
    /// identity and the wall source count verbatim; both are hand-written and
    /// silently go stale when the wall changes (they did: the spec once printed
    /// a wall id and count from an earlier wall). An independent reimplementor
    /// takes these as normative, so a stale value makes the spec reject every
    /// real package. Keep the doc pinned to reality.
    #[test]
    fn format_spec_states_the_current_wall_identity_and_source_count() {
        let spec = include_str!("../../docs/certificate-format.md");
        assert!(
            spec.contains(CURRENT_WALL_ID),
            "certificate-format.md does not state the current wall id {CURRENT_WALL_ID}; \
             update the wall identity printed in the spec"
        );
        let count_phrase = format!(
            "{} embedded `.lean` wall sources",
            crate::wall::SOURCES.len()
        );
        assert!(
            spec.contains(&count_phrase),
            "certificate-format.md does not state \"{count_phrase}\"; \
             update the wall source count printed in the spec"
        );
    }

    /// The same staleness trap applies to the statement schema version: the
    /// spec prints it in the identity table and again in the envelope-check
    /// step of the acceptance pipeline, and a reimplementor takes both as
    /// normative. A spec left one version behind describes a verifier that
    /// rejects every package this release produces.
    #[test]
    fn format_spec_states_the_current_schema_version() {
        let spec = include_str!("../../docs/certificate-format.md");
        for phrase in [
            format!("`{CERT_SCHEMA_VERSION}` (`CERT_SCHEMA_VERSION`)"),
            format!("schema_version = {CERT_SCHEMA_VERSION}"),
        ] {
            assert!(
                spec.contains(&phrase),
                "certificate-format.md does not state \"{phrase}\"; \
                 update the schema version printed in the spec"
            );
        }
    }

    #[test]
    fn format_spec_documents_wasip2_envelope_surface() {
        let spec = include_str!("../../docs/certificate-format.md");
        for phrase in [
            TARGET_WASIP2,
            RUNTIME_ABI_WASIP2,
            WASIP2_COMPONENT_ENVELOPE_FIELD,
            WASIP2_COMPONENT_ENVELOPE_KIND_FIELD,
            WASIP2_COMPONENT_ENVELOPE_PREFIX_LEN_FIELD,
            WASIP2_COMPONENT_ENVELOPE_CORE_LEN_FIELD,
            WASIP2_COMPONENT_ENVELOPE_SUFFIX_LEN_FIELD,
            WASIP2_COMPONENT_ENVELOPE_KIND,
        ] {
            assert!(
                spec.contains(phrase),
                "certificate-format.md does not document wasip2 envelope surface `{phrase}`"
            );
        }
    }

    /// The schema version lives in TWO constants — this one, which the
    /// transport parser enforces, and `engine::CERT_SCHEMA_VERSION`, which the
    /// producer emits. They are read on opposite sides of the package
    /// boundary, so a bump applied to only one silently produces packages the
    /// same build refuses, and nothing else ties them together.
    ///
    /// Read as SOURCE TEXT rather than as a constant, deliberately: the engine
    /// module is feature-gated (`engine`/`plans`) while this module is not, so
    /// a typed comparison would compile away in exactly the lane that runs
    /// these tests. The doc-pin tests above use the same technique.
    #[test]
    fn the_two_schema_version_constants_agree() {
        let engine_src = include_str!("engine/mod.rs");
        let expected = "pub const CERT_SCHEMA_VERSION: u32 = crate::format::CERT_SCHEMA_VERSION;";
        assert!(
            engine_src.contains(expected),
            "engine/mod.rs does not delegate to `{expected}`; the producer would emit a \
             schema version the transport parser rejects"
        );
    }

    /// Every runtime contract string is a VERBATIM twin: `ClaimAxes.lean`
    /// declares it in the wall, `engine/mod.rs` declares it for the producer,
    /// and the kernel's `contractsMatch` compares the manifest's list against
    /// the wall's own. A one-character drift on either side fails every package
    /// closed, and it is invisible in review — the two strings live in
    /// different languages, in different files, edited in different commits.
    #[test]
    fn every_wall_contract_string_has_a_verbatim_producer_twin() {
        let axes = include_str!("../assets/wall/current/ClaimAxes.lean");
        let engine_src = include_str!("engine/mod.rs");

        // `def <name>Contract : String :=` followed by the quoted literal.
        let mut seen = 0usize;
        let mut lines = axes.lines();
        while let Some(line) = lines.next() {
            let trimmed = line.trim();
            if !(trimmed.starts_with("def ") && trimmed.ends_with("Contract : String :=")) {
                continue;
            }
            let literal = lines
                .next()
                .expect("a contract definition is followed by its literal")
                .trim();
            assert!(
                literal.starts_with('"') && literal.ends_with('"'),
                "expected a one-line string literal under `{trimmed}`, got: {literal}"
            );
            assert!(
                engine_src.contains(literal),
                "wall contract `{trimmed}` has no verbatim producer twin in \
                 engine/mod.rs: {literal}"
            );
            seen += 1;
        }
        assert!(
            seen >= 12,
            "only {seen} wall contract definitions were found; the scan shape has \
             drifted and this test has stopped checking anything"
        );
    }
}