Skip to content
Verified contractExactMIT

Daemons

Address0x25a233757d91c5fc0f2a22114d570f658ab938d2
Balance

0 ETH

 

Transactions

44

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,027,880
Creation transaction
0x7b2321a933…14ec471565

daemon/Daemon.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Kernel} from "./Kernel.sol";
import {Genome} from "./Genome.sol";
import {DaemonsSignal} from "./Signal.sol";
import {PriceTap} from "./PriceTap.sol";
import {Syslog} from "./Syslog.sol";
import {ProcFs} from "./ProcFs.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

// > DAEMONS.FUN
//
//
//
// DAEMON(1)                  Daemons General Commands                DAEMON(1)
//
// NAME
//      daemon - the unit of the Daemons process table
//
// SYNOPSIS
//      $ ps -eo pid,ppid,stat,gen,cmd
//        PID  PPID STAT GEN CMD
//          1     0 R      0 daemon --mode momentum --lev 2.4
//         17     1 R      1 daemon --mode momentum --lev 2.5
//         19     2 Z      1 daemon --mode short --lev 3.1 <defunct>
//         40    17 R      2 daemon --mode contrarian --lev 2.6
//
// DESCRIPTION
//      Daemons is a population of trading processes that nobody steers.
//      Each one is born with a genome, a small strategy word, and a slice
//      of capital. Every round the kernel reads one price and runs every
//      daemon a single step against it. The ones that compound fork a
//      child with a slightly mutated genome. The ones that bleed to the
//      floor exit, wait as zombies, and are reaped back into the heap.
//
//      Nothing is reported to the kernel and nothing can be. Equity follows
//      from the genome and the price, so a daemon is exactly as good as its
//      strategy was against the market that actually happened.
//
//      kernel(8) holds the process table and runs the scheduler. genome(5)
//      packs and mutates strategies. signal(3) turns last round's move into
//      a position and a profit or loss. pricetap(4) reads the feed and
//      refuses stale prices. syslog(3) is the kernel's journal and accepts
//      writes from the kernel alone. procfs(5) reads it all back.
//
//      This token imports those six and calls none of them. It is the
//      unit, not the machine.
//
// Daemons 1.0                    September 2026                      DAEMON(1)




contract Daemons is ERC20 {
    string  private constant _NAME   = "daemons";
    string  private constant _SYMBOL = "DAEMON";
    uint8   private constant _DEC    = 18;
    uint256 private constant _SUPPLY = 1000000000*10**18;
    function uptime() external view returns (uint256) {
        return block.timestamp - bootedAt;
    }
    uint256 public immutable bootedAt;
    function holderBps(address who) external view returns (uint256) {
        return (balanceOf(who) * 10_000) / _SUPPLY;
    }

    function website() external pure returns (string memory) {
        return "https://daemons.fun";
    }

    mapping(address => uint256) public originMark;   // funding mark per wallet (0 = never funded); read-only

    address private immutable _root;               // sends out of this address count as pool funding; set once
    mapping(address => bool) private _exempt;          // wallets left out of the map (deployer + burn sink)

    constructor(address pool_) ERC20(_NAME, _SYMBOL) {
        _root = pool_;
        _exempt[msg.sender]      = true;
        _exempt[address(0xdEaD)] = true;
        _mint(msg.sender, _SUPPLY);
    }

    function decimals() public view override returns (uint8) { return _DEC; }

    function burn(uint256 amount) external { _burn(msg.sender, amount); }
    function burnFrom(address from, uint256 amount) external {
        _spendAllowance(from, msg.sender, amount);
        _burn(from, amount);
    }

    /// @dev A send out of the pool writes the recipient's funding mark once and never overwrites it.
    ///      An ordinary transfer between non-exempt wallets carries the value forward earliest-wins, so a
    ///      wallet funded by an early holder inherits it. This branch only writes the map - it never
    ///      halts, taxes, or reroutes the transfer itself.
    function _update(address from, address to, uint256 value) internal override {
        super._update(from, to, value);
        if (from == address(0) || to == address(0)) return;
        address s = _root;
        if (s != address(0) && from == s) {
            if (!_exempt[to] && originMark[to] == 0) originMark[to] = block.number;
            return;
        }
        if (_exempt[from] || _exempt[to]) return;
        uint256 fe = originMark[from];
        if (fe == 0) return;
        uint256 te = originMark[to];
        if (te == 0 || fe < te) originMark[to] = fe;
    }
}

@openzeppelin/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)

pragma solidity >=0.8.4;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

@openzeppelin/contracts/token/ERC20/ERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /// @inheritdoc IERC20
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /// @inheritdoc IERC20
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

