Skip to content
Verified contractExactMIT

PerceptionProgram

Address0xd172eca1ebf93bc2bf656196ca68bd81ed86fca0
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,998,258
Creation transaction
0x68580a3f2d…94b7acc991

src/PerceptionProgram.sol

// SPDX-License-Identifier: MIT
// Copyright (c) 2026 CypherDAO
/*******************************************************************************
      ___           ___           ___           ___                         ___           ___
     /  /\         /__/\         /  /\         /__/\         _____         /  /\         /  /\
    /  /:/         \  \:\       /  /::\       |  |::\       /  /::\       /  /:/_       /  /::\
   /  /:/           \__\:\     /  /:/\:\      |  |:|:\     /  /:/\:\     /  /:/ /\     /  /:/\:\
  /  /:/  ___   ___ /  /::\   /  /:/~/::\   __|__|:|\:\   /  /:/~/::\   /  /:/ /:/_   /  /:/~/:/
 /__/:/  /  /\ /__/\  /:/\:\ /__/:/ /:/\:\ /__/::::| \:\ /__/:/ /:/\:| /__/:/ /:/ /\ /__/:/ /:/___
 \  \:\ /  /:/ \  \:\/:/__\/ \  \:\/:/__\/ \  \:\~~\__\/ \  \:\/:/~/:/ \  \:\/:/ /:/ \  \:\/:::::/
  \  \:\  /:/   \  \::/       \  \::/       \  \:\        \  \::/ /:/   \  \::/ /:/   \  \::/~~~~
   \  \:\/:/     \  \:\        \  \:\        \  \:\        \  \:\/:/     \  \:\/:/     \  \:\
    \  \::/       \  \:\        \  \:\        \  \:\        \  \::/       \  \::/       \  \:\
     \__\/         \__\/         \__\/         \__\/         \__\/         \__\/         \__\/
                       P E R C E P T I O N   .   C A N A R Y   .   B R A I N 0 2 5
 Perception Chamber: the frozen program, deployed on its own and pinned by the token.
*******************************************************************************/
pragma solidity 0.8.30;

import {Blob} from "./Blob.sol";
import {Brain025} from "./Brain025.sol";

/// @title PerceptionProgram - the frozen Perception Chamber PRG, reassembled from its blobs
/// @notice The one program every token runs: tony-b025-a-vis4.prg, 52,104 bytes, sha256 355645a6…, held in
///         data blobs (STOP || bytes) and reassembled by EXTCODECOPY. The BRAIN025 slot inside it sits at
///         `brainOffset` (the file offset of $7500), asserted at construction by its marker and by the
///         admission of the blank slot it ships with, so `prgWithBrain` can patch nowhere else. Nothing
///         here changes after construction: no owner, no setter, no upgrade.
contract PerceptionProgram {
    bytes8 internal constant MARKER = "BRAIN025";

    address[] private _parts;
    /// @notice sha256 of the whole PRG
    bytes32 public immutable hash;
    /// @notice the PRG's length in bytes
    uint256 public immutable size;
    /// @notice the file offset of the BRAIN025 slot ($7500 minus the load address, plus the two address bytes)
    uint256 public immutable brainOffset;

    error NoParts();
    error WrongSize(uint256 got, uint256 expected);
    error WrongHash(bytes32 got, bytes32 expected);
    error MarkerNotAtOffset(uint256 offset);
    error SlotOutOfRange(uint256 offset, uint256 size);
    error ZeroCommitment();

    constructor(address[] memory parts_, bytes32 expectedHash, uint256 expectedSize, uint256 brainOffset_) {
        if (parts_.length == 0) revert NoParts();
        if (expectedHash == bytes32(0) || expectedSize == 0) revert ZeroCommitment();
        _parts = parts_;
        bytes memory p = _assemble(parts_);
        if (p.length != expectedSize) revert WrongSize(p.length, expectedSize);
        bytes32 h = sha256(p);
        if (h != expectedHash) revert WrongHash(h, expectedHash);
        if (brainOffset_ + Brain025.SLOT_BYTES > p.length) revert SlotOutOfRange(brainOffset_, p.length);
        bytes memory slot = new bytes(Brain025.SLOT_BYTES);
        for (uint256 i = 0; i < Brain025.SLOT_BYTES; ++i) slot[i] = p[brainOffset_ + i];
        for (uint256 i = 0; i < 8; ++i) if (slot[i] != MARKER[i]) revert MarkerNotAtOffset(brainOffset_);
        Brain025.checkSlot(slot); // the PRG ships an admissible slot at the offset
        hash = h;
        size = p.length;
        brainOffset = brainOffset_;
    }

    function partCount() external view returns (uint256) { return _parts.length; }
    function part(uint256 i) external view returns (address) { return _parts[i]; }

    /// @notice the PRG, byte for byte
    function prg() public view returns (bytes memory) { return _assemble(_parts); }

    function _assemble(address[] memory parts_) internal view returns (bytes memory out) {
        uint256 total;
        for (uint256 i = 0; i < parts_.length; ++i) total += Blob.lengthOf(parts_[i]);
        out = new bytes(total);
        uint256 cursor;
        for (uint256 i = 0; i < parts_.length; ++i) {
            bytes memory piece = Blob.read(parts_[i]); // reverts NotABlob for anything that is not STOP || bytes
            uint256 n = piece.length;
            assembly ("memory-safe") {
                mcopy(add(add(out, 32), cursor), add(piece, 32), n)
            }
            cursor += n;
        }
    }
}

src/Blob.sol

// SPDX-License-Identifier: MIT
// Copyright (c) 2026 CypherDAO
/*******************************************************************************
      ___           ___           ___           ___                         ___           ___
     /  /\         /__/\         /  /\         /__/\         _____         /  /\         /  /\
    /  /:/         \  \:\       /  /::\       |  |::\       /  /::\       /  /:/_       /  /::\
   /  /:/           \__\:\     /  /:/\:\      |  |:|:\     /  /:/\:\     /  /:/ /\     /  /:/\:\
  /  /:/  ___   ___ /  /::\   /  /:/~/::\   __|__|:|\:\   /  /:/~/::\   /  /:/ /:/_   /  /:/~/:/
 /__/:/  /  /\ /__/\  /:/\:\ /__/:/ /:/\:\ /__/::::| \:\ /__/:/ /:/\:| /__/:/ /:/ /\ /__/:/ /:/___
 \  \:\ /  /:/ \  \:\/:/__\/ \  \:\/:/__\/ \  \:\~~\__\/ \  \:\/:/~/:/ \  \:\/:/ /:/ \  \:\/:::::/
  \  \:\  /:/   \  \::/       \  \::/       \  \:\        \  \::/ /:/   \  \::/ /:/   \  \::/~~~~
   \  \:\/:/     \  \:\        \  \:\        \  \:\        \  \:\/:/     \  \:\/:/     \  \:\
    \  \::/       \  \:\        \  \:\        \  \:\        \  \::/       \  \::/       \  \:\
     \__\/         \__\/         \__\/         \__\/         \__\/         \__\/         \__\/
                       P E R C E P T I O N   .   C A N A R Y   .   B R A I N 0 2 5
 Perception Chamber: the data-contract primitive, an internal library compiled into the token.
*******************************************************************************/
pragma solidity 0.8.30;

