Skip to content
Verified contractExactMIT

JobRegistryConfiguration

Address0x175b9087a8d088073c9896f0cbf7b072b6ed11bf
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.25

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.25+commit.b61c2a91
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,171,772
Creation transaction
0x4e41d2a439…5da0edd8de

31 files

contracts/v2/implementation/JobRegistryConfiguration.sol

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

import {Governable} from "../Governable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ITaxPolicy} from "../interfaces/ITaxPolicy.sol";
import {TaxAcknowledgement} from "../libraries/TaxAcknowledgement.sol";
import {IValidationModule} from "../interfaces/IValidationModule.sol";
import {IStakeManager} from "../interfaces/IStakeManager.sol";
import {IFeePool} from "../interfaces/IFeePool.sol";
import {IIdentityRegistry} from "../interfaces/IIdentityRegistry.sol";
import {IReputationEngine} from "../interfaces/IReputationEngine.sol";
import {IDisputeModule} from "../interfaces/IDisputeModule.sol";
import {ICertificateNFT} from "../interfaces/ICertificateNFT.sol";
import {IJobRegistryAck} from "../interfaces/IJobRegistryAck.sol";
import {IAuditModule} from "../interfaces/IAuditModule.sol";
import {TOKEN_SCALE} from "../Constants.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import "./JobRegistryBase.sol";
import "./FixedDelegate.sol";

/// @notice Fixed configuration implementation for JobRegistry. Deploy via the modular deployment helper.
contract JobRegistryConfiguration is JobRegistryBase, DelegateOnly {
    constructor() JobRegistryBase(msg.sender) {}

    function moduleId() external pure returns (bytes32) {
        return keccak256("JobRegistryConfiguration:v1");
    }

    function setPauser(address _pauser) external onlyDelegateCall {
        return _entry_setPauser(_pauser);
    }

    function setPauserManager(address manager) external onlyDelegateCall {
        return _entry_setPauserManager(manager);
    }

    function setModules(
        IValidationModule _validation,
        IStakeManager _stakeMgr,
        IReputationEngine _reputation,
        IDisputeModule _disputeModule,
        ICertificateNFT _certNFT,
        IFeePool _feePool,
        address[] calldata _ackModules
    ) external onlyDelegateCall {
        return _entry_setModules(_validation, _stakeMgr, _reputation, _disputeModule, _certNFT, _feePool, _ackModules);
    }

    /// @notice Update the identity registry used for agent verification.
    /// @param registry Address of the IdentityRegistry contract.
    function setIdentityRegistry(IIdentityRegistry registry) external onlyDelegateCall {
        return _entry_setIdentityRegistry(registry);
    }

    /// @notice Switch the active dispute module.
    /// @param module Address of the new dispute module contract.
    function setDisputeModule(IDisputeModule module) external onlyDelegateCall {
        return _entry_setDisputeModule(module);
    }

    /// @notice Update the validation module used to source validator lists.
    /// @param module ValidationModule contract address.
    function setValidationModule(IValidationModule module) external onlyDelegateCall {
        return _entry_setValidationModule(module);
    }

    /// @notice Update the audit module used for post-completion spot checks.
    /// @param module Address of the audit module contract (zero to disable).
    function setAuditModule(IAuditModule module) external onlyDelegateCall {
        return _entry_setAuditModule(module);
    }

    /// @notice Update the stake manager reference.
    /// @param manager StakeManager contract address.
    function setStakeManager(IStakeManager manager) external onlyDelegateCall {
        return _entry_setStakeManager(manager);
    }

    /// @notice Update the reputation engine reference.
    function setReputationEngine(IReputationEngine engine) external onlyDelegateCall {
        return _entry_setReputationEngine(engine);
    }

    /// @notice Update the certificate NFT module reference.
    function setCertificateNFT(ICertificateNFT nft) external onlyDelegateCall {
        return _entry_setCertificateNFT(nft);
    }

    /// @notice Update the ENS root node used for agent verification.
    /// @param node Namehash of the agent parent node (e.g. `agent.agi.eth`).
    function setAgentRootNode(bytes32 node) external onlyDelegateCall {
        return _entry_setAgentRootNode(node);
    }

    /// @notice Update the Merkle root for the agent allowlist.
    /// @param root Merkle root of approved agent addresses.
    function setAgentMerkleRoot(bytes32 root) external onlyDelegateCall {
        return _entry_setAgentMerkleRoot(root);
    }

    /// @notice Increment the agent authorization cache version, invalidating all
    /// existing cached authorizations.
    function bumpAgentAuthCacheVersion() public onlyDelegateCall {
        return _entry_bumpAgentAuthCacheVersion();
    }

    /// @notice Update the ENS root node used for validator verification.
    /// @param node Namehash of the validator parent node (e.g. `club.agi.eth`).
    function setValidatorRootNode(bytes32 node) external onlyDelegateCall {
        return _entry_setValidatorRootNode(node);
    }

    /// @notice Update the Merkle root for the validator allowlist.
    /// @param root Merkle root of approved validator addresses.
    function setValidatorMerkleRoot(bytes32 root) external onlyDelegateCall {
        return _entry_setValidatorMerkleRoot(root);
    }

    /// @notice Refresh or invalidate cached agent authorization entries.
    /// @param agent Address of the agent being updated.
    /// @param authorized True to refresh the cache entry, false to invalidate it.
    function updateAgentAuthCache(address agent, bool authorized) external onlyDelegateCall {
        return _entry_updateAgentAuthCache(agent, authorized);
    }

    /// @notice Update the duration for cached agent authorizations.
    /// @param duration Seconds an authorization remains valid in cache.
    function setAgentAuthCacheDuration(uint256 duration) external onlyDelegateCall {
        return _entry_setAgentAuthCacheDuration(duration);
    }

    /// @notice update the FeePool contract used for revenue sharing
    function setFeePool(IFeePool _feePool) external onlyDelegateCall {
        return _entry_setFeePool(_feePool);
    }

    /// @notice update the treasury address used for blacklisted payouts
    /// @dev Treasury must be zero (burn) or a non-owner address
    function setTreasury(address _treasury) external onlyDelegateCall {
        return _entry_setTreasury(_treasury);
    }

    /// @notice update the required agent stake for each job
    function setJobStake(uint96 stake) external onlyDelegateCall {
        return _entry_setJobStake(stake);
    }

    /// @notice update the minimum global stake required for agents when applying
    function setMinAgentStake(uint256 stake) external onlyDelegateCall {
        return _entry_setMinAgentStake(stake);
    }

    /// @notice update the percentage of each job reward taken as a protocol fee
    function setFeePct(uint256 _feePct) external onlyDelegateCall {
        return _entry_setFeePct(_feePct);
    }

    /// @notice update validator reward percentage of job reward
    function setValidatorRewardPct(uint256 pct) external onlyDelegateCall {
        return _entry_setValidatorRewardPct(pct);
    }

    /// @notice set the maximum allowed job reward
    function setMaxJobReward(uint256 maxReward) external onlyDelegateCall {
        return _entry_setMaxJobReward(maxReward);
    }

    /// @notice set the maximum allowed job duration in seconds
    function setJobDurationLimit(uint256 limit) external onlyDelegateCall {
        return _entry_setJobDurationLimit(limit);
    }

    /// @notice Set the maximum number of simultaneously active jobs an agent may hold.
    /// @dev A value of zero disables the limit.
    function setMaxActiveJobsPerAgent(uint256 limit) external onlyDelegateCall {
        return _entry_setMaxActiveJobsPerAgent(limit);
    }

    /// @notice set additional grace period after a job's deadline before it can expire
    function setExpirationGracePeriod(uint256 period) external onlyDelegateCall {
        return _entry_setExpirationGracePeriod(period);
    }

    /// @notice Sets the TaxPolicy contract holding the canonical disclaimer.
    /// @dev Only callable by the owner; the policy address cannot be zero and
    /// must explicitly report tax exemption.
    function setTaxPolicy(ITaxPolicy _policy) external onlyDelegateCall {
        return _entry_setTaxPolicy(_policy);
    }

    /// @notice Pause job lifecycle interactions
    function pause() external onlyDelegateCall {
        return _entry_pause();
    }

    /// @notice Resume job lifecycle interactions
    function unpause() external onlyDelegateCall {
        return _entry_unpause();
    }

    /// @notice Allow or revoke an acknowledger address.
    /// @dev When `allowed` is true, `acknowledger` must be a non-zero address representing a valid contract or EOA.
    /// @param acknowledger Address granted permission to acknowledge for users.
    /// @param allowed True to allow the address, false to revoke.
    function setAcknowledger(address acknowledger, bool allowed) external onlyDelegateCall {
        return _entry_setAcknowledger(acknowledger, allowed);
    }

    function setJobParameters(uint256 maxReward, uint256 stake) external onlyDelegateCall {
        return _entry_setJobParameters(maxReward, stake);
    }

    /// @notice Apply a batch of configuration updates atomically.
    /// @param config Packed configuration toggles and values to apply.
    /// @param acknowledgerUpdates Acknowledger allow/deny list updates.
    /// @param ackModules Additional acknowledge-for modules to enable.
    function applyConfiguration(
        ConfigUpdate calldata config,
        AcknowledgerUpdate[] calldata acknowledgerUpdates,
        address[] calldata ackModules
    ) external onlyDelegateCall {
        return _entry_applyConfiguration(config, acknowledgerUpdates, ackModules);
    }

    /// @notice Owner can delist an unassigned job and refund the employer.
    /// @param jobId Identifier of the job to delist.
    function delistJob(uint256 jobId) external onlyDelegateCall {
        return _entry_delistJob(jobId);
    }
}

@openzeppelin/contracts/access/AccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

@openzeppelin/contracts/access/IAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

@openzeppelin/contracts/governance/TimelockController.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (governance/TimelockController.sol)

pragma solidity ^0.8.20;

import {AccessControl} from "../access/AccessControl.sol";
import {ERC721Holder} from "../token/ERC721/utils/ERC721Holder.sol";
import {ERC1155Holder} from "../token/ERC1155/utils/ERC1155Holder.sol";
import {Address} from "../utils/Address.sol";
import {IERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module which acts as a timelocked controller. When set as the
 * owner of an `Ownable` smart contract, it enforces a timelock on all
 * `onlyOwner` maintenance operations. This gives time for users of the
 * controlled contract to exit before a potentially dangerous maintenance
 * operation is applied.
 *
 * By default, this contract is self administered, meaning administration tasks
 * have to go through the timelock process. The proposer (resp executor) role
 * is in charge of proposing (resp executing) operations. A common use case is
 * to position this {TimelockController} as the owner of a smart contract, with
 * a multisig or a DAO as the sole proposer.
 */
contract TimelockController is AccessControl, ERC721Holder, ERC1155Holder {
    bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
    bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
    bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE");
    uint256 internal constant _DONE_TIMESTAMP = uint256(1);

    mapping(bytes32 id => uint256) private _timestamps;
    uint256 private _minDelay;

    enum OperationState {
        Unset,
        Waiting,
        Ready,
        Done
    }

    /**
     * @dev Mismatch between the parameters length for an operation call.
     */
    error TimelockInvalidOperationLength(uint256 targets, uint256 payloads, uint256 values);

    /**
     * @dev The schedule operation doesn't meet the minimum delay.
     */
    error TimelockInsufficientDelay(uint256 delay, uint256 minDelay);

    /**
     * @dev The current state of an operation is not as required.
     * The `expectedStates` is a bitmap with the bits enabled for each OperationState enum position
     * counting from right to left.
     *
     * See {_encodeStateBitmap}.
     */
    error TimelockUnexpectedOperationState(bytes32 operationId, bytes32 expectedStates);

    /**
     * @dev The predecessor to an operation not yet done.
     */
    error TimelockUnexecutedPredecessor(bytes32 predecessorId);

    /**
     * @dev The caller account is not authorized.
     */
    error TimelockUnauthorizedCaller(address caller);

    /**
     * @dev Emitted when a call is scheduled as part of operation `id`.
     */
    event CallScheduled(
        bytes32 indexed id,
        uint256 indexed index,
        address target,
        uint256 value,
        bytes data,
        bytes32 predecessor,
        uint256 delay
    );

    /**
     * @dev Emitted when a call is performed as part of operation `id`.
     */
    event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);

    /**
     * @dev Emitted when new proposal is scheduled with non-zero salt.
     */
    event CallSalt(bytes32 indexed id, bytes32 salt);

    /**
     * @dev Emitted when operation `id` is cancelled.
     */
    event Cancelled(bytes32 indexed id);

    /**
     * @dev Emitted when the minimum delay for future operations is modified.
     */
    event MinDelayChange(uint256 oldDuration, uint256 newDuration);

    /**
     * @dev Initializes the contract with the following parameters:
     *
     * - `minDelay`: initial minimum delay in seconds for operations
     * - `proposers`: accounts to be granted proposer and canceller roles
     * - `executors`: accounts to be granted executor role
     * - `admin`: optional account to be granted admin role; disable with zero address
     *
     * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment
     * without being subject to delay, but this role should be subsequently renounced in favor of
     * administration through timelocked proposals. Previous versions of this contract would assign
     * this admin to the deployer automatically and should be renounced as well.
     */
    constructor(uint256 minDelay, address[] memory proposers, address[] memory executors, address admin) {
        // self administration
        _grantRole(DEFAULT_ADMIN_ROLE, address(this));

        // optional admin
        if (admin != address(0)) {
            _grantRole(DEFAULT_ADMIN_ROLE, admin);
        }

        // register proposers and cancellers
        for (uint256 i = 0; i < proposers.length; ++i) {
            _grantRole(PROPOSER_ROLE, proposers[i]);
            _grantRole(CANCELLER_ROLE, proposers[i]);
        }

        // register executors
        for (uint256 i = 0; i < executors.length; ++i) {
            _grantRole(EXECUTOR_ROLE, executors[i]);
        }

        _minDelay = minDelay;
        emit MinDelayChange(0, minDelay);
    }

    /**
     * @dev Modifier to make a function callable only by a certain role. In
     * addition to checking the sender's role, `address(0)` 's role is also
     * considered. Granting a role to `address(0)` is equivalent to enabling
     * this role for everyone.
     */
    modifier onlyRoleOrOpenRole(bytes32 role) {
        if (!hasRole(role, address(0))) {
            _checkRole(role, _msgSender());
        }
        _;
    }

    /**
     * @dev Contract might receive/hold ETH as part of the maintenance process.
     */
    receive() external payable virtual {}

    /// @inheritdoc IERC165
    function supportsInterface(
        bytes4 interfaceId
    ) public view virtual override(AccessControl, ERC1155Holder) returns (bool) {
        return super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns whether an id corresponds to a registered operation. This
     * includes both Waiting, Ready, and Done operations.
     */
    function isOperation(bytes32 id) public view returns (bool) {
        return getOperationState(id) != OperationState.Unset;
    }

    /**
     * @dev Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready".
     */
    function isOperationPending(bytes32 id) public view returns (bool) {
        OperationState state = getOperationState(id);
        return state == OperationState.Waiting || state == OperationState.Ready;
    }

    /**
     * @dev Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending".
     */
    function isOperationReady(bytes32 id) public view returns (bool) {
        return getOperationState(id) == OperationState.Ready;
    }

    /**
     * @dev Returns whether an operation is done or not.
     */
    function isOperationDone(bytes32 id) public view returns (bool) {
        return getOperationState(id) == OperationState.Done;
    }

    /**
     * @dev Returns the timestamp at which an operation becomes ready (0 for
     * unset operations, 1 for done operations).
     */
    function getTimestamp(bytes32 id) public view virtual returns (uint256) {
        return _timestamps[id];
    }

    /**
     * @dev Returns operation state.
     */
    function getOperationState(bytes32 id) public view virtual returns (OperationState) {
        uint256 timestamp = getTimestamp(id);
        if (timestamp == 0) {
            return OperationState.Unset;
        } else if (timestamp == _DONE_TIMESTAMP) {
            return OperationState.Done;
        } else if (timestamp > block.timestamp) {
            return OperationState.Waiting;
        } else {
            return OperationState.Ready;
        }
    }

    /**
     * @dev Returns the minimum delay in seconds for an operation to become valid.
     *
     * This value can be changed by executing an operation that calls `updateDelay`.
     */
    function getMinDelay() public view virtual returns (uint256) {
        return _minDelay;
    }

    /**
     * @dev Returns the identifier of an operation containing a single
     * transaction.
     */
    function hashOperation(
        address target,
        uint256 value,
        bytes calldata data,
        bytes32 predecessor,
        bytes32 salt
    ) public pure virtual returns (bytes32) {
        return keccak256(abi.encode(target, value, data, predecessor, salt));
    }

    /**
     * @dev Returns the identifier of an operation containing a batch of
     * transactions.
     */
    function hashOperationBatch(
        address[] calldata targets,
        uint256[] calldata values,
        bytes[] calldata payloads,
        bytes32 predecessor,
        bytes32 salt
    ) public pure virtual returns (bytes32) {
        return keccak256(abi.encode(targets, values, payloads, predecessor, salt));
    }

    /**
     * @dev Schedule an operation containing a single transaction.
     *
     * Emits {CallSalt} if salt is nonzero, and {CallScheduled}.
     *
     * Requirements:
     *
     * - the caller must have the 'proposer' role.
     */
    function schedule(
        address target,
        uint256 value,
        bytes calldata data,
        bytes32 predecessor,
        bytes32 salt,
        uint256 delay
    ) public virtual onlyRole(PROPOSER_ROLE) {
        bytes32 id = hashOperation(target, value, data, predecessor, salt);
        _schedule(id, delay);
        emit CallScheduled(id, 0, target, value, data, predecessor, delay);
        if (salt != bytes32(0)) {
            emit CallSalt(id, salt);
        }
    }

    /**
     * @dev Schedule an operation containing a batch of transactions.
     *
     * Emits {CallSalt} if salt is nonzero, and one {CallScheduled} event per transaction in the batch.
     *
     * Requirements:
     *
     * - the caller must have the 'proposer' role.
     */
    function scheduleBatch(
        address[] calldata targets,
        uint256[] calldata values,
        bytes[] calldata payloads,
        bytes32 predecessor,
        bytes32 salt,
        uint256 delay
    ) public virtual onlyRole(PROPOSER_ROLE) {
        if (targets.length != values.length || targets.length != payloads.length) {
            revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length);
        }

        bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
        _schedule(id, delay);
        for (uint256 i = 0; i < targets.length; ++i) {
            emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay);
        }
        if (salt != bytes32(0)) {
            emit CallSalt(id, salt);
        }
    }

    /**
     * @dev Schedule an operation that is to become valid after a given delay.
     */
    function _schedule(bytes32 id, uint256 delay) private {
        if (isOperation(id)) {
            revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Unset));
        }
        uint256 minDelay = getMinDelay();
        if (delay < minDelay) {
            revert TimelockInsufficientDelay(delay, minDelay);
        }
        _timestamps[id] = block.timestamp + delay;
    }

    /**
     * @dev Cancel an operation.
     *
     * Requirements:
     *
     * - the caller must have the 'canceller' role.
     */
    function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {
        if (!isOperationPending(id)) {
            revert TimelockUnexpectedOperationState(
                id,
                _encodeStateBitmap(OperationState.Waiting) | _encodeStateBitmap(OperationState.Ready)
            );
        }
        delete _timestamps[id];

        emit Cancelled(id);
    }

    /**
     * @dev Execute an (ready) operation containing a single transaction.
     *
     * Emits a {CallExecuted} event.
     *
     * Requirements:
     *
     * - the caller must have the 'executor' role.
     */
    // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
    // thus any modifications to the operation during reentrancy should be caught.
    // slither-disable-next-line reentrancy-eth
    function execute(
        address target,
        uint256 value,
        bytes calldata payload,
        bytes32 predecessor,
        bytes32 salt
    ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
        bytes32 id = hashOperation(target, value, payload, predecessor, salt);

        _beforeCall(id, predecessor);
        _execute(target, value, payload);
        emit CallExecuted(id, 0, target, value, payload);
        _afterCall(id);
    }

    /**
     * @dev Execute an (ready) operation containing a batch of transactions.
     *
     * Emits one {CallExecuted} event per transaction in the batch.
     *
     * Requirements:
     *
     * - the caller must have the 'executor' role.
     */
    // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
    // thus any modifications to the operation during reentrancy should be caught.
    // slither-disable-next-line reentrancy-eth
    function executeBatch(
        address[] calldata targets,
        uint256[] calldata values,
        bytes[] calldata payloads,
        bytes32 predecessor,
        bytes32 salt
    ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
        if (targets.length != values.length || targets.length != payloads.length) {
            revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length);
        }

        bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);

        _beforeCall(id, predecessor);
        for (uint256 i = 0; i < targets.length; ++i) {
            address target = targets[i];
            uint256 value = values[i];
            bytes calldata payload = payloads[i];
            _execute(target, value, payload);
            emit CallExecuted(id, i, target, value, payload);
        }
        _afterCall(id);
    }

    /**
     * @dev Execute an operation's call.
     */
    function _execute(address target, uint256 value, bytes calldata data) internal virtual {
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        Address.verifyCallResult(success, returndata);
    }

    /**
     * @dev Checks before execution of an operation's calls.
     */
    function _beforeCall(bytes32 id, bytes32 predecessor) private view {
        if (!isOperationReady(id)) {
            revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready));
        }
        if (predecessor != bytes32(0) && !isOperationDone(predecessor)) {
            revert TimelockUnexecutedPredecessor(predecessor);
        }
    }

    /**
     * @dev Checks after execution of an operation's calls.
     */
    function _afterCall(bytes32 id) private {
        if (!isOperationReady(id)) {
            revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready));
        }
        _timestamps[id] = _DONE_TIMESTAMP;
    }

    /**
     * @dev Changes the minimum timelock duration for future operations.
     *
     * Emits a {MinDelayChange} event.
     *
     * Requirements:
     *
     * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
     * an operation where the timelock is the target and the data is the ABI-encoded call to this function.
     */
    function updateDelay(uint256 newDelay) external virtual {
        address sender = _msgSender();
        if (sender != address(this)) {
            revert TimelockUnauthorizedCaller(sender);
        }
        emit MinDelayChange(_minDelay, newDelay);
        _minDelay = newDelay;
    }

    /**
     * @dev Encodes a `OperationState` into a `bytes32` representation where each bit enabled corresponds to
     * the underlying position in the `OperationState` enum. For example:
     *
     * 0x000...1000
     *   ^^^^^^----- ...
     *         ^---- Done
     *          ^--- Ready
     *           ^-- Waiting
     *            ^- Unset
     */
    function _encodeStateBitmap(OperationState operationState) internal pure returns (bytes32) {
        return bytes32(1 << uint8(operationState));
    }
}

