mahbot 0.7.3

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
//! Container-level removal of AI-provenance metadata from generated image
//! artifacts, applied at the single point where they are written.
//!
//! Platforms read the container metadata a provider leaves on generated bytes to
//! auto-apply an AI label; [`strip_image_provenance`] splices exactly those
//! carriers out (the removal sets are the match arms below) and rewrites
//! nothing else:
//!
//! * Pixels stay bit-identical — nothing is re-encoded, resized, cropped or
//!   dithered. The only rewritten bytes are container framing: the CRC of a
//!   rebuilt `eXIf`, and the WebP RIFF size and `VP8X` feature flags.
//! * Only whole known carriers are dropped, so colour and rendering state
//!   survives by construction. EXIF orientation is rendering state, not
//!   provenance: a non-identity orientation is rebuilt as a payload carrying
//!   that tag alone, so the strip never rotates an image.
//! * Content-sniffed, never extension-based, and fail-open: what this pass
//!   cannot confidently parse is written untouched, and a pass that changes
//!   nothing reports that back, so re-running it is a no-op.
//!
//! Known gaps, both resolved in favour of leaving the artifact untouched: a WebP
//! whose final odd-length chunk omits its pad byte, and a PNG whose chunk CRCs do
//! not match the framing (the walk trusts lengths, not checksums).
//!
//! Deliberately not addressed:
//!
//! 1. The generator-side invisible watermark (e.g. SynthID), which the provider
//!    embeds in the pixels themselves.
//! 2. Disclosure obligations are unaffected — removing this metadata does not
//!    discharge any duty to disclose AI-generated content. Jurisdictional
//!    direction for intent: China prohibits removing or concealing AI labels
//!    *and* providing tools to do so, and India bars intermediaries from
//!    enabling removal/suppression. This strips the metadata on our own
//!    generated artifacts; it is not a general-purpose label-removal feature,
//!    and must not be extended into one.

use image::metadata::Orientation;
use std::borrow::Cow;

// ── Signatures ──────────────────────────────────────────────────────────

/// PNG file signature.
const PNG_SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";

/// JPEG start-of-image marker and sniff signature: SOI plus the next marker's
/// introducer (a bare `FF D8` is not enough to claim a JPEG).
const JPEG_SOI: &[u8; 2] = &[0xFF, 0xD8];

/// RIFF/WEBP container magics (the `RIFF` size field sits between them).
const RIFF_MAGIC: &[u8; 4] = b"RIFF";
const WEBP_MAGIC: &[u8; 4] = b"WEBP";

/// JPEG marker bytes the walk classifies by name.
const JPEG_TEM: u8 = 0x01;
const JPEG_EOI: u8 = 0xD9;
const JPEG_SOS: u8 = 0xDA;
const JPEG_APP1: u8 = 0xE1;
const JPEG_APP11: u8 = 0xEB;
const JPEG_APP13: u8 = 0xED;
const JPEG_COM: u8 = 0xFE;

/// `Exif\0\0` prefix the JPEG/Exif spec puts in front of the TIFF block.
const EXIF_PREFIX: &[u8] = b"Exif\0\0";

/// `VP8X` feature-flag bits for the removed WebP carriers.
const VP8X_FLAG_EXIF: u8 = 0x08;
const VP8X_FLAG_XMP: u8 = 0x04;

// ── Entry point ─────────────────────────────────────────────────────────

/// Strip AI-provenance metadata from generated-artifact bytes.
///
/// Returns `Cow::Borrowed` when the bytes are not a confidently parsed
/// PNG/JPEG/WebP, carry no removal-set carrier, or would come back unchanged.
#[must_use]
pub(crate) fn strip_image_provenance(bytes: &[u8]) -> Cow<'_, [u8]> {
    let stripped = if bytes.starts_with(PNG_SIGNATURE) {
        strip_png(bytes)
    } else if bytes.starts_with(JPEG_SOI) && bytes.get(2) == Some(&0xFF) {
        strip_jpeg(bytes)
    } else if bytes.len() >= 12 && bytes.starts_with(RIFF_MAGIC) && &bytes[8..12] == WEBP_MAGIC {
        strip_webp(bytes)
    } else {
        None
    };

    match stripped {
        // Only bytes that actually changed are owned, so a caller can treat
        // `Cow::Owned` as "this artifact was normalized".
        Some(rewritten) if rewritten != bytes => Cow::Owned(rewritten),
        _ => Cow::Borrowed(bytes),
    }
}

// ── PNG ─────────────────────────────────────────────────────────────────