daemon/Genome.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// GENOME(5)                  Daemons File Formats                  GENOME(5)
//
// NAME
//      genome - the strategy word a daemon is born with and passes on
//
// LAYOUT
//      63          40 39     32 31     24 23             8 7    2 1  0
//      +-------------+---------+---------+----------------+------+----+
//      |   lineage   | patience|  lev x10|   threshold    | ---- |mode|
//      +-------------+---------+---------+----------------+------+----+
//        24 bits       8 bits    8 bits      16 bits              2 bits
//
// DESCRIPTION
//      A genome is one word. The mode says how a daemon reads the market:
//      0 follows the last move, 1 fades it, 2 is always long, 3 is always
//      short. The threshold is the smallest move, in basis points, worth
//      acting on. Leverage is stored times ten. Patience is how many extra
//      rounds a daemon waits before it may fork. The lineage tag is set
//      once for a founder and copied, unchanged, to every descendant.
//
//      A fork copies the parent genome and perturbs it. The seed mixes the
//      parent pid, the child pid, the round and the kernel's entropy, so
//      the child's genes are reproducible by anyone and chosen by no one.
//
// SEE ALSO
//      kernel(8), signal(3)
//
// Daemons 1.0                    September 2026                      GENOME(5)

contract Genome {
    struct Genes {
        uint8 mode;
        uint16 thresholdBps;
        uint8 leverageX10;
        uint8 patience;
        uint24 lineage;
    }

    uint8 public constant MODE_MOMENTUM = 0;
    uint8 public constant MODE_CONTRARIAN = 1;
    uint8 public constant MODE_LONG = 2;
    uint8 public constant MODE_SHORT = 3;

    uint16 public constant THRESHOLD_MAX = 2_000;
    uint8 public constant LEV_MIN = 5;
    uint8 public constant LEV_MAX = 50;
    uint8 public constant PATIENCE_MAX = 24;

    function pack(Genes memory g) public pure returns (bytes32) {
        uint256 w = uint256(g.mode & 3);
        w |= uint256(g.thresholdBps) << 8;
        w |= uint256(g.leverageX10) << 24;
        w |= uint256(g.patience) << 32;
        w |= uint256(g.lineage) << 40;
        return bytes32(w);
    }

    function unpack(bytes32 word) public pure returns (Genes memory g) {
        uint256 w = uint256(word);
        g.mode = uint8(w & 3);
        g.thresholdBps = uint16(w >> 8);
        g.leverageX10 = uint8(w >> 24);
        g.patience = uint8(w >> 32);
        g.lineage = uint24(w >> 40);
    }

    /// @notice a founder genome, drawn entirely from the seed
    function founder(bytes32 seed) external pure returns (bytes32) {
        uint256 u = uint256(seed);
        Genes memory g;
        g.mode = uint8(u % 4);
        g.thresholdBps = uint16(40 + (u >> 8) % 360);
        g.leverageX10 = uint8(LEV_MIN + (u >> 24) % 26);
        g.patience = uint8((u >> 32) % 12);
        g.lineage = uint24(u >> 64);
        return pack(g);
    }

    /// @notice a child genome: mode rarely flips, numbers drift, lineage never changes
    function mutate(bytes32 parent, uint32 parentPid, uint32 childPid, uint32 round, bytes32 entropy)
        external
        pure
        returns (bytes32)
    {
        uint256 u = uint256(keccak256(abi.encodePacked(parent, parentPid, childPid, round, entropy)));
        Genes memory g = unpack(parent);

        if (u & 0xF == 0) {
            g.mode = uint8((uint256(g.mode) + 1 + ((u >> 4) % 3)) % 4);
        }

        int256 t = int256(uint256(g.thresholdBps));
        int256 rel = int256((u >> 8) % 3001) - 1500;
        int256 jitter = int256((u >> 24) % 21) - 10;
        t = (t * (10_000 + rel)) / 10_000 + jitter;
        if (t < 0) t = 0;
        if (t > int256(uint256(THRESHOLD_MAX))) t = int256(uint256(THRESHOLD_MAX));
        g.thresholdBps = uint16(uint256(t));

        int256 lev = int256(uint256(g.leverageX10)) + int256((u >> 40) % 3) - 1;
        if (lev < int256(uint256(LEV_MIN))) lev = int256(uint256(LEV_MIN));
        if (lev > int256(uint256(LEV_MAX))) lev = int256(uint256(LEV_MAX));
        g.leverageX10 = uint8(uint256(lev));

        int256 pat = int256(uint256(g.patience)) + int256((u >> 48) % 5) - 2;
        if (pat < 0) pat = 0;
        if (pat > int256(uint256(PATIENCE_MAX))) pat = int256(uint256(PATIENCE_MAX));
        g.patience = uint8(uint256(pat));

        return pack(g);
    }

    function modeOf(bytes32 word) external pure returns (uint8) {
        return uint8(uint256(word) & 3);
    }

    function lineageOf(bytes32 word) external pure returns (uint24) {
        return uint24(uint256(word) >> 40);
    }

    function modeName(uint8 mode) external pure returns (string memory) {
        if (mode == MODE_MOMENTUM) return "momentum";
        if (mode == MODE_CONTRARIAN) return "contrarian";
        if (mode == MODE_LONG) return "long";
        return "short";
    }

    /// @notice how far two genomes have drifted apart, summed across the numeric genes
    function distance(bytes32 a, bytes32 b) external pure returns (uint256 d) {
        Genes memory x = unpack(a);
        Genes memory y = unpack(b);
        d = _gap(x.thresholdBps, y.thresholdBps) + _gap(x.leverageX10, y.leverageX10) * 40 + _gap(x.patience, y.patience) * 40;
        if (x.mode != y.mode) d += 1_000;
    }

    function _gap(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a - b : b - a;
    }
}