@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol

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

pragma solidity >=0.6.2;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC-1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC-1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/utils/ERC1155Holder.sol)

pragma solidity ^0.8.20;

import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
import {IERC1155Receiver} from "../IERC1155Receiver.sol";

/**
 * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC-1155 tokens.
 *
 * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
 * stuck.
 */
abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
    }

    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
}

@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/ERC721/IERC721Receiver.sol

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

pragma solidity >=0.5.0;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/utils/ERC721Holder.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
 * {IERC721-setApprovalForAll}.
 */
abstract contract ERC721Holder is IERC721Receiver {
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

@openzeppelin/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                revert(add(returndata, 0x20), mload(returndata))
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

@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;
    }
}

@openzeppelin/contracts/utils/Errors.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

@openzeppelin/contracts/utils/Pausable.sol

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

@openzeppelin/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

@openzeppelin/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

contracts/v2/Constants.sol

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

// Shared AGI Jobs v2 constants.
// @dev Auto-generated by scripts/generate-constants.ts
// Canonical $AGIALPHA token on Ethereum mainnet.
address constant AGIALPHA = 0xA61a3B3a130a9c20768EEBF97E21515A6046a1fA;

// Standard decimals for $AGIALPHA.
uint8 constant AGIALPHA_DECIMALS = 18;

// ERC-20 metadata for $AGIALPHA.
string constant AGIALPHA_SYMBOL = "AGIALPHA";
string constant AGIALPHA_NAME = "AGI ALPHA";

// Base unit scaling factor for $AGIALPHA (10 ** decimals).
uint256 constant TOKEN_SCALE = 1000000000000000000;

// Address used for burning tokens.
address constant BURN_ADDRESS = 0x0000000000000000000000000000000000000000;

contracts/v2/Governable.sol

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

/// @title Governable
/// @notice Simple governance-controlled access mechanism where all privileged
/// calls must come through a TimelockController. This enforces delayed
/// execution and coordination via a timelock or multisig that inherits from
/// OpenZeppelin's TimelockController.

import {TimelockController} from "@openzeppelin/contracts/governance/TimelockController.sol";

abstract contract Governable {
    TimelockController public governance;

    event GovernanceUpdated(address indexed newGovernance);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /// @dev Thrown when a zero address is supplied where a non-zero address is required.
    error ZeroAddress();

    /// @dev Thrown when the caller is not the governance contract.
    error NotGovernance();

    constructor(address _governance) {
        if (_governance == address(0)) revert ZeroAddress();
        _setGovernance(_governance);
    }

    function _setGovernance(address _governance) internal {
        if (_governance == address(0)) revert ZeroAddress();
        address previousOwner = address(governance);
        governance = TimelockController(payable(_governance));
        emit GovernanceUpdated(_governance);
        emit OwnershipTransferred(previousOwner, _governance);
    }

    function _checkGovernor() internal view {
        if (msg.sender != address(governance)) revert NotGovernance();
    }

    modifier onlyGovernance() {
        _checkGovernor();
        _;
    }

    function setGovernance(address _governance) public onlyGovernance {
        _setGovernance(_governance);
    }

    function transferOwnership(address newOwner) public onlyGovernance {
        _setGovernance(newOwner);
    }

    /// @notice Compatibility helper for systems expecting Ownable-style `owner()`
    function owner() public view returns (address) {
        return address(governance);
    }
}

contracts/v2/implementation/FixedDelegate.sol

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

interface IFixedImplementation {
    function moduleId() external pure returns (bytes32);
}

/// @dev Contains no storage. Controllers keep their implementation addresses immutable.
abstract contract FixedDelegate {
    error InvalidImplementation(address implementation, bytes32 expectedId);

    function _checkedImplementation(address implementation, bytes32 expectedId) internal view returns (address) {
        if (implementation.code.length == 0) {
            revert InvalidImplementation(implementation, expectedId);
        }
        if (IFixedImplementation(implementation).moduleId() != expectedId) {
            revert InvalidImplementation(implementation, expectedId);
        }
        return implementation;
    }

    function _delegate(address implementation) internal {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            calldatacopy(ptr, 0, calldatasize())
            let success := delegatecall(gas(), implementation, ptr, calldatasize(), 0, 0)
            returndatacopy(ptr, 0, returndatasize())
            switch success
            case 0 { revert(ptr, returndatasize()) }
            default { return(ptr, returndatasize()) }
        }
    }
}

/// @dev Prevents direct calls to implementation entry points; no storage slot is consumed.
abstract contract DelegateOnly {
    address private immutable _self = address(this);
    error DirectImplementationCall();

    function _checkDelegateCall() internal view {
        if (address(this) == _self) revert DirectImplementationCall();
    }

    modifier onlyDelegateCall() {
        _checkDelegateCall();
        _;
    }
}

contracts/v2/implementation/JobRegistryBase.sol

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

import {Governable} from "../Governable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ITaxPolicy} from "../interfaces/ITaxPolicy.sol";
import {TaxAcknowledgement} from "../libraries/TaxAcknowledgement.sol";
import {IValidationModule} from "../interfaces/IValidationModule.sol";
import {IStakeManager} from "../interfaces/IStakeManager.sol";
import {IFeePool} from "../interfaces/IFeePool.sol";
import {IIdentityRegistry} from "../interfaces/IIdentityRegistry.sol";
import {IReputationEngine} from "../interfaces/IReputationEngine.sol";
import {IDisputeModule} from "../interfaces/IDisputeModule.sol";
import {ICertificateNFT} from "../interfaces/ICertificateNFT.sol";
import {IJobRegistryAck} from "../interfaces/IJobRegistryAck.sol";
import {IAuditModule} from "../interfaces/IAuditModule.sol";
import {TOKEN_SCALE} from "../Constants.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

error JobParametersUnset();
error RewardOverflow();
error RewardTooHigh();
error InvalidDeadline();
error InvalidAgentTypes();
error InvalidSpecHash();
error DurationTooLong();
error InvalidPercentages();
error BlacklistedEmployer();
error CannotExpire();
error DeadlineNotReached();
error InvalidPercentage();
error InvalidValidationModule();
error InvalidStakeManager();
error InvalidReputationModule();
error InvalidDisputeModule();
error InvalidCertificateNFT();
error InvalidAuditModule();
error PolicyNotTaxExempt();
error InvalidFeePool();
error InvalidIdentityRegistry();
error IdentityRegistryNotSet();
error InvalidTaxPolicy();
error InvalidTreasury();
error InvalidAckModule();
error NotGovernanceOrPauser();
error NotGovernanceOrPauserManager();
error NotAcknowledger();
error ZeroAcknowledgerAddress();
error StakeOverflow();
error NotOpen();
error BlacklistedAgent();
error NotAuthorizedAgent();
error AgentTypeNotAllowed();
error InvalidJobState();
error OnlyAgent();
error DeadlinePassed();
error OnlyValidationModule();
error NotSubmitted();
error EvidenceMissing();
error OnlyParticipant();
error CannotDispute();
error Blacklisted();
error OnlyDisputeModule();
error NoDispute();
error NotReady();
error CannotCancel();
error OnlyEmployer();
error BurnReceiptMissing();
error BurnNotConfirmed();
error BurnAmountTooLow();
error InsufficientAgentStake(uint256 required, uint256 actual);
error MaxActiveJobsReached(uint256 limit);
error InvalidEscalationState(uint8 state);
error EmptySubdomain();