/// Walk a PNG, dropping the provenance carriers and rebuilding `eXIf` around a
/// preserved non-identity orientation.
///
/// `None` when the walk is not structurally confident (truncated or overrunning
/// chunk, first chunk not `IHDR`, no terminating zero-length `IEND`) or when
/// nothing in the removal set was found.
fn strip_png(bytes: &[u8]) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(bytes.len());
    out.extend_from_slice(PNG_SIGNATURE);
    let mut pos = PNG_SIGNATURE.len();
    let mut removed = false;

    loop {
        let length = read_be_u32(bytes, pos)? as usize;
        let chunk_type = read_fourcc(bytes, pos.checked_add(4)?)?;
        let payload_start = pos.checked_add(8)?;
        let payload_end = payload_start.checked_add(length)?;
        let chunk_end = payload_end.checked_add(4)?;
        if chunk_end > bytes.len() {
            return None;
        }
        // The walk is only trusted when the stream opens with IHDR.
        if pos == PNG_SIGNATURE.len() && &chunk_type != b"IHDR" {
            return None;
        }

        match &chunk_type {
            b"IEND" => {
                if length != 0 {
                    return None;
                }
                out.extend_from_slice(&bytes[pos..chunk_end]);
                // Anything a producer left after IEND is copied verbatim.
                out.extend_from_slice(&bytes[chunk_end..]);
                return removed.then_some(out);
            }
            b"eXIf" => {
                removed = true;
                // A raw TIFF block: keep only a non-identity orientation.
                if let Some(minimal) =
                    minimal_exif_with_orientation(&bytes[payload_start..payload_end])
                {
                    push_png_chunk(&mut out, b"eXIf", &minimal);
                }
            }
            b"tEXt" | b"zTXt" | b"iTXt" | b"caBX" => removed = true,
            // IHDR, PLTE, IDAT, iCCP, gAMA, cHRM, sRGB, tRNS, pHYs, bKGD,
            // acTL/fcTL/fdAT and unknown chunks: verbatim, CRC included.
            _ => out.extend_from_slice(&bytes[pos..chunk_end]),
        }

        pos = chunk_end;
    }
}

/// Append one PNG chunk: big-endian length, four-byte type, payload and the
/// CRC-32 of type+payload (the length field counts the payload only).
fn push_png_chunk(out: &mut Vec<u8>, chunk_type: &[u8], payload: &[u8]) {
    let mut crc = flate2::Crc::new();
    crc.update(chunk_type);
    crc.update(payload);
    let length = u32::try_from(payload.len()).expect("rebuilt metadata fits a chunk length");
    out.extend_from_slice(&length.to_be_bytes());
    out.extend_from_slice(chunk_type);
    out.extend_from_slice(payload);
    out.extend_from_slice(&crc.sum().to_be_bytes());
}

// ── JPEG ────────────────────────────────────────────────────────────────

/// Walk a JPEG marker stream, dropping the provenance segments.
///
/// Only reached for bytes the sniffer already matched as a JPEG. `None` when the
/// framing is not confidently parsed (a stray `0x00` marker outside a scan, an
/// out-of-bounds length field, running out of bytes) or when nothing in the
/// removal set was found.
fn strip_jpeg(bytes: &[u8]) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(bytes.len());
    out.extend_from_slice(JPEG_SOI);
    let mut pos = JPEG_SOI.len();
    let mut removed = false;

    loop {
        // Every position outside a scan starts with a marker introducer; 0xFF
        // fill bytes ahead of a marker are legal.
        if bytes.get(pos) != Some(&0xFF) {
            return None;
        }
        let marker_start = pos;
        while bytes.get(pos) == Some(&0xFF) {
            pos += 1;
        }
        let marker = *bytes.get(pos)?;
        pos += 1;
        if marker == 0x00 {
            return None;
        }

        match marker {
            JPEG_EOI => {
                // EOI plus any trailer, verbatim.
                out.extend_from_slice(&bytes[marker_start..]);
                return removed.then_some(out);
            }
            JPEG_TEM | 0xD0..=0xD7 => out.extend_from_slice(&bytes[marker_start..pos]),
            JPEG_SOS => {
                let length = usize::from(read_be_u16(bytes, pos)?);
                if length < 2 {
                    return None;
                }
                let scan_start = pos.checked_add(length)?;
                if scan_start > bytes.len() {
                    return None;
                }
                out.extend_from_slice(&bytes[marker_start..scan_start]);

                // Entropy-coded data: byte stuffing (`FF 00`), restart markers
                // (`FF D0..=FF D7`) and runs of `FF` fill bytes belong to the
                // scan; the scan ends at `FF` followed by any other byte. A
                // progressive JPEG simply re-enters this loop per scan.
                let mut scan_pos = scan_start;
                let scan_end = loop {
                    let i = scan_pos + bytes.get(scan_pos..)?.iter().position(|&b| b == 0xFF)?;
                    match bytes.get(i + 1) {
                        None => return None,
                        Some(&next)
                            if next == 0x00 || next == 0xFF || (0xD0..=0xD7).contains(&next) =>
                        {
                            scan_pos = i + 1;
                        }
                        Some(_) => break i,
                    }
                };
                out.extend_from_slice(&bytes[scan_start..scan_end]);
                pos = scan_end;
            }
            _ => {
                let length = usize::from(read_be_u16(bytes, pos)?);
                if length < 2 {
                    return None;
                }
                let payload_start = pos.checked_add(2)?;
                let payload_end = pos.checked_add(length)?;
                if payload_end > bytes.len() {
                    return None;
                }
                let payload = &bytes[payload_start..payload_end];

                match marker {
                    // APP1 carries only metadata — EXIF, XMP/ExtendedXMP and rare
                    // vendor variants; the rendering-relevant side data of a JPEG
                    // lives elsewhere (JFIF APP0, ICC APP2, Adobe APP14, the
                    // ISO 21496-1 gain map in APP2). A prefixed EXIF block with a
                    // non-identity orientation is rebuilt around that tag alone,
                    // every other APP1 is dropped.
                    JPEG_APP1 => {
                        removed = true;
                        if payload.starts_with(EXIF_PREFIX)
                            && let Some(minimal) = minimal_exif_with_orientation(payload)
                        {
                            push_jpeg_segment(&mut out, marker, &minimal);
                        }
                    }
                    // JUMBF/C2PA only; other APP11 payloads (e.g. JPEG-HDR).
                    JPEG_APP11 if payload.starts_with(b"JP") => removed = true,
                    // The Photoshop IRB carrying IPTC; `Adobe_CM` is kept.
                    JPEG_APP13
                        if payload.starts_with(b"Photoshop 3.0\0")
                            || payload.starts_with(b"Adobe_Photoshop2.5") =>
                    {
                        removed = true;
                    }
                    JPEG_COM => removed = true,
                    // JFIF APP0, ICC APP2, Adobe APP14, DQT/DHT/SOF/DRI/... and
                    // unknown segments: verbatim, length field included.
                    _ => out.extend_from_slice(&bytes[marker_start..payload_end]),
                }

                pos = payload_end;
            }
        }
    }
}