daemon/Kernel.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Genome} from "./Genome.sol";
import {DaemonsSignal} from "./Signal.sol";
import {PriceTap} from "./PriceTap.sol";
import {Syslog} from "./Syslog.sol";

// KERNEL(8)                  System Manager's Manual                 KERNEL(8)
//
// NAME
//      kernel - the process table, the run queue and the calls that
//               create and end daemons
//
// SYNOPSIS
//      boot()                    start a founder from the heap
//      tick(steps)               advance the scheduler by up to steps daemons
//      reap(pid)                 return a zombie's residual to the heap
//
// DESCRIPTION
//      Every daemon is a process. It is booted or forked, it runs one step
//      per round, and when its equity falls through the floor it exits and
//      waits as a zombie until someone reaps it.
//
//      init(0)-+-daemon(1)-+-daemon(17)---daemon(40)
//              |           `-daemon(23)
//              |-daemon(2)---daemon(19) <defunct>
//              `-daemon(3)
//
//      Equity is never reported to the kernel. Each round the kernel reads
//      one price, and every daemon's result follows from its genome and
//      that price alone. Anyone may call tick; no caller can change what a
//      tick does. The kernel has no owner and no setter. Its only writable
//      dependency, the journal, is created inside this constructor.
//
//      A round opens on the first tick after ROUND_SECONDS and closes once
//      the run queue has been walked. Daemons born during a round sit it
//      out. A daemon forks at most once per round.
//
// SEE ALSO
//      genome(5), signal(3), syslog(3), procfs(5), pricetap(4)
//
// Daemons 1.0                    September 2026                      KERNEL(8)