/// @title JobRegistry
/// @notice Coordinates job lifecycle and external modules.
/// @dev Tax obligations never accrue to this registry or its owner. All
/// liabilities remain with employers, agents, and validators as expressed by
/// the owner‑controlled `TaxPolicy` reference.
abstract contract JobRegistryBase is Governable, ReentrancyGuard, TaxAcknowledgement, Pausable {
    /// @notice Module version for compatibility checks.
    uint256 public constant version = 2;

    enum State {
        None,
        Created,
        Applied,
        Submitted,
        Completed,
        Disputed,
        Finalized,
        Cancelled
    }

    struct Job {
        address employer;
        address agent;
        uint128 reward;
        uint96 stake;
        uint128 burnReceiptAmount;
        bytes32 uriHash;
        bytes32 resultHash;
        bytes32 specHash;
        uint256 packedMetadata;
    }

    struct JobMetadata {
        State state;
        bool success;
        bool burnConfirmed;
        uint8 agentTypes;
        uint32 feePct;
        uint32 agentPct;
        uint64 deadline;
        uint64 assignedAt;
    }

    uint256 internal constant _STATE_OFFSET = 0;
    uint256 internal constant _SUCCESS_OFFSET = 3;
    uint256 internal constant _BURN_CONFIRMED_OFFSET = 4;
    uint256 internal constant _AGENT_TYPES_OFFSET = 5;
    uint256 internal constant _FEE_PCT_OFFSET = 13;
    uint256 internal constant _AGENT_PCT_OFFSET = 45;
    uint256 internal constant _DEADLINE_OFFSET = 77;
    uint256 internal constant _ASSIGNED_AT_OFFSET = 141;

    uint256 internal constant _STATE_MASK = 0x7 << _STATE_OFFSET;
    uint256 internal constant _SUCCESS_MASK = 1 << _SUCCESS_OFFSET;
    uint256 internal constant _BURN_CONFIRMED_MASK = 1 << _BURN_CONFIRMED_OFFSET;
    uint256 internal constant _AGENT_TYPES_MASK = uint256(0xFF) << _AGENT_TYPES_OFFSET;
    uint256 internal constant _FEE_PCT_MASK = uint256(type(uint32).max) << _FEE_PCT_OFFSET;
    uint256 internal constant _AGENT_PCT_MASK = uint256(type(uint32).max) << _AGENT_PCT_OFFSET;
    uint256 internal constant _DEADLINE_MASK = uint256(type(uint64).max) << _DEADLINE_OFFSET;
    uint256 internal constant _ASSIGNED_AT_MASK = uint256(type(uint64).max) << _ASSIGNED_AT_OFFSET;

    function _encodeMetadata(JobMetadata memory metadata) internal pure returns (uint256 packed) {
        packed = (uint256(uint8(metadata.state)) << _STATE_OFFSET) | (metadata.success ? (1 << _SUCCESS_OFFSET) : 0)
            | (metadata.burnConfirmed ? (1 << _BURN_CONFIRMED_OFFSET) : 0)
            | (uint256(metadata.agentTypes) << _AGENT_TYPES_OFFSET) | (uint256(metadata.feePct) << _FEE_PCT_OFFSET)
            | (uint256(metadata.agentPct) << _AGENT_PCT_OFFSET) | (uint256(metadata.deadline) << _DEADLINE_OFFSET)
            | (uint256(metadata.assignedAt) << _ASSIGNED_AT_OFFSET);
    }

    function _decodeMetadata(uint256 packed) internal pure returns (JobMetadata memory metadata) {
        metadata.state = State(uint8((packed & _STATE_MASK) >> _STATE_OFFSET));
        metadata.success = (packed & _SUCCESS_MASK) != 0;
        metadata.burnConfirmed = (packed & _BURN_CONFIRMED_MASK) != 0;
        metadata.agentTypes = uint8((packed & _AGENT_TYPES_MASK) >> _AGENT_TYPES_OFFSET);
        metadata.feePct = uint32((packed & _FEE_PCT_MASK) >> _FEE_PCT_OFFSET);
        metadata.agentPct = uint32((packed & _AGENT_PCT_MASK) >> _AGENT_PCT_OFFSET);
        metadata.deadline = uint64((packed & _DEADLINE_MASK) >> _DEADLINE_OFFSET);
        metadata.assignedAt = uint64((packed & _ASSIGNED_AT_MASK) >> _ASSIGNED_AT_OFFSET);
    }

    function _getState(Job storage job) internal view returns (State) {
        return State(uint8((job.packedMetadata & _STATE_MASK) >> _STATE_OFFSET));
    }

    function _setState(Job storage job, State state) internal {
        job.packedMetadata = (job.packedMetadata & ~_STATE_MASK) | (uint256(uint8(state)) << _STATE_OFFSET);
    }

    function _getSuccess(Job storage job) internal view returns (bool) {
        return (job.packedMetadata & _SUCCESS_MASK) != 0;
    }

    function _setSuccess(Job storage job, bool success) internal {
        if (success) {
            job.packedMetadata = job.packedMetadata | _SUCCESS_MASK;
        } else {
            job.packedMetadata = job.packedMetadata & ~_SUCCESS_MASK;
        }
    }

    function _getBurnConfirmed(Job storage job) internal view returns (bool) {
        return (job.packedMetadata & _BURN_CONFIRMED_MASK) != 0;
    }

    function _setBurnConfirmed(Job storage job, bool burnConfirmed) internal {
        if (burnConfirmed) {
            job.packedMetadata = job.packedMetadata | _BURN_CONFIRMED_MASK;
        } else {
            job.packedMetadata = job.packedMetadata & ~_BURN_CONFIRMED_MASK;
        }
    }

    function _getAgentTypes(Job storage job) internal view returns (uint8) {
        return uint8((job.packedMetadata & _AGENT_TYPES_MASK) >> _AGENT_TYPES_OFFSET);
    }

    function _getFeePct(Job storage job) internal view returns (uint32) {
        return uint32((job.packedMetadata & _FEE_PCT_MASK) >> _FEE_PCT_OFFSET);
    }

    function _getAgentPct(Job storage job) internal view returns (uint32) {
        return uint32((job.packedMetadata & _AGENT_PCT_MASK) >> _AGENT_PCT_OFFSET);
    }

    function _setAgentPct(Job storage job, uint32 pct) internal {
        job.packedMetadata = (job.packedMetadata & ~_AGENT_PCT_MASK) | (uint256(pct) << _AGENT_PCT_OFFSET);
    }

    function _getDeadline(Job storage job) internal view returns (uint64) {
        return uint64((job.packedMetadata & _DEADLINE_MASK) >> _DEADLINE_OFFSET);
    }

    function _getAssignedAt(Job storage job) internal view returns (uint64) {
        return uint64((job.packedMetadata & _ASSIGNED_AT_MASK) >> _ASSIGNED_AT_OFFSET);
    }

    function _setAssignedAt(Job storage job, uint64 timestamp) internal {
        job.packedMetadata = (job.packedMetadata & ~_ASSIGNED_AT_MASK) | (uint256(timestamp) << _ASSIGNED_AT_OFFSET);
    }

    function decodeJobMetadata(uint256 packed) public pure returns (JobMetadata memory) {
        return _decodeMetadata(packed);
    }

    uint256 public nextJobId;
    mapping(uint256 => Job) public jobs;

    struct BurnReceipt {
        uint256 amount;
        uint256 blockNumber;
        bool exists;
    }

    mapping(uint256 => mapping(bytes32 => BurnReceipt)) internal burnReceipts;
    mapping(uint256 => uint256) public pendingValidationEntropy;
    mapping(uint256 => bool) public validationStartPending;
    mapping(uint256 => address[]) internal jobValidators;
    mapping(uint256 => mapping(address => bool)) internal jobValidatorVotes;
    mapping(uint256 => bool) public reputationProcessed;

    /// @notice Tracks job outcomes for each employer.
    struct EmployerStats {
        /// @notice Number of successfully finalised jobs.
        uint256 successful;
        /// @notice Number of jobs that ended in dispute or failure.
        uint256 failed;
    }

    mapping(address => EmployerStats) public employerStats;

    struct ConfigUpdateFlags {
        bool pauserUpdated;
        bool modulesUpdated;
        bool pauserManagerUpdated;
        bool identityRegistryUpdated;
        bool disputeModuleUpdated;
        bool validationModuleUpdated;
        bool stakeManagerUpdated;
        bool reputationModuleUpdated;
        bool certificateNFTUpdated;
        bool auditModuleUpdated;
        bool feePoolUpdated;
        bool taxPolicyUpdated;
        bool treasuryUpdated;
        bool jobStakeUpdated;
        bool minAgentStakeUpdated;
        bool feePctUpdated;
        bool validatorRewardPctUpdated;
        bool maxJobRewardUpdated;
        bool maxJobDurationUpdated;
        bool maxActiveJobsUpdated;
        bool expirationGracePeriodUpdated;
        bool agentRootUpdated;
        bool agentMerkleUpdated;
        bool validatorRootUpdated;
        bool validatorMerkleUpdated;
        bool agentAuthCacheDurationUpdated;
        bool agentAuthCacheVersionBumped;
        uint256 ackModulesAdded;
    }

    function _encodeConfigurationFlags(ConfigUpdateFlags memory flags) internal pure returns (uint256) {
        uint256 bitmap;

        if (flags.pauserUpdated) bitmap |= 1 << 0;
        if (flags.modulesUpdated) bitmap |= 1 << 1;
        if (flags.pauserManagerUpdated) bitmap |= 1 << 2;
        if (flags.identityRegistryUpdated) bitmap |= 1 << 3;
        if (flags.disputeModuleUpdated) bitmap |= 1 << 4;
        if (flags.validationModuleUpdated) bitmap |= 1 << 5;
        if (flags.stakeManagerUpdated) bitmap |= 1 << 6;
        if (flags.reputationModuleUpdated) bitmap |= 1 << 7;
        if (flags.certificateNFTUpdated) bitmap |= 1 << 8;
        if (flags.auditModuleUpdated) bitmap |= 1 << 9;
        if (flags.feePoolUpdated) bitmap |= 1 << 10;
        if (flags.taxPolicyUpdated) bitmap |= 1 << 11;
        if (flags.treasuryUpdated) bitmap |= 1 << 12;
        if (flags.jobStakeUpdated) bitmap |= 1 << 13;
        if (flags.minAgentStakeUpdated) bitmap |= 1 << 14;
        if (flags.feePctUpdated) bitmap |= 1 << 15;
        if (flags.validatorRewardPctUpdated) bitmap |= 1 << 16;
        if (flags.maxJobRewardUpdated) bitmap |= 1 << 17;
        if (flags.maxJobDurationUpdated) bitmap |= 1 << 18;
        if (flags.maxActiveJobsUpdated) bitmap |= 1 << 19;
        if (flags.expirationGracePeriodUpdated) bitmap |= 1 << 20;
        if (flags.agentRootUpdated) bitmap |= 1 << 21;
        if (flags.agentMerkleUpdated) bitmap |= 1 << 22;
        if (flags.validatorRootUpdated) bitmap |= 1 << 23;
        if (flags.validatorMerkleUpdated) bitmap |= 1 << 24;
        if (flags.agentAuthCacheDurationUpdated) bitmap |= 1 << 25;
        if (flags.agentAuthCacheVersionBumped) bitmap |= 1 << 26;

        return bitmap;
    }

    /// @notice Tracks the number of active jobs assigned to each agent.
    mapping(address => uint256) public activeJobs;
    /// @notice Optional governance-configured limit on active jobs per agent. Zero disables the limit.
    uint256 public maxActiveJobsPerAgent;

    function getJobValidators(uint256 jobId) external view returns (address[] memory) {
        return jobValidators[jobId];
    }

    function getJobValidatorVote(uint256 jobId, address validator) external view returns (bool) {
        return jobValidatorVotes[jobId][validator];
    }

    function validatorCommittee(uint256 jobId)
        external
        view
        returns (address[] memory validators, bool[] memory approvals)
    {
        address[] storage stored = jobValidators[jobId];
        uint256 length = stored.length;
        validators = new address[](length);
        approvals = new bool[](length);
        for (uint256 i; i < length;) {
            address validator = stored[i];
            validators[i] = validator;
            approvals[i] = jobValidatorVotes[jobId][validator];
            unchecked {
                ++i;
            }
        }
    }

    function getSpecHash(uint256 jobId) external view returns (bytes32) {
        return jobs[jobId].specHash;
    }

    function burnEvidenceStatus(uint256 jobId) public view returns (bool burnRequired, bool burnSatisfied) {
        burnRequired = _isBurnRequired();
        if (!burnRequired) {
            return (false, true);
        }
        Job storage job = jobs[jobId];
        burnSatisfied = _getBurnConfirmed(job);
    }

    /// @notice Determine whether validation should be deferred until burn evidence is available.
    function _shouldDeferValidation(uint256 jobId) internal view returns (bool) {
        (bool burnRequired, bool burnSatisfied) = burnEvidenceStatus(jobId);
        return burnRequired && !burnSatisfied;
    }

    function _isBurnRequired() internal view returns (bool) {
        IStakeManager manager = stakeManager;
        return address(manager) != address(0) && manager.burnPct() > 0;
    }

    function _clearValidatorData(uint256 jobId) internal {
        address[] storage validators = jobValidators[jobId];
        uint256 length = validators.length;
        if (length == 0) {
            return;
        }
        for (uint256 i; i < length;) {
            delete jobValidatorVotes[jobId][validators[i]];
            unchecked {
                ++i;
            }
        }
        delete jobValidators[jobId];
    }

    function _clearValidationStart(uint256 jobId) internal {
        if (validationStartPending[jobId]) {
            validationStartPending[jobId] = false;
            delete pendingValidationEntropy[jobId];
        }
    }

    function _startValidation(uint256 jobId, uint256 entropy) internal {
        validationStartPending[jobId] = false;
        delete pendingValidationEntropy[jobId];
        if (address(validationModule) != address(0)) {
            validationModule.start(jobId, entropy);
            emit ValidationStartTriggered(jobId);
        }
    }

    function _maybeStartValidation(uint256 jobId, bytes32 resultHash) internal {
        if (address(validationModule) == address(0)) {
            return;
        }

        uint256 entropy = uint256(
            keccak256(
                abi.encodePacked(
                    jobId, msg.sender, resultHash, block.timestamp, block.prevrandao, blockhash(block.number - 1)
                )
            )
        );

        if (_shouldDeferValidation(jobId)) {
            pendingValidationEntropy[jobId] = entropy;
            validationStartPending[jobId] = true;
            emit ValidationStartPending(jobId);
            return;
        }

        _startValidation(jobId, entropy);
    }

    /// @notice Records evidence of a token burn by the employer.
    /// @dev Employers must acknowledge the active tax policy before calling.
    function _entry_submitBurnReceipt(uint256 jobId, bytes32 burnTxHash, uint256 amount, uint256 blockNumber)
        internal
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
    {
        Job storage job = jobs[jobId];
        if (job.employer != msg.sender) revert OnlyEmployer();
        burnReceipts[jobId][burnTxHash] = BurnReceipt({amount: amount, blockNumber: blockNumber, exists: true});
        emit BurnReceiptSubmitted(jobId, burnTxHash, amount, blockNumber);
    }

    function hasBurnReceipt(uint256 jobId, bytes32 burnTxHash) external view returns (bool) {
        return burnReceipts[jobId][burnTxHash].exists;
    }

    /// @notice Retrieve raw reputation statistics for an employer.
    /// @param employer Address of the employer to query.
    /// @return successful Count of successfully finalised jobs.
    /// @return failed Count of jobs that failed or were disputed.
    function getEmployerReputation(address employer) external view returns (uint256 successful, uint256 failed) {
        EmployerStats storage stats = employerStats[employer];
        return (stats.successful, stats.failed);
    }

    /// @notice Compute a normalized employer reputation score.
    /// @dev Returns the ratio of positive to total outcomes scaled by 1e18.
    /// A score of 1e18 represents a perfect record, while 0 indicates only
    /// negative outcomes. If an employer has no history, the score is 0.
    /// @param employer Address of the employer to query.
    /// @return score Reputation score in 18-decimal fixed point.
    function getEmployerScore(address employer) external view returns (uint256 score) {
        EmployerStats storage stats = employerStats[employer];
        uint256 total = stats.successful + stats.failed;
        if (total == 0) {
            return 0;
        }
        return (stats.successful * TOKEN_SCALE) / total;
    }

    /// @notice Confirms previously submitted burn evidence.
    /// @dev Employers must acknowledge the active tax policy before calling.
    function _entry_confirmEmployerBurn(uint256 jobId, bytes32 burnTxHash)
        internal
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
    {
        Job storage job = jobs[jobId];
        if (job.employer != msg.sender) revert OnlyEmployer();
        if (!burnReceipts[jobId][burnTxHash].exists) revert BurnReceiptMissing();
        _setBurnConfirmed(job, true);
        job.burnReceiptAmount = uint128(burnReceipts[jobId][burnTxHash].amount);
        emit BurnConfirmed(jobId, burnTxHash);
        if (validationStartPending[jobId] && _getState(job) == State.Submitted) {
            _startValidation(jobId, pendingValidationEntropy[jobId]);
        }
    }

    IValidationModule public validationModule;
    IStakeManager public stakeManager;
    IReputationEngine public reputationEngine;
    IDisputeModule public disputeModule;
    ICertificateNFT public certificateNFT;
    IAuditModule public auditModule;
    ITaxPolicy public taxPolicy;
    IFeePool public feePool;
    IIdentityRegistry public identityRegistry;
    address public treasury;
    address public pauser;
    address public pauserManager;

    /// @notice Addresses allowed to acknowledge the tax policy for others.
    /// @dev Each acknowledger must be a valid contract or externally owned account.
    mapping(address => bool) public acknowledgers;

    modifier onlyGovernanceOrPauser() {
        if (msg.sender != address(governance) && msg.sender != pauser) {
            revert NotGovernanceOrPauser();
        }
        _;
    }

    function _setPauser(address _pauser) internal {
        pauser = _pauser;
        emit PauserUpdated(_pauser);
    }

    function _entry_setPauser(address _pauser) internal {
        if (msg.sender != address(governance) && msg.sender != pauserManager) {
            revert NotGovernanceOrPauserManager();
        }
        _setPauser(_pauser);
    }

    function _entry_setPauserManager(address manager) internal onlyGovernance {
        pauserManager = manager;
        emit PauserManagerUpdated(manager);
    }

    function _setIdentityRegistry(IIdentityRegistry registry) internal {
        if (address(registry) == address(0)) revert InvalidIdentityRegistry();
        if (registry.version() != 2) revert InvalidIdentityRegistry();
        identityRegistry = registry;
        _bumpAgentAuthCacheVersionInternal();
        if (address(validationModule) != address(0)) {
            try validationModule.bumpValidatorAuthCacheVersion() {} catch {}
        }
        emit IdentityRegistryUpdated(address(registry));
        emit ModuleUpdated("IdentityRegistry", address(registry));
    }

    function _setDisputeModule(IDisputeModule module) internal {
        if (address(module) == address(0)) revert InvalidDisputeModule();
        if (module.version() != 2) revert InvalidDisputeModule();
        disputeModule = module;
        emit DisputeModuleUpdated(address(module));
        emit ModuleUpdated("DisputeModule", address(module));
    }

    function _setValidationModule(IValidationModule module) internal {
        if (address(module) == address(0)) revert InvalidValidationModule();
        if (module.version() != 2) revert InvalidValidationModule();
        validationModule = module;
        emit ValidationModuleUpdated(address(module));
        emit ModuleUpdated("ValidationModule", address(module));
    }

    function _setAuditModule(IAuditModule module) internal {
        if (address(module) == address(0)) {
            auditModule = module;
            emit AuditModuleUpdated(address(module));
            emit ModuleUpdated("AuditModule", address(module));
            return;
        }
        if (module.version() == 0) revert InvalidAuditModule();
        auditModule = module;
        emit AuditModuleUpdated(address(module));
        emit ModuleUpdated("AuditModule", address(module));
    }

    function _setStakeManager(IStakeManager _stakeMgr) internal {
        if (address(_stakeMgr) == address(0)) revert InvalidStakeManager();
        if (_stakeMgr.version() != 2) revert InvalidStakeManager();
        stakeManager = _stakeMgr;
        acknowledgers[address(_stakeMgr)] = true;
        emit AcknowledgerUpdated(address(_stakeMgr), true);
        emit StakeManagerUpdated(address(_stakeMgr));
        emit ModuleUpdated("StakeManager", address(_stakeMgr));
    }

    function _setReputationEngine(IReputationEngine _reputation) internal {
        if (address(_reputation) == address(0)) revert InvalidReputationModule();
        if (_reputation.version() != 2) revert InvalidReputationModule();
        reputationEngine = _reputation;
        emit ReputationEngineUpdated(address(_reputation));
        emit ModuleUpdated("ReputationEngine", address(_reputation));
    }

    function _setCertificateNFT(ICertificateNFT _certNFT) internal {
        if (address(_certNFT) == address(0)) revert InvalidCertificateNFT();
        if (_certNFT.version() != 2) revert InvalidCertificateNFT();
        certificateNFT = _certNFT;
        emit CertificateNFTUpdated(address(_certNFT));
        emit ModuleUpdated("CertificateNFT", address(_certNFT));
    }

    function _setFeePool(IFeePool _feePool) internal {
        if (address(_feePool) == address(0) || _feePool.version() != 2) {
            revert InvalidFeePool();
        }
        feePool = _feePool;
        emit FeePoolUpdated(address(_feePool));
        emit ModuleUpdated("FeePool", address(_feePool));
    }

    function _setTaxPolicy(ITaxPolicy _policy) internal {
        if (address(_policy) == address(0)) revert InvalidTaxPolicy();
        if (!_policy.isTaxExempt()) revert PolicyNotTaxExempt();
        taxPolicy = _policy;
        emit TaxPolicyUpdated(address(_policy), _policy.policyVersion());
        emit ModuleUpdated("TaxPolicy", address(_policy));
    }

    function _setTreasury(address _treasury) internal {
        if (_treasury != address(0) && _treasury == owner()) revert InvalidTreasury();
        treasury = _treasury;
        emit TreasuryUpdated(_treasury);
    }

    function _setJobStake(uint96 stake) internal {
        jobStake = stake;
        emit JobParametersUpdated(0, stake, maxJobReward, maxJobDuration, minAgentStake);
    }

    function _setMinAgentStake(uint256 stake) internal {
        if (stake > type(uint96).max) revert StakeOverflow();
        minAgentStake = uint96(stake);
        emit JobParametersUpdated(0, jobStake, maxJobReward, maxJobDuration, stake);
    }

    function _applyFeeConfiguration(
        uint256 newFeePct,
        uint256 newValidatorRewardPct,
        bool updateFee,
        bool updateValidator
    ) internal returns (bool feeChanged, bool validatorChanged) {
        if (newFeePct > 100 || newValidatorRewardPct > 100) revert InvalidPercentage();
        if (newFeePct + newValidatorRewardPct > 100) revert InvalidPercentage();
        if (updateFee && newFeePct != feePct) {
            feePct = newFeePct;
            emit FeePctUpdated(newFeePct);
            feeChanged = true;
        }
        if (updateValidator && newValidatorRewardPct != validatorRewardPct) {
            validatorRewardPct = newValidatorRewardPct;
            emit ValidatorRewardPctUpdated(newValidatorRewardPct);
            validatorChanged = true;
        }
    }

    function _setMaxJobReward(uint256 maxReward) internal {
        maxJobReward = maxReward;
        emit JobParametersUpdated(0, jobStake, maxReward, maxJobDuration, minAgentStake);
    }

    function _setJobDurationLimit(uint256 limit) internal {
        maxJobDuration = limit;
        emit JobParametersUpdated(0, jobStake, maxJobReward, limit, minAgentStake);
    }

    function _setMaxActiveJobsPerAgent(uint256 limit) internal {
        maxActiveJobsPerAgent = limit;
        emit MaxActiveJobsPerAgentUpdated(limit);
    }

    function _setExpirationGracePeriod(uint256 period) internal {
        expirationGracePeriod = period;
        emit ExpirationGracePeriodUpdated(period);
    }

    function _setAgentRootNode(bytes32 node) internal {
        if (address(identityRegistry) == address(0)) revert IdentityRegistryNotSet();
        identityRegistry.setAgentRootNode(node);
        _bumpAgentAuthCacheVersionInternal();
        emit AgentRootNodeUpdated(node);
    }

    function _setAgentMerkleRoot(bytes32 root) internal {
        if (address(identityRegistry) == address(0)) revert IdentityRegistryNotSet();
        identityRegistry.setAgentMerkleRoot(root);
        _bumpAgentAuthCacheVersionInternal();
        emit AgentMerkleRootUpdated(root);
    }

    function _setValidatorRootNode(bytes32 node) internal {
        if (address(identityRegistry) == address(0)) revert IdentityRegistryNotSet();
        if (address(validationModule) == address(0)) revert InvalidValidationModule();
        identityRegistry.setClubRootNode(node);
        validationModule.bumpValidatorAuthCacheVersion();
        emit ValidatorRootNodeUpdated(node);
    }

    function _setValidatorMerkleRoot(bytes32 root) internal {
        if (address(identityRegistry) == address(0)) revert IdentityRegistryNotSet();
        if (address(validationModule) == address(0)) revert InvalidValidationModule();
        identityRegistry.setValidatorMerkleRoot(root);
        validationModule.bumpValidatorAuthCacheVersion();
        emit ValidatorMerkleRootUpdated(root);
    }

    function _setAgentAuthCacheDuration(uint256 duration) internal {
        agentAuthCacheDuration = duration;
        emit AgentAuthCacheDurationUpdated(duration);
    }

    function _verifyAndCacheAgentIdentity(address agent, string calldata subdomain, bytes32[] calldata proof)
        internal
        returns (bytes32 node, bool viaWrapper, bool viaMerkle)
    {
        if (bytes(subdomain).length == 0) revert EmptySubdomain();
        if (address(identityRegistry) == address(0)) revert IdentityRegistryNotSet();

        string memory cachedSubdomain = agentSubdomains[agent];
        bytes32 providedHash = keccak256(bytes(subdomain));
        bool cachedMatches = bytes(cachedSubdomain).length != 0 && keccak256(bytes(cachedSubdomain)) == providedHash;

        (bool authorized, bytes32 resolvedNode, bool wrapper, bool merkle) =
            identityRegistry.verifyAgent(agent, subdomain, proof);
        if (!authorized) revert NotAuthorizedAgent();

        if (!cachedMatches) {
            agentSubdomains[agent] = subdomain;
            emit AgentSubdomainUpdated(agent, subdomain);
        }

        return (resolvedNode, wrapper, merkle);
    }

    function _bumpAgentAuthCacheVersionInternal() internal {
        unchecked {
            ++agentAuthCacheVersion;
        }
        emit AgentAuthCacheVersionBumped(agentAuthCacheVersion);
    }

    function _setAcknowledger(address acknowledger, bool allowed) internal {
        if (allowed && acknowledger == address(0)) revert ZeroAcknowledgerAddress();
        acknowledgers[acknowledger] = allowed;
        emit AcknowledgerUpdated(acknowledger, allowed);
    }

    function _enableAckModule(address module) internal {
        (bool ok, bytes memory data) =
            module.staticcall(abi.encodeWithSelector(IJobRegistryAck.acknowledgeFor.selector, address(0)));
        if (!ok || data.length < 64) revert InvalidAckModule();
        acknowledgers[module] = true;
        emit AcknowledgerUpdated(module, true);
    }

    function _applyModuleBundle(ModuleBundle memory modules, address[] calldata ackModules)
        internal
        returns (
            bool validationChanged,
            bool stakeManagerChanged,
            bool reputationChanged,
            bool disputeChanged,
            bool certificateChanged,
            bool feePoolChanged,
            uint256 ackModuleCount
        )
    {
        _setValidationModule(modules.validation);
        validationChanged = true;

        _setStakeManager(modules.stakeManager);
        stakeManagerChanged = true;

        _setReputationEngine(modules.reputation);
        reputationChanged = true;

        _setDisputeModule(modules.dispute);
        disputeChanged = true;

        _setCertificateNFT(modules.certificateNFT);
        certificateChanged = true;

        _setFeePool(modules.feePool);
        feePoolChanged = true;

        uint256 ackLen = ackModules.length;
        for (uint256 i; i < ackLen;) {
            _enableAckModule(ackModules[i]);
            unchecked {
                ++i;
            }
        }
        ackModuleCount = ackLen;
    }

    // cache successful agent authorizations
    mapping(address => bool) public agentAuthCache;
    mapping(address => uint256) public agentAuthExpiry;
    mapping(address => uint256) public agentAuthVersion;
    uint256 public agentAuthCacheVersion;
    uint256 public agentAuthCacheDuration;
    mapping(address => string) public agentSubdomains;

    /// @dev Reusable gate enforcing acknowledgement of the latest tax policy
    /// version for callers other than the owner, dispute module, or validation module.

    modifier onlyAfterDeadline(uint256 jobId) {
        Job storage job = jobs[jobId];
        if (_getState(job) != State.Applied) revert CannotExpire();
        uint64 deadline = _getDeadline(job);
        if (block.timestamp <= uint256(deadline) + expirationGracePeriod) revert DeadlineNotReached();
        _;
    }

    // default agent stake requirement configured by owner
    uint96 public jobStake;
    uint96 public minAgentStake;
    uint96 public constant DEFAULT_JOB_STAKE = uint96(TOKEN_SCALE);
    uint256 public feePct;
    uint256 public constant DEFAULT_FEE_PCT = 5;
    uint256 public maxJobReward;
    uint256 public maxJobDuration;
    uint256 public validatorRewardPct;
    uint256 public constant DEFAULT_VALIDATOR_REWARD_PCT = 8;
    uint256 public expirationGracePeriod;

    // module configuration events
    event ModuleUpdated(string module, address indexed newAddress);
    event ValidationModuleUpdated(address module);
    event StakeManagerUpdated(address manager);
    event ReputationEngineUpdated(address engine);
    event DisputeModuleUpdated(address module);
    event CertificateNFTUpdated(address nft);
    event AuditModuleUpdated(address module);
    event AuditModuleCallbackFailed(uint256 indexed jobId, bytes data);
    event IdentityRegistryUpdated(address identityRegistry);
    event ValidatorRewardPctUpdated(uint256 pct);
    event PauserUpdated(address indexed pauser);
    event PauserManagerUpdated(address indexed pauserManager);
    /// @notice Emitted when the tax policy reference or version changes.
    /// @param policy Address of the TaxPolicy contract.
    /// @param version Incrementing version participants must acknowledge.
    event TaxPolicyUpdated(address policy, uint256 version);
    /// @notice Emitted when a participant acknowledges the tax policy, placing
    /// full tax responsibility on the caller while the contract owner remains
    /// exempt. The acknowledgement text is included in the event so explorers
    /// like Etherscan can surface the exact disclaimer the participant
    /// accepted.
    /// @param user Address of the acknowledging participant.
    /// @param version Tax policy version that was acknowledged.
    /// @param acknowledgement Human‑readable disclaimer confirming the caller
    ///        bears all tax liability.
    event TaxAcknowledged(address indexed user, uint256 version, string acknowledgement);

    /// @notice Emitted when an acknowledger role is updated.
    /// @param acknowledger Address being granted or revoked the role.
    /// @param allowed True if the address can acknowledge for others.
    event AcknowledgerUpdated(address indexed acknowledger, bool allowed);

    event AgentRootNodeUpdated(bytes32 node);
    event AgentMerkleRootUpdated(bytes32 root);
    event ValidatorRootNodeUpdated(bytes32 node);
    event ReputationProcessingMarked(uint256 indexed jobId);
    event ValidatorMerkleRootUpdated(bytes32 root);
    event AgentAuthCacheUpdated(address indexed agent, bool authorized);
    event AgentAuthCacheDurationUpdated(uint256 duration);
    event AgentAuthCacheVersionBumped(uint256 version);
    /// @notice Emitted when an agent's ENS identity is verified during a job action.
    event AgentIdentityVerified(
        address indexed agent, bytes32 indexed node, string label, bool viaWrapper, bool viaMerkle
    );
    event AgentSubdomainUpdated(address indexed agent, string subdomain);

    // job parameter template event
    event JobParametersUpdated(
        uint256 reward, uint256 stake, uint256 maxJobReward, uint256 maxJobDuration, uint256 minAgentStake
    );

    event ConfigurationApplied(
        address indexed caller, uint256 flags, uint256 acknowledgerUpdates, uint256 ackModulesAdded
    );

    struct ModuleBundle {
        IValidationModule validation;
        IStakeManager stakeManager;
        IReputationEngine reputation;
        IDisputeModule dispute;
        ICertificateNFT certificateNFT;
        IFeePool feePool;
    }

    struct ConfigUpdate {
        bool setPauser;
        address pauser;
        bool setPauserManager;
        address pauserManager;
        bool setModuleBundle;
        ModuleBundle modules;
        bool setIdentityRegistry;
        address identityRegistry;
        bool setDisputeModule;
        address disputeModule;
        bool setValidationModule;
        address validationModule;
        bool setAuditModule;
        address auditModule;
        bool setStakeManager;
        address stakeManager;
        bool setReputationModule;
        address reputationModule;
        bool setCertificateNFT;
        address certificateNFT;
        bool setFeePool;
        address feePool;
        bool setTaxPolicy;
        address taxPolicy;
        bool setTreasury;
        address treasury;
        bool setJobStake;
        uint96 jobStake;
        bool setMinAgentStake;
        uint256 minAgentStake;
        bool setFeePct;
        uint256 feePct;
        bool setValidatorRewardPct;
        uint256 validatorRewardPct;
        bool setMaxJobReward;
        uint256 maxJobReward;
        bool setJobDurationLimit;
        uint256 jobDurationLimit;
        bool setMaxActiveJobsPerAgent;
        uint256 maxActiveJobsPerAgent;
        bool setExpirationGracePeriod;
        uint256 expirationGracePeriod;
        bool setAgentRootNode;
        bytes32 agentRootNode;
        bool setAgentMerkleRoot;
        bytes32 agentMerkleRoot;
        bool setValidatorRootNode;
        bytes32 validatorRootNode;
        bool setValidatorMerkleRoot;
        bytes32 validatorMerkleRoot;
        bool setAgentAuthCacheDuration;
        uint256 agentAuthCacheDuration;
        bool bumpAgentAuthCacheVersion;
    }

    struct AcknowledgerUpdate {
        address acknowledger;
        bool allowed;
    }

    // job lifecycle events
    event JobFunded(uint256 indexed jobId, address indexed employer, uint256 reward, uint256 fee);
    event JobCreated(
        uint256 indexed jobId,
        address indexed employer,
        address indexed agent,
        uint256 reward,
        uint256 stake,
        uint256 fee,
        bytes32 specHash,
        string uri
    );
    /// @notice Emitted when an agent submits an application for a job.
    event ApplicationSubmitted(uint256 indexed jobId, address indexed applicant, string subdomain);
    /// @notice Emitted when an agent becomes the active assignee for a job.
    event AgentAssigned(uint256 indexed jobId, address indexed agent, string subdomain);
    /// @notice Emitted when work has been submitted for validation.
    event ResultSubmitted(
        uint256 indexed jobId, address indexed worker, bytes32 resultHash, string resultURI, string subdomain
    );
    /// @dev Legacy alias for {AgentAssigned}. Kept for backwards compatibility.
    event JobApplied(uint256 indexed jobId, address indexed agent, string subdomain);
    /// @dev Legacy alias for {ResultSubmitted}. Kept for backwards compatibility.
    event JobSubmitted(
        uint256 indexed jobId, address indexed worker, bytes32 resultHash, string resultURI, string subdomain
    );
    event JobCompleted(uint256 indexed jobId, bool success);
    /// @notice Emitted when job funds are disbursed
    /// @param jobId Identifier of the job
    /// @param worker Agent who performed the job
    /// @param base Amount paid from the job's escrow
    /// @param bonus Additional amount paid from the reward pool
    /// @param fee Protocol fee routed to the FeePool
    event JobPayout(uint256 indexed jobId, address indexed worker, uint256 base, uint256 bonus, uint256 fee);
    /// @notice Emitted when a job is finalized
    /// @param jobId Identifier of the job
    /// @param worker Agent who performed the job
    event JobFinalized(uint256 indexed jobId, address indexed worker);
    event JobCancelled(uint256 indexed jobId);
    event BurnReceiptSubmitted(uint256 indexed jobId, bytes32 indexed burnTxHash, uint256 amount, uint256 blockNumber);
    event BurnConfirmed(uint256 indexed jobId, bytes32 indexed burnTxHash);
    event BurnDiscrepancy(uint256 indexed jobId, uint256 receiptAmount, uint256 expectedAmount);
    event ValidationStartPending(uint256 indexed jobId);
    event ValidationStartTriggered(uint256 indexed jobId);
    /// @notice Emitted when an assigned job is cancelled after missing its deadline
    /// @param jobId Identifier of the expired job
    /// @param caller Address that triggered the expiration
    event JobExpired(uint256 indexed jobId, address indexed caller);
    event JobTimedOut(uint256 indexed jobId, address indexed caller);
    event JobDisputed(uint256 indexed jobId, address indexed caller);
    event JobEscalatedByGovernance(uint256 indexed jobId, address indexed caller, string reason);
    event DisputeResolved(uint256 indexed jobId, bool employerWins);
    event FeePoolUpdated(address pool);
    event FeePctUpdated(uint256 feePct);
    event ExpirationGracePeriodUpdated(uint256 period);
    event MaxActiveJobsPerAgentUpdated(uint256 limit);
    event GovernanceFinalized(uint256 indexed jobId, address indexed caller, bool fundsRedirected);
    event TreasuryUpdated(address treasury);

    constructor(address governance_) Governable(governance_) {}

    // ---------------------------------------------------------------------
    // Owner configuration
    // ---------------------------------------------------------------------
    // Setters below are executed manually via Etherscan's "Write Contract"
    // tab using the authorized owner account.
    function _entry_setModules(
        IValidationModule _validation,
        IStakeManager _stakeMgr,
        IReputationEngine _reputation,
        IDisputeModule _disputeModule,
        ICertificateNFT _certNFT,
        IFeePool _feePool,
        address[] calldata _ackModules
    ) internal onlyGovernance {
        ModuleBundle memory bundle = ModuleBundle({
            validation: _validation,
            stakeManager: _stakeMgr,
            reputation: _reputation,
            dispute: _disputeModule,
            certificateNFT: _certNFT,
            feePool: _feePool
        });
        _applyModuleBundle(bundle, _ackModules);
    }

    /// @notice Update the identity registry used for agent verification.
    /// @param registry Address of the IdentityRegistry contract.
    function _entry_setIdentityRegistry(IIdentityRegistry registry) internal onlyGovernance {
        _setIdentityRegistry(registry);
    }

    /// @notice Switch the active dispute module.
    /// @param module Address of the new dispute module contract.
    function _entry_setDisputeModule(IDisputeModule module) internal onlyGovernance {
        _setDisputeModule(module);
    }

    /// @notice Update the validation module used to source validator lists.
    /// @param module ValidationModule contract address.
    function _entry_setValidationModule(IValidationModule module) internal onlyGovernance {
        _setValidationModule(module);
    }

    /// @notice Update the audit module used for post-completion spot checks.
    /// @param module Address of the audit module contract (zero to disable).
    function _entry_setAuditModule(IAuditModule module) internal onlyGovernance {
        _setAuditModule(module);
    }

    /// @notice Update the stake manager reference.
    /// @param manager StakeManager contract address.
    function _entry_setStakeManager(IStakeManager manager) internal onlyGovernance {
        _setStakeManager(manager);
    }

    /// @notice Update the reputation engine reference.
    function _entry_setReputationEngine(IReputationEngine engine) internal onlyGovernance {
        _setReputationEngine(engine);
    }

    /// @notice Update the certificate NFT module reference.
    function _entry_setCertificateNFT(ICertificateNFT nft) internal onlyGovernance {
        _setCertificateNFT(nft);
    }

    /// @notice Update the ENS root node used for agent verification.
    /// @param node Namehash of the agent parent node (e.g. `agent.agi.eth`).
    function _entry_setAgentRootNode(bytes32 node) internal onlyGovernance {
        _setAgentRootNode(node);
    }

    /// @notice Update the Merkle root for the agent allowlist.
    /// @param root Merkle root of approved agent addresses.
    function _entry_setAgentMerkleRoot(bytes32 root) internal onlyGovernance {
        _setAgentMerkleRoot(root);
    }

    /// @notice Increment the agent authorization cache version, invalidating all
    /// existing cached authorizations.
    function _entry_bumpAgentAuthCacheVersion() internal onlyGovernance {
        _bumpAgentAuthCacheVersionInternal();
    }

    /// @notice Update the ENS root node used for validator verification.
    /// @param node Namehash of the validator parent node (e.g. `club.agi.eth`).
    function _entry_setValidatorRootNode(bytes32 node) internal onlyGovernance {
        _setValidatorRootNode(node);
    }

    /// @notice Update the Merkle root for the validator allowlist.
    /// @param root Merkle root of approved validator addresses.
    function _entry_setValidatorMerkleRoot(bytes32 root) internal onlyGovernance {
        _setValidatorMerkleRoot(root);
    }

    /// @notice Refresh or invalidate cached agent authorization entries.
    /// @param agent Address of the agent being updated.
    /// @param authorized True to refresh the cache entry, false to invalidate it.
    function _entry_updateAgentAuthCache(address agent, bool authorized) internal onlyGovernance {
        agentAuthCache[agent] = authorized;
        agentAuthExpiry[agent] = authorized ? block.timestamp + agentAuthCacheDuration : 0;
        agentAuthVersion[agent] = authorized ? agentAuthCacheVersion : 0;
        emit AgentAuthCacheUpdated(agent, authorized);
    }

    /// @notice Update the duration for cached agent authorizations.
    /// @param duration Seconds an authorization remains valid in cache.
    function _entry_setAgentAuthCacheDuration(uint256 duration) internal onlyGovernance {
        _setAgentAuthCacheDuration(duration);
    }

    /// @notice update the FeePool contract used for revenue sharing
    function _entry_setFeePool(IFeePool _feePool) internal onlyGovernance {
        _setFeePool(_feePool);
    }

    /// @notice update the treasury address used for blacklisted payouts
    /// @dev Treasury must be zero (burn) or a non-owner address
    function _entry_setTreasury(address _treasury) internal onlyGovernance {
        _setTreasury(_treasury);
    }

    /// @notice update the required agent stake for each job
    function _entry_setJobStake(uint96 stake) internal onlyGovernance {
        _setJobStake(stake);
    }

    /// @notice update the minimum global stake required for agents when applying
    function _entry_setMinAgentStake(uint256 stake) internal onlyGovernance {
        _setMinAgentStake(stake);
    }

    /// @notice update the percentage of each job reward taken as a protocol fee
    function _entry_setFeePct(uint256 _feePct) internal onlyGovernance {
        _applyFeeConfiguration(_feePct, validatorRewardPct, true, false);
    }

    /// @notice update validator reward percentage of job reward
    function _entry_setValidatorRewardPct(uint256 pct) internal onlyGovernance {
        _applyFeeConfiguration(feePct, pct, false, true);
    }

    /// @notice set the maximum allowed job reward
    function _entry_setMaxJobReward(uint256 maxReward) internal onlyGovernance {
        _setMaxJobReward(maxReward);
    }

    /// @notice set the maximum allowed job duration in seconds
    function _entry_setJobDurationLimit(uint256 limit) internal onlyGovernance {
        _setJobDurationLimit(limit);
    }

    /// @notice Set the maximum number of simultaneously active jobs an agent may hold.
    /// @dev A value of zero disables the limit.
    function _entry_setMaxActiveJobsPerAgent(uint256 limit) internal onlyGovernance {
        _setMaxActiveJobsPerAgent(limit);
    }

    /// @notice set additional grace period after a job's deadline before it can expire
    function _entry_setExpirationGracePeriod(uint256 period) internal onlyGovernance {
        _setExpirationGracePeriod(period);
    }

    /// @notice Sets the TaxPolicy contract holding the canonical disclaimer.
    /// @dev Only callable by the owner; the policy address cannot be zero and
    /// must explicitly report tax exemption.
    function _entry_setTaxPolicy(ITaxPolicy _policy) internal onlyGovernance {
        _setTaxPolicy(_policy);
    }

    /// @notice Pause job lifecycle interactions
    function _entry_pause() internal onlyGovernanceOrPauser {
        _pause();
    }

    /// @notice Resume job lifecycle interactions
    function _entry_unpause() internal onlyGovernanceOrPauser {
        _unpause();
    }

    /// @notice Confirms this registry and its owner are perpetually tax‑exempt.
    /// @return Always true; no tax liability can accrue here.
    function isTaxExempt() external pure returns (bool) {
        return true;
    }

    /// @notice Returns the on-chain acknowledgement string stating that all
    /// taxes are the responsibility of employers, agents, and validators.
    function taxAcknowledgement() external view returns (string memory) {
        if (address(taxPolicy) == address(0)) return "";
        return taxPolicy.acknowledgement();
    }

    /// @notice Returns the URI pointing to the full off-chain tax policy.
    function taxPolicyURI() external view returns (string memory) {
        if (address(taxPolicy) == address(0)) return "";
        return taxPolicy.policyURI();
    }

    /// @notice Convenience helper returning both acknowledgement and URI.
    /// @return ack Plain-text disclaimer confirming tax responsibilities.
    /// @return uri Off-chain document location (e.g., IPFS hash).
    function taxPolicyDetails() external view returns (string memory ack, string memory uri) {
        if (address(taxPolicy) == address(0)) return ("", "");
        (ack, uri) = taxPolicy.policyDetails();
    }

    /// @notice Allow or revoke an acknowledger address.
    /// @dev When `allowed` is true, `acknowledger` must be a non-zero address representing a valid contract or EOA.
    /// @param acknowledger Address granted permission to acknowledge for users.
    /// @param allowed True to allow the address, false to revoke.
    function _entry_setAcknowledger(address acknowledger, bool allowed) internal onlyGovernance {
        _setAcknowledger(acknowledger, allowed);
    }

    /// @notice Internal helper to acknowledge the current tax policy for a user.
    /// @param user Address being marked as having acknowledged the policy.
    function _acknowledge(address user) internal returns (string memory ack) {
        if (address(taxPolicy) == address(0)) revert InvalidTaxPolicy();
        ack = taxPolicy.acknowledgeFor(user);
        emit TaxAcknowledged(user, taxPolicy.policyVersion(), ack);
    }

    /// @notice Acknowledge the current tax policy.
    /// @dev Retrieves the acknowledgement text from the `TaxPolicy` contract
    /// and emits it for off-chain visibility so participants have an on-chain
    /// record of the exact disclaimer accepted.
    /// @return ack Human‑readable disclaimer confirming the caller bears all
    /// tax responsibility.
    function _entry_acknowledgeTaxPolicy() internal returns (string memory ack) {
        ack = _acknowledge(msg.sender);
    }

    /// @notice Acknowledge the current tax policy on behalf of a user.
    /// @param user Address acknowledging the policy.
    /// @return ack Human-readable disclaimer confirming the caller bears all tax responsibility.
    function _entry_acknowledgeFor(address user) internal returns (string memory ack) {
        if (!acknowledgers[msg.sender]) revert NotAcknowledger();
        ack = _acknowledge(user);
    }

    function _entry_setJobParameters(uint256 maxReward, uint256 stake) internal onlyGovernance {
        if (stake > type(uint96).max) revert StakeOverflow();
        _setJobStake(uint96(stake));
        _setMaxJobReward(maxReward);
    }

    /// @notice Apply a batch of configuration updates atomically.
    /// @param config Packed configuration toggles and values to apply.
    /// @param acknowledgerUpdates Acknowledger allow/deny list updates.
    /// @param ackModules Additional acknowledge-for modules to enable.
    function _entry_applyConfiguration(
        ConfigUpdate calldata config,
        AcknowledgerUpdate[] calldata acknowledgerUpdates,
        address[] calldata ackModules
    ) internal onlyGovernance {
        uint256 ackUpdateLen = acknowledgerUpdates.length;
        for (uint256 i; i < ackUpdateLen;) {
            AcknowledgerUpdate calldata entry = acknowledgerUpdates[i];
            _setAcknowledger(entry.acknowledger, entry.allowed);
            unchecked {
                ++i;
            }
        }

        ConfigUpdateFlags memory flags;

        if (config.setPauser) {
            _setPauser(config.pauser);
            flags.pauserUpdated = true;
        }

        if (config.setPauserManager) {
            pauserManager = config.pauserManager;
            emit PauserManagerUpdated(config.pauserManager);
            flags.pauserManagerUpdated = true;
        }

        if (config.setModuleBundle) {
            (
                bool validationChanged,
                bool stakeChanged,
                bool reputationChanged,
                bool disputeChanged,
                bool certificateChanged,
                bool feeChanged,
                uint256 ackCount
            ) = _applyModuleBundle(config.modules, ackModules);
            flags.modulesUpdated = true;
            flags.validationModuleUpdated = validationChanged;
            flags.stakeManagerUpdated = stakeChanged;
            flags.reputationModuleUpdated = reputationChanged;
            flags.disputeModuleUpdated = disputeChanged;
            flags.certificateNFTUpdated = certificateChanged;
            flags.feePoolUpdated = feeChanged;
            flags.ackModulesAdded = ackCount;
        } else if (ackModules.length > 0) {
            uint256 ackLen = ackModules.length;
            for (uint256 i; i < ackLen;) {
                _enableAckModule(ackModules[i]);
                unchecked {
                    ++i;
                }
            }
            flags.ackModulesAdded = ackLen;
            flags.modulesUpdated = true;
        }

        if (config.setIdentityRegistry) {
            _setIdentityRegistry(IIdentityRegistry(config.identityRegistry));
            flags.identityRegistryUpdated = true;
            flags.agentAuthCacheVersionBumped = true;
            flags.modulesUpdated = true;
        }

        if (config.setDisputeModule) {
            _setDisputeModule(IDisputeModule(config.disputeModule));
            flags.disputeModuleUpdated = true;
            flags.modulesUpdated = true;
        }

        if (config.setValidationModule) {
            _setValidationModule(IValidationModule(config.validationModule));
            flags.validationModuleUpdated = true;
            flags.modulesUpdated = true;
        }

        if (config.setAuditModule) {
            _setAuditModule(IAuditModule(config.auditModule));
            flags.auditModuleUpdated = true;
            flags.modulesUpdated = true;
        }

        if (config.setStakeManager) {
            _setStakeManager(IStakeManager(config.stakeManager));
            flags.stakeManagerUpdated = true;
            flags.modulesUpdated = true;
        }

        if (config.setReputationModule) {
            _setReputationEngine(IReputationEngine(config.reputationModule));
            flags.reputationModuleUpdated = true;
            flags.modulesUpdated = true;
        }

        if (config.setCertificateNFT) {
            _setCertificateNFT(ICertificateNFT(config.certificateNFT));
            flags.certificateNFTUpdated = true;
            flags.modulesUpdated = true;
        }

        if (config.setFeePool) {
            _setFeePool(IFeePool(config.feePool));
            flags.feePoolUpdated = true;
            flags.modulesUpdated = true;
        }

        if (config.setTaxPolicy) {
            _setTaxPolicy(ITaxPolicy(config.taxPolicy));
            flags.taxPolicyUpdated = true;
        }

        if (config.setTreasury) {
            _setTreasury(config.treasury);
            flags.treasuryUpdated = true;
        }

        if (config.setJobStake) {
            _setJobStake(config.jobStake);
            flags.jobStakeUpdated = true;
        }

        if (config.setMinAgentStake) {
            _setMinAgentStake(config.minAgentStake);
            flags.minAgentStakeUpdated = true;
        }

        if (config.setMaxJobReward) {
            _setMaxJobReward(config.maxJobReward);
            flags.maxJobRewardUpdated = true;
        }

        if (config.setJobDurationLimit) {
            _setJobDurationLimit(config.jobDurationLimit);
            flags.maxJobDurationUpdated = true;
        }

        if (config.setMaxActiveJobsPerAgent) {
            _setMaxActiveJobsPerAgent(config.maxActiveJobsPerAgent);
            flags.maxActiveJobsUpdated = true;
        }

        if (config.setExpirationGracePeriod) {
            _setExpirationGracePeriod(config.expirationGracePeriod);
            flags.expirationGracePeriodUpdated = true;
        }

        if (config.setAgentRootNode) {
            _setAgentRootNode(config.agentRootNode);
            flags.agentRootUpdated = true;
            flags.agentAuthCacheVersionBumped = true;
        }

        if (config.setAgentMerkleRoot) {
            _setAgentMerkleRoot(config.agentMerkleRoot);
            flags.agentMerkleUpdated = true;
            flags.agentAuthCacheVersionBumped = true;
        }

        if (config.setValidatorRootNode) {
            _setValidatorRootNode(config.validatorRootNode);
            flags.validatorRootUpdated = true;
        }

        if (config.setValidatorMerkleRoot) {
            _setValidatorMerkleRoot(config.validatorMerkleRoot);
            flags.validatorMerkleUpdated = true;
        }

        if (config.setAgentAuthCacheDuration) {
            _setAgentAuthCacheDuration(config.agentAuthCacheDuration);
            flags.agentAuthCacheDurationUpdated = true;
        }

        if (config.bumpAgentAuthCacheVersion) {
            _bumpAgentAuthCacheVersionInternal();
            flags.agentAuthCacheVersionBumped = true;
        }

        if (config.setFeePct || config.setValidatorRewardPct) {
            uint256 newFee = config.setFeePct ? config.feePct : feePct;
            uint256 newValidator = config.setValidatorRewardPct ? config.validatorRewardPct : validatorRewardPct;
            (bool feeChanged, bool validatorChanged) =
                _applyFeeConfiguration(newFee, newValidator, config.setFeePct, config.setValidatorRewardPct);
            if (feeChanged) flags.feePctUpdated = true;
            if (validatorChanged) flags.validatorRewardPctUpdated = true;
        }

        _emitConfigurationApplied(flags, ackUpdateLen);
    }

    function _emitConfigurationApplied(ConfigUpdateFlags memory flags, uint256 ackUpdateLen) internal {
        emit ConfigurationApplied(msg.sender, _encodeConfigurationFlags(flags), ackUpdateLen, flags.ackModulesAdded);
    }

    // ---------------------------------------------------------------------
    // Job lifecycle
    // ---------------------------------------------------------------------
    function _createJob(uint256 reward, uint64 deadline, uint8 agentTypes, bytes32 specHash, string calldata uri)
        internal
        whenNotPaused
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
        nonReentrant
        returns (uint256 jobId)
    {
        if (reward == 0 && jobStake == 0) revert JobParametersUnset();
        if (reward > type(uint128).max) revert RewardOverflow();
        if (maxJobReward != 0 && reward > maxJobReward) revert RewardTooHigh();
        if (deadline <= block.timestamp) revert InvalidDeadline();
        if (agentTypes == 0 || agentTypes > 3) revert InvalidAgentTypes();
        if (specHash == bytes32(0)) revert InvalidSpecHash();
        if (maxJobDuration > 0 && uint256(deadline) - block.timestamp > maxJobDuration) revert DurationTooLong();
        if (feePct + validatorRewardPct > 100) revert InvalidPercentages();
        if (address(reputationEngine) != address(0) && reputationEngine.isBlacklisted(msg.sender)) {
            revert BlacklistedEmployer();
        }
        unchecked {
            nextJobId++;
        }
        jobId = nextJobId;
        uint32 feePctSnapshot = uint32(feePct);
        _initialiseJobStorage(jobId, reward, deadline, agentTypes, specHash, uri, feePctSnapshot);
        uint256 fee = _fundJob(jobId, reward, feePctSnapshot);
        _emitJobCreated(jobId, reward, fee, specHash, uri);
    }

    function _entry_createJob(uint256 reward, uint64 deadline, bytes32 specHash, string calldata uri)
        internal
        returns (uint256 jobId)
    {
        jobId = _createJob(reward, deadline, 3, specHash, uri);
    }

    function _emitJobCreated(uint256 jobId, uint256 reward, uint256 fee, bytes32 specHash, string calldata uri)
        internal
    {
        emit JobCreated(jobId, msg.sender, address(0), reward, uint256(jobStake), fee, specHash, uri);
    }

    function _initialiseJobStorage(
        uint256 jobId,
        uint256 reward,
        uint64 deadline,
        uint8 agentTypes,
        bytes32 specHash,
        string calldata uri,
        uint32 feePctSnapshot
    ) internal {
        bytes32 uriHash = keccak256(bytes(uri));
        JobMetadata memory metadata;
        metadata.state = State.Created;
        metadata.success = false;
        metadata.burnConfirmed = false;
        metadata.agentTypes = agentTypes;
        metadata.feePct = feePctSnapshot;
        metadata.agentPct = 100;
        metadata.deadline = deadline;
        metadata.assignedAt = 0;

        Job storage job = jobs[jobId];
        job.employer = msg.sender;
        job.agent = address(0);
        job.reward = uint128(reward);
        job.stake = jobStake;
        job.burnReceiptAmount = 0;
        job.uriHash = uriHash;
        job.resultHash = bytes32(0);
        job.specHash = specHash;
        job.packedMetadata = _encodeMetadata(metadata);
    }

    function _fundJob(uint256 jobId, uint256 reward, uint32 feePctSnapshot) internal returns (uint256 fee) {
        if (address(stakeManager) == address(0) || reward == 0) {
            return 0;
        }

        fee = (reward * feePctSnapshot) / 100;
        stakeManager.lockReward(bytes32(jobId), msg.sender, reward + fee);
        emit JobFunded(jobId, msg.sender, reward, fee);
    }

    function _entry_createJobWithAgentTypes(
        uint256 reward,
        uint64 deadline,
        uint8 agentTypes,
        bytes32 specHash,
        string calldata uri
    ) internal returns (uint256 jobId) {
        jobId = _createJob(reward, deadline, agentTypes, specHash, uri);
    }

    /**
     * @notice Acknowledge the tax policy and create a job in one transaction.
     * @dev `reward` uses 18-decimal base units. Caller must `approve` the
     *      StakeManager for `reward + fee` $AGIALPHA before calling.
     * @param reward Job reward in $AGIALPHA with 18 decimals.
     * @param uri Metadata URI describing the job.
     * @return jobId Identifier of the newly created job.
     */
    function _entry_acknowledgeAndCreateJob(uint256 reward, uint64 deadline, bytes32 specHash, string calldata uri)
        internal
        returns (uint256 jobId)
    {
        _acknowledge(msg.sender);
        jobId = _createJob(reward, deadline, 3, specHash, uri);
    }

    function _entry_acknowledgeAndCreateJobWithAgentTypes(
        uint256 reward,
        uint64 deadline,
        uint8 agentTypes,
        bytes32 specHash,
        string calldata uri
    ) internal returns (uint256 jobId) {
        _acknowledge(msg.sender);
        jobId = _createJob(reward, deadline, agentTypes, specHash, uri);
    }

    function _applyForJob(uint256 jobId, string calldata subdomain, bytes32[] calldata proof)
        internal
        whenNotPaused
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
    {
        Job storage job = jobs[jobId];
        if (_getState(job) != State.Created) revert NotOpen();
        if (address(reputationEngine) != address(0)) {
            if (reputationEngine.isBlacklisted(msg.sender)) revert BlacklistedAgent();
        }
        if (bytes(subdomain).length == 0) revert EmptySubdomain();
        if (address(identityRegistry) == address(0)) revert IdentityRegistryNotSet();
        _authorizeAgent(subdomain, proof);
        uint8 agentTypes = _getAgentTypes(job);
        if (agentTypes > 0) {
            IIdentityRegistry.AgentType aType = identityRegistry.getAgentType(msg.sender);
            if ((agentTypes & (1 << uint8(aType))) == 0) {
                revert AgentTypeNotAllowed();
            }
        }
        if (address(reputationEngine) != address(0)) {
            reputationEngine.onApply(msg.sender);
        }
        uint32 agentPct = _processStakeOnApply(job);
        _assertActiveJobCapacity();
        emit ApplicationSubmitted(jobId, msg.sender, subdomain);
        job.agent = msg.sender;
        _setAgentPct(job, agentPct);
        _setState(job, State.Applied);
        _setAssignedAt(job, uint64(block.timestamp));
        activeJobs[msg.sender] = activeJobs[msg.sender] + 1;
        emit AgentAssigned(jobId, msg.sender, subdomain);
        emit JobApplied(jobId, msg.sender, subdomain);
    }

    function _entry_applyForJob(uint256 jobId, string calldata subdomain, bytes32[] calldata proof)
        internal
        nonReentrant
    {
        _applyForJob(jobId, subdomain, proof);
    }

    function _authorizeAgent(string calldata subdomain, bytes32[] calldata proof) internal {
        bool authorized = agentAuthCache[msg.sender] && agentAuthExpiry[msg.sender] > block.timestamp
            && agentAuthVersion[msg.sender] == agentAuthCacheVersion;
        string memory cachedSubdomain = agentSubdomains[msg.sender];
        bool hasCached = bytes(cachedSubdomain).length != 0;
        bytes32 providedHash = keccak256(bytes(subdomain));
        bytes32 cachedHash;
        if (hasCached) {
            cachedHash = keccak256(bytes(cachedSubdomain));
        }
        bool cachedMatches = hasCached && cachedHash == providedHash;
        if (authorized && !cachedMatches) {
            authorized = false;
        }
        if (!authorized) {
            bytes32 node;
            bool viaWrapper;
            bool viaMerkle;
            (authorized, node, viaWrapper, viaMerkle) = identityRegistry.verifyAgent(msg.sender, subdomain, proof);
            if (authorized) {
                emit AgentIdentityVerified(msg.sender, node, subdomain, viaWrapper, viaMerkle);
                agentAuthCache[msg.sender] = true;
                agentAuthExpiry[msg.sender] = block.timestamp + agentAuthCacheDuration;
                agentAuthVersion[msg.sender] = agentAuthCacheVersion;
                if (!cachedMatches) {
                    agentSubdomains[msg.sender] = subdomain;
                    emit AgentSubdomainUpdated(msg.sender, subdomain);
                    cachedMatches = true;
                }
            }
        }
        if (!authorized) revert NotAuthorizedAgent();
    }

    function _processStakeOnApply(Job storage job) internal returns (uint32 agentPct) {
        agentPct = 100;
        if (address(stakeManager) == address(0)) {
            return agentPct;
        }

        uint256 requiredStake = uint256(minAgentStake);
        if (requiredStake > 0) {
            uint256 currentStake = stakeManager.stakeOf(msg.sender, IStakeManager.Role.Agent);
            if (currentStake < requiredStake) {
                revert InsufficientAgentStake(requiredStake, currentStake);
            }
        }

        if (job.stake > 0) {
            uint64 lockTime;
            uint64 deadline = _getDeadline(job);
            if (uint256(deadline) > block.timestamp) {
                lockTime = uint64(uint256(deadline) - block.timestamp);
            }
            stakeManager.lockStake(msg.sender, uint256(job.stake), lockTime);
        }

        agentPct = uint32(stakeManager.getTotalPayoutPct(msg.sender));
    }

    function _assertActiveJobCapacity() internal view {
        uint256 activeLimit = maxActiveJobsPerAgent;
        if (activeLimit == 0) {
            return;
        }

        uint256 active = activeJobs[msg.sender];
        if (active >= activeLimit) {
            revert MaxActiveJobsReached(activeLimit);
        }
    }

    /**
     * @notice Acknowledge the current tax policy and apply for a job.
     * @dev No tokens are transferred. Job reward and stake amounts elsewhere
     *      use 18-decimal $AGIALPHA units. Any stake deposits require prior
     *      `approve` calls on the $AGIALPHA token via the `StakeManager`.
     * @param jobId Identifier of the job to apply for.
     */
    function _entry_acknowledgeAndApply(uint256 jobId, string calldata subdomain, bytes32[] calldata proof)
        internal
        nonReentrant
    {
        _acknowledge(msg.sender);
        _applyForJob(jobId, subdomain, proof);
    }

    /**
     * @notice Deposit stake, implicitly acknowledge the tax policy if needed,
     *         and apply for a job in a single call.
     * @dev `amount` uses 18-decimal base units. Caller must `approve` the
     *      `StakeManager` to pull `amount` $AGIALPHA beforehand. If the caller
     *      has not yet acknowledged the tax policy, this helper will do so
     *      automatically on their behalf.
     * @param jobId Identifier of the job to apply for.
     * @param amount Stake amount in $AGIALPHA with 18 decimals.
     */
    function _entry_stakeAndApply(uint256 jobId, uint256 amount, string calldata subdomain, bytes32[] calldata proof)
        internal
        nonReentrant
    {
        _acknowledge(msg.sender);
        stakeManager.depositStakeFor(msg.sender, IStakeManager.Role.Agent, amount);
        _applyForJob(jobId, subdomain, proof);
    }

    /// @notice Agent submits work for validation and selects validators.
    /// @param jobId Identifier of the job being submitted.
    /// @param resultHash Hash of the completed work.
    /// @param resultURI Metadata URI describing the completed work.
    function _entry_submit(
        uint256 jobId,
        bytes32 resultHash,
        string calldata resultURI,
        string calldata subdomain,
        bytes32[] calldata proof
    )
        internal
        whenNotPaused
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
        nonReentrant
    {
        Job storage job = jobs[jobId];
        if (_getState(job) != State.Applied) revert InvalidJobState();
        if (msg.sender != job.agent) revert OnlyAgent();
        if (block.timestamp > _getDeadline(job)) revert DeadlinePassed();
        if (address(reputationEngine) != address(0)) {
            if (reputationEngine.isBlacklisted(msg.sender)) revert BlacklistedAgent();
            if (reputationEngine.isBlacklisted(job.employer)) revert BlacklistedEmployer();
        }
        _validateAgentSubmission(job, subdomain, proof);
        job.resultHash = resultHash;
        _setState(job, State.Submitted);
        emit ResultSubmitted(jobId, msg.sender, resultHash, resultURI, subdomain);
        emit JobSubmitted(jobId, msg.sender, resultHash, resultURI, subdomain);
        _maybeStartValidation(jobId, resultHash);
    }

    function _validateAgentSubmission(Job storage job, string calldata subdomain, bytes32[] calldata proof) internal {
        (bytes32 node, bool viaWrapper, bool viaMerkle) = _verifyAndCacheAgentIdentity(msg.sender, subdomain, proof);
        emit AgentIdentityVerified(msg.sender, node, subdomain, viaWrapper, viaMerkle);

        uint8 agentTypes = _getAgentTypes(job);
        if (agentTypes > 0) {
            IIdentityRegistry.AgentType aType = identityRegistry.getAgentType(msg.sender);
            if ((agentTypes & (1 << uint8(aType))) == 0) {
                revert AgentTypeNotAllowed();
            }
        }
    }

    /// @notice Acknowledge the tax policy and submit work in one call.
    function _entry_acknowledgeAndSubmit(
        uint256 jobId,
        bytes32 resultHash,
        string calldata resultURI,
        string calldata subdomain,
        bytes32[] calldata proof
    ) internal {
        _acknowledge(msg.sender);
        _entry_submit(jobId, resultHash, resultURI, subdomain, proof);
    }

    /// @notice Record job outcome after validation.
    /// @dev Only the ValidationModule may call this entry point with the
    ///      computed result of the commit-reveal process. This function only
    ///      updates the job state and emits the completion event; the employer
    ///      or governance must call {finalize} separately to settle funds.
    /// @param jobId Identifier of the job being validated.
    /// @param success True if validators approved the job.
    function _finalizeAfterValidation(uint256 jobId, bool success) internal {
        if (msg.sender != address(validationModule)) revert OnlyValidationModule();
        Job storage job = jobs[jobId];
        if (_getState(job) != State.Submitted) revert NotSubmitted();
        _clearValidationStart(jobId);
        _setSuccess(job, success);
        _setState(job, success ? State.Completed : State.Disputed);
        emit JobCompleted(jobId, success);
    }

    /// @notice Record that reputation updates have already been applied for a job.
    /// @param jobId Identifier of the job that triggered the update.
    function _entry_markReputationProcessed(uint256 jobId) internal {
        if (msg.sender != address(validationModule)) revert OnlyValidationModule();
        reputationProcessed[jobId] = true;
        emit ReputationProcessingMarked(jobId);
    }

    /// @param jobId Identifier of the job being finalised.
    /// @param success True if validators approved the job.
    function _entry_finalizeAfterValidation(uint256 jobId, bool success)
        internal
        whenNotPaused
        nonReentrant
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
    {
        _finalizeAfterValidation(jobId, success);
    }

    function _entry_validationComplete(uint256 jobId, bool success)
        internal
        whenNotPaused
        nonReentrant
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
    {
        _finalizeAfterValidation(jobId, success);
    }

    /// @notice Record a failed job outcome when validation quorum is not met.
    /// @dev This function only updates the job state; the employer or
    ///      governance must later call {finalize} to settle funds and
    ///      reputation changes.
    /// @param jobId Identifier of the job being recorded.
    function _entry_forceFinalize(uint256 jobId)
        internal
        whenNotPaused
        nonReentrant
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
    {
        if (msg.sender != address(validationModule)) revert OnlyValidationModule();
        Job storage job = jobs[jobId];
        if (_getState(job) != State.Submitted) revert NotSubmitted();
        _clearValidationStart(jobId);
        _setSuccess(job, false);
        _setState(job, State.Completed);
        emit JobCompleted(jobId, false);
    }

    /// @notice Receive validation outcome from the ValidationModule
    /// @param jobId Identifier of the job
    /// @param success True if validators approved the job
    /// @param validators Validators that participated in validation
    function _entry_onValidationResult(uint256 jobId, bool success, address[] calldata validators)
        internal
        whenNotPaused
        nonReentrant
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
    {
        _clearValidatorData(jobId);
        if (validators.length > 0) {
            address[] storage storedValidators = jobValidators[jobId];
            for (uint256 i; i < validators.length;) {
                address validator = validators[i];
                storedValidators.push(validator);
                jobValidatorVotes[jobId][validator] = validationModule.votes(jobId, validator);
                unchecked {
                    ++i;
                }
            }
        }
        _finalizeAfterValidation(jobId, success);
    }

    /// @notice Agent or employer disputes a job outcome with a hash of off-chain evidence.
    /// @param jobId Identifier of the disputed job.
    /// @param evidenceHash Keccak256 hash of the evidence stored off-chain.
    /// @param reason Plain-text description or URI describing the dispute.
    function _entry_dispute(uint256 jobId, bytes32 evidenceHash, string calldata reason)
        internal
        whenNotPaused
        nonReentrant
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
    {
        _dispute(jobId, evidenceHash, reason);
    }

    /// @notice Escalate a stalled validation into the dispute process.
    /// @dev Callable only by governance (timelock/SystemPause) as part of the incident response playbook.
    /// @param jobId Identifier of the job requiring manual intervention.
    /// @param reason Context string explaining the escalation.
    function _entry_escalateToDispute(uint256 jobId, string calldata reason)
        internal
        onlyGovernance
        whenNotPaused
        nonReentrant
    {
        Job storage job = jobs[jobId];
        JobMetadata memory metadata = decodeJobMetadata(job.packedMetadata);
        State state = metadata.state;
        if (!(state == State.Submitted || state == State.Completed)) {
            revert InvalidEscalationState(uint8(state));
        }
        _setState(job, State.Disputed);
        string memory rationale = bytes(reason).length == 0 ? "governance-escalation" : reason;
        if (address(disputeModule) != address(0)) {
            disputeModule.raiseGovernanceDispute(jobId, rationale);
        }
        emit JobEscalatedByGovernance(jobId, msg.sender, rationale);
    }

    /// @notice Backwards-compatible wrapper for legacy integrations.
    /// @dev Calls {dispute} with the provided evidence hash.
    function _entry_raiseDispute(uint256 jobId, bytes32 evidenceHash) internal {
        _dispute(jobId, evidenceHash, "");
    }

    /// @notice Overload supporting plain-text dispute reasons.
    /// @param jobId Identifier of the disputed job.
    /// @param reason Plain-text or URI reason for the dispute.
    function _entry_raiseDispute(uint256 jobId, string calldata reason) internal {
        _dispute(jobId, bytes32(0), reason);
    }

    /**
     * @notice Acknowledge the tax policy if needed and raise a dispute with
     *         supporting evidence stored off-chain.
     * @dev No tokens are transferred; any stake requirements elsewhere use
     *      18-decimal $AGIALPHA units that must have been approved previously.
     * @param jobId Identifier of the disputed job.
     * @param evidenceHash Keccak256 hash of the off-chain evidence.
     */
    function _entry_acknowledgeAndDispute(uint256 jobId, bytes32 evidenceHash, string calldata reason) internal {
        if (address(taxPolicy) != address(0) && !taxPolicy.hasAcknowledged(msg.sender)) {
            _acknowledge(msg.sender);
        }
        _dispute(jobId, evidenceHash, reason);
    }

    /// @notice Backwards-compatible helper without a reason string.
    function _entry_acknowledgeAndDispute(uint256 jobId, bytes32 evidenceHash) internal {
        _dispute(jobId, evidenceHash, "");
    }

    function _dispute(uint256 jobId, bytes32 evidenceHash, string memory reason) internal {
        if (evidenceHash == bytes32(0) && bytes(reason).length == 0) {
            revert EvidenceMissing();
        }
        Job storage job = jobs[jobId];
        if (msg.sender != job.agent && msg.sender != job.employer) {
            revert OnlyParticipant();
        }
        State state = _getState(job);
        bool success = _getSuccess(job);
        if (!(state == State.Completed || (state == State.Disputed && !success))) {
            revert CannotDispute();
        }
        if (state == State.Completed) {
            _setState(job, State.Disputed);
        }
        if (address(reputationEngine) != address(0)) {
            if (reputationEngine.isBlacklisted(msg.sender)) revert Blacklisted();
            if (reputationEngine.isBlacklisted(job.agent)) revert BlacklistedAgent();
            if (reputationEngine.isBlacklisted(job.employer)) revert BlacklistedEmployer();
        }
        if (address(disputeModule) != address(0)) {
            disputeModule.raiseDispute(jobId, msg.sender, evidenceHash, reason);
        }
        emit JobDisputed(jobId, msg.sender);
    }

    /// @notice Resolve a dispute relayed by the dispute module.
    /// @dev After resolution this function only records the result, moving the
    ///      job to the completed state. The employer or governance must call
    ///      {finalize} separately to settle funds and reputation.
    /// @param jobId Identifier of the disputed job
    /// @param employerWins True if the employer won the dispute
    function _entry_resolveDispute(uint256 jobId, bool employerWins) internal whenNotPaused nonReentrant {
        if (msg.sender != address(disputeModule)) revert OnlyDisputeModule();
        Job storage job = jobs[jobId];
        if (_getState(job) != State.Disputed) revert NoDispute();

        _setSuccess(job, !employerWins);
        _setState(job, State.Completed);
        _clearValidatorData(jobId);
        if (reputationProcessed[jobId]) {
            delete reputationProcessed[jobId];
        }
        emit DisputeResolved(jobId, employerWins);
    }

    /// @notice Finalize a job and trigger payouts and reputation changes.
    /// @dev The dispute module may call this without acknowledgement as it
    ///      merely relays the arbiter's ruling and holds no tax liability.
    function _entry_finalize(uint256 jobId)
        internal
        whenNotPaused
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
        nonReentrant
    {
        _finalizeByEmployer(jobId);
    }

    function _finalizeByEmployer(uint256 jobId) internal {
        Job storage job = jobs[jobId];
        if (msg.sender != job.employer && msg.sender != address(governance)) {
            revert OnlyEmployer();
        }
        _finalize(jobId);
    }

    function _finalize(uint256 jobId) internal whenNotPaused {
        Job storage job = jobs[jobId];
        if (_getState(job) != State.Completed) revert NotReady();
        bool isGov = msg.sender == address(governance);
        _clearValidationStart(jobId);
        uint256 burnRate = address(stakeManager) != address(0) ? stakeManager.burnPct() : 0;
        bool agentBlacklisted;
        bool employerBlacklisted;
        if (address(reputationEngine) != address(0)) {
            agentBlacklisted = reputationEngine.isBlacklisted(job.agent);
            employerBlacklisted = reputationEngine.isBlacklisted(job.employer);
            if (!isGov) {
                if (reputationEngine.isBlacklisted(msg.sender)) revert Blacklisted();
                if (agentBlacklisted) revert BlacklistedAgent();
                if (employerBlacklisted) revert BlacklistedEmployer();
            }
        }
        _setState(job, State.Finalized);
        bytes32 jobKey = bytes32(jobId);
        bool fundsRedirected;
        address[] memory validators = jobValidators[jobId];
        bool success = _getSuccess(job);
        bool reputationHandled = reputationProcessed[jobId];
        if (success) {
            IFeePool pool = feePool;
            uint256 validatorReward;
            if (validators.length > 0 && validatorRewardPct > 0) {
                validatorReward = (uint256(job.reward) * validatorRewardPct) / 100;
            }

            uint256 rewardAfterValidator = uint256(job.reward) - validatorReward;
            uint256 fee;
            uint32 agentPctRaw = _getAgentPct(job);
            uint256 agentPct = agentPctRaw == 0 ? 100 : agentPctRaw;
            if (address(stakeManager) != address(0)) {
                if (address(pool) != address(0) && job.reward > 0) {
                    fee = (uint256(job.reward) * _getFeePct(job)) / 100;
                }
            }
            uint256 agentAmount = (rewardAfterValidator * agentPct) / 100;
            if (address(stakeManager) != address(0)) {
                address payee = job.agent;
                if (isGov && treasury != address(0) && agentBlacklisted) {
                    payee = treasury;
                    fundsRedirected = true;
                }

                address employerParam = isGov ? job.employer : msg.sender;
                stakeManager.finalizeJobFundsWithPct(
                    jobKey, employerParam, payee, agentPct, rewardAfterValidator, validatorReward, fee, pool, isGov
                );

                if (validatorReward > 0) {
                    if (validators.length > 0) {
                        stakeManager.distributeValidatorRewards(jobKey, validatorReward);
                    } else {
                        stakeManager.releaseReward(jobKey, job.employer, payee, validatorReward, true);
                    }
                }
                if (job.stake > 0) {
                    if (isGov && treasury != address(0) && agentBlacklisted) {
                        stakeManager.slash(
                            job.agent, IStakeManager.Role.Agent, uint256(job.stake), treasury, validators
                        );
                    } else {
                        stakeManager.releaseStake(job.agent, uint256(job.stake));
                    }
                }
                if (_getBurnConfirmed(job) && burnRate > 0) {
                    uint256 expectedBurn = (agentAmount * burnRate) / 100;
                    if (uint256(job.burnReceiptAmount) != expectedBurn) {
                        emit BurnDiscrepancy(jobId, job.burnReceiptAmount, expectedBurn);
                    }
                }
            }
            if (address(reputationEngine) != address(0) && !reputationHandled) {
                uint256 completionTime = block.timestamp - uint256(_getAssignedAt(job));
                uint256 payout = agentAmount * 1e12;
                uint256 agentGain = reputationEngine.calculateReputationPoints(payout, completionTime);
                reputationEngine.onFinalize(job.agent, true, payout, completionTime);
                if (validators.length > 0) {
                    for (uint256 i; i < validators.length;) {
                        address val = validators[i];
                        if (jobValidatorVotes[jobId][val]) {
                            reputationEngine.rewardValidator(val, agentGain);
                        }
                        unchecked {
                            ++i;
                        }
                    }
                }
            }
            if (address(certificateNFT) != address(0)) {
                certificateNFT.mint(job.agent, jobId, job.uriHash);
            }
            uint256 bonus = agentAmount - rewardAfterValidator;
            emit JobPayout(jobId, job.agent, rewardAfterValidator, bonus, fee);
        } else {
            if (address(stakeManager) != address(0)) {
                uint256 fee = (uint256(job.reward) * _getFeePct(job)) / 100;
                address recipient = job.employer;
                if (isGov && treasury != address(0) && employerBlacklisted) {
                    recipient = treasury;
                    fundsRedirected = true;
                }
                if (job.reward > 0) {
                    stakeManager.redistributeEscrow(jobKey, recipient, uint256(job.reward) + fee, validators);
                }
                if (job.stake > 0) {
                    stakeManager.slash(job.agent, IStakeManager.Role.Agent, uint256(job.stake), recipient, validators);
                }
            }
            if (address(reputationEngine) != address(0) && !reputationHandled) {
                reputationEngine.onFinalize(job.agent, false, 0, 0);
            }
        }
        if (success) {
            employerStats[job.employer].successful++;
        } else {
            employerStats[job.employer].failed++;
        }
        emit JobFinalized(jobId, job.agent);
        if (address(auditModule) != address(0)) {
            try auditModule.onJobFinalized(jobId, job.agent, success, job.resultHash) {}
            catch (bytes memory err) {
                emit AuditModuleCallbackFailed(jobId, err);
            }
        }
        if (isGov) {
            emit GovernanceFinalized(jobId, msg.sender, fundsRedirected);
        }
        address agentAddr = job.agent;
        if (agentAddr != address(0)) {
            uint256 activeCount = activeJobs[agentAddr];
            if (activeCount > 0) {
                activeJobs[agentAddr] = activeCount - 1;
            }
        }
        _clearValidatorData(jobId);
        if (reputationProcessed[jobId]) {
            delete reputationProcessed[jobId];
        }
    }

    /// @notice Acknowledge the tax policy and finalise the job in one call.
    /// @param jobId Identifier of the job to finalise
    function _entry_acknowledgeAndFinalize(uint256 jobId) internal {
        _acknowledge(msg.sender);
        _entry_finalize(jobId);
    }

    /// @notice Acknowledge the tax policy and cancel a job in one call.
    /// @param jobId Identifier of the job to cancel
    function _entry_acknowledgeAndCancel(uint256 jobId) internal {
        _acknowledge(msg.sender);
        _entry_cancelJob(jobId);
    }

    /// @notice Cancel an unassigned job and refund the employer.
    /// @dev Convenience wrapper matching earlier interface expectations.
    /// Calls {cancelJob} which handles tax acknowledgement checks and
    /// refunds any locked reward back to the employer.
    /// @param jobId Identifier of the job to cancel.
    function _entry_cancel(uint256 jobId) internal {
        _entry_cancelJob(jobId);
    }

    /// @notice Cancel a job before completion and refund the employer.
    function _cancelJob(uint256 jobId) internal whenNotPaused {
        Job storage job = jobs[jobId];
        if (!(_getState(job) == State.Created && job.agent == address(0))) {
            revert CannotCancel();
        }
        _setState(job, State.Cancelled);
        if (address(stakeManager) != address(0) && job.reward > 0) {
            uint256 fee = (uint256(job.reward) * _getFeePct(job)) / 100;
            stakeManager.refundEscrow(bytes32(jobId), job.employer, uint256(job.reward) + fee);
        }
        _clearValidatorData(jobId);
        if (reputationProcessed[jobId]) {
            delete reputationProcessed[jobId];
        }
        emit JobCancelled(jobId);
    }

    function _entry_cancelJob(uint256 jobId)
        internal
        nonReentrant
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
    {
        Job storage job = jobs[jobId];
        if (msg.sender != job.employer) revert OnlyEmployer();
        if (address(reputationEngine) != address(0)) {
            if (reputationEngine.isBlacklisted(msg.sender)) revert BlacklistedEmployer();
        }
        _cancelJob(jobId);
    }

    /// @notice Owner can delist an unassigned job and refund the employer.
    /// @param jobId Identifier of the job to delist.
    function _entry_delistJob(uint256 jobId) internal onlyGovernance {
        _cancelJob(jobId);
    }

    /// @notice Mark an applied job as timed out and settle funds directly.
    /// @param jobId Identifier of the job to mark as timed out.
    function _entry_claimTimeout(uint256 jobId)
        internal
        whenNotPaused
        nonReentrant
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
    {
        Job storage job = jobs[jobId];
        address gov = address(governance);
        if (msg.sender != job.employer && msg.sender != gov) {
            revert OnlyEmployer();
        }
        if (_getState(job) != State.Applied) revert InvalidJobState();
        uint256 expiry = uint256(_getDeadline(job)) + expirationGracePeriod;
        if (block.timestamp <= expiry) revert CannotExpire();

        address employer = job.employer;
        address agent = job.agent;
        uint128 reward = job.reward;
        uint96 stakeAmount = job.stake;
        uint32 feePctSnapshot = _getFeePct(job);

        _setSuccess(job, false);
        _setState(job, State.Finalized);

        if (address(stakeManager) != address(0)) {
            bytes32 jobKey = bytes32(jobId);
            uint256 fee = (uint256(reward) * feePctSnapshot) / 100;
            uint256 totalRefund = uint256(reward) + fee;
            if (totalRefund > 0) {
                address[] memory validators = new address[](0);
                stakeManager.redistributeEscrow(jobKey, employer, totalRefund, validators);
            }
            if (stakeAmount > 0 && agent != address(0)) {
                stakeManager.slash(agent, IStakeManager.Role.Agent, uint256(stakeAmount), employer);
            }
        }

        employerStats[employer].failed++;

        job.agent = address(0);
        _setAgentPct(job, 0);
        _setAssignedAt(job, 0);
        job.reward = 0;
        job.stake = 0;
        _setBurnConfirmed(job, false);
        job.burnReceiptAmount = 0;
        job.resultHash = bytes32(0);

        if (agent != address(0)) {
            uint256 activeCount = activeJobs[agent];
            if (activeCount > 0) {
                activeJobs[agent] = activeCount - 1;
            }
        }
        _clearValidatorData(jobId);
        if (reputationProcessed[jobId]) {
            delete reputationProcessed[jobId];
        }
        emit JobTimedOut(jobId, msg.sender);
    }

    /// @notice Cancel an assigned job that failed to submit before its deadline.
    /// @dev Only the employer or governance may trigger this after the deadline.
    /// @param jobId Identifier of the job to cancel.
    function _entry_cancelExpiredJob(uint256 jobId)
        internal
        onlyAfterDeadline(jobId)
        whenNotPaused
        requiresTaxAcknowledgement(taxPolicy, msg.sender, owner(), address(disputeModule), address(validationModule))
        nonReentrant
    {
        Job storage job = jobs[jobId];
        if (msg.sender != job.employer && msg.sender != address(governance)) {
            revert OnlyEmployer();
        }
        _setSuccess(job, false);
        _setState(job, State.Completed);
        _finalize(jobId);
        emit JobExpired(jobId, msg.sender);
    }

    // ---------------------------------------------------------------------
    // Ether rejection
    // ---------------------------------------------------------------------
    /// @dev Prevent accidental ETH transfers; this registry never holds funds
    /// and cannot accrue tax liabilities. All value flows through the
    /// StakeManager or DisputeModule according to participant actions.
    receive() external payable {
        revert("JobRegistry: no ether");
    }

    /// @dev Reject calls with unexpected calldata or funds.
    fallback() external payable {
        revert("JobRegistry: no ether");
    }
}