/// Append one JPEG segment (`FF <marker>` plus a big-endian length that counts
/// itself).
fn push_jpeg_segment(out: &mut Vec<u8>, marker: u8, payload: &[u8]) {
    out.push(0xFF);
    out.push(marker);
    let length = u16::try_from(payload.len() + 2).expect("rebuilt metadata fits a segment length");
    out.extend_from_slice(&length.to_be_bytes());
    out.extend_from_slice(payload);
}

// ── WebP ────────────────────────────────────────────────────────────────

/// Walk a RIFF/WEBP container, dropping the provenance chunks.
///
/// Only reached for bytes the sniffer already matched as a WebP.
///
/// One pass, with the `VP8X` feature flags patched at the end: the flags mirror
/// which carriers survived, and the spec puts `VP8X` ahead of the metadata it
/// describes. `None` when the framing is not confidently parsed or nothing in
/// the removal set was found.
fn strip_webp(bytes: &[u8]) -> Option<Vec<u8>> {
    let riff_end = (read_le_u32(bytes, 4)? as usize).checked_add(8)?;
    if riff_end > bytes.len() {
        return None;
    }

    let mut out = Vec::with_capacity(bytes.len());
    out.extend_from_slice(RIFF_MAGIC);
    out.extend_from_slice(&[0; 4]); // RIFF size, patched below
    out.extend_from_slice(WEBP_MAGIC);

    // Offset of the `VP8X` flags byte in `out`, and the carriers seen.
    let mut flags_at = None;
    let (mut saw_exif, mut saw_xmp, mut saw_c2pa) = (false, false, false);
    let mut kept_exif = false;
    let mut pos = 12;
    while pos < riff_end {
        let (fourcc, payload_start, payload_end, chunk_end) =
            read_webp_chunk(bytes, pos, riff_end)?;
        match &fourcc {
            b"EXIF" => {
                saw_exif = true;
                if let Some(minimal) =
                    minimal_exif_with_orientation(&bytes[payload_start..payload_end])
                {
                    kept_exif = true;
                    push_webp_chunk(&mut out, b"EXIF", &minimal);
                }
            }
            b"XMP " => saw_xmp = true,
            b"C2PA" => saw_c2pa = true,
            b"VP8X" => {
                // Only a `VP8X` that actually carries its flags byte is patched;
                // a zero-length one has nothing to patch and must not be mistaken
                // for the chunk that follows it.
                if payload_end > payload_start {
                    flags_at = Some(out.len() + 8);
                }
                out.extend_from_slice(&bytes[pos..chunk_end]);
            }
            // `VP8 `, `VP8L`, `ALPH`, `ICCP`, `ANIM`, `ANMF`, unknown chunks.
            _ => out.extend_from_slice(&bytes[pos..chunk_end]),
        }
        pos = chunk_end;
    }
    if !(saw_exif || saw_xmp || saw_c2pa) {
        return None;
    }

    if let Some(flags) = flags_at.and_then(|at| out.get_mut(at)) {
        // XMP never survives; EXIF survives only as the rebuilt orientation
        // payload. Every other feature bit is left alone.
        *flags &= !(VP8X_FLAG_EXIF | VP8X_FLAG_XMP);
        if kept_exif {
            *flags |= VP8X_FLAG_EXIF;
        }
    }

    // The declared size covers the rebuilt chunks only: bytes a producer left
    // after the original RIFF end stay an undeclared trailer, exactly as they
    // were, so the framing we emit matches the input's.
    let riff_size = u32::try_from(out.len().checked_sub(8)?).ok()?;
    out[4..8].copy_from_slice(&riff_size.to_le_bytes());
    out.extend_from_slice(&bytes[riff_end..]);
    Some(out)
}

/// Parse the RIFF chunk starting at `pos`, returning its fourcc, payload start,
/// payload end and padded chunk end. `None` on any overrun past `riff_end`.
fn read_webp_chunk(
    bytes: &[u8],
    pos: usize,
    riff_end: usize,
) -> Option<([u8; 4], usize, usize, usize)> {
    let fourcc = read_fourcc(bytes, pos)?;
    let size = read_le_u32(bytes, pos.checked_add(4)?)? as usize;
    let payload_start = pos.checked_add(8)?;
    let payload_end = payload_start.checked_add(size)?;
    let chunk_end = payload_end.checked_add(size & 1)?;
    if chunk_end > riff_end {
        return None;
    }
    Some((fourcc, payload_start, payload_end, chunk_end))
}

/// Append one RIFF chunk: four-byte id, little-endian payload size, payload and
/// the mandatory pad byte when the payload length is odd.
fn push_webp_chunk(out: &mut Vec<u8>, fourcc: &[u8], payload: &[u8]) {
    let size = u32::try_from(payload.len()).expect("rebuilt metadata fits a chunk length");
    out.extend_from_slice(fourcc);
    out.extend_from_slice(&size.to_le_bytes());
    out.extend_from_slice(payload);
    if size & 1 != 0 {
        out.push(0);
    }
}