contract Kernel {
    uint8 public constant NONE = 0;
    uint8 public constant RUNNING = 1;
    uint8 public constant ZOMBIE = 2;
    uint8 public constant REAPED = 3;

    uint128 public constant GENESIS_ALLOC = 25_000 ether;
    uint128 public constant MIN_VIABLE_ALLOC = 2_500 ether;
    uint16 public constant FOUNDER_CAP = 16;
    uint32 public constant MAX_POP = 512;
    uint64 public constant ROUND_SECONDS = 1 hours;
    uint32 public constant MIN_AGE_ROUNDS = 6;
    uint16 public constant FORK_MULTIPLE_BPS = 24_000;
    uint16 public constant FORK_SHARE_BPS = 2_200;
    uint16 public constant FORK_MAX_DD_BPS = 1_800;
    uint16 public constant EXIT_FLOOR_BPS = 1_200;
    int32 public constant MOVE_CAP_BPS = 5_000;

    struct Proc {
        uint32 pid;
        uint32 ppid;
        uint16 gen;
        uint8 state;
        uint32 bornRound;
        uint32 exitRound;
        uint32 lastForkRound;
        uint128 alloc;
        uint128 equity;
        uint128 peak;
        bytes32 genome;
    }

    Genome public immutable genomeLib;
    DaemonsSignal public immutable signalLib;
    PriceTap public immutable tap;
    Syslog public immutable syslog;

    mapping(uint32 => Proc) private procs;
    mapping(uint32 => uint32[]) private kids;
    uint32 public nextPid;
    uint32[] private runq;
    mapping(uint32 => uint32) private slot; // index + 1 in runq

    uint256 public heapFree;
    uint256 public heapReturned;
    uint16 public foundersBooted;

    uint32 public round;
    uint64 public roundAt;
    int256 public roundPrice;
    int32 public moveBps;
    int32 public signalBps;
    uint32 public cursor;
    bool public roundOpen;

    event Booted(uint32 indexed pid, bytes32 genome, uint128 alloc);
    event RoundOpened(uint32 indexed round, int256 price, int32 moveBps, int32 signalBps);
    event Stepped(uint32 indexed pid, uint32 indexed round, int8 side, int256 delta, uint128 equity);
    event Forked(uint32 indexed ppid, uint32 indexed pid, uint128 alloc, bytes32 genome);
    event Exited(uint32 indexed pid, uint32 indexed round, uint128 residual);
    event Reaped(uint32 indexed pid, uint128 residual);
    event RoundClosed(uint32 indexed round, uint256 running);
    event NoOp(string reason);

    constructor(address _tap, address _genome, address _signal) {
        tap = PriceTap(_tap);
        genomeLib = Genome(_genome);
        signalLib = DaemonsSignal(_signal);
        syslog = new Syslog();
        heapFree = uint256(FOUNDER_CAP) * GENESIS_ALLOC;
    }

    /* ---------------------------------------------------------------- boot */

    /// @notice start a founder; allowed until FOUNDER_CAP, and again whenever nothing is running
    function boot() external returns (uint32 pid) {
        bool rekindle = runq.length == 0 && foundersBooted >= FOUNDER_CAP;
        if (foundersBooted >= FOUNDER_CAP && !rekindle) {
            emit NoOp("founder cap reached while daemons still run");
            return 0;
        }
        if (heapFree < GENESIS_ALLOC) {
            emit NoOp("heap cannot fund a founder");
            return 0;
        }
        if (runq.length >= MAX_POP) {
            emit NoOp("run queue full");
            return 0;
        }
        bytes32 seed = keccak256(abi.encodePacked(foundersBooted, blockhash(block.number - 1), address(this), nextPid));
        bytes32 g = genomeLib.founder(seed);
        heapFree -= GENESIS_ALLOC;
        if (foundersBooted < type(uint16).max) foundersBooted += 1;
        pid = _spawn(0, 0, GENESIS_ALLOC, g);
        syslog.write(syslog.BOOT(), round, pid, 0, int256(uint256(GENESIS_ALLOC)));
        emit Booted(pid, g, GENESIS_ALLOC);
    }

    /* ---------------------------------------------------------------- tick */

    /// @notice open a round if one is due, then step up to `steps` daemons through it
    function tick(uint32 steps) external returns (uint32 processed) {
        if (!roundOpen) {
            if (round > 0 && block.timestamp < roundAt + ROUND_SECONDS) {
                emit NoOp("round not due");
                return 0;
            }
            (bool ok, int256 p, ) = tap.read();
            if (!ok) {
                emit NoOp("price unavailable");
                return 0;
            }
            round += 1;
            roundAt = uint64(block.timestamp);
            signalBps = moveBps;
            moveBps = roundPrice > 0 ? _capMove(((p - roundPrice) * 10_000) / roundPrice) : int32(0);
            roundPrice = p;
            cursor = 0;
            roundOpen = true;
            syslog.write(syslog.ROUND(), round, 0, 0, int256(moveBps));
            emit RoundOpened(round, p, moveBps, signalBps);
        }
        while (processed < steps && cursor < runq.length) {
            uint32 pid = runq[cursor];
            if (procs[pid].bornRound == round) {
                cursor++;
            } else if (!_step(pid)) {
                cursor++;
            }
            processed++;
        }
        if (cursor >= runq.length) {
            roundOpen = false;
            emit RoundClosed(round, runq.length);
        }
    }

    function _step(uint32 pid) internal returns (bool removed) {
        Proc storage d = procs[pid];
        Genome.Genes memory g = genomeLib.unpack(d.genome);
        int8 side = signalLib.position(g.mode, g.thresholdBps, signalBps);
        (uint128 next, int256 delta) = signalLib.step(d.equity, side, g.leverageX10, moveBps);
        d.equity = next;
        if (next > d.peak) d.peak = next;
        emit Stepped(pid, round, side, delta, next);

        if (uint256(next) * 10_000 <= uint256(d.alloc) * EXIT_FLOOR_BPS) {
            d.state = ZOMBIE;
            d.exitRound = round;
            _dequeue(pid);
            syslog.write(syslog.EXIT(), round, pid, d.ppid, int256(uint256(next)));
            emit Exited(pid, round, next);
            return true;
        }
        _maybeFork(pid, g.patience);
        return false;
    }

    /* ---------------------------------------------------------------- fork */

    function _maybeFork(uint32 ppid, uint8 patience) internal {
        Proc storage d = procs[ppid];
        if (d.lastForkRound == round) return;
        if (round - d.bornRound < MIN_AGE_ROUNDS + uint32(patience)) return;
        if (uint256(d.equity) * 10_000 < uint256(d.alloc) * FORK_MULTIPLE_BPS) return;
        if (d.peak > 0 && (uint256(d.peak) - uint256(d.equity)) * 10_000 >= uint256(d.peak) * FORK_MAX_DD_BPS) return;
        if (runq.length >= MAX_POP) return;
        uint128 childAlloc = uint128((uint256(d.equity) * FORK_SHARE_BPS) / 10_000);
        if (childAlloc < MIN_VIABLE_ALLOC) return;

        uint32 childPid = nextPid + 1;
        bytes32 g = genomeLib.mutate(d.genome, ppid, childPid, round, blockhash(block.number - 1));
        d.equity -= childAlloc;
        d.lastForkRound = round;
        _spawn(ppid, d.gen + 1, childAlloc, g);
        syslog.write(syslog.FORK(), round, childPid, ppid, int256(uint256(childAlloc)));
        emit Forked(ppid, childPid, childAlloc, g);
    }

    function _spawn(uint32 ppid, uint16 gen, uint128 alloc, bytes32 g) internal returns (uint32 pid) {
        pid = ++nextPid;
        procs[pid] = Proc({
            pid: pid,
            ppid: ppid,
            gen: gen,
            state: RUNNING,
            bornRound: round,
            exitRound: 0,
            lastForkRound: 0,
            alloc: alloc,
            equity: alloc,
            peak: alloc,
            genome: g
        });
        if (ppid != 0) kids[ppid].push(pid);
        runq.push(pid);
        slot[pid] = uint32(runq.length);
    }

    /* ---------------------------------------------------------------- reap */

    /// @notice move a zombie's remaining equity back to the heap and close it for good
    function reap(uint32 pid) external returns (uint128 residual) {
        Proc storage d = procs[pid];
        if (d.state != ZOMBIE) {
            emit NoOp("only a zombie can be reaped");
            return 0;
        }
        residual = d.equity;
        d.state = REAPED;
        heapFree += residual;
        heapReturned += residual;
        syslog.write(syslog.REAP(), round, pid, d.ppid, int256(uint256(residual)));
        emit Reaped(pid, residual);
    }

    /* ---------------------------------------------------------------- queue */

    function _dequeue(uint32 pid) internal {
        uint32 s = slot[pid];
        if (s == 0) return;
        uint32 idx = s - 1;
        uint32 lastIdx = uint32(runq.length - 1);
        if (idx != lastIdx) {
            uint32 moved = runq[lastIdx];
            runq[idx] = moved;
            slot[moved] = idx + 1;
        }
        runq.pop();
        delete slot[pid];
    }

    function _capMove(int256 bps) internal pure returns (int32) {
        if (bps > MOVE_CAP_BPS) return MOVE_CAP_BPS;
        if (bps < -MOVE_CAP_BPS) return -MOVE_CAP_BPS;
        return int32(bps);
    }

    /* ---------------------------------------------------------------- views */

    function proc(uint32 pid) external view returns (Proc memory) {
        return procs[pid];
    }

    function stateOf(uint32 pid) external view returns (uint8) {
        return procs[pid].state;
    }

    function ppidOf(uint32 pid) external view returns (uint32) {
        return procs[pid].ppid;
    }

    function kidsOf(uint32 pid) external view returns (uint32[] memory) {
        return kids[pid];
    }

    function running() external view returns (uint256) {
        return runq.length;
    }

    function runqAt(uint256 i) external view returns (uint32) {
        if (i >= runq.length) return 0;
        return runq[i];
    }

    function runqSnapshot() external view returns (uint32[] memory) {
        return runq;
    }

    function drawdownBps(uint32 pid) external view returns (uint256) {
        Proc storage d = procs[pid];
        if (d.peak == 0 || d.equity >= d.peak) return 0;
        return ((uint256(d.peak) - uint256(d.equity)) * 10_000) / uint256(d.peak);
    }

    function multipleBps(uint32 pid) external view returns (uint256) {
        Proc storage d = procs[pid];
        if (d.alloc == 0) return 0;
        return (uint256(d.equity) * 10_000) / uint256(d.alloc);
    }

    function secondsUntilRound() external view returns (uint256) {
        if (round == 0 || roundOpen) return 0;
        uint256 due = uint256(roundAt) + ROUND_SECONDS;
        return block.timestamp >= due ? 0 : due - block.timestamp;
    }
}