contracts/v2/interfaces/IAuditModule.sol

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

/// @title IAuditModule
/// @notice Interface for scheduling and recording post-completion job audits.
interface IAuditModule {
    /// @notice Module version for compatibility checks.
    function version() external view returns (uint256);

    /// @notice Emitted when a job is randomly selected for an audit.
    event AuditScheduled(
        uint256 indexed jobId,
        address indexed agent,
        bytes32 resultHash,
        bytes32 seed
    );

    /// @notice Emitted when an authorised auditor records the audit outcome.
    event AuditRecorded(
        uint256 indexed jobId,
        address indexed auditor,
        bool passed,
        string details
    );

    /// @notice Emitted when an audit failure triggers a reputation penalty.
    event AuditPenaltyApplied(
        uint256 indexed jobId,
        address indexed agent,
        uint256 penalty
    );

    /// @notice Notify the audit module that a job has been finalised.
    /// @param jobId Identifier of the job.
    /// @param agent Worker that completed the job.
    /// @param success True if the job was approved by validators.
    /// @param resultHash Hash of the job output committed on-chain.
    function onJobFinalized(
        uint256 jobId,
        address agent,
        bool success,
        bytes32 resultHash
    ) external;
}

contracts/v2/interfaces/ICertificateNFT.sol

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