// ── EXIF orientation ────────────────────────────────────────────────────

/// The payload rebuilt to carry nothing but the EXIF orientation, in the same
/// container form as `payload` (the `Exif\0\0` prefix is preserved when present).
/// `None` when `payload` has no parseable non-identity orientation; every other
/// tag is dropped, since orientation is the only one that affects rendering.
///
/// The tag is read with the `image` crate's parser — the one the consumers decode
/// through (`util::exif_orientation`) — so the rule cannot drift from theirs.
fn minimal_exif_with_orientation(payload: &[u8]) -> Option<Vec<u8>> {
    let tiff = payload.strip_prefix(EXIF_PREFIX).unwrap_or(payload);
    let orientation = Orientation::from_exif_chunk(tiff)?;
    if orientation == Orientation::NoTransforms {
        return None;
    }
    let orientation = orientation.to_exif();

    let prefixed = payload.starts_with(EXIF_PREFIX);
    let mut out = Vec::with_capacity(if prefixed { 32 } else { 26 });
    if prefixed {
        out.extend_from_slice(EXIF_PREFIX);
    }
    out.extend_from_slice(b"II\x2A\x00"); // little-endian TIFF magic
    out.extend_from_slice(&8u32.to_le_bytes()); // IFD0 offset
    out.extend_from_slice(&1u16.to_le_bytes()); // one entry
    out.extend_from_slice(&[0x12, 0x01, 0x03, 0x00]); // tag 0x0112, type SHORT
    out.extend_from_slice(&1u32.to_le_bytes()); // count 1
    out.extend_from_slice(&[orientation, 0x00, 0x00, 0x00]); // value
    out.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // no next IFD
    Some(out)
}

// ── Primitive reads ─────────────────────────────────────────────────────

/// Four-byte identifier at `offset`.
fn read_fourcc(bytes: &[u8], offset: usize) -> Option<[u8; 4]> {
    let end = offset.checked_add(4)?;
    bytes.get(offset..end)?.try_into().ok()
}

/// Big-endian `u16` at `offset`.
fn read_be_u16(bytes: &[u8], offset: usize) -> Option<u16> {
    let end = offset.checked_add(2)?;
    let raw: [u8; 2] = bytes.get(offset..end)?.try_into().ok()?;
    Some(u16::from_be_bytes(raw))
}

/// Big-endian `u32` at `offset`.
fn read_be_u32(bytes: &[u8], offset: usize) -> Option<u32> {
    let raw: [u8; 4] = bytes.get(offset..offset.checked_add(4)?)?.try_into().ok()?;
    Some(u32::from_be_bytes(raw))
}

/// Little-endian `u32` at `offset`.
fn read_le_u32(bytes: &[u8], offset: usize) -> Option<u32> {
    let raw: [u8; 4] = bytes.get(offset..offset.checked_add(4)?)?.try_into().ok()?;
    Some(u32::from_le_bytes(raw))
}

#[cfg(test)]
mod tests {
    use super::*;
    use image::ImageEncoder as _;

    // ── Fixtures ────────────────────────────────────────────────────────

    /// A 2×2 opaque RGBA image with four distinct pixels.
    fn sample_rgba() -> image::RgbaImage {
        image::RgbaImage::from_raw(
            2,
            2,
            vec![
                255, 0, 0, 255, // red
                0, 255, 0, 255, // green
                0, 0, 255, 255, // blue
                255, 255, 0, 255, // yellow
            ],
        )
        .expect("valid 2x2 RGBA buffer")
    }

    /// The same four pixels without an alpha channel (JPEG/WebP fixtures).
    fn sample_rgb() -> image::RgbImage {
        image::RgbImage::from_raw(
            2,
            2,
            vec![
                255, 0, 0, // red
                0, 255, 0, // green
                0, 0, 255, // blue
                255, 255, 0, // yellow
            ],
        )
        .expect("valid 2x2 RGB buffer")
    }

    /// Decoded RGBA pixels of an image in any supported container.
    fn rgba_pixels(bytes: &[u8]) -> Vec<u8> {
        image::load_from_memory(bytes)
            .expect("fixture must decode")
            .to_rgba8()
            .into_raw()
    }

    /// The rewritten bytes of a fixture that must be normalized.
    fn rewritten(bytes: &[u8]) -> Vec<u8> {
        match strip_image_provenance(bytes) {
            Cow::Owned(out) => out,
            Cow::Borrowed(_) => panic!("a metadata-bearing fixture must be rewritten"),
        }
    }

    fn encode_png(img: &image::RgbaImage) -> Vec<u8> {
        let mut out = Vec::new();
        image::codecs::png::PngEncoder::new(&mut out)
            .write_image(
                img.as_raw(),
                img.width(),
                img.height(),
                image::ExtendedColorType::Rgba8,
            )
            .expect("PNG encode");
        out
    }

    fn encode_jpeg(img: &image::RgbImage) -> Vec<u8> {
        let mut out = Vec::new();
        image::codecs::jpeg::JpegEncoder::new(&mut out)
            .encode_image(&image::DynamicImage::ImageRgb8(img.clone()))
            .expect("JPEG encode");
        out
    }

    fn encode_webp_lossless(img: &image::RgbImage) -> Vec<u8> {
        let mut out = Vec::new();
        image::codecs::webp::WebPEncoder::new_lossless(&mut out)
            .encode(
                img.as_raw(),
                img.width(),
                img.height(),
                image::ExtendedColorType::Rgb8,
            )
            .expect("WebP encode");
        out
    }