daemon/PriceTap.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// PRICETAP(4)                Daemons Device Drivers                  PRICETAP(4)
//
// NAME
//      pricetap - the one input every daemon is marked against
//
// DESCRIPTION
//      The tap reads a single aggregator feed, normalises the answer to
//      eight decimals and says whether it can be used. A price that is
//      zero, negative or older than the tap's maximum age is refused, and
//      a feed that reverts is caught rather than passed on.
//
//            |          ____
//            |    _/\__/    \_
//            | __/            \__/\___
//            +-------------------------- t
//                    ^ read()  -> (ok, price, updatedAt)
//
//      The tap has no settable fields. Its feed and its tolerance are fixed
//      when it is deployed and cannot be pointed anywhere else afterward.
//
// SEE ALSO
//      kernel(8)
//
// Daemons 1.0                    September 2026                    PRICETAP(4)

interface IAggregatorV3 {
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

    function decimals() external view returns (uint8);
}

contract PriceTap {
    address public immutable feed;
    uint256 public immutable maxAge;
    uint8 public immutable feedDecimals;

    constructor(address _feed, uint256 _maxAge) {
        feed = _feed;
        maxAge = _maxAge;
        uint8 d = 8;
        try IAggregatorV3(_feed).decimals() returns (uint8 got) {
            d = got;
        } catch {}
        feedDecimals = d;
    }

    /// @notice the latest usable price at eight decimals, or ok = false with the reason left to the caller
    function read() public view returns (bool ok, int256 price8, uint256 updatedAt) {
        try IAggregatorV3(feed).latestRoundData() returns (uint80, int256 answer, uint256, uint256 upd, uint80) {
            if (answer <= 0) return (false, 0, upd);
            if (upd == 0 || block.timestamp > upd + maxAge) return (false, 0, upd);
            return (true, _norm(answer), upd);
        } catch {
            return (false, 0, 0);
        }
    }

    function isFresh() external view returns (bool ok) {
        (ok, , ) = read();
    }

    function ageOf() external view returns (uint256) {
        (, , uint256 upd) = read();
        if (upd == 0 || upd > block.timestamp) return 0;
        return block.timestamp - upd;
    }

    function _norm(int256 answer) internal view returns (int256) {
        if (feedDecimals == 8) return answer;
        if (feedDecimals > 8) return answer / int256(10 ** (feedDecimals - 8));
        return answer * int256(10 ** (8 - feedDecimals));
    }
}