/// @title ICertificateNFT
/// @notice Interface for minting non-fungible job completion certificates
interface ICertificateNFT {
    /// @notice Module version for compatibility checks.
    function version() external view returns (uint256);
    /// @dev Reverts when caller is not the authorised JobRegistry
    error NotJobRegistry(address caller);

    /// @dev Reverts when attempting to mint more than once for the same job
    error CertificateAlreadyMinted(uint256 jobId);

    /// @dev Reverts when an empty metadata hash is supplied
    error EmptyURI();

    event CertificateMinted(address indexed to, uint256 indexed jobId, bytes32 uriHash);

    /// @notice Mint a completion certificate NFT for a job
    /// @param to Recipient of the certificate
    /// @param jobId Identifier of the job; doubles as the NFT tokenId
    /// @param uriHash Hash of the metadata URI for the certificate
    /// @return tokenId The identifier of the minted certificate
    /// @dev Reverts with {NotJobRegistry} if called by an unauthorised address
    function mint(
        address to,
        uint256 jobId,
        bytes32 uriHash
    ) external returns (uint256 tokenId);
}

contracts/v2/interfaces/IDisputeModule.sol

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

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

/// @title IDisputeModule
/// @notice Minimal interface for the dispute module used by the arbitrator committee.
interface IDisputeModule {
    function version() external view returns (uint256);