/// @title Blob - immutable bytes as a CREATE2 data contract (step 6 of the sequence)
/// @notice The persistence primitive of Perception Chamber: a payload becomes the runtime code of a
///         contract that can never run (its first byte is STOP), has no owner, no upgrade, no
///         self-destruct and no storage, and whose address is a deterministic function of exactly three
///         published inputs - the deployer, the payload's SHA-256 (the salt), and this fixed initcode
///         template. An internal library: the token that saves minds inlines it and is itself the
///         deployer, so every blob of a collection lives in that token's namespace.
///
///         Three identities, kept apart on purpose:
///           - the payload's SHA-256:  canonical content identity (the brain's canonical hash, the
///                                     education's stream hash); it is what a revision records;
///           - the CREATE2 address:    where those bytes are stored within THIS deployer's namespace.
///                                     Not derivable from the payload alone: the deployer is an input;
///                                     another deployment of the collection stores the same bytes at
///                                     another address, and continuity between deployments is a matter
///                                     of content hashes and provenance, never of equal addresses;
///           - the revision id:        biographical identity, the token's concern, not this library's.
///         Identical payloads under one deployer share one blob: `persist` is idempotent, so a second
///         revision that reaches the same bytes reuses the blob and keeps its own revision identity.
///
///         The template is the one `fixtures/create2/identity.json` pins and this suite reproduces:
///           initcode = INIT_PREFIX || 0x00 || payload
///           INIT_PREFIX = 600B 59 81 38 03 80 92 59 39 F3
///                       = PUSH1 0x0B; MSIZE; DUP2; CODESIZE; SUB; DUP1; SWAP3; MSIZE; CODECOPY; RETURN
///                       (returns everything after its own eleven bytes as the runtime)
///           runtime  = 0x00 || payload            (STOP, then the bytes, read back past the STOP)
///           salt     = sha256(payload)
///           address  = keccak256(0xff || deployer || salt || keccak256(initcode))[12:]
library Blob {
    /// @dev the eleven-byte deployer stub, fixed forever: it is an input to every address
    bytes11 internal constant INIT_PREFIX = hex"600B5981380380925939F3";
    /// @dev EIP-170: a runtime may be at most 24,576 bytes; one of them is the STOP
    uint256 internal constant MAX_PAYLOAD = 24_575;
    /// @dev EIP-3860: initcode may be at most 49,152 bytes; with MAX_PAYLOAD the initcode is 24,587, so this
    ///      bound never binds here - stated so the reasoning is on record
    uint256 internal constant MAX_INITCODE = 49_152;

    /// @dev a blob of nothing has no meaning here; refused rather than stored
    error EmptyPayload();
    /// @dev the runtime would exceed EIP-170
    error PayloadTooLong(uint256 length, uint256 max);
    /// @dev code exists at the deterministic address and is not STOP || payload: the namespace is corrupt for
    ///      this content, and nothing here guesses; the caller fails closed
    error BlobConflict(address at, bytes32 expectedRuntimeHash, bytes32 foundRuntimeHash);
    /// @dev CREATE2 returned no contract, or one at a different address than derived (cannot happen when the
    ///      derivation is right and the address was empty; checked so it is a proof, not an assumption)
    error BlobDeployFailed(address expected, address got);
    /// @dev the account read is not a blob: empty, or its first byte is not STOP
    error NotABlob(address at);

    // ------------------------------------------------------------------ the template, as bytes
    /// @notice the exact initcode for a payload
    function initcode(bytes memory payload) internal pure returns (bytes memory) {
        return abi.encodePacked(INIT_PREFIX, bytes1(0), payload);
    }

    /// @notice the exact runtime a blob of this payload has
    function runtime(bytes memory payload) internal pure returns (bytes memory) {
        return abi.encodePacked(bytes1(0), payload);
    }

    /// @notice the salt: the payload's SHA-256, which is also its canonical content identity
    function saltOf(bytes memory payload) internal pure returns (bytes32) {
        return sha256(payload);
    }

    /// @notice keccak256 of the runtime: what EXTCODEHASH of the blob returns
    function runtimeHash(bytes memory payload) internal pure returns (bytes32) {
        return keccak256(runtime(payload));
    }

    // ------------------------------------------------------------------ the address
    /// @notice the CREATE2 address of `payload`'s blob under `deployer`: the deployer is an explicit input
    function addressOf(address deployer, bytes memory payload) internal pure returns (address) {
        return addressOf(deployer, saltOf(payload), keccak256(initcode(payload)));
    }

    /// @notice the CREATE2 formula itself
    function addressOf(address deployer, bytes32 salt, bytes32 initcodeHash) internal pure returns (address) {
        // the low 160 bits of the hash are the address; the cast is the specification
        // forge-lint: disable-next-line(unsafe-typecast)
        return address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, initcodeHash)))));
    }

    // ------------------------------------------------------------------ persistence
    /// @notice store `payload` as a blob under this contract, idempotently
    /// @dev The address is derived first. If nothing is there, CREATE2 deploys the blob and the result
    ///      must be that address. If code is there and its EXTCODEHASH is keccak256(STOP || payload), the
    ///      blob already exists - identical content persisted before - and it is reused: no deployment, no
    ///      failure, the same address. Anything else at that address is a conflict and reverts. The
    ///      payload is bounded by EIP-170 before any of this, so a CREATE2 can never fail on size.
    /// @return at the blob's address
    /// @return deployed true if this call created it, false if it was already there
    function persist(bytes memory payload) internal returns (address at, bool deployed) {
        if (payload.length == 0) revert EmptyPayload();
        if (payload.length > MAX_PAYLOAD) revert PayloadTooLong(payload.length, MAX_PAYLOAD);
        bytes memory code = initcode(payload);
        bytes32 salt = saltOf(payload);
        at = addressOf(address(this), salt, keccak256(code));
        bytes32 want = keccak256(runtime(payload));
        bytes32 have = at.codehash;
        if (at.code.length != 0) {
            if (have != want) revert BlobConflict(at, want, have);
            return (at, false);
        }
        address got;
        assembly ("memory-safe") {
            got := create2(0, add(code, 32), mload(code), salt)
        }
        if (got != at) revert BlobDeployFailed(at, got);
        deployed = true;
    }

    // ------------------------------------------------------------------ reading back
    /// @notice the payload of the blob at `at`: its code past the STOP byte, by EXTCODECOPY
    function read(address at) internal view returns (bytes memory payload) {
        uint256 size = at.code.length;
        if (size == 0) revert NotABlob(at);
        bytes memory first = new bytes(1);
        assembly ("memory-safe") {
            extcodecopy(at, add(first, 32), 0, 1)
        }
        if (first[0] != 0) revert NotABlob(at);
        payload = new bytes(size - 1);
        assembly ("memory-safe") {
            extcodecopy(at, add(payload, 32), 1, sub(size, 1))
        }
    }

    /// @notice the payload length of the blob at `at` without copying it (0 if there is no code)
    function lengthOf(address at) internal view returns (uint256) {
        uint256 size = at.code.length;
        return size == 0 ? 0 : size - 1;
    }

    /// @notice true if the account at `at` is exactly the blob of `payload` (by EXTCODEHASH, no copy)
    function holds(address at, bytes memory payload) internal view returns (bool) {
        return at.code.length != 0 && at.codehash == runtimeHash(payload);
    }
}