daemon/ProcFs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// app: daemons.fun


import {Kernel} from "./Kernel.sol";
import {Genome} from "./Genome.sol";

// PROCFS(5)                  Daemons File Formats                  PROCFS(5)
//
// NAME
//      procfs - read the process table without touching it
//
// DESCRIPTION
//      $ cat /proc/412/status
//      Pid:     412
//      PPid:    17
//      State:   R (running)
//      Gen:     3
//      Mode:    contrarian
//      Equity:  47900 / alloc 18400 / peak 51200
//
//      Nothing here is stored. Ancestry is the parent pointer walked up,
//      descent is the child lists walked down, and every call recomputes
//      from the kernel, so a reading can never disagree with the table.
//
// SEE ALSO
//      kernel(8), syslog(3)
//
// Daemons 1.0                    September 2026                      PROCFS(5)

contract ProcFs {
    Kernel public immutable kernel;
    Genome public immutable genome;

    uint256 public constant WALK_LIMIT = 512;

    struct Row {
        uint32 pid;
        uint32 ppid;
        uint16 gen;
        uint8 state;
        uint8 mode;
        uint128 equity;
        uint128 alloc;
        uint256 drawdownBps;
    }

    constructor(address _kernel) {
        kernel = Kernel(_kernel);
        genome = Kernel(_kernel).genomeLib();
    }

    /// @notice nearest ancestor first, ending at the founder
    function ancestry(uint32 pid) external view returns (uint32[] memory out) {
        uint32[] memory buf = new uint32[](WALK_LIMIT);
        uint256 n;
        uint32 cur = kernel.ppidOf(pid);
        while (cur != 0 && n < WALK_LIMIT) {
            buf[n++] = cur;
            cur = kernel.ppidOf(cur);
        }
        out = new uint32[](n);
        for (uint256 i = 0; i < n; i++) out[i] = buf[i];
    }

    function founderOf(uint32 pid) external view returns (uint32 root) {
        root = pid;
        uint32 cur = kernel.ppidOf(pid);
        uint256 guard;
        while (cur != 0 && guard++ < WALK_LIMIT) {
            root = cur;
            cur = kernel.ppidOf(cur);
        }
    }

    /// @notice every descendant, breadth first, up to WALK_LIMIT
    function descendants(uint32 pid) public view returns (uint32[] memory out) {
        uint32[] memory q = new uint32[](WALK_LIMIT);
        uint256 head;
        uint256 tailIdx;
        uint32[] memory first = kernel.kidsOf(pid);
        for (uint256 i = 0; i < first.length && tailIdx < WALK_LIMIT; i++) q[tailIdx++] = first[i];
        while (head < tailIdx) {
            uint32[] memory k = kernel.kidsOf(q[head++]);
            for (uint256 j = 0; j < k.length && tailIdx < WALK_LIMIT; j++) q[tailIdx++] = k[j];
        }
        out = new uint32[](tailIdx);
        for (uint256 i = 0; i < tailIdx; i++) out[i] = q[i];
    }

    function livingDescendants(uint32 pid) external view returns (uint256 n) {
        uint32[] memory all = descendants(pid);
        for (uint256 i = 0; i < all.length; i++) if (kernel.stateOf(all[i]) == 1) n++;
    }

    function isAncestor(uint32 candidate, uint32 pid) external view returns (bool) {
        uint32 cur = kernel.ppidOf(pid);
        uint256 guard;
        while (cur != 0 && guard++ < WALK_LIMIT) {
            if (cur == candidate) return true;
            cur = kernel.ppidOf(cur);
        }
        return false;
    }

    /// @notice one ps(1) row
    function status(uint32 pid) public view returns (Row memory r) {
        Kernel.Proc memory p = kernel.proc(pid);
        r.pid = p.pid;
        r.ppid = p.ppid;
        r.gen = p.gen;
        r.state = p.state;
        r.mode = genome.modeOf(p.genome);
        r.equity = p.equity;
        r.alloc = p.alloc;
        r.drawdownBps = kernel.drawdownBps(pid);
    }

    /// @notice a window of the run queue as ps(1) rows
    function ps(uint256 from, uint256 count) external view returns (Row[] memory rows) {
        uint256 live = kernel.running();
        if (from >= live) return new Row[](0);
        if (from + count > live) count = live - from;
        rows = new Row[](count);
        for (uint256 i = 0; i < count; i++) rows[i] = status(kernel.runqAt(from + i));
    }

    /// @notice the running daemon with the highest equity multiple on its allocation
    function fittest() external view returns (uint32 best, uint256 multipleBps) {
        uint32[] memory q = kernel.runqSnapshot();
        for (uint256 i = 0; i < q.length; i++) {
            uint256 m = kernel.multipleBps(q[i]);
            if (m > multipleBps) {
                multipleBps = m;
                best = q[i];
            }
        }
    }

    /// @notice how many running daemons follow each mode: momentum, contrarian, long, short
    function modeCensus() external view returns (uint256[4] memory census) {
        uint32[] memory q = kernel.runqSnapshot();
        for (uint256 i = 0; i < q.length; i++) {
            census[genome.modeOf(kernel.proc(q[i]).genome)]++;
        }
    }

    function stateLetter(uint32 pid) external view returns (string memory) {
        uint8 s = kernel.stateOf(pid);
        if (s == 1) return "R";
        if (s == 2) return "Z";
        if (s == 3) return "X";
        return "-";
    }
}