    /// Splice extra chunks in right after IHDR (always 25 bytes including the
    /// length, type and CRC).
    fn png_with_extra_chunks(base: &[u8], extra: &[u8]) -> Vec<u8> {
        assert_eq!(&base[12..16], b"IHDR");
        let mut out = base[..33].to_vec();
        out.extend_from_slice(extra);
        out.extend_from_slice(&base[33..]);
        out
    }

    /// A PNG carrying every removal-set chunk plus colour state that must
    /// survive.
    fn png_with_metadata() -> Vec<u8> {
        let base = encode_png(&sample_rgba());
        let mut extra = Vec::new();
        push_png_chunk(&mut extra, b"gAMA", &[0x00, 0x00, 0xB1, 0x8F]);
        push_png_chunk(&mut extra, b"iCCP", b"icc\0\0not-a-zlib-stream");
        push_png_chunk(
            &mut extra,
            b"zTXt",
            b"Raw profile type iptc\0\0not-a-zlib-stream",
        );
        push_png_chunk(
            &mut extra,
            b"iTXt",
            b"XML:com.adobe.xmp\0\x00\x00\0\0<x:xmpmeta/>",
        );
        push_png_chunk(&mut extra, b"caBX", b"jumb\0\x10\0\0c2pa\x11manifest");
        png_with_extra_chunks(&base, &extra)
    }

    /// Chunk types of a PNG, in file order.
    fn png_chunk_types(bytes: &[u8]) -> Vec<[u8; 4]> {
        let mut types = Vec::new();
        let mut pos = 8;
        while pos + 12 <= bytes.len() {
            let length = u32::from_be_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize;
            types.push(bytes[pos + 4..pos + 8].try_into().unwrap());
            pos += 12 + length;
        }
        types
    }

    /// The `Make` (`0x010F`) value in `exif_with_orientation_and_make_tag`, which
    /// the rebuild must not carry over.
    const MAKE_TAG_VALUE: &[u8] = b"ABC\0";

    /// Whether a rebuilt payload still carries the fixture's `Make` tag value.
    fn carries_make_tag(payload: &[u8]) -> bool {
        payload
            .windows(MAKE_TAG_VALUE.len())
            .any(|w| w == MAKE_TAG_VALUE)
    }

    /// A raw-TIFF EXIF block with an orientation entry plus a `Make` (`0x010F`)
    /// entry that the rebuild must not carry over.
    fn exif_with_orientation_and_make_tag(orientation: u8) -> Vec<u8> {
        let mut out = b"II*\0".to_vec();
        out.extend_from_slice(&8u32.to_le_bytes()); // IFD0 offset
        out.extend_from_slice(&2u16.to_le_bytes()); // two entries
        out.extend_from_slice(&[0x12, 0x01, 0x03, 0x00]); // tag 0x0112, SHORT
        out.extend_from_slice(&[0x01, 0x00, 0x00, 0x00]); // count 1
        out.extend_from_slice(&[orientation, 0x00, 0x00, 0x00]); // value
        out.extend_from_slice(&[0x0F, 0x01, 0x02, 0x00]); // tag 0x010F, ASCII
        out.extend_from_slice(&[0x04, 0x00, 0x00, 0x00]); // count 4
        out.extend_from_slice(MAKE_TAG_VALUE); // inline value
        out.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // no next IFD
        out
    }

    /// Splice raw segments in right after SOI.
    fn jpeg_with_segments(base: &[u8], segments: &[Vec<u8>]) -> Vec<u8> {
        assert!(base.starts_with(JPEG_SOI));
        let mut out = base[..2].to_vec();
        for segment in segments {
            out.extend_from_slice(segment);
        }
        out.extend_from_slice(&base[2..]);
        out
    }

    fn jpeg_segment(marker: u8, payload: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        push_jpeg_segment(&mut out, marker, payload);
        out
    }

    /// The APPn/COM segments preceding the first scan, as `(marker, payload)`.
    fn jpeg_header_segments(bytes: &[u8]) -> Vec<(u8, Vec<u8>)> {
        let mut segments = Vec::new();
        let mut pos = 2;
        while bytes.get(pos) == Some(&0xFF) {
            while bytes.get(pos) == Some(&0xFF) {
                pos += 1;
            }
            let Some(&marker) = bytes.get(pos) else {
                break;
            };
            pos += 1;
            if marker == JPEG_SOS || marker == JPEG_EOI {
                break;
            }
            if marker == JPEG_TEM || (0xD0..=0xD7).contains(&marker) {
                continue;
            }
            let Some(length) = read_be_u16(bytes, pos) else {
                break;
            };
            let end = pos + usize::from(length);
            segments.push((marker, bytes[pos + 2..end].to_vec()));
            pos = end;
        }
        segments
    }

    fn has_segment(segments: &[(u8, Vec<u8>)], marker: u8, prefix: &[u8]) -> bool {
        segments
            .iter()
            .any(|(m, payload)| *m == marker && payload.starts_with(prefix))
    }

    /// Chunks of a RIFF/WEBP container, as `(fourcc, payload)`.
    fn webp_chunks(bytes: &[u8]) -> Vec<([u8; 4], Vec<u8>)> {
        let mut chunks = Vec::new();
        let riff_end = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize + 8;
        let mut pos = 12;
        while pos < riff_end {
            let fourcc = bytes[pos..pos + 4].try_into().unwrap();
            let size = u32::from_le_bytes(bytes[pos + 4..pos + 8].try_into().unwrap()) as usize;
            chunks.push((fourcc, bytes[pos + 8..pos + 8 + size].to_vec()));
            pos += 8 + size + (size & 1);
        }
        chunks
    }

