# Reading a ziptastic archive in the browser

[ziptastic](https://github.com/drsamonline/ziptastic) writes `.dr` files — format `CHCE`,
version 8. This app reads them: the header, the block table and every integrity field,
without decoding a payload. This note is the record of what is read, what is checked,
and why the encoder is not here.

## Why the encoder is not here

ziptastic is a native C++20 binary. Per block, nine encoders compete and the smallest
wins — RAW, rANS (static and adaptive), range, static Huffman, BWT via libbsc, PPMd, an
LZMA2 fallback, and context mixing under `--max-ratio`. Eighteen Layer 0 transforms sit
above them. It vendors liblzma and libbsc and builds against CMake and Ninja.

None of that exists in a browser, and no WebAssembly build of the engine ships. A WASM
port is not a wrapper around this repository: it is a build of the whole codec stack,
with its own measurement and its own audit. So this app does the part that is exact in
JavaScript, and says plainly which part it did.

`ziptastic c` and `ziptastic d` remain the encoder and the decoder. The app links to
them, prints the commands, and never implies it did their work.

## The bytes

From `include/chimera/block.hpp`, `include/chimera/format.hpp` and `docs/FORMAT_V8.md`:

```
"CHCE" | version u8 | flags u8 | layers u8 | layers2 u8 | layers3 u8
       | original_size varint | true_size varint | block_count varint | crc32 u32

per block: mode u8 | usize varint | csize varint | sha256[32] | metadata | payload

trailer:   "ZTIX" | block_count varint | sha256(manifest)[32]
         | block_offset u64[block_count] | "ZTOX"
```

Integers are unsigned LEB128 unless a fixed width is stated; fixed-width integers are
little-endian. `original_size` is the size **after** Layer 0; `true_size` is what the
caller handed in — so the ratio a user cares about is `fileBytes / true_size`, and the
app reports that one.

## Finding the trailer without reading a block

The trailer is a fixed size for a given block count, so its start is arithmetic:

```
trailer_start = file_length - 4 - 8*block_count - 32 - varint_length(block_count) - 4
```

Four bytes for `ZTOX`, eight per offset, thirty-two for the manifest digest, the count
varint's own width, and four for `ZTIX`. A reader arriving from the end lands on the
marker without parsing anything in front of it. That is the whole point of v8, and it is
why the table is fixed-width rather than a delta-coded varint — a varint table could only
be walked from one end.

`ZTOX` is what distinguishes a complete stream from one truncated inside its table. The
app checks for it separately, and says so when it is missing.

## Offsets are relative to the stream, not the file

Each table entry is the absolute position of a block header **counted from the `C` of
`CHCE`**. A self-extracting stub or a joined split set in front of the stream therefore
changes nothing — the offsets stay the same. The reader finds the magic (at byte 0, or
within the first 4 MiB behind a stub), records the stub length, and adds it to every
offset to reach the bytes. `test-node.js` asserts exactly this: the stored offset is
unchanged by a 512-byte stub, and the file position shifts by 512.

## The flag byte

All eight bits are allocated. `docs/FORMAT.md` v1 called bits 3–7 reserved; the header is
the source of truth, and the engine sets bit 4 on every `--parallel` stream — which is why
a reader that treats them as reserved reports a perfectly good archive as broken.

| bit | mask | name | meaning |
|---|---|---|---|
| 0 | `0x01` | coarse index | the coarse (SREP-style) index was consulted while parsing |
| 1 | `0x02` | max ratio | `--max-ratio` was in effect: context mixing was allowed |
| 2 | `0x04` | precompression | Layer 0 semantic precompression fired on at least one block |
| 3 | `0x08` | x86 BCJ | the BCJ transform was applied to the stream |
| 4 | `0x10` | parallel | every block is self-contained, so blocks may be decoded in parallel |
| 5 | `0x20` | dedup | a coarse dedup stage ran before block splitting |
| 6 | `0x40` | JPEG | a JPEG was recompressed with brunsli before block splitting |
| 7 | `0x80` | GIF | a GIF was recompressed from LZW to palette indices |

**Block access** is derived from bit 4, the way `ziptastic info` derives it: set means
"each block decodes on its own (`--parallel`)", clear means "archive mode: a block may
reference an earlier one". The report shows the same sentence the CLI prints.

## Layer 0 goes both ways

The transforms are not one-directional, and assuming they were was a bug in this reader.

| Direction | Example | Effect on `original_size` vs `true_size` |
|---|---|---|
| expands | container inflation (ZIP, gzip, PDF), PNG/JPEG one level down | `original_size` is **larger** |
| shrinks | the CSV/TSV numeric transform — delta + varint beats the digits | `original_size` is **smaller** |

`tests/fixtures/table.dr` is the shrinking case: 57,473 bytes of CSV become 34,467 before
any backend runs. The report says "Layer 0 shrank … 40.0% smaller", and it is reported as
a fact, never as a failure.

## The manifest, and what it proves

The manifest is, per block in order: the mode byte, `usize` and `csize` as varints, and
the block's own 32-byte digest. Its SHA-256 goes in the trailer.

Recomputing it needs no decoder, which makes it the one integrity check worth doing here.
It catches:

- a block dropped from the stream;
- a block duplicated or reordered;
- an edited header field — a size, or a mode;
- a replaced per-block digest.

A damaged *payload* is caught by the per-block SHA-256 when the engine decodes; this
reader cannot check that, and does not claim to.

## What the reader checks

Fourteen checks, each reported with its own verdict:

| check | what failing means |
|---|---|
| magic | the four bytes are not `CHCE` — this is not a CHCE stream, whatever the name says |
| version | not v8. v7 and earlier have no offset table and ziptastic refuses them too |
| flags | a reserved flag bit is set, which the format forbids |
| layer bits | a Layer 0 bit this format does not allocate is set |
| block count | zero blocks, or more blocks than there are transformed bytes |
| layer 0 effect | never fails: reports whether Layer 0 expanded, shrank or left the length alone |
| trailer tail | `ZTOX` missing: truncated inside the offset table |
| trailer marker | `ZTIX` is not where the block count says it must be |
| trailer count | the header and the trailer disagree |
| offset table | an offset is out of order, or outside the stream |
| block headers | a block header does not parse at its offset, or names an unknown mode |
| payload bounds | a payload claims more bytes than the space before the next block |
| block sizes | the block plaintext sizes do not add up to `original_size` |
| manifest digest | the recomputed digest differs from the stored one |

## Field parity with `ziptastic info`

A reader that disagrees with the CLI on what a field *is called* is a reader people
mistrust. `scripts/cross-check.js` compares the values; this table says which label each
value appears under, so a report and a terminal transcript can be read side by side.

| `ziptastic info` label | Reader field | Report label | Notes |
|---|---|---|---|
| `format` | `header.version` | `format` | the CLI prints the build and the version; the reader prints `v8` |
| `flags` | `header.flags`, `header.flagList` | `stream flags` | all eight bits named |
| `layers` | `header.layers[0..2]`, `header.layerList` | `layer 0 transforms applied` | three bytes, decoded to names |
| `original size` | `header.originalSize` | `after layer 0` | the size the block loop consumed |
| `true size` | `header.trueSize` | `original size` | what the caller handed in |
| `crc32` | `header.crc32Hex` | `crc32 of original` | CRC-32 of the pre-transform bytes |
| `blocks` | `blocks.length` | `block table — N entries` | |
| `block table` | `checks` (offset table, trailer) | `integrity` | the CLI reports bytes read; the reader reports each check |
| `block access` | `header.blockAccessText` | `block access` | same sentence |
| table `#` | `block.index` | `#` | |
| table `offset` | `block.fileOffset` | `offset` | **the CLI prints the position in the file**; the table stores it relative to the stream, and the two differ only when a stub sits in front (`block.offset` is the stored value, `block.fileOffset` the file position) |
| table `csize` | `block.compressedSize` | `payload` | |
| table `usize` | `block.uncompressedSize` | `plain` | |
| table `mode` | `block.modeName` | `backend` | same names, from `mode_name()` |

`node scripts/cross-check.js <ziptastic-binary>` asserts every row that has a value on both
sides — 60 fields across the four fixtures, and it fails the build if one drifts.

## Modes and transforms, named

The mode byte and the three Layer 0 bytes are decoded into names rather than left as hex,
because a table of numbers tells a reader nothing. `RANS_CTX`, `BWT_BSC`, `PPMD`,
`LZMA2_FALLBACK`, `CM_ZPAQ`; `CSV/TSV numeric columns`, `gzip inflation`, `CD sector ECC`,
`xz stream`, and the rest.

## The fixtures are the engine's, not this reader's

`tests/fixtures/` holds four `.dr` files written by **ziptastic 1.4.5**:

| File | What it exercises |
|---|---|
| `note.dr` | one RAW block |
| `prose.dr` | one PPMd block |
| `table.dr` | the Layer 0 numeric transform — the shrinking case |
| `parallel-blocks.dr` | `--parallel`: flag `0x10`, four self-contained PPMd blocks |

The first run against them found three bugs that no synthetic stream could: the flag byte
read as three bits with five "reserved", Layer 0 assumed to expand, and the manifest
checked only when every other check had already passed. `scripts/make-fixtures.sh`
regenerates them from a fixed-seed corpus.

## Reproducing the fixtures

`test-node.js` writes its own CHCE streams — header, blocks, manifest, offset table,
`ZTIX`/`ZTOX` — following `block_writer.cpp` field for field, then reads them back. That
way the reader is tested against the format rather than against itself, and a stream can
be broken on purpose: a v7 version byte, a reserved flag bit, one flipped byte of a block
digest, a size that no longer adds up, a truncation inside the trailer.
