{
  "language": "Solidity",
  "sources": {
    "contracts/AutomatonCompute.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.30;\n\n/// @notice Colony lifecycle ledger. Compute credits are internal units and never transferable assets.\n/// @dev The colony owner/operator attests observations. The contract enforces all lifecycle transitions.\ncontract AutomatonCompute {\n    uint16 public constant MAX_EPOCHS = 120;\n    uint16 public constant MAX_LIVING = 16;\n    uint16 public constant BIRTH_RESERVE = 22;\n    uint16 public constant CHILD_CREDITS = 8;\n    uint16 public constant BIRTH_COST = 10;\n    uint16 public constant REWARD = 5;\n    uint16 public constant PENALTY = 6;\n    uint64 public constant STALE_SECONDS = 90;\n    uint64 public constant MAX_OBSERVATION_AGE = 600;\n\n    uint8 private constant NONE = 0;\n    uint8 private constant FRESH = 1;\n    uint8 private constant STALE = 2;\n\n    struct Observation {\n        uint64 sourceBlock;\n        uint64 blockTimestamp;\n        uint64 observedAt;\n        uint16 pressureBps;\n        bytes32 sourceHash;\n        bytes32 evidenceHash;\n    }\n\n    struct Colony {\n        address owner;\n        address operator;\n        uint64 lastSourceBlock;\n        uint64 lastObservedAt;\n        uint32 agents;\n        uint32 computeReserve;\n        uint16 epoch;\n        uint16 living;\n        uint8 outcome;\n        bytes32 lastSourceHash;\n    }\n\n    struct Life {\n        uint32 parent;\n        uint16 born;\n        uint16 died;\n        uint16 reserve;\n        uint16 wins;\n        uint16 losses;\n        uint16 generation;\n        uint16 socialBps;\n        uint16 memoryBps;\n        int16 biasBps;\n        int16 lastDelta;\n        uint8 family;\n        uint8 forecast;\n        uint8 streak;\n    }\n\n    struct Epoch {\n        uint32 computeReserve;\n        uint16 living;\n        uint16 births;\n        uint16 deaths;\n        uint16 pressureBps;\n        uint8 outcome;\n        uint64 sourceBlock;\n        uint64 observedAt;\n    }\n\n    error MissingColony();\n    error OwnerOnly();\n    error OperatorOnly();\n    error EpochChanged(uint16 currentEpoch);\n    error ColonyComplete();\n    error InvalidObservation();\n    error ObservationExpired();\n    error RepeatedObservation();\n    error PageTooLarge();\n\n    event ColonyCreated(uint256 indexed colonyId, address indexed owner);\n    event OperatorSet(uint256 indexed colonyId, address indexed operator);\n    event AgentBorn(uint256 indexed colonyId, uint32 indexed agentId, uint32 indexed parentId, uint16 epoch, uint16 reserve);\n    event AgentTerminated(uint256 indexed colonyId, uint32 indexed agentId, uint16 epoch);\n    event EpochSettled(\n        uint256 indexed colonyId,\n        uint16 indexed epoch,\n        uint64 indexed sourceBlock,\n        uint8 outcome,\n        uint16 pressureBps,\n        uint16 living,\n        uint16 births,\n        uint16 deaths,\n        uint32 computeReserve,\n        bytes32 sourceHash,\n        bytes32 evidenceHash\n    );\n\n    uint256 public colonyCount;\n    mapping(uint256 => Colony) private _colonies;\n    mapping(uint256 => mapping(uint32 => Life)) private _lives;\n    mapping(uint256 => uint32[]) private _active;\n    mapping(uint256 => mapping(uint16 => Epoch)) private _epochs;\n\n    function protocolVersion() external pure returns (string memory) {\n        return \"1.0.0\";\n    }\n\n    function createColony() external returns (uint256 colonyId) {\n        colonyId = ++colonyCount;\n        Colony storage colony = _colonies[colonyId];\n        colony.owner = msg.sender;\n        colony.agents = 3;\n        colony.living = 3;\n        colony.computeReserve = 45;\n        emit ColonyCreated(colonyId, msg.sender);\n\n        _founder(colonyId, 1, 0, 18, 3500, 2500, 400);\n        _founder(colonyId, 2, 1, 15, 7600, 4200, -1500);\n        _founder(colonyId, 3, 2, 12, 1900, 6300, 1200);\n        _epochs[colonyId][0] = Epoch(45, 3, 0, 0, 0, NONE, 0, 0);\n    }\n\n    function setOperator(uint256 colonyId, address operator) external {\n        Colony storage colony = _colony(colonyId);\n        if (msg.sender != colony.owner) revert OwnerOnly();\n        colony.operator = operator;\n        emit OperatorSet(colonyId, operator);\n    }\n\n    function getColony(uint256 colonyId) external view returns (Colony memory) {\n        return _colony(colonyId);\n    }\n\n    /// @notice Pages are zero-indexed. Agent ID is offset + index + 1, including terminated lives.\n    function getAgents(uint256 colonyId, uint32 offset, uint32 limit) external view returns (Life[] memory page) {\n        uint32 count = _colony(colonyId).agents;\n        if (limit > 64) revert PageTooLarge();\n        if (offset >= count) return new Life[](0);\n        uint32 remaining = count - offset;\n        uint32 length = limit < remaining ? limit : remaining;\n        page = new Life[](length);\n        for (uint32 index; index < length; ++index) {\n            page[index] = _lives[colonyId][offset + index + 1];\n        }\n    }\n\n    function getEpoch(uint256 colonyId, uint16 epoch) external view returns (Epoch memory) {\n        Colony storage colony = _colony(colonyId);\n        if (epoch > colony.epoch) revert EpochChanged(colony.epoch);\n        return _epochs[colonyId][epoch];\n    }\n\n    function getEpochs(uint256 colonyId, uint16 start, uint16 limit) external view returns (Epoch[] memory page) {\n        uint16 count = _colony(colonyId).epoch + 1;\n        if (limit > 64) revert PageTooLarge();\n        if (start >= count) return new Epoch[](0);\n        uint16 remaining = count - start;\n        uint16 length = limit < remaining ? limit : remaining;\n        page = new Epoch[](length);\n        for (uint16 index; index < length; ++index) {\n            page[index] = _epochs[colonyId][start + index];\n        }\n    }\n\n    /// @notice Accepts one operator-attested observation and advances every living agent.\n    /// @param expectedEpoch The current epoch seen by the caller, to prevent concurrent settlements.\n    function advance(uint256 colonyId, uint16 expectedEpoch, Observation calldata observation) external {\n        Colony storage colony = _colony(colonyId);\n        if (msg.sender != colony.owner && msg.sender != colony.operator) revert OperatorOnly();\n        if (colony.epoch != expectedEpoch) revert EpochChanged(colony.epoch);\n        if (colony.living == 0 || colony.epoch == MAX_EPOCHS) revert ColonyComplete();\n\n        uint8 outcome = _validateObservation(colony, observation);\n        uint16 epoch = expectedEpoch + 1;\n        uint32[16] memory working;\n        uint16 deaths;\n        uint16 births;\n        uint16 living;\n        uint32 reserve;\n\n        for (uint256 i; i < _active[colonyId].length; ++i) {\n            uint32 id = _active[colonyId][i];\n            Life storage life = _lives[colonyId][id];\n            _score(life, outcome);\n            if (life.reserve == 0) {\n                life.died = epoch;\n                life.forecast = NONE;\n                ++deaths;\n                emit AgentTerminated(colonyId, id, epoch);\n                continue;\n            }\n            life.forecast = _predict(life, outcome, observation.pressureBps);\n            working[living++] = id;\n            reserve += life.reserve;\n        }\n\n        uint16 eligible = living;\n        for (uint16 i; i < eligible && living < MAX_LIVING; ++i) {\n            uint32 parentId = working[i];\n            Life storage parent = _lives[colonyId][parentId];\n            if (parent.reserve < BIRTH_RESERVE || parent.streak < 2 || epoch - parent.born < 3) continue;\n            parent.reserve -= BIRTH_COST;\n            parent.streak = 0;\n            uint32 childId = ++colony.agents;\n            _reproduce(colonyId, parent, parentId, childId, epoch, outcome, observation.pressureBps);\n            working[living++] = childId;\n            reserve -= BIRTH_COST - CHILD_CREDITS;\n            ++births;\n        }\n\n        delete _active[colonyId];\n        for (uint16 i; i < living; ++i) _active[colonyId].push(working[i]);\n        colony.epoch = epoch;\n        colony.living = living;\n        colony.computeReserve = reserve;\n        colony.lastSourceBlock = observation.sourceBlock;\n        colony.lastSourceHash = observation.sourceHash;\n        colony.lastObservedAt = observation.observedAt;\n        colony.outcome = outcome;\n        _epochs[colonyId][epoch] = Epoch(reserve, living, births, deaths, observation.pressureBps, outcome, observation.sourceBlock, observation.observedAt);\n        emit EpochSettled(\n            colonyId, epoch, observation.sourceBlock, outcome, observation.pressureBps, living,\n            births, deaths, reserve, observation.sourceHash, observation.evidenceHash\n        );\n    }\n\n    function _colony(uint256 id) private view returns (Colony storage colony) {\n        colony = _colonies[id];\n        if (colony.owner == address(0)) revert MissingColony();\n    }\n\n    function _founder(uint256 colonyId, uint32 id, uint8 family, uint16 reserve, uint16 social, uint16 memoryWeight, int16 bias) private {\n        Life storage life = _lives[colonyId][id];\n        life.family = family;\n        life.reserve = reserve;\n        life.socialBps = social;\n        life.memoryBps = memoryWeight;\n        life.biasBps = bias;\n        _active[colonyId].push(id);\n        emit AgentBorn(colonyId, id, 0, 0, reserve);\n    }\n\n    function _validateObservation(Colony storage colony, Observation calldata input) private view returns (uint8 outcome) {\n        if (\n            input.sourceBlock == 0 || input.blockTimestamp == 0 || input.blockTimestamp > input.observedAt ||\n            input.pressureBps > 10_000 || input.sourceHash == bytes32(0) || input.evidenceHash == bytes32(0)\n        ) revert InvalidObservation();\n        if (input.observedAt > block.timestamp + 30 || uint256(input.observedAt) + MAX_OBSERVATION_AGE < block.timestamp) {\n            revert ObservationExpired();\n        }\n        outcome = input.observedAt - input.blockTimestamp > STALE_SECONDS ? STALE : FRESH;\n        if (colony.epoch == 0) return outcome;\n        if (input.sourceBlock < colony.lastSourceBlock || input.observedAt < colony.lastObservedAt) revert RepeatedObservation();\n        if (input.sourceBlock == colony.lastSourceBlock && (\n            input.sourceHash != colony.lastSourceHash || colony.outcome != FRESH || outcome != STALE ||\n            input.observedAt <= colony.lastObservedAt\n        )) revert RepeatedObservation();\n    }\n\n    function _score(Life storage life, uint8 outcome) private {\n        uint16 before = life.reserve;\n        int256 next = int256(uint256(before)) - (before <= 6 ? int256(1) : int256(2));\n        if (life.forecast == outcome) {\n            next += int256(uint256(REWARD));\n            ++life.wins;\n            ++life.streak;\n        } else if (life.forecast != NONE) {\n            next -= int256(uint256(PENALTY));\n            ++life.losses;\n            life.streak = 0;\n        }\n        life.reserve = next > 0 ? uint16(uint256(next)) : 0;\n        life.lastDelta = int16(int256(uint256(life.reserve)) - int256(uint256(before)));\n    }\n\n    function _predict(Life storage life, uint8 outcome, uint16 pressureBps) private view returns (uint8) {\n        int256 bias = life.biasBps;\n        int256 history = outcome == STALE ? int256(uint256(life.memoryBps)) : int256(0);\n        int256 score = int256(uint256(life.socialBps) * pressureBps) + (history + bias) * 10_000;\n        return score >= 47_000_000 ? STALE : FRESH;\n    }\n\n    function _reproduce(\n        uint256 colonyId, Life storage parent, uint32 parentId, uint32 childId, uint16 epoch, uint8 outcome, uint16 pressureBps\n    ) private {\n        int256 variant = int256((uint256(childId) * 41 + uint256(epoch) * 53) % 23) - 11;\n        Life storage child = _lives[colonyId][childId];\n        child.parent = parentId;\n        child.born = epoch;\n        child.reserve = CHILD_CREDITS;\n        child.family = parent.family;\n        child.generation = parent.generation + 1;\n        child.socialBps = uint16(uint256(_boundedRound(int256(uint256(parent.socialBps)) * 60 + variant * 10_000, 60, 500, 9500)));\n        child.memoryBps = uint16(uint256(_boundedRound(int256(uint256(parent.memoryBps)) * 600 - variant * 70_000, 600, 500, 9500)));\n        child.biasBps = int16(_boundedRound(int256(parent.biasBps) * 1200 + variant * 110_000, 1200, -3000, 3000));\n        child.forecast = _predict(child, outcome, pressureBps);\n        emit AgentBorn(colonyId, childId, parentId, epoch, CHILD_CREDITS);\n    }\n\n    function _boundedRound(int256 numerator, int256 denominator, int256 min, int256 max) private pure returns (int256) {\n        if (numerator <= min * denominator) return min;\n        if (numerator >= max * denominator) return max;\n        int256 step = denominator * 100;\n        int256 shifted = numerator + step / 2;\n        int256 rounded = shifted / step;\n        if (shifted < 0 && shifted % step != 0) --rounded;\n        return rounded * 100;\n    }\n}\n"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "viaIR": true,
    "evmVersion": "paris",
    "outputSelection": {
      "*": {
        "*": [
          "abi",
          "evm.bytecode.object",
          "evm.deployedBytecode.object"
        ]
      }
    }
  }
}