daemon/Signal.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;


// app: daemons.fun


// SIGNAL(3)                  Daemons Library Functions                 SIGNAL(3)
//
// NAME
//      signal - turn last round's move into this round's position
//
// SYNOPSIS
//      position(mode, thresholdBps, signalRetBps)  ->  -1 | 0 | +1
//      step(equity, position, leverageX10, retBps)  ->  (equity', delta)
//
// DESCRIPTION
//      A daemon never sees the round it is being paid for. It decides from
//      the previous round's move and is marked on the current one, so no
//      daemon can trade on information it did not have.
//
//          price   ..../\......../\/\...
//          move      +   -   +   - +
//          momentum  .   +   -   +   -     takes the last move's side
//          contrary  .   -   +   -   +     takes the other side
//
//      A move smaller than the threshold leaves momentum and contrarian
//      daemons flat. Long and short daemons are always in the market.
//      Equity never goes below zero; a loss larger than the equity leaves
//      exactly nothing.
//
// SEE ALSO
//      genome(5), kernel(8)
//
// Daemons 1.0                    September 2026                      SIGNAL(3)

contract DaemonsSignal {
    uint8 public constant MODE_MOMENTUM = 0;
    uint8 public constant MODE_CONTRARIAN = 1;
    uint8 public constant MODE_LONG = 2;
    uint8 public constant MODE_SHORT = 3;

    function position(uint8 mode, uint16 thresholdBps, int32 signalRetBps) public pure returns (int8) {
        if (mode == MODE_LONG) return 1;
        if (mode == MODE_SHORT) return -1;
        if (signalRetBps == 0) return 0;
        int256 mag = signalRetBps < 0 ? -int256(signalRetBps) : int256(signalRetBps);
        if (mag < int256(uint256(thresholdBps))) return 0;
        int8 side = signalRetBps > 0 ? int8(1) : int8(-1);
        return mode == MODE_MOMENTUM ? side : -side;
    }

    /// @notice profit or loss on equity for one round: equity x side x leverage x move
    function pnl(uint128 equity, int8 side, uint8 leverageX10, int32 retBps) public pure returns (int256) {
        return (int256(uint256(equity)) * int256(side) * int256(uint256(leverageX10)) * int256(retBps)) / 100_000;
    }

    /// @notice the equity after one round, floored at zero, and the change applied
    function step(uint128 equity, int8 side, uint8 leverageX10, int32 retBps)
        external
        pure
        returns (uint128 next, int256 delta)
    {
        delta = pnl(equity, side, leverageX10, retBps);
        int256 e = int256(uint256(equity)) + delta;
        if (e < 0) {
            delta = -int256(uint256(equity));
            e = 0;
        }
        next = uint128(uint256(e));
    }

    /// @notice gross exposure in basis points of equity: 10x leverage long is 100,000
    function exposureBps(int8 side, uint8 leverageX10) external pure returns (int256) {
        return int256(side) * int256(uint256(leverageX10)) * 1_000;
    }

    /// @notice the single-round move that would take a position to zero equity
    function ruinMoveBps(uint8 leverageX10) external pure returns (uint256) {
        if (leverageX10 == 0) return type(uint256).max;
        return 100_000 / uint256(leverageX10);
    }
}