src/Brain025.sol

// SPDX-License-Identifier: MIT
// Copyright (c) 2026 CypherDAO
/*******************************************************************************
      ___           ___           ___           ___                         ___           ___
     /  /\         /__/\         /  /\         /__/\         _____         /  /\         /  /\
    /  /:/         \  \:\       /  /::\       |  |::\       /  /::\       /  /:/_       /  /::\
   /  /:/           \__\:\     /  /:/\:\      |  |:|:\     /  /:/\:\     /  /:/ /\     /  /:/\:\
  /  /:/  ___   ___ /  /::\   /  /:/~/::\   __|__|:|\:\   /  /:/~/::\   /  /:/ /:/_   /  /:/~/:/
 /__/:/  /  /\ /__/\  /:/\:\ /__/:/ /:/\:\ /__/::::| \:\ /__/:/ /:/\:| /__/:/ /:/ /\ /__/:/ /:/___
 \  \:\ /  /:/ \  \:\/:/__\/ \  \:\/:/__\/ \  \:\~~\__\/ \  \:\/:/~/:/ \  \:\/:/ /:/ \  \:\/:::::/
  \  \:\  /:/   \  \::/       \  \::/       \  \:\        \  \::/ /:/   \  \::/ /:/   \  \::/~~~~
   \  \:\/:/     \  \:\        \  \:\        \  \:\        \  \:\/:/     \  \:\/:/     \  \:\
    \  \::/       \  \:\        \  \:\        \  \:\        \  \::/       \  \::/       \  \:\
     \__\/         \__\/         \__\/         \__\/         \__\/         \__\/         \__\/
                       P E R C E P T I O N   .   C A N A R Y   .   B R A I N 0 2 5
 Perception Chamber: the learner, an internal library compiled into the token.
*******************************************************************************/
pragma solidity 0.8.30;