    function setTaxPolicy(ITaxPolicy policy) external;

    function raiseDispute(
        uint256 jobId,
        address claimant,
        bytes32 evidenceHash,
        string calldata reason
    ) external;

    function raiseGovernanceDispute(uint256 jobId, string calldata reason) external;

    function resolveDispute(uint256 jobId, bool employerWins) external;

    function resolveWithSignatures(
        uint256 jobId,
        bool employerWins,
        bytes[] calldata signatures
    ) external;

    function submitEvidence(
        uint256 jobId,
        bytes32 evidenceHash,
        string calldata uri
    ) external;

    function slashValidator(
        address juror,
        uint256 amount,
        address employer
    ) external;
}

contracts/v2/interfaces/IFeePool.sol

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

/// @title IFeePool
/// @notice Minimal interface for depositing job fees
interface IFeePool {
    /// @notice contract version for compatibility checks
    function version() external view returns (uint256);

    /// @notice notify the pool about newly received fees
    /// @dev The pool burns the configured percentage and escrows the remainder for stakers.
    /// @param amount amount of tokens transferred to the pool scaled to 18 decimals
    function depositFee(uint256 amount) external;

    /// @notice distribute pending fees to stakers
    /// @dev All fee amounts use 18 decimal units.
    function distributeFees() external;