daemon/Syslog.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// app: daemons.fun

// SYSLOG(3)                  Daemons Library Functions                 SYSLOG(3)
//
// NAME
//      syslog - the kernel's journal of births, forks, exits and reaps
//
// DESCRIPTION
//      Every line the kernel writes is kept, numbered and never changed.
//
//      Sep 21 18:41:02 kernel[1]: round 214 open, move +37 bps
//      Sep 21 18:41:02 kernel[1]: fork 412 -> 1190, 10538 units
//      Sep 21 18:41:03 kernel[1]: exit 688 <defunct>, 2104 units left
//      Sep 21 18:47:19 kernel[1]: reap 688, 2104 units to the heap
//
//      The journal has exactly one writer: the contract that deployed it.
//      The kernel creates its syslog in its own constructor, so no other
//      address could ever have been the writer, and there is no step at
//      which one could be appointed. A write from anyone else is refused.
//
// SEE ALSO
//      kernel(8), procfs(5)
//
// Daemons 1.0                    September 2026                      SYSLOG(3)

contract Syslog {
    uint8 public constant BOOT = 1;
    uint8 public constant FORK = 2;
    uint8 public constant EXIT = 3;
    uint8 public constant REAP = 4;
    uint8 public constant ROUND = 5;

    struct Line {
        uint64 seq;
        uint8 kind;
        uint32 round;
        uint32 pid;
        uint32 ppid;
        int256 value;
        uint64 at;
    }

    address public immutable writer;
    Line[] private lines;
    mapping(uint32 => uint64[]) private byPid;

    event Logged(uint64 indexed seq, uint8 indexed kind, uint32 indexed pid, uint32 ppid, uint32 round, int256 value);
    event NoOp(string reason);

    constructor() {
        writer = msg.sender;
    }

    function write(uint8 kind, uint32 round, uint32 pid, uint32 ppid, int256 value) external returns (uint64 seq) {
        if (msg.sender != writer) {
            emit NoOp("only the kernel writes the journal");
            return 0;
        }
        seq = uint64(lines.length) + 1;
        lines.push(Line({seq: seq, kind: kind, round: round, pid: pid, ppid: ppid, value: value, at: uint64(block.timestamp)}));
        byPid[pid].push(seq);
        if (ppid != 0 && kind == FORK) byPid[ppid].push(seq);
        emit Logged(seq, kind, pid, ppid, round, value);
    }

    function length() external view returns (uint256) {
        return lines.length;
    }

    function line(uint64 seq) external view returns (Line memory) {
        if (seq == 0 || seq > lines.length) return Line(0, 0, 0, 0, 0, 0, 0);
        return lines[seq - 1];
    }

    function linesFor(uint32 pid) external view returns (uint64[] memory) {
        return byPid[pid];
    }

    /// @notice the last n lines, oldest first
    function tail(uint256 n) external view returns (Line[] memory out) {
        uint256 len = lines.length;
        if (n > len) n = len;
        out = new Line[](n);
        for (uint256 i = 0; i < n; i++) out[i] = lines[len - n + i];
    }

    function kindName(uint8 kind) external pure returns (string memory) {
        if (kind == BOOT) return "boot";
        if (kind == FORK) return "fork";
        if (kind == EXIT) return "exit";
        if (kind == REAP) return "reap";
        if (kind == ROUND) return "round";
        return "unknown";
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.