/// @title Brain025 - the BRAIN02.5 learner, part 1: the retina
/// @notice A pure transcription of the retina of the frozen BRAIN02.5 reference
///         (`vendor/brain025/tools/brain025_ref.py`, which keeps `brain02_ref.py`'s
///         senses, pseudo-senses and table interpreter unchanged). Nothing here is
///         designed: every rule is the reference's, and every constant is checked
///         against the fixture layer derived from it (`chamber-v2/fixtures/retina/`).
///
///         What this part covers, and only this:
///           - the stored-sense decoding of a 15-byte LESSON25 record into 27 signed
///             nibbles (`unpackLesson`), which is what a lesson stream gives a replay;
///           - the reference vector's orientation `h_of` (`hOf`) and the explicit
///             conversion to the 0/1 flag the goldens record (`hRightFlag`);
///           - the nine pseudo-senses (`pseudo`), the 36-value block (`values`);
///           - the retina-5 table T1 (`RETINA_T1`) and its interpreter (`flags`),
///             producing the exact 80 binary inputs of the perceptron.
///         Part 2 adds the perceptron itself, still pure and still the reference's:
///           - `forward`: the ten accumulators, `acc[o] = mood[o] + Σ w[o][i]` over the set
///             flags, and the first-largest action (`argmax`, lowest index on a tie);
///           - `learn`: rule 2, `p == t` an exact no-op, else `+1` on row t and `-1` on
///             row p at every set flag, saturating at +127 / -128, never wrapping.
///         Mood is an argument of `forward` because the reference's forward fixtures
///         exercise it; a canonical BRAIN025 slot has all ten mood bytes zero and learning
///         is mood-free (`learn` calls forward with zero mood, as the reference does).
///         Part 3 adds the ordered, lesson-level replay, still pure and still the reference's
///         `replay(start_slot, lesson_bytes)`: the slot checked as `check_slot` checks it, the
///         stream as `check_lessons` checks it, then per lesson the nibble decoding, the flags,
///         the recorded absolute action converted by `to_relative` under the block's `h_of`
///         when the slot's vocabulary byte is 1, the mood-free `learn`, the recorded
///         prediction compared to the recomputed one (a mismatch reverts here, where the
///         reference only records it), the education counter advanced on a taken lesson,
///         and the child slot rebuilt as `slot_bytes` rebuilds it. Blobs, persistence, the
///         token and SAVE MIND are later parts and are deliberately absent.
///
///         Two representations of orientation exist in the reference and are kept
///         apart here by name:
///           - `h`      the signed orientation, +1 or -1, never 0 (`h_of`); it is what
///                      the pseudo-senses compare against (`d == h`, `d == -h`) and what
///                      the relative vocabulary is expressed in (`to_relative`, a later part);
///           - `hRight` the flag `1 if h == 1 else 0`; it is value index 20 of the block
///                      (the first pseudo-sense) and the `h` field the golden
///                      `retina-5.json` records. The fixture record byte is hRight.
///         `hRightFlag(hOf(x))` is the only conversion, and it is one-way: the flag
///         does not carry the sign form and nothing here reconstructs h from it.
library Brain025 {
    // ------------------------------------------------------------------ shape
    /// @dev the 27 stored senses of a BRAIN02.5 block: the twenty of BRAIN02 (0..19) then the seven terrain (20..26)
    uint256 internal constant SENSE_COUNT = 27;
    /// @dev the nine pseudo-senses derived from the first twenty, value indices 20..28
    uint256 internal constant PSEUDO_COUNT = 9;
    /// @dev the 36 values the table indexes: 20 senses, 9 pseudo-senses, 7 terrain (value indices 29..35)
    uint256 internal constant VALUE_COUNT = 36;
    /// @dev value index of the first terrain quantity (`TERRAIN_BASE` in the reference)
    uint256 internal constant TERRAIN_BASE = 29;
    /// @dev the number of binary inputs the retina produces: the width of the perceptron
    uint256 internal constant INPUTS = 80;
    /// @dev one LESSON25 record: 27 nibbles in 14 bytes, then the action byte
    uint256 internal constant LESSON_BYTES = 15;
    /// @dev the retina id the slot header carries at byte 17
    uint8 internal constant RETINA_ID = 5;
    /// @dev the slot: a 24-byte header, 800 weights at [24, 824), 10 mood bytes at [824, 834)
    uint256 internal constant SLOT_BYTES = 834;
    uint256 internal constant WEIGHTS_OFFSET = 24;
    uint256 internal constant MOOD_OFFSET = 824;
    /// @dev the eight-byte marker at [0, 8)
    bytes8 internal constant MARKER = "BRAIN025";
    /// @dev the layout byte at offset 9
    uint8 internal constant LAYOUT = 3;
    /// @dev the rule byte at offset 15
    uint8 internal constant RULE = 2;
    /// @dev the highest kind byte (offset 8) the machine's own check allows
    uint8 internal constant KIND_MAX = 2;
    /// @dev header offsets read by name
    uint8 internal constant OFF_KIND = 8;
    uint8 internal constant OFF_LAYOUT = 9;
    uint8 internal constant OFF_INPUTS = 10;
    uint8 internal constant OFF_HIDDEN = 11;
    uint8 internal constant OFF_OUTPUTS = 12;
    uint8 internal constant OFF_PERIOD = 13;
    uint8 internal constant OFF_LINEAGE = 14;
    uint8 internal constant OFF_RULE = 15;
    uint8 internal constant OFF_VOCABULARY = 16;
    uint8 internal constant OFF_RETINA = 17;
    uint8 internal constant OFF_EDUCATION = 18; // u16 little-endian at [18, 20)
    /// @dev the ten outputs, absolute or relative actions 0..9
    uint256 internal constant OUTPUTS = 10;
    /// @dev the weight block: 10 rows x 80 int8, output-major, exactly slot bytes [24, 824)
    uint256 internal constant WEIGHT_BYTES = OUTPUTS * INPUTS;
    /// @dev the saturation box of rule 2 (the reference's LO, HI)
    int8 internal constant WEIGHT_LO = -128;
    int8 internal constant WEIGHT_HI = 127;

    // ------------------------------------------------------------------ the table
    /// @dev the table operators the reference defines; T1 uses only the first four
    uint8 internal constant OP_GE = 0;
    uint8 internal constant OP_LE = 1;
    uint8 internal constant OP_EQN = 2;
    uint8 internal constant OP_AND = 3;

    /// @dev one table entry is three bytes: op (u8), a (u8, a value index), k (int8: a threshold, or a
    ///      second value index for AND)
    uint256 internal constant ENTRY_BYTES = 3;

    /// @notice the retina-5 table T1, exactly the 240 bytes of `fixtures/retina/T1.bin`
    ///         (sha256 82173346…): `brain02_ref.table_R1b()`'s sixty-four entries then the
    ///         sixteen terrain entries of `brain025_ref.terrain_entries()`, each as (op, a, k).
    bytes internal constant RETINA_T1 =
        hex"000001000301000401000501000601000701000801000901000a01000b01000c01000d01000e01000f010012010013010001010101ff001c01001c02001c03001c04001c05001c06001c070002010002020002030002040002050002060002070102ff0102fe0102fd0102fc0102fb0102fa0102f9001101001102001103001104001105001106001107021000021001021002021003021004021005021006021007021008021009001801001901001a01030c17031819001b01001501001601001d01001d03001e03001e04001e06001f01001f03002001002003002005002101002103002201002204002302002304";

    /// @dev thrown by the interpreter on an operator T1 does not use (ANDNOT, OR, XNOR are defined by the
    ///      reference but appear in no BRAIN02.5 table); the library refuses rather than guessing
    error UnsupportedOp(uint256 entry, uint8 op);
    /// @dev thrown when a table is not exactly INPUTS entries of ENTRY_BYTES
    error BadTableLength(uint256 length);
    /// @dev thrown when a lesson record is not exactly LESSON_BYTES
    error BadLessonLength(uint256 length);
    /// @dev thrown by `signedNibble` on a value above 15: a nibble has four bits, nothing here guesses at more
    error BadNibble(uint8 n);
    /// @dev thrown when a weight block is not exactly WEIGHT_BYTES
    error BadWeightsLength(uint256 length);
    /// @dev thrown when a taught action is not one of the ten outputs
    error BadAction(uint8 action);
    /// @dev thrown if an accumulator left int16; impossible with 80 int8 weights and an int8 mood (|acc| <= 10,368),
    ///      kept so the type is a proof and not an assumption
    error AccumulatorOverflow(uint256 output, int256 acc);
    /// @dev the slot is not exactly SLOT_BYTES (the reference's check_slot: 24 + 10 x 80 + 10)
    error BadSlotLength(uint256 length);
    /// @dev the first eight bytes are not "BRAIN025"
    error BadMarker(bytes8 marker);
    /// @dev a header byte is not what this reference requires: offset 8 kind (<= 2), 9 layout (3), 10 inputs (80),
    ///      11 hidden (0), 12 outputs (10), 15 rule (2), 16 vocabulary (<= 1), 17 retina (5)
    error BadHeaderByte(uint8 offset, uint8 value);
    /// @dev a mood byte is not zero: replay will not reinterpret such a slot (the reference's check_slot)
    error MoodNotZero(uint8 output, int8 value);
    /// @dev the stream is not a whole number of 15-byte lessons
    error BadStreamLength(uint256 length);
    /// @dev a lesson's taught nibble is above 9 (the reference's check_lessons, before any lesson is applied)
    error BadTaughtAction(uint256 lesson, uint8 taught);
    /// @dev the machine's recorded mood-free prediction differs from the recomputed one at this lesson
    error PredictionMismatch(uint256 lesson, uint8 recorded, uint8 recomputed);
    /// @dev the education counter would leave its 16-bit field (the reference's slot_bytes cannot encode it either)
    error EducationOverflow(uint256 education);

    /// @notice the table as bytes, for a test to compare with the fixture
    function retinaTable() internal pure returns (bytes memory) {
        return RETINA_T1;
    }

    // ------------------------------------------------------------------ stored-sense decoding
    /// @notice `brain025_ref.unpack_lesson`: the 27 signed nibbles of one LESSON25 record and its action byte
    /// @dev nibble i lives in byte i/2: the low nibble for even i, the high nibble for odd i; a nibble n
    ///      is signed as `n - 16 if n >= 8 else n`, i.e. the range -8..7. Byte 14 holds the taught
    ///      absolute action in its low nibble and the raw recorded prediction in its high nibble; both are
    ///      returned undecoded, exactly as the reference returns them (their meaning is a later part).
    /// @param lesson exactly 15 bytes
    /// @return x the 27 stored senses, signed
    /// @return taughtAbs the low nibble of byte 14
    /// @return predictedRaw the high nibble of byte 14
    function unpackLesson(bytes memory lesson)
        internal
        pure
        returns (int8[SENSE_COUNT] memory x, uint8 taughtAbs, uint8 predictedRaw)
    {
        (taughtAbs, predictedRaw) = unpackLessonInto(lesson, x);
    }

    /// @notice `unpackLesson` writing into a caller-owned array: every one of the 27 entries is assigned on
    ///         every call, so a reused array carries nothing from a previous lesson (lever 5 of study D)
    function unpackLessonInto(bytes memory lesson, int8[SENSE_COUNT] memory x)
        internal
        pure
        returns (uint8 taughtAbs, uint8 predictedRaw)
    {
        if (lesson.length != LESSON_BYTES) revert BadLessonLength(lesson.length);
        for (uint256 i = 0; i < SENSE_COUNT; ++i) {
            uint8 b = uint8(lesson[i >> 1]);
            uint8 n = (i & 1) == 0 ? (b & 15) : (b >> 4);
            x[i] = signedNibble(n);
        }
        uint8 last = uint8(lesson[LESSON_BYTES - 1]);
        taughtAbs = last & 15;
        predictedRaw = last >> 4;
    }

    /// @notice the reference's `sx`: a 4-bit two's-complement nibble to its signed value, -8..7
    function signedNibble(uint8 n) internal pure returns (int8) {
        if (n > 15) revert BadNibble(n);
        // 0..7 are themselves; 8..15 read as n - 16, i.e. -8..-1: both ranges are within int8
        // forge-lint: disable-next-line(unsafe-typecast)
        return n >= 8 ? int8(int16(uint16(n)) - 16) : int8(n);
    }

    // ------------------------------------------------------------------ orientation
    /// @notice `brain02_ref.h_of`: the signed orientation of the reference vector, +1 or -1
    /// @dev rx = x[1] (dx), ry = x[2] (dy); rx > 0 → +1; rx < 0 → -1; rx == 0 → +1 if x[3]
    ///      (facingRight) is non-zero else -1. Never 0: the third branch resolves the tie by facing.
    function hOf(int8[SENSE_COUNT] memory x) internal pure returns (int8 h) {
        int8 rx = x[1];
        if (rx > 0) return 1;
        if (rx < 0) return -1;
        return x[3] != 0 ? int8(1) : int8(-1);
    }

    /// @notice the one conversion from the signed orientation to the flag the goldens and the block record:
    ///         `hRight = 1 if h == 1 else 0` (the reference's `pseudo`, first value). One-way by design.
    function hRightFlag(int8 h) internal pure returns (uint8) {
        return h == 1 ? 1 : 0;
    }

    /// @dev the reference's HDIR: the horizontal direction of an absolute action nibble
    ///      {1 left: -1, 2 right: +1, 6 jump left: -1, 7 jump right: +1, 8 build left: -1, 9 build right: +1},
    ///      0 for every other nibble. The argument is the raw nibble `x[16] & 15`, so a negative stored
    ///      value reads through its two's-complement nibble exactly as Python's `& 15` does.
    function hdir(uint8 nibble) internal pure returns (int8) {
        if (nibble == 2 || nibble == 7 || nibble == 9) return 1;
        if (nibble == 1 || nibble == 6 || nibble == 8) return -1;
        return 0;
    }

    // ------------------------------------------------------------------ the pseudo-senses
    /// @notice `brain02_ref.pseudo`: the nine values at indices 20..28, from the first twenty senses
    /// @dev [hRight, lastTowardRef (d == h), lastAwayRef (d == -h), refAbove (ry > 0),
    ///       facingRef (facing == hRight), stepAhead (x[9] and not x[10]), wallAhead (x[9] and x[10]),
    ///       buildableAndClear (x[14] and not x[9]), adx (|rx|)]; d = HDIR[x[16] & 15], facing = x[3] != 0
    function pseudo(int8[SENSE_COUNT] memory x) internal pure returns (int8[PSEUDO_COUNT] memory p) {
        int8[VALUE_COUNT] memory v;
        pseudoInto(x, v);
        for (uint256 i = 0; i < PSEUDO_COUNT; ++i) p[i] = v[20 + i];
    }

    /// @notice `pseudo` written straight into value indices 20..28 of a caller-owned 36-value block; all
    ///         nine are assigned on every call (lever 5 of study D)
    function pseudoInto(int8[SENSE_COUNT] memory x, int8[VALUE_COUNT] memory v) internal pure {
        int8 rx = x[1];
        int8 ry = x[2];
        int8 h = hOf(x);
        uint8 hRight = hRightFlag(h);
        int8 d = hdir(uint8(x[16]) & 15);
        uint8 facing = x[3] != 0 ? 1 : 0;
        bool s9 = x[9] != 0;
        bool s10 = x[10] != 0;
        bool s14 = x[14] != 0;
        // hRight is 0 or 1
        // forge-lint: disable-next-line(unsafe-typecast)
        v[20] = int8(hRight);
        v[21] = d == h ? int8(1) : int8(0);
        v[22] = d == -h ? int8(1) : int8(0);
        v[23] = ry > 0 ? int8(1) : int8(0);
        v[24] = facing == hRight ? int8(1) : int8(0);
        v[25] = (s9 && !s10) ? int8(1) : int8(0);
        v[26] = (s9 && s10) ? int8(1) : int8(0);
        v[27] = (s14 && !s9) ? int8(1) : int8(0);
        v[28] = rx < 0 ? -rx : rx; // |rx| is at most 8, which int8 holds
    }

    /// @notice `brain025_ref.values`: the 36 values of one block - senses 0..19, pseudo 20..28, terrain 29..35
    function values(int8[SENSE_COUNT] memory x) internal pure returns (int8[VALUE_COUNT] memory v) {
        valuesInto(x, v);
    }

    /// @notice `values` into a caller-owned block: indices 0..19 the senses, 20..28 the pseudo-senses,
    ///         29..35 the terrain - all 36 assigned on every call (lever 5 of study D)
    function valuesInto(int8[SENSE_COUNT] memory x, int8[VALUE_COUNT] memory v) internal pure {
        for (uint256 i = 0; i < 20; ++i) v[i] = x[i];
        pseudoInto(x, v);
        for (uint256 i = 20; i < SENSE_COUNT; ++i) v[TERRAIN_BASE + (i - 20)] = x[i];
    }

    // ------------------------------------------------------------------ the interpreter
    /// @notice `brain025_ref.flags(table_T1(), x)`: the 80 binary inputs of one block under T1
    function flags(int8[SENSE_COUNT] memory x) internal pure returns (uint8[INPUTS] memory z) {
        return evaluate(RETINA_T1, x);
    }

    /// @notice the table interpreter over the 36 values of a block, for a table of exactly 80 entries
    /// @dev GE: v[a] >= k; LE: v[a] <= k; EQN: (v[a] & 15) == k, the low nibble of the two's-complement
    ///      value, as Python's `& 15` reads a negative int; AND: v[a] != 0 and v[k] != 0 with k a value
    ///      index. Any other operator reverts. An index outside 0..35 reverts (array bounds).
    function evaluate(bytes memory table, int8[SENSE_COUNT] memory x)
        internal
        pure
        returns (uint8[INPUTS] memory z)
    {
        int8[VALUE_COUNT] memory v;
        evaluateInto(table, x, v, z);
    }

    /// @notice `evaluate` into caller-owned value and flag arrays: all 36 values and all 80 flags are
    ///         assigned on every call, so reused arrays carry nothing between lessons (lever 5 of study D)
    function evaluateInto(bytes memory table, int8[SENSE_COUNT] memory x, int8[VALUE_COUNT] memory v, uint8[INPUTS] memory z)
        internal
        pure
    {
        if (table.length != INPUTS * ENTRY_BYTES) revert BadTableLength(table.length);
        valuesInto(x, v);
        // lever 2 of study D: one word load per entry instead of three bounds-checked byte indexes. The
        // entry's three bytes are the top three of the loaded word (op, a, k); the length check above
        // is what makes every entry address valid, and the bytes past an entry are simply not used.
        uint256 base;
        assembly ("memory-safe") {
            base := add(table, 32)
        }
        for (uint256 e = 0; e < INPUTS; ++e) {
            uint256 entry;
            assembly ("memory-safe") {
                entry := mload(add(base, mul(e, 3)))
            }
            // op is the top byte: the shift leaves at most 8 bits, the cast cannot truncate
            // forge-lint: disable-next-line(unsafe-typecast)
            uint8 op = uint8(entry >> 248);
            // a is the second byte: the cast truncates the op byte above it, on purpose
            // forge-lint: disable-next-line(unsafe-typecast)
            uint256 a = uint8(entry >> 240);
            // k is the third byte, truncating the two above it on purpose, then reinterpreted as signed
            // forge-lint: disable-next-line(unsafe-typecast)
            int8 k = int8(uint8(entry >> 232));
            bool f;
            if (op == OP_GE) f = v[a] >= k;
            else if (op == OP_LE) f = v[a] <= k;
            // the two's-complement reinterpretation is the point: Python's `v & 15` on a negative int and
            // this low nibble of uint8(int8) agree; k is compared through the same reinterpretation
            // forge-lint: disable-next-line(unsafe-typecast)
            else if (op == OP_EQN) f = (uint8(v[a]) & 15) == uint8(k);
            // for AND, k is a value index; a negative k reinterprets to 128..255 and the bounds check reverts
            // forge-lint: disable-next-line(unsafe-typecast)
            else if (op == OP_AND) f = v[a] != 0 && v[uint8(k)] != 0;
            else revert UnsupportedOp(e, op);
            z[e] = f ? 1 : 0;
        }
    }

    // ------------------------------------------------------------------ the forward pass
    /// @notice `brain02_ref.forward(w, z, mood)`: the ten accumulators and the first-largest action
    /// @dev acc[o] = mood[o] + Σ_{i : z[i] != 0} w[o][i], summed exactly (no intermediate saturation),
    ///      then the lowest output index among the largest accumulators. `z` is read as the reference reads
    ///      it: any non-zero flag counts as set. Weights are the 800 slot bytes, output-major, w[o][i] at
    ///      byte o*80 + i, each an int8.
    /// @param w exactly 800 bytes, rows of 80
    /// @param z the 80 binary inputs
    /// @param mood the ten mood bytes; all zero for any admissible slot, non-zero only in the function fixtures
    function forward(bytes memory w, uint8[INPUTS] memory z, int8[OUTPUTS] memory mood)
        internal
        pure
        returns (int16[OUTPUTS] memory acc, uint8 action)
    {
        int256[OUTPUTS] memory sum;
        action = forwardInto(w, z, mood, sum, acc);
    }

    /// @notice `forward` with caller-owned sum and accumulator arrays: every sum is set to its mood before
    ///         the pass and every accumulator is assigned after it, so reuse carries nothing (lever 5)
    function forwardInto(bytes memory w, uint8[INPUTS] memory z, int8[OUTPUTS] memory mood, int256[OUTPUTS] memory sum, int16[OUTPUTS] memory acc)
        internal
        pure
        returns (uint8 action)
    {
        if (w.length != WEIGHT_BYTES) revert BadWeightsLength(w.length);
        // lever 1 of study D, the loop order the owner approved under the differential gate: one pass over
        // the inputs, and for each set flag its ten weights (one per output row, 80 bytes apart in the
        // canonical output-major block) added into ten 256-bit sums. The ten sums are the same integer
        // sums as the reference's per-output loops - addition is associative and commutative, and no
        // partial sum can leave |10,368| (proved in the differential suite) - so nothing about the result
        // changes; only the order the terms are visited. Each weight byte is read with mload/byte and
        // sign-extended from its top bit, which is the int8 the slot stores. The canonical representation
        // is untouched: w is the 800 slot bytes in, and stays so.
        for (uint256 o = 0; o < OUTPUTS; ++o) sum[o] = mood[o];
        assembly ("memory-safe") {
            let p := add(w, 32) // the weight of input 0 for output 0
            let zp := z // the flag of input 0 (each flag is a full memory word)
            for { let i := 0 } lt(i, 80) { i := add(i, 1) } {
                if iszero(iszero(mload(zp))) {
                    let wp := p
                    let sp := sum
                    for { let o := 0 } lt(o, 10) { o := add(o, 1) } {
                        mstore(sp, add(mload(sp), signextend(0, byte(0, mload(wp)))))
                        wp := add(wp, 80)
                        sp := add(sp, 32)
                    }
                }
                p := add(p, 1)
                zp := add(zp, 32)
            }
        }
        for (uint256 o = 0; o < OUTPUTS; ++o) {
            int256 total = sum[o];
            if (total < type(int16).min || total > type(int16).max) revert AccumulatorOverflow(o, total);
            // bounded to int16 by the check above
            // forge-lint: disable-next-line(unsafe-typecast)
            acc[o] = int16(total);
        }
        action = argmax(acc);
    }

    /// @notice the reference's `max(range(10), key=(acc[o], -o))`: the largest accumulator, and on a tie
    ///         the lowest output index. A strictly larger later accumulator wins; an equal one does not.
    function argmax(int16[OUTPUTS] memory acc) internal pure returns (uint8 best) {
        int16 top = acc[0];
        for (uint256 o = 1; o < OUTPUTS; ++o) {
            if (acc[o] > top) {
                top = acc[o];
                // o < 10
                // forge-lint: disable-next-line(unsafe-typecast)
                best = uint8(o);
            }
        }
    }

    // ------------------------------------------------------------------ the learning rule (rule 2)
    /// @notice `brain02_ref.learn(w, z, t)`: predict without mood; if the prediction is the target, nothing
    ///         changes; otherwise raise row t and lower row p by one at every set flag, saturating.
    /// @dev Mutates `w` in place. `p == t` is an exact no-op: not one byte of `w` is touched. The rows other
    ///      than t and p are never touched; within rows t and p only the columns whose flag is set are
    ///      touched. +1 stops at +127 and -1 stops at -128: the reference's min/max, never a wrap.
    /// @param w exactly 800 bytes, output-major, updated in place
    /// @param z the 80 binary inputs of the lesson
    /// @param t the taught action, 0..9, already in the vocabulary the weights are in (the lesson-level
    ///          conversion from the recorded absolute action is a later part, not this function's)
    /// @return p the mood-free prediction before the update
    /// @return took true when the weights were updated (p != t), which is what advances the education count
    function learn(bytes memory w, uint8[INPUTS] memory z, uint8 t) internal pure returns (uint8 p, bool took) {
        int256[OUTPUTS] memory sum;
        int16[OUTPUTS] memory acc;
        int8[OUTPUTS] memory zeroMood;
        return learnWith(w, z, t, sum, acc, zeroMood);
    }

    /// @notice `learn` with caller-owned scratch: `sum` and `acc` are fully rewritten by forwardInto;
    ///         `zeroMood` is only read and must be all zero (the caller owns that invariant; replay's
    ///         scratch never writes it). Lever 5 of study D.
    function learnWith(bytes memory w, uint8[INPUTS] memory z, uint8 t, int256[OUTPUTS] memory sum, int16[OUTPUTS] memory acc, int8[OUTPUTS] memory zeroMood)
        internal
        pure
        returns (uint8 p, bool took)
    {
        if (t >= OUTPUTS) revert BadAction(t);
        p = forwardInto(w, z, zeroMood, sum, acc);
        if (p == t) return (p, false);
        uint256 rowT = uint256(t) * INPUTS;
        uint256 rowP = uint256(p) * INPUTS;
        // lever 4 of study D: the same two saturating updates per set flag, read in place (mload/byte/
        // signextend, as forward reads) and written back with mstore8, which stores exactly one byte, so
        // no neighbouring weight can be touched. +1 stops at +127 (slt against 127) and -1 stops at -128
        // (sgt against not(127), which is -128 in two's complement); the stored byte is the low byte of
        // the 256-bit result, which for an in-range int8 is its slot byte. Rows other than t and p are
        // never addressed; columns whose flag is clear are skipped. The canonical bytes stay canonical.
        assembly ("memory-safe") {
            let tp := add(add(w, 32), rowT) // row t, column 0
            let pp := add(add(w, 32), rowP) // row p, column 0
            let zp := z
            for { let i := 0 } lt(i, 80) { i := add(i, 1) } {
                if iszero(iszero(mload(zp))) {
                    let wt := signextend(0, byte(0, mload(tp)))
                    if slt(wt, 127) { mstore8(tp, add(wt, 1)) }
                    let wp := signextend(0, byte(0, mload(pp)))
                    if sgt(wp, not(127)) { mstore8(pp, sub(wp, 1)) }
                }
                tp := add(tp, 1)
                pp := add(pp, 1)
                zp := add(zp, 32)
            }
        }
        took = true;
    }

    // ------------------------------------------------------------------ the vocabulary
    /// @notice `brain02_ref.to_relative(a, h)`: a recorded absolute action to the reference-relative one
    /// @dev left (1) / right (2) become toward (1) / away (2); jump left (6) / jump right (7) become jump
    ///      toward (6) / jump away (7); build left (8) / build right (9) become build toward (8) / build
    ///      away (9): the base when the action's direction equals h, base + 1 when it opposes h. Idle, up,
    ///      down and jump (0, 3, 4, 5) are unchanged. `h` is the signed orientation from `hOf`.
    function toRelative(uint8 a, int8 h) internal pure returns (uint8) {
        int8 d = hdir(a);
        if (d == 0) return a;
        uint8 base = a < 3 ? 1 : (a < 8 ? 6 : 8);
        return d == h ? base : base + 1;
    }

    // ------------------------------------------------------------------ the slot
    /// @notice the reference's `check_slot`: fail closed on anything that is not a BRAIN02.5 slot of exactly
    ///         this reference's shape, including a non-zero mood, which replay will not reinterpret
    function checkSlot(bytes memory slot) internal pure {
        if (slot.length != SLOT_BYTES) revert BadSlotLength(slot.length);
        bytes8 marker;
        for (uint256 i = 0; i < 8; ++i) marker |= bytes8(slot[i]) >> (8 * i);
        if (marker != MARKER) revert BadMarker(marker);
        if (uint8(slot[OFF_LAYOUT]) != LAYOUT) revert BadHeaderByte(OFF_LAYOUT, uint8(slot[OFF_LAYOUT]));
        if (uint8(slot[OFF_RETINA]) != RETINA_ID) revert BadHeaderByte(OFF_RETINA, uint8(slot[OFF_RETINA]));
        if (uint8(slot[OFF_INPUTS]) != INPUTS) revert BadHeaderByte(OFF_INPUTS, uint8(slot[OFF_INPUTS]));
        if (uint8(slot[OFF_HIDDEN]) != 0) revert BadHeaderByte(OFF_HIDDEN, uint8(slot[OFF_HIDDEN]));
        if (uint8(slot[OFF_OUTPUTS]) != OUTPUTS) revert BadHeaderByte(OFF_OUTPUTS, uint8(slot[OFF_OUTPUTS]));
        if (uint8(slot[OFF_RULE]) != RULE) revert BadHeaderByte(OFF_RULE, uint8(slot[OFF_RULE]));
        if (uint8(slot[OFF_VOCABULARY]) > 1) revert BadHeaderByte(OFF_VOCABULARY, uint8(slot[OFF_VOCABULARY]));
        if (uint8(slot[OFF_KIND]) > KIND_MAX) revert BadHeaderByte(OFF_KIND, uint8(slot[OFF_KIND]));
        for (uint256 o = 0; o < OUTPUTS; ++o) {
            int8 m = int8(uint8(slot[MOOD_OFFSET + o]));
            // o < 10
            // forge-lint: disable-next-line(unsafe-typecast)
            if (m != 0) revert MoodNotZero(uint8(o), m);
        }
    }

    /// @notice the education counter, u16 little-endian at [18, 20)
    function educationOf(bytes memory slot) internal pure returns (uint16) {
        return uint16(uint8(slot[OFF_EDUCATION])) | (uint16(uint8(slot[OFF_EDUCATION + 1])) << 8);
    }

    /// @notice the reference's `slot_bytes(kind, vocab, W, education, mood=zero, period, lineage, rule, retina_id)`
    ///         with every named field taken from `parent`: the marker, then kind, LAYOUT, 80, 0, 10, period,
    ///         lineage, rule, vocabulary, retina, education (little-endian), four zero bytes; the 800 weights;
    ///         ten zero mood bytes. Bytes [20, 24) are written zero whatever the parent held, as slot_bytes
    ///         writes them; the parent's mood is zero by checkSlot, and so is the child's.
    function buildSlot(bytes memory parent, bytes memory w, uint16 education) internal pure returns (bytes memory child) {
        if (w.length != WEIGHT_BYTES) revert BadWeightsLength(w.length);
        child = new bytes(SLOT_BYTES);
        for (uint256 i = 0; i < 8; ++i) child[i] = MARKER[i];
        child[OFF_KIND] = parent[OFF_KIND];
        child[OFF_LAYOUT] = bytes1(LAYOUT);
        // INPUTS is 80 and OUTPUTS is 10: both are header bytes by definition
        // forge-lint: disable-next-line(unsafe-typecast)
        child[OFF_INPUTS] = bytes1(uint8(INPUTS));
        child[OFF_HIDDEN] = 0;
        // forge-lint: disable-next-line(unsafe-typecast)
        child[OFF_OUTPUTS] = bytes1(uint8(OUTPUTS));
        child[OFF_PERIOD] = parent[OFF_PERIOD];
        child[OFF_LINEAGE] = parent[OFF_LINEAGE];
        child[OFF_RULE] = parent[OFF_RULE];
        child[OFF_VOCABULARY] = parent[OFF_VOCABULARY];
        child[OFF_RETINA] = parent[OFF_RETINA];
        // the two bytes of a uint16, low first: masked and shifted, neither cast can lose a bit
        // forge-lint: disable-next-line(unsafe-typecast)
        child[OFF_EDUCATION] = bytes1(uint8(education & 0xFF));
        // forge-lint: disable-next-line(unsafe-typecast)
        child[OFF_EDUCATION + 1] = bytes1(uint8(education >> 8));
        // [20, 24) stay zero; the weights in one word-oriented copy (lever 3 of study D); the mood stays zero
        uint256 off = WEIGHTS_OFFSET;
        uint256 len = WEIGHT_BYTES;
        assembly ("memory-safe") {
            mcopy(add(child, add(32, off)), add(w, 32), len)
        }
    }

    // ------------------------------------------------------------------ the replay
    /// @dev the per-lesson working memory of one replay, allocated once and reused for every lesson
    ///      (lever 5 of study D). Safe to reuse because every "into" function assigns every element of
    ///      the arrays it fills on every call: `lesson` all 15 bytes, `x` all 27, `v` all 36, `z` all 80,
    ///      `sum` and `acc` all 10; `zeroMood` is never written; `table` is the constant, read only.
    struct Scratch {
        bytes table;
        bytes lesson;
        int8[SENSE_COUNT] x;
        int8[VALUE_COUNT] v;
        uint8[INPUTS] z;
        int256[OUTPUTS] sum;
        int16[OUTPUTS] acc;
        int8[OUTPUTS] zeroMood;
    }

    /// @dev what happened, as the reference's record reports it
    struct Replay {
        uint256 lessons;          // entries in the stream
        uint256 applied;          // lessons that moved the weights (p != t)
        uint256 noChange;         // lessons where p == t
        uint16 educationBefore;   // the parent's counter
        uint16 educationAfter;    // the child's counter: before + applied
        uint8 vocabulary;         // the slot's vocabulary byte, 0 absolute or 1 reference-relative
        uint8 kind;               // the kind byte, carried unchanged
    }

    /// @notice `brain025_ref.replay(start_slot, lesson_bytes)`: the rule applied to each lesson in the order
    ///         the machine recorded them, from the parent slot to the child slot
    /// @dev The parent is checked first (checkSlot), then the whole stream (a multiple of 15 bytes, every
    ///      taught nibble <= 9) before any lesson is applied, as the reference does. Per lesson: the 27
    ///      senses from the 15 bytes; the 80 flags; the taught action converted by toRelative under the
    ///      block's hOf when the vocabulary byte is 1, else used as recorded; learn (mood-free); the recorded
    ///      high nibble compared with the recomputed prediction - a difference reverts with the lesson
    ///      index, where the reference records it and carries on; education += 1 when the lesson took. The
    ///      child is built as slot_bytes builds it. Nothing is persisted and nothing is hashed here; the
    ///      caller hashes the child with sha256 for the canonical hash.
    function replay(bytes memory parent, bytes memory lessons) internal pure returns (bytes memory child, Replay memory rec) {
        checkSlot(parent);
        if (lessons.length % LESSON_BYTES != 0) revert BadStreamLength(lessons.length);
        rec.lessons = lessons.length / LESSON_BYTES;
        for (uint256 k = 0; k < rec.lessons; ++k) {
            uint8 taught = uint8(lessons[k * LESSON_BYTES + LESSON_BYTES - 1]) & 15;
            if (taught > 9) revert BadTaughtAction(k, taught);
        }
        rec.vocabulary = uint8(parent[OFF_VOCABULARY]);
        rec.kind = uint8(parent[OFF_KIND]);
        rec.educationBefore = educationOf(parent);
        // the 800 weight bytes out of the parent in one word-oriented copy (lever 3 of study D): the same
        // bytes a byte loop would move, at a small fraction of its gas; parent is exactly SLOT_BYTES here
        bytes memory w = new bytes(WEIGHT_BYTES);
        uint256 off = WEIGHTS_OFFSET;
        uint256 len = WEIGHT_BYTES;
        assembly ("memory-safe") {
            mcopy(add(w, 32), add(parent, add(32, off)), len)
        }
        uint256 education = rec.educationBefore;
        Scratch memory s;
        s.table = RETINA_T1;
        s.lesson = new bytes(LESSON_BYTES);
        for (uint256 k = 0; k < rec.lessons; ++k) {
            for (uint256 i = 0; i < LESSON_BYTES; ++i) s.lesson[i] = lessons[k * LESSON_BYTES + i];
            (uint8 taughtAbs, uint8 recorded) = unpackLessonInto(s.lesson, s.x);
            evaluateInto(s.table, s.x, s.v, s.z);
            uint8 t = rec.vocabulary == 1 ? toRelative(taughtAbs, hOf(s.x)) : taughtAbs;
            (uint8 p, bool took) = learnWith(w, s.z, t, s.sum, s.acc, s.zeroMood);
            if (p != recorded) revert PredictionMismatch(k, recorded, p);
            if (took) { rec.applied++; education++; } else { rec.noChange++; }
        }
        if (education > type(uint16).max) revert EducationOverflow(education);
        // bounded by the check above
        // forge-lint: disable-next-line(unsafe-typecast)
        rec.educationAfter = uint16(education);
        child = buildSlot(parent, w, rec.educationAfter);
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=../rehearsal/lib/forge-std/src/",
    "rehearsal/=../rehearsal/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.