    #[expect(
        clippy::trivially_copy_pass_by_ref,
        reason = "call sites pass fourcc literals, which read better by reference"
    )]
    fn webp_chunk<'a>(chunks: &'a [([u8; 4], Vec<u8>)], fourcc: &[u8; 4]) -> Option<&'a [u8]> {
        chunks
            .iter()
            .find(|(id, _)| id == fourcc)
            .map(|(_, payload)| payload.as_slice())
    }

    /// A `VP8X` payload: flags, three reserved bytes, canvas dimensions.
    fn vp8x_payload(flags: u8, width: u32, height: u32) -> Vec<u8> {
        let mut payload = vec![flags, 0, 0, 0];
        payload.extend_from_slice(&(width - 1).to_le_bytes()[..3]);
        payload.extend_from_slice(&(height - 1).to_le_bytes()[..3]);
        payload
    }

    fn write_riff_size(bytes: &mut [u8]) {
        let size = u32::try_from(bytes.len() - 8).expect("fixture fits u32");
        bytes[4..8].copy_from_slice(&size.to_le_bytes());
    }

    /// The `VP8L` payload the lossless encoder emits for `img`.
    fn webp_vp8l(img: &image::RgbImage) -> Vec<u8> {
        webp_chunks(&encode_webp_lossless(img))
            .into_iter()
            .find(|(fourcc, _)| fourcc == b"VP8L")
            .map(|(_, payload)| payload)
            .expect("lossless encoder emits a VP8L chunk")
    }

    /// A RIFF/WEBP fixture: `VP8X` with `flags`, the `VP8L` payload, then `extra`
    /// chunks, with the RIFF size field written.
    fn webp_fixture(
        img: &image::RgbImage,
        vp8l: &[u8],
        flags: u8,
        extra: &[(&[u8], &[u8])],
    ) -> Vec<u8> {
        let mut fixture = Vec::new();
        fixture.extend_from_slice(RIFF_MAGIC);
        fixture.extend_from_slice(&[0; 4]);
        fixture.extend_from_slice(WEBP_MAGIC);
        push_webp_chunk(
            &mut fixture,
            b"VP8X",
            &vp8x_payload(flags, img.width(), img.height()),
        );
        push_webp_chunk(&mut fixture, b"VP8L", vp8l);
        for (fourcc, payload) in extra {
            push_webp_chunk(&mut fixture, fourcc, payload);
        }
        write_riff_size(&mut fixture);
        fixture
    }

    // ── PNG ─────────────────────────────────────────────────────────────

    #[test]
    fn png_drops_metadata_chunks_and_keeps_rendering_state() {
        let base = encode_png(&sample_rgba());
        let fixture = png_with_metadata();
        assert_eq!(rgba_pixels(&fixture), rgba_pixels(&base));

        let out = rewritten(&fixture);

        let types = png_chunk_types(&out);
        assert!(types.contains(b"IHDR"));
        assert!(types.contains(b"IDAT"));
        assert!(types.contains(b"IEND"));
        assert!(types.contains(b"gAMA"));
        assert!(types.contains(b"iCCP"));
        for gone in [b"zTXt", b"iTXt", b"caBX"] {
            assert!(!types.contains(gone), "{gone:?} must be dropped");
        }
        assert_eq!(rgba_pixels(&out), rgba_pixels(&base));
    }

    #[test]
    fn png_keeps_non_identity_orientation_and_drops_the_rest() {
        let base = encode_png(&sample_rgba());
        let mut extra = Vec::new();
        push_png_chunk(&mut extra, b"eXIf", &exif_with_orientation_and_make_tag(6));
        let fixture = png_with_extra_chunks(&base, &extra);
        assert_eq!(rgba_pixels(&fixture), rgba_pixels(&base));

        let out = rewritten(&fixture);
        let types = png_chunk_types(&out);
        assert!(types.contains(b"eXIf"));
        assert_eq!(
            crate::util::exif_orientation(&out).map(Orientation::to_exif),
            Some(6)
        );
        assert_eq!(rgba_pixels(&out), rgba_pixels(&base));

        // Orientation 1 (identity) and an unparsable eXIf are dropped outright.
        for payload in [
            exif_with_orientation_and_make_tag(1),
            b"not a tiff block".to_vec(),
        ] {
            let mut extra = Vec::new();
            push_png_chunk(&mut extra, b"eXIf", &payload);
            let fixture = png_with_extra_chunks(&base, &extra);
            let out = rewritten(&fixture);
            assert!(!png_chunk_types(&out).contains(b"eXIf"));
            assert_eq!(rgba_pixels(&out), rgba_pixels(&base));
        }
    }

    // ── JPEG ────────────────────────────────────────────────────────────

    #[test]
    fn jpeg_drops_metadata_segments_and_keeps_rendering_state() {
        let base = encode_jpeg(&sample_rgb());
        let fixture = jpeg_with_segments(
            &base,
            &[
                jpeg_segment(0xE1, b"http://ns.adobe.com/xap/1.0/\0<x:xmpmeta/>"),
                jpeg_segment(0xED, b"Photoshop 3.0\0iptc"),
                jpeg_segment(0xEB, b"JP\0\x01\0\0jumb-c2pa"),
                jpeg_segment(JPEG_COM, b"generated by a model"),
                jpeg_segment(0xE2, b"ICC_PROFILE\0\x01\x01fake-icc-bytes"),
                // Standard 12-byte Adobe APP14 (transform 1 = YCbCr).
                jpeg_segment(0xEE, b"Adobe\x00\x64\x00\x00\x00\x00\x01"),
            ],
        );
        assert_eq!(rgba_pixels(&fixture), rgba_pixels(&base));

        let out = rewritten(&fixture);

        let segments = jpeg_header_segments(&out);
        assert!(has_segment(&segments, 0xE0, b"JFIF\0"));
        assert!(has_segment(&segments, 0xE2, b"ICC_PROFILE\0"));
        assert!(has_segment(&segments, 0xEE, b"Adobe"));
        assert!(!has_segment(
            &segments,
            0xE1,
            b"http://ns.adobe.com/xap/1.0/"
        ));
        assert!(!has_segment(&segments, 0xED, b"Photoshop 3.0\0"));
        assert!(!has_segment(&segments, 0xEB, b"JP"));
        assert!(!segments.iter().any(|(marker, _)| *marker == JPEG_COM));
        assert_eq!(rgba_pixels(&out), rgba_pixels(&base));

        // A truncated stream cannot be walked confidently: pass through.
        let truncated = &base[..base.len() / 2];
        assert_eq!(strip_image_provenance(truncated), truncated);
    }

    #[test]
    fn jpeg_keeps_non_identity_orientation_and_drops_the_rest() {
        let base = encode_jpeg(&sample_rgb());
        let mut exif = EXIF_PREFIX.to_vec();
        exif.extend_from_slice(&exif_with_orientation_and_make_tag(6));
        let fixture = jpeg_with_segments(&base, &[jpeg_segment(JPEG_APP1, &exif)]);

        let out = rewritten(&fixture);
        let segments = jpeg_header_segments(&out);
        assert_eq!(
            crate::util::exif_orientation(&out).map(Orientation::to_exif),
            Some(6)
        );
        let app1: Vec<_> = segments
            .iter()
            .filter(|(marker, _)| *marker == JPEG_APP1)
            .collect();
        assert_eq!(app1.len(), 1);
        // Only the orientation tag survives, in the prefixed container form.
        assert!(app1[0].1.starts_with(EXIF_PREFIX));
        assert!(!carries_make_tag(&app1[0].1));

        // Orientation 1 leaves nothing to preserve: the APP1 is gone.
        let mut exif = EXIF_PREFIX.to_vec();
        exif.extend_from_slice(&exif_with_orientation_and_make_tag(1));
        let fixture = jpeg_with_segments(&base, &[jpeg_segment(JPEG_APP1, &exif)]);
        let out = rewritten(&fixture);
        assert!(
            !jpeg_header_segments(&out)
                .iter()
                .any(|(marker, _)| *marker == JPEG_APP1)
        );
        assert_eq!(rgba_pixels(&out), rgba_pixels(&base));
    }

    #[test]
    fn jpeg_copies_entropy_data_and_scans_verbatim() {
        // A progressive-style skeleton (two scans, restart markers, `FF 00`
        // stuffing, an `FF FF` fill run, a trailer after EOI) that never decodes:
        // the walk is asserted byte-for-byte, which is the strongest statement
        // that entropy-coded data survives — and the comment flanking each scan
        // only disappears if the walk really re-enters the marker loop there.
        let soi = JPEG_SOI.to_vec();
        let head_com = jpeg_segment(JPEG_COM, b"generated by a model");
        let dqt = jpeg_segment(0xDB, b"quant tables");
        let sos_1 = jpeg_segment(JPEG_SOS, b"scan-1 header");
        let scan_1 = vec![
            0x01, 0xFF, 0x00, 0x02, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xD0, 0x04, 0xFF, 0xD3, 0x05,
        ];
        let mid_com = jpeg_segment(JPEG_COM, b"comment between scans");
        let dht = jpeg_segment(0xC4, b"huffman tables");
        let sos_2 = jpeg_segment(JPEG_SOS, b"scan-2 header");
        let scan_2 = vec![0x06, 0xFF, 0x00, 0x07, 0xFF, 0x00];
        let tail = vec![0xFF, 0xD9];
        let trailer = b"TRAILER".to_vec();

        let parts: [&[u8]; 11] = [
            &soi, &head_com, &dqt, &sos_1, &scan_1, &mid_com, &dht, &sos_2, &scan_2, &tail,
            &trailer,
        ];
        let kept: [&[u8]; 9] = [
            &soi, &dqt, &sos_1, &scan_1, &dht, &sos_2, &scan_2, &tail, &trailer,
        ];
        let fixture = parts.concat();
        let expected = kept.concat();

        let out = rewritten(&fixture);
        assert_eq!(out, expected);
    }

    // ── WebP ────────────────────────────────────────────────────────────

    #[test]
    fn webp_drops_metadata_chunks_and_patches_vp8x_flags() {
        let img = sample_rgb();
        let encoded = encode_webp_lossless(&img);
        let vp8l = webp_vp8l(&img);

        // ICC + EXIF + XMP flags set: the two dropped carriers must clear,
        // ICC must survive.
        let fixture = webp_fixture(
            &img,
            &vp8l,
            0x2C,
            &[
                (b"EXIF", &exif_with_orientation_and_make_tag(1)),
                (b"XMP ", b"<x:xmpmeta/>"),
                (b"C2PA", b"jumb\0\x10\0\0c2pa"),
            ],
        );
        assert_eq!(rgba_pixels(&fixture), rgba_pixels(&encoded));

        let out = rewritten(&fixture);

        let chunks = webp_chunks(&out);
        assert_eq!(webp_chunk(&chunks, b"VP8L"), Some(vp8l.as_slice()));
        assert_eq!(webp_chunk(&chunks, b"EXIF"), None);
        assert_eq!(webp_chunk(&chunks, b"XMP "), None);
        assert_eq!(webp_chunk(&chunks, b"C2PA"), None);
        assert_eq!(webp_chunk(&chunks, b"VP8X").unwrap()[0], 0x20);
        assert_eq!(
            out.len() - 8,
            u32::from_le_bytes(out[4..8].try_into().unwrap()) as usize
        );
        assert_eq!(rgba_pixels(&out), rgba_pixels(&encoded));

        // A `VP8X` advertising carriers the container does not hold: the output's
        // flags describe the output, so both bits clear.
        let fixture = webp_fixture(&img, &vp8l, 0x0C, &[(b"C2PA", b"jumb\0\x10\0\0c2pa")]);
        let out = rewritten(&fixture);
        assert_eq!(webp_chunk(&webp_chunks(&out), b"VP8X").unwrap()[0], 0x00);
    }

    #[test]
    fn webp_keeps_non_identity_orientation_and_sets_the_flag() {
        let img = sample_rgb();
        let encoded = encode_webp_lossless(&img);
        let vp8l = webp_vp8l(&img);

        // ICC + XMP flags set and the EXIF flag unset even though an `EXIF` chunk
        // is present: keeping the orientation must also set the flag.
        let fixture = webp_fixture(
            &img,
            &vp8l,
            0x24,
            &[
                (b"EXIF", &exif_with_orientation_and_make_tag(6)),
                (b"XMP ", b"<x:xmpmeta/>"),
            ],
        );
        assert_eq!(rgba_pixels(&fixture), rgba_pixels(&encoded));

        let out = rewritten(&fixture);

        let chunks = webp_chunks(&out);
        assert_eq!(
            crate::util::exif_orientation(&out).map(Orientation::to_exif),
            Some(6)
        );
        // Only the orientation tag survives, in the chunk's raw-TIFF form.
        let exif = webp_chunk(&chunks, b"EXIF").unwrap();
        assert!(!exif.starts_with(EXIF_PREFIX));
        assert!(!carries_make_tag(exif));
        assert_eq!(webp_chunk(&chunks, b"XMP "), None);
        assert_eq!(webp_chunk(&chunks, b"VP8X").unwrap()[0], 0x28);
        assert_eq!(rgba_pixels(&out), rgba_pixels(&encoded));
    }

    #[test]
    fn webp_leaves_a_vp8x_without_a_flags_byte_unpatched() {
        // A zero-length `VP8X` has no flags byte to patch, and the chunk that
        // follows it must not be mistaken for one (which silently corrupts its
        // fourcc).
        let img = sample_rgb();
        let vp8l = webp_vp8l(&img);
        let mut fixture = Vec::new();
        fixture.extend_from_slice(RIFF_MAGIC);
        fixture.extend_from_slice(&[0; 4]);
        fixture.extend_from_slice(WEBP_MAGIC);
        push_webp_chunk(&mut fixture, b"VP8X", &[]);
        push_webp_chunk(&mut fixture, b"VP8L", &vp8l);
        push_webp_chunk(&mut fixture, b"XMP ", b"<x:xmpmeta/>");
        write_riff_size(&mut fixture);

        let out = rewritten(&fixture);
        let chunks = webp_chunks(&out);
        assert_eq!(webp_chunk(&chunks, b"VP8L"), Some(vp8l.as_slice()));
        assert_eq!(webp_chunk(&chunks, b"XMP "), None);
    }

    #[test]
    fn webp_leaves_a_trailer_outside_the_declared_size() {
        let img = sample_rgb();
        let encoded = encode_webp_lossless(&img);
        let mut fixture = webp_fixture(&img, &webp_vp8l(&img), 0x20, &[(b"XMP ", b"<x:xmpmeta/>")]);
        let trailer = b"TRAILER";
        fixture.extend_from_slice(trailer);

        let out = rewritten(&fixture);

        // The trailer stays undeclared, exactly as the input framed it.
        assert!(out.ends_with(trailer));
        let declared = u32::from_le_bytes(out[4..8].try_into().unwrap()) as usize;
        assert_eq!(declared, out.len() - 8 - trailer.len());
        assert_eq!(rgba_pixels(&out), rgba_pixels(&encoded));
    }

    // ── Pass-through and idempotency ────────────────────────────────────

    #[test]
    fn non_images_and_unparsable_payloads_pass_through_unchanged() {
        let png = encode_png(&sample_rgba());
        let mp4 = b"\0\0\0\x18ftypmp42\0\0\0\0mp42isom avc1".as_slice();
        let cases: [&[u8]; 3] = [
            b"<svg xmlns=\"http://www.w3.org/2000/svg\"><rect/></svg>",
            mp4,
            &png[..20], // truncated PNG: signature only
        ];
        for bytes in cases {
            let stripped = strip_image_provenance(bytes);
            assert!(matches!(stripped, Cow::Borrowed(_)));
            assert_eq!(stripped.as_ref(), bytes);
        }

        // A second pass has nothing left to remove and says so — including for a
        // rebuilt orientation payload, which the first pass re-emits byte-for-byte.
        let mut extra = Vec::new();
        push_png_chunk(&mut extra, b"eXIf", &exif_with_orientation_and_make_tag(6));
        for fixture in [
            png_with_metadata(),
            png_with_extra_chunks(&encode_png(&sample_rgba()), &extra),
        ] {
            let stripped = rewritten(&fixture);
            assert!(matches!(
                strip_image_provenance(&stripped),
                Cow::Borrowed(_)
            ));
        }
    }
}