    /// @notice claim accumulated rewards for caller
    /// @dev Rewards use 18 decimal units.
    function claimRewards() external;

    /// @notice governance-controlled emergency withdrawal of tokens from the pool
    /// @dev Amount uses 18 decimal units.
    /// @param to address receiving the tokens
    /// @param amount token amount with 18 decimals
    function governanceWithdraw(address to, uint256 amount) external;

    /// @notice Transfer reward tokens to a recipient.
    /// @param to address receiving the reward
    /// @param amount token amount with 18 decimals
    function reward(address to, uint256 amount) external;
}

contracts/v2/interfaces/IIdentityRegistry.sol

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

interface IIdentityRegistry {
    /// @notice Module version for compatibility checks.
    function version() external view returns (uint256);
    enum AgentType {
        Human,
        AI
    }
    function isAuthorizedAgent(
        address claimant,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external view returns (bool);

    function isAuthorizedValidator(
        address claimant,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external view returns (bool);

    function verifyAgent(
        address claimant,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external returns (bool ok, bytes32 node, bool viaWrapper, bool viaMerkle);

    function verifyValidator(
        address claimant,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external returns (bool ok, bytes32 node, bool viaWrapper, bool viaMerkle);

    function verifyNode(
        address claimant,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external returns (bool ok, bytes32 node, bool viaWrapper, bool viaMerkle);

    // owner configuration
    function setENS(address ensAddr) external;
    function setNameWrapper(address wrapper) external;
    function setReputationEngine(address engine) external;
    function setAgentRootNode(bytes32 root) external;
    function setClubRootNode(bytes32 root) external;
    function setNodeRootNode(bytes32 root) external;
    function setAgentMerkleRoot(bytes32 root) external;
    function setValidatorMerkleRoot(bytes32 root) external;

    // manual allowlists
    function addAdditionalAgent(address agent) external;
    function removeAdditionalAgent(address agent) external;
    function addAdditionalValidator(address validator) external;
    function removeAdditionalValidator(address validator) external;
    function addAdditionalNodeOperator(address nodeOperator) external;
    function removeAdditionalNodeOperator(address nodeOperator) external;

    function setAgentType(address agent, AgentType agentType) external;

    // views
    function additionalAgents(address account) external view returns (bool);
    function additionalValidators(address account) external view returns (bool);
    function additionalNodeOperators(address account) external view returns (bool);
    function getAgentType(address agent) external view returns (AgentType);

    // profile metadata
    function setAgentProfileURI(address agent, string calldata uri) external;
    function updateAgentProfile(
        string calldata subdomain,
        bytes32[] calldata proof,
        string calldata uri
    ) external;
    function agentProfileURI(address agent) external view returns (string memory);
}

contracts/v2/interfaces/IJobRegistryAck.sol

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

interface IJobRegistryAck {
    function acknowledgeTaxPolicy() external returns (string memory);
    function acknowledgeFor(address user) external returns (string memory);
}

contracts/v2/interfaces/IReputationEngine.sol

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

/// @title IReputationEngine
/// @notice Interface for tracking and updating participant reputation scores
interface IReputationEngine {
    /// @notice Module version for compatibility checks.
    function version() external view returns (uint256);
    /// @dev Reverts when a caller is not authorised to update reputation
    error UnauthorizedCaller(address caller);

    /// @dev Reverts when attempting to act on a blacklisted user
    error BlacklistedUser(address user);
    /// @dev Reverts when array lengths for validator context mismatch
    error ArrayLengthMismatch();

    event ReputationUpdated(address indexed user, int256 delta, uint256 newScore);
    event BlacklistUpdated(address indexed user, bool status);
    event StakeManagerUpdated(address stakeManager);
    event ScoringWeightsUpdated(uint256 stakeWeight, uint256 reputationWeight);

    /// @notice Increase a user's reputation score
    /// @param user Address whose reputation is increased
    /// @param amount Amount to add to the user's score
    /// @dev Reverts with {UnauthorizedCaller} if caller is not permitted
    ///      or {BlacklistedUser} if the user is blacklisted
    function add(address user, uint256 amount) external;

    /// @notice Decrease a user's reputation score
    /// @param user Address whose reputation is decreased
    /// @param amount Amount to subtract from the user's score
    /// @dev Reverts with {UnauthorizedCaller} if caller is not permitted
    ///      or {BlacklistedUser} if the user is blacklisted
    function subtract(address user, uint256 amount) external;

    /// @notice Retrieve a user's reputation score
    /// @param user Address to query
    /// @return The current reputation score of the user
    function reputation(address user) external view returns (uint256);

    /// @notice Alias for {reputation} for backwards compatibility
    function getReputation(address user) external view returns (uint256);

    /// @notice Alternate view to mirror v1 naming
    function reputationOf(address user) external view returns (uint256);

    /// @notice Retrieve accumulated entropy penalties for a user
    /// @param user Address to query
    /// @return The current entropy score of the user
    function entropy(address user) external view returns (uint256);

    /// @notice Alias for {entropy}
    function getEntropy(address user) external view returns (uint256);

    /// @notice Alternate view for legacy naming
    function entropyOf(address user) external view returns (uint256);

    /// @notice Check if a user is blacklisted
    /// @param user Address to query
    /// @return True if the user is blacklisted
    function isBlacklisted(address user) external view returns (bool);

    /// @notice Determine whether a user meets the premium access threshold
    /// @param user Address to query
    /// @return True if the user's reputation meets or exceeds the threshold
    function meetsThreshold(address user) external view returns (bool);

    /// @notice Owner functions

    /// @notice Allow or disallow a caller to update reputation
    /// @param caller Address of the caller to configure
    /// @param allowed True to authorise the caller, false to revoke
    function setCaller(address caller, bool allowed) external;

    /// @notice Backwards compatible alias for {setCaller}
    function setAuthorizedCaller(address caller, bool allowed) external;

    /// @notice Set the minimum score threshold for certain actions
    function setThreshold(uint256 newThreshold) external;

    /// @notice Set premium reputation threshold
    function setPremiumThreshold(uint256 newThreshold) external;

    /// @notice Add or remove a user from the blacklist
    /// @param user Address to update
    /// @param status True to blacklist the user, false to remove
    function setBlacklist(address user, bool status) external;

    /// @notice Job lifecycle hooks
    function onApply(address user) external view;

    function onFinalize(address user, bool success, uint256 payout, uint256 duration) external;

    function rewardValidator(address validator, uint256 agentGain) external;

    /// @notice Update agent and validator reputation for a completed job.
    /// @param jobId Identifier of the job being settled.
    /// @param agent Address of the agent that executed the job.
    /// @param validators Validator committee that assessed the job.
    /// @param success True if the job was approved by validators.
    /// @param validatorRevealed Flags indicating whether each validator revealed their vote.
    /// @param validatorVotes Recorded vote for each validator (true = approval).
    /// @param payout Agent payout expressed with 18 decimals.
    /// @param duration Time elapsed between assignment and completion in seconds.
    function updateScores(
        uint256 jobId,
        address agent,
        address[] calldata validators,
        bool success,
        bool[] calldata validatorRevealed,
        bool[] calldata validatorVotes,
        uint256 payout,
        uint256 duration
    ) external;

    /// @notice Compute reputation gain for an agent based on payout and duration.
    /// @param payout Amount paid to the agent (18-decimal).
    /// @param duration Job duration in seconds.
    /// @return Reputation points awarded to the agent.
    function calculateReputationPoints(uint256 payout, uint256 duration)
        external
        view
        returns (uint256);

    /// @notice Retrieve combined operator score using stake and reputation
    /// @param operator Address to query
    /// @return Weighted score used for ranking
    function getOperatorScore(address operator) external view returns (uint256);

    /// @notice Set the StakeManager used for stake lookups
    /// @param manager Address of the StakeManager contract
    function setStakeManager(address manager) external;

    /// @notice Update weighting factors for stake and reputation contributions
    /// @param stakeWeight Weight applied to stake (scaled by TOKEN_SCALE)
    /// @param reputationWeight Weight applied to reputation (scaled by TOKEN_SCALE)
    function setScoringWeights(uint256 stakeWeight, uint256 reputationWeight) external;
}

contracts/v2/interfaces/IStakeManager.sol

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

import {IFeePool} from "./IFeePool.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @title IStakeManager
/// @notice Interface for staking balances, job escrows and slashing logic
interface IStakeManager {
    /// @notice Module version for compatibility checks.
    function version() external view returns (uint256);
    /// @notice participant roles
    enum Role {
        Agent,
        Validator,
        Platform
    }

    event StakeDeposited(address indexed user, Role indexed role, uint256 amount);
    event StakeWithdrawn(address indexed user, Role indexed role, uint256 amount);
    event StakeEscrowLocked(bytes32 indexed jobId, address indexed from, uint256 amount);
    event StakeReleased(bytes32 indexed jobId, address indexed to, uint256 amount);
    event RewardPaid(bytes32 indexed jobId, address indexed to, uint256 amount);
    event TokensBurned(bytes32 indexed jobId, uint256 amount);
    /// @notice Emitted when an employer finalizes a job's funds.
    /// @dev Signals that any subsequent burn events stem from employer action.
    event JobFundsFinalized(bytes32 indexed jobId, address indexed employer);
    /// @notice Emitted when the operator reward pool balance changes.
    event RewardPoolUpdated(uint256 balance);
    event StakeTimeLocked(address indexed user, uint256 amount, uint64 unlockTime);
    event StakeUnlocked(address indexed user, uint256 amount);
    event StakeSlashed(
        address indexed user,
        Role role,
        address indexed employer,
        address indexed treasury,
        uint256 employerShare,
        uint256 treasuryShare,
        uint256 operatorShare,
        uint256 validatorShare,
        uint256 burnShare
    );
    event EscrowPenaltyApplied(
        bytes32 indexed jobId,
        address indexed recipient,
        uint256 amount,
        uint256 employerShare,
        uint256 treasuryShare,
        uint256 operatorShare,
        uint256 validatorShare,
        uint256 burnShare
    );
    /// @notice Emitted when stake is slashed from a participant.
    /// @param agent Address whose stake was reduced.
    /// @param amount Total amount slashed from the agent.
    /// @param validator Address of the validator or recipient that triggered the slash.
    event Slash(address indexed agent, uint256 amount, address indexed validator);

    /// @notice Emitted when a validator receives a reward from slashing.
    /// @param validator Address of the validator being rewarded.
    /// @param amount Amount of tokens transferred to the validator.
    /// @param jobId Optional job identifier associated with the reward.
    event RewardValidator(address indexed validator, uint256 amount, bytes32 indexed jobId);
    event DisputeFeeLocked(address indexed payer, uint256 amount);
    event DisputeFeePaid(address indexed to, uint256 amount);
    event DisputeModuleUpdated(address module);
    event ValidationModuleUpdated(address module);
    event ValidatorLockManagerUpdated(address indexed manager, bool allowed);
    event ValidatorStakeLocked(uint256 indexed jobId, address indexed validator, uint256 amount, uint64 unlockTime);
    event ValidatorStakeUnlocked(uint256 indexed jobId, address indexed validator, uint256 amount);
    event ModulesUpdated(address jobRegistry, address disputeModule);
    event MinStakeUpdated(uint256 minStake);
    event RoleMinimumUpdated(Role indexed role, uint256 minStake);
    event SlashingPercentagesUpdated(uint256 employerSlashPct, uint256 treasurySlashPct);
    event OperatorSlashPctUpdated(uint256 operatorSlashPct);
    event ValidatorSlashRewardPctUpdated(uint256 validatorSlashRewardPct);
    event SlashDistributionUpdated(
        uint256 employerSlashPct,
        uint256 treasurySlashPct,
        uint256 operatorSlashPct,
        uint256 validatorSlashRewardPct
    );
    event SlashPercentsUpdated(
        uint256 employerSlashPct,
        uint256 treasurySlashPct,
        uint256 validatorSlashRewardPct,
        uint256 operatorSlashPct,
        uint256 burnSlashPct
    );
    event OperatorSlashShareAllocated(address indexed user, Role indexed role, uint256 amount);
    event TreasuryUpdated(address indexed treasury);
    event TreasuryAllowlistUpdated(address indexed treasury, bool allowed);
    event MaxStakePerAddressUpdated(uint256 maxStake);
    event MaxAGITypesUpdated(uint256 oldMax, uint256 newMax);
    event AGITypeUpdated(address indexed nft, uint256 payoutPct);
    event AGITypeRemoved(address indexed nft);
    event MaxTotalPayoutPctUpdated(uint256 oldMax, uint256 newMax);
    event ParametersUpdated(
        uint256 minStake,
        uint256 employerSlashPct,
        uint256 treasurySlashPct,
        uint256 operatorSlashPct,
        uint256 validatorSlashRewardPct,
        uint256 burnSlashPct,
        uint256 feePct,
        uint256 burnPct,
        uint256 validatorRewardPct
    );
    event AutoStakeTuningEnabled(bool enabled);
    event AutoStakeConfigUpdated(
        uint256 threshold,
        uint256 upPct,
        uint256 downPct,
        uint256 window,
        uint256 floor,
        uint256 ceil,
        int256 tempThreshold,
        int256 hThreshold,
        uint256 disputeWeight,
        uint256 tempWeight,
        uint256 hamWeight
    );
    event ThermostatUpdated(address indexed thermostat);
    event HamiltonianFeedUpdated(address indexed feed);
    event FeePctUpdated(uint256 pct);
    event BurnPctUpdated(uint256 pct);
    event ValidatorRewardPctUpdated(uint256 pct);
    event FeePoolUpdated(address indexed feePool);

    /// @notice deposit stake for caller for a specific role
    /// @param role participant role receiving credit
    /// @param amount token amount with 18 decimals to deposit
    function depositStake(Role role, uint256 amount) external;

    /// @notice acknowledge the tax policy and deposit stake in one call
    function acknowledgeAndDeposit(Role role, uint256 amount) external;

    /// @notice deposit stake on behalf of a user for a specific role
    function depositStakeFor(address user, Role role, uint256 amount) external;

    /// @notice withdraw available stake for a specific role
    /// @param role participant role of the stake being withdrawn
    /// @param amount token amount with 18 decimals to withdraw
    function withdrawStake(Role role, uint256 amount) external;

    /// @notice acknowledge the tax policy and withdraw stake in one call
    function acknowledgeAndWithdraw(Role role, uint256 amount) external;

    /// @notice view the minimum stake override for a role (0 => fallback to global min)
    function roleMinimumStake(Role role) external view returns (uint256);

    /// @notice update minimum stake overrides for all roles
    function setRoleMinimums(uint256 agent, uint256 validator, uint256 platform) external;

    /// @notice update the minimum stake override for a single role
    function setRoleMinimum(Role role, uint256 amount) external;

    /// @notice lock a portion of a user's stake for a period of time
    /// @param user address whose stake is being locked
    /// @param amount token amount with 18 decimals
    /// @param lockTime seconds until the stake unlocks
    function lockStake(address user, uint256 amount, uint64 lockTime) external;

    /// @notice update the allowlist of addresses permitted to manage validator locks
    function setValidatorLockManager(address manager, bool allowed) external;

    /// @notice lock validator stake for a validation round
    /// @param jobId identifier of the job requesting validation
    /// @param user validator address whose stake is being locked
    /// @param amount token amount with 18 decimals
    /// @param lockTime seconds until the stake unlocks
    function lockValidatorStake(uint256 jobId, address user, uint256 amount, uint64 lockTime) external;

    /// @notice lock job reward from an employer
    function lockReward(bytes32 jobId, address from, uint256 amount) external;

    /// @notice generic escrow lock when job ID is managed externally
    function lock(address from, uint256 amount) external;

    /// @notice release locked job reward to recipient
    /// @param jobId unique job identifier
    /// @param employer employer responsible for burns
    /// @param to recipient of the reward
    /// @param amount base token amount with 18 decimals before bonuses
    function releaseReward(
        bytes32 jobId,
        address employer,
        address to,
        uint256 amount,
        bool applyBoost
    ) external;

    /// @notice refund escrowed funds without fees or burns
    function refundEscrow(bytes32 jobId, address to, uint256 amount) external;

    /// @notice redistribute escrowed funds according to the configured slash distribution
    function redistributeEscrow(bytes32 jobId, address recipient, uint256 amount) external;

    /// @notice redistribute escrowed funds with validator weighting
    function redistributeEscrow(
        bytes32 jobId,
        address recipient,
        uint256 amount,
        address[] calldata validators
    ) external;

    /// @notice release previously locked stake for a user
    function releaseStake(address user, uint256 amount) external;

    /// @notice release stake locked for validation
    function unlockValidatorStake(uint256 jobId, address user, uint256 amount) external;

    /// @notice release funds locked via {lock}
    /// @param employer employer responsible for burns
    /// @param to recipient of the tokens
    /// @param amount base token amount with 18 decimals before bonuses
    function release(address employer, address to, uint256 amount, bool applyBoost) external;

    /// @notice finalize job funds by paying agent and forwarding fees
    function finalizeJobFunds(
        bytes32 jobId,
        address employer,
        address agent,
        uint256 reward,
        uint256 validatorReward,
        uint256 fee,
        IFeePool feePool,
        bool byGovernance
    ) external;

    /// @notice finalize job funds with a precomputed payout percentage
    function finalizeJobFundsWithPct(
        bytes32 jobId,
        address employer,
        address agent,
        uint256 agentPct,
        uint256 reward,
        uint256 validatorReward,
        uint256 fee,
        IFeePool feePool,
        bool byGovernance
    ) external;

    /// @notice fund the operator reward pool
    function fundOperatorRewardPool(uint256 amount) external;

    /// @notice withdraw tokens from the operator reward pool
    function withdrawOperatorRewardPool(address to, uint256 amount) external;

    /// @notice distribute validator rewards among selected validators
    ///         weighted by their NFT multipliers
    function distributeValidatorRewards(bytes32 jobId, uint256 amount) external;

    /// @notice Current burn percentage applied to rewards
    function burnPct() external view returns (uint256);

    /// @notice Validator share of slashed stakes
    function validatorSlashRewardPct() external view returns (uint256);

    /// @notice Cap on total payout percentage across AGI types
    function maxTotalPayoutPct() external view returns (uint256);

    /// @notice ERC20 token used for staking operations
    function token() external view returns (IERC20);

    /// @notice current balance of the operator reward pool
    function operatorRewardPool() external view returns (uint256);

    /// @notice set the dispute module authorized to manage dispute fees
    function setDisputeModule(address module) external;

    /// @notice set the validation module used for validator lookups
    function setValidationModule(address module) external;

    /// @notice update job registry and dispute module in one call
    /// @dev Staking is disabled until `jobRegistry` is configured.
    function setModules(address _jobRegistry, address _disputeModule) external;

    /// @notice lock a dispute fee from the payer
    function lockDisputeFee(address payer, uint256 amount) external;

    /// @notice pay out a locked dispute fee to the recipient
    function payDisputeFee(address to, uint256 amount) external;

    /// @notice slash stake from a user for a specific role
    /// @param user address whose stake will be reduced
    /// @param role participant role of the slashed stake
    /// @param amount token amount with 18 decimals to slash
    /// @param employer recipient of the employer share
    function slash(address user, Role role, uint256 amount, address employer) external;
    function slash(
        address user,
        Role role,
        uint256 amount,
        address employer,
        address[] calldata validators
    ) external;

    /// @notice slash validator stake during dispute resolution
    /// @param user address whose stake will be reduced
    /// @param amount token amount with 18 decimals to slash
    /// @param recipient address receiving the slashed share
    function slash(address user, uint256 amount, address recipient) external;
    function slash(
        address user,
        uint256 amount,
        address recipient,
        address[] calldata validators
    ) external;

    function governanceSlash(
        address user,
        Role role,
        uint256 pctBps,
        address beneficiary
    ) external returns (uint256 amount);

    /// @notice owner configuration helpers
    function setMinStake(uint256 _minStake) external;
    function setSlashPercents(
        uint16 employerSlashPct,
        uint16 treasurySlashPct,
        uint16 validatorSlashPct,
        uint16 operatorSlashPct,
        uint16 burnSlashPct
    ) external;

    function setSlashingPercentages(uint256 _employerSlashPct, uint256 _treasurySlashPct) external;
    function setSlashingParameters(uint256 _employerSlashPct, uint256 _treasurySlashPct) external;
    function setValidatorSlashRewardPct(uint256 _validatorSlashPct) external;
    function setSlashingDistribution(
        uint256 _employerSlashPct,
        uint256 _treasurySlashPct,
        uint256 _validatorSlashPct
    ) external;

    function setOperatorSlashPct(uint256 _operatorSlashPct) external;

    function setSlashDistribution(
        uint256 _employerSlashPct,
        uint256 _treasurySlashPct,
        uint256 _operatorSlashPct,
        uint256 _validatorSlashPct
    ) external;
    function setTreasury(address _treasury) external;
    function setTreasuryAllowlist(address _treasury, bool allowed) external;
    function setMaxStakePerAddress(uint256 maxStake) external;
    function setMaxAGITypes(uint256 newMax) external;
    function setMaxTotalPayoutPct(uint256 newMax) external;
    function addAGIType(address nft, uint256 payoutPct) external;
    function removeAGIType(address nft) external;
    function setFeePct(uint256 pct) external;
    function setFeePool(IFeePool pool) external;
    function setBurnPct(uint256 pct) external;
    function setValidatorRewardPct(uint256 pct) external;
    function autoTuneStakes(bool enabled) external;
    function configureAutoStake(
        uint256 threshold,
        uint256 upPct,
        uint256 downPct,
        uint256 window,
        uint256 floor,
        uint256 ceil,
        int256 tempThreshold,
        int256 hThreshold,
        uint256 disputeWeight,
        uint256 tempWeight,
        uint256 hamWeight
    ) external;
    function setThermostat(address thermostat) external;
    function setHamiltonianFeed(address feed) external;
    function recordDispute() external;
    function checkpointStake() external;

    /// @notice return total stake deposited by a user for a role
    function stakeOf(address user, Role role) external view returns (uint256);

    /// @notice return aggregate stake for a role
    function totalStake(Role role) external view returns (uint256);

    /// @notice return aggregate stake weighted by NFT multipliers for a role
    function totalBoostedStake(Role role) external view returns (uint256);

    /// @notice Recalculate boosted stake for a user when NFT holdings change
    /// @param user address whose boosted stake is being updated
    /// @param role participant role of the stake
    function syncBoostedStake(address user, Role role) external;

    /// @notice address of the JobRegistry authorized to deposit fees
    function jobRegistry() external view returns (address);

    /// @notice Total payout percentage for a participant based on AGI type NFTs
    /// @dev Returns 100 when the user holds no approved NFTs.
    function getTotalPayoutPct(address user) external view returns (uint256);
}

contracts/v2/interfaces/ITaxPolicy.sol

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

/// @title ITaxPolicy
/// @notice Interface for retrieving tax policy details.
interface ITaxPolicy {
    /// @notice Record that the caller has acknowledged the current policy.
    /// @return disclaimer Confirmation text stating the caller bears all tax liability.
    function acknowledge() external returns (string memory disclaimer);

    /// @notice Record that `user` has acknowledged the current policy.
    /// @param user Address of the participant.
    /// @return disclaimer Confirmation text stating the participant bears all tax liability.
    function acknowledgeFor(address user) external returns (string memory disclaimer);

    /// @notice Allow or revoke an acknowledger address.
    /// @dev Only callable by the policy owner.
    /// @param acknowledger Address granted permission to acknowledge for users.
    /// @param allowed True to allow the address, false to revoke.
    function setAcknowledger(address acknowledger, bool allowed) external;

    /// @notice Batch update acknowledger permissions with per-address flags.
    /// @param acknowledgers Array of addresses to update.
    /// @param allowed Boolean flags matching `acknowledgers` by index.
    function setAcknowledgers(address[] calldata acknowledgers, bool[] calldata allowed) external;

    /// @notice Clears the acknowledgement record for a user.
    /// @param user Address whose acknowledgement should be revoked.
    function revokeAcknowledgement(address user) external;

    /// @notice Clears acknowledgement records for multiple users.
    /// @param users Addresses whose acknowledgements should be revoked.
    function revokeAcknowledgements(address[] calldata users) external;

    /// @notice Check if a user has acknowledged the policy.
    /// @param user Address of the participant.
    function hasAcknowledged(address user) external view returns (bool);

    /// @notice Check if an address is authorised to call {acknowledgeFor}.
    /// @param acknowledger Address of the delegate.
    function acknowledgerAllowed(address acknowledger) external view returns (bool);

    /// @notice Returns the policy version a user has acknowledged.
    /// @param user Address of the participant.
    /// @return version Policy version acknowledged by `user`.
    function acknowledgedVersion(address user) external view returns (uint256 version);

    /// @notice Returns the acknowledgement text without recording acceptance.
    /// @return disclaimer Confirms all taxes fall on employers, agents, and validators.
    function acknowledgement() external view returns (string memory disclaimer);

    /// @notice Returns the URI pointing to the canonical policy document.
    /// @return uri Off-chain document location (e.g., IPFS hash).
    function policyURI() external view returns (string memory uri);

    /// @notice Convenience helper returning both acknowledgement and policy URI.
    /// @return ack Plain-text disclaimer confirming participant tax duties.
    /// @return uri Off-chain document location.
    function policyDetails()
        external
        view
        returns (string memory ack, string memory uri);

    /// @notice Current version number of the policy text.
    function policyVersion() external view returns (uint256);

    /// @notice Increments the policy version without changing text or URI.
    function bumpPolicyVersion() external;

    /// @notice Indicates that the contract and its owner hold no tax liability.
    /// @return Always true; the infrastructure is perpetually tax‑exempt.
    function isTaxExempt() external pure returns (bool);
}

contracts/v2/interfaces/IValidationModule.sol

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

/// @title IValidationModule
/// @notice Interface for validator selection and commit-reveal voting
interface IValidationModule {
    /// @notice Module version for compatibility checks.
    function version() external view returns (uint256);

    enum SelectionStrategy {
        Rotating,
        Reservoir
    }

    enum FailoverAction {
        None,
        ExtendReveal,
        EscalateDispute
    }
    event ValidatorsSelected(uint256 indexed jobId, address[] validators);
    event ValidationCommitted(
        uint256 indexed jobId,
        address indexed validator,
        bytes32 commitHash,
        string subdomain
    );
    event ValidationRevealed(
        uint256 indexed jobId,
        address indexed validator,
        bool approve,
        bytes32 burnTxHash,
        string subdomain
    );
    event ValidationTallied(
        uint256 indexed jobId,
        bool success,
        uint256 approvals,
        uint256 rejections
    );
    event ValidationResult(uint256 indexed jobId, bool success);
    event ValidationQuorumFailed(
        uint256 indexed jobId,
        uint256 revealed,
        uint256 quorumTarget
    );
    event ValidationFailover(
        uint256 indexed jobId,
        FailoverAction action,
        uint256 newRevealDeadline,
        string reason
    );
    event ValidatorSubdomainUpdated(address indexed validator, string subdomain);
    event SelectionStrategyUpdated(SelectionStrategy strategy);
    event ParametersUpdated(
        uint256 committeeSize,
        uint256 commitWindow,
        uint256 revealWindow,
        uint256 approvalThreshold,
        uint256 slashingPct
    );

    /// @notice Select validators for a given job.
    /// @param jobId Identifier of the job.
    /// @param entropy Optional caller-provided entropy mixed with on-chain data.
    /// @return Array of selected validator addresses.
    function selectValidators(uint256 jobId, uint256 entropy)
        external
        returns (address[] memory);

    /// @notice Start validation for a job and select validators
    /// @param jobId Identifier of the job
    /// @param entropy Caller-provided entropy mixed with on-chain sources
    /// @return validators Array of selected validator addresses
    function start(
        uint256 jobId,
        uint256 entropy
    ) external returns (address[] memory validators);

    /// @notice Commit a validation hash for a job
    /// @param jobId Identifier of the job being voted on
    /// @param commitHash Hash of the vote and salt
    /// @param subdomain ENS subdomain label used for ownership verification
    /// @param proof Merkle proof validating the subdomain
    function commitValidation(
        uint256 jobId,
        bytes32 commitHash,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external;


    /// @notice Reveal a previously committed validation vote
    /// @param jobId Identifier of the job
    /// @param approve True to approve, false to reject
    /// @param salt Salt used in the original commitment
    /// @param subdomain ENS subdomain label used for ownership verification
    /// @param proof Merkle proof validating the subdomain
    function revealValidation(
        uint256 jobId,
        bool approve,
        bytes32 burnTxHash,
        bytes32 salt,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external;


    /// @notice Finalize validation round and slash incorrect validators
    /// @param jobId Identifier of the job
    /// @return success True if validators approved the job
    function finalize(uint256 jobId) external returns (bool success);

    /// @notice Alias for finalize using legacy naming.
    function finalizeValidation(uint256 jobId) external returns (bool success);

    /// @notice Force finalize after the reveal deadline plus grace period
    /// @param jobId Identifier of the job
    /// @return success True if validators approved the job
    function forceFinalize(uint256 jobId) external returns (bool success);


    /// @notice Execute a circuit-breaker style failover for an in-flight validation round.
    /// @param jobId Identifier of the job in question.
    /// @param action Failover action (extend the reveal window or escalate to dispute).
    /// @param extension Additional seconds added to the reveal window when extending.
    /// @param reason Human readable reason emitted for transparency.
    function triggerFailover(
        uint256 jobId,
        FailoverAction action,
        uint64 extension,
        string calldata reason
    ) external;


    /// @notice Batch update core validation parameters
    /// @param committeeSize Number of validators selected per job
    /// @param commitWindow Duration of commit phase in seconds
    /// @param revealWindow Duration of reveal phase in seconds
    /// @param approvalThreshold Percentage of stake required for approval
    /// @param slashingPct Percentage of stake slashed for incorrect votes
    function setParameters(
        uint256 committeeSize,
        uint256 commitWindow,
        uint256 revealWindow,
        uint256 approvalThreshold,
        uint256 slashingPct
    ) external;

    /// @notice Set the number of validators selected per job.
    function setValidatorsPerJob(uint256 count) external;

    /// @notice Owner configuration for timing windows
    function setCommitRevealWindows(uint256 commitWindow, uint256 revealWindow) external;

    /// @notice Convenience wrapper for timing configuration.
    function setTiming(uint256 commitWindow, uint256 revealWindow) external;

    /// @notice Owner configuration for validator counts
    function setValidatorBounds(uint256 minValidators, uint256 maxValidators) external;

    /// @notice Set the required number of validator approvals.
    function setRequiredValidatorApprovals(uint256 count) external;

    /// @notice Reset the validation nonce for a job after it is finalized or disputed
    /// @param jobId Identifier of the job
    function resetJobNonce(uint256 jobId) external;

    /// @notice Update approval threshold percentage
    function setApprovalThreshold(uint256 pct) external;

    /// @notice Toggle automatic tracking of the supermajority approval target.
    function setAutoApprovalTarget(bool enabled) external;

    /// @notice Update percentage of stake slashed for incorrect validator votes
    function setValidatorSlashingPct(uint256 pct) external;

    /// @notice Configure the penalty applied when validators fail to reveal.
    function setNonRevealPenalty(uint256 penaltyBps, uint256 banBlocks) external;

    /// @notice Update quorum requirements for validator reveals.
    function setRevealQuorum(uint256 pct, uint256 minValidators) external;

    /// @notice Update the cool-off delay before early finalization is permitted.
    function setEarlyFinalizeDelay(uint256 delay) external;

    /// @notice Update the force finalize grace period after the reveal window.
    function setForceFinalizeGrace(uint256 grace) external;

    /// @notice Map validators to ENS subdomains for selection
    function setValidatorSubdomains(
        address[] calldata accounts,
        string[] calldata subdomains
    ) external;

    /// @notice Map the caller to an ENS subdomain for selection.
    function setMySubdomain(string calldata subdomain) external;

    /// @notice Configure the validator sampling strategy.
    function setSelectionStrategy(SelectionStrategy strategy) external;

    /// @notice Invalidate all cached validator authorizations.
    function bumpValidatorAuthCacheVersion() external;


    /// @notice Return validators selected for a job
    /// @param jobId Identifier of the job
    /// @return validators Array of validator addresses
    function validators(uint256 jobId) external view returns (address[] memory validators);

    /// @notice Retrieve a validator's vote outcome for a job
    /// @param jobId Identifier of the job
    /// @param validator Address of the validator
    /// @return approved True if the validator approved the job
    function votes(
        uint256 jobId,
        address validator
    ) external view returns (bool approved);

    function failoverStates(uint256 jobId)
        external
        view
        returns (
            FailoverAction action,
            uint64 extensions,
            uint64 lastExtendedTo,
            uint64 lastTriggeredAt,
            bool escalated
        );
}

contracts/v2/libraries/TaxAcknowledgement.sol

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

import {ITaxPolicy} from "../interfaces/ITaxPolicy.sol";

abstract contract TaxAcknowledgement {
    error TaxPolicyNotAcknowledged(address account);

    modifier requiresTaxAcknowledgement(
        ITaxPolicy policy,
        address account,
        address owner,
        address exempt1,
        address exempt2
    ) {
        if (
            account != owner &&
            account != exempt1 &&
            account != exempt2 &&
            address(policy) != address(0)
        ) {
            if (!policy.hasAcknowledged(account)) {
                revert TaxPolicyNotAcknowledged(account);
            }
        }
        _;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.