@agenticprimitives/contracts 1.0.0-alpha.47 → 1.0.0-alpha.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/AUDIT.md +36 -4
  2. package/deployments-faithchain.json +94 -68
  3. package/deployments-hopechain.json +71 -52
  4. package/dist/abi/AccountBootstrap.json +99 -0
  5. package/dist/abi/AgentAccount.json +95 -56
  6. package/dist/abi/AgentAccountFactory.json +189 -0
  7. package/dist/abi/AgentNameAttributeResolver.json +188 -0
  8. package/dist/abi/AgentNameRegistry.json +170 -0
  9. package/dist/abi/AgentNameUniversalResolver.json +188 -0
  10. package/dist/abi/AgentProfileResolver.json +188 -0
  11. package/dist/abi/AgentRegistryBase.json +193 -0
  12. package/dist/abi/AgentRelationship.json +193 -0
  13. package/dist/abi/AgenticGovernance.json +123 -0
  14. package/dist/abi/AgreementRegistry.json +193 -0
  15. package/dist/abi/AllowedMethodsEnforcer.json +193 -0
  16. package/dist/abi/AllowedTargetsEnforcer.json +193 -0
  17. package/dist/abi/ApprovedHashRegistry.json +220 -0
  18. package/dist/abi/AttestationRegistry.json +193 -0
  19. package/dist/abi/CallDataHashEnforcer.json +193 -0
  20. package/dist/abi/CustodyPolicy.json +195 -80
  21. package/dist/abi/DelegationManager.json +185 -0
  22. package/dist/abi/DigestBindingEnforcer.json +188 -0
  23. package/dist/abi/Eip7702.json +13 -0
  24. package/dist/abi/EstateProjectionRegistry.json +193 -0
  25. package/dist/abi/Generation5Bridge.json +355 -0
  26. package/dist/abi/GeoFeatureRegistry.json +193 -0
  27. package/dist/abi/ICustodyEpochView.json +28 -0
  28. package/dist/abi/IDelegationManager.json +18 -0
  29. package/dist/abi/IGeneration4Reads.json +143 -0
  30. package/dist/abi/IGeneration5Account.json +33 -0
  31. package/dist/abi/IGeneration5Voucher.json +26 -0
  32. package/dist/abi/IMoveAccountView.json +57 -0
  33. package/dist/abi/IMoveCustodyView.json +169 -0
  34. package/dist/abi/IMoveFactoryView.json +41 -0
  35. package/dist/abi/ITimelockVeto.json +93 -0
  36. package/dist/abi/OntologyTermRegistry.json +211 -0
  37. package/dist/abi/PayloadClassesEnforcer.json +193 -0
  38. package/dist/abi/PaymentEnforcer.json +188 -0
  39. package/dist/abi/PaymentEscrow.json +177 -0
  40. package/dist/abi/PaymentReceiptRegistry.json +206 -0
  41. package/dist/abi/PermissionlessSubregistry.json +188 -0
  42. package/dist/abi/PricedSubregistry.json +215 -0
  43. package/dist/abi/QuorumEnforcer.json +193 -0
  44. package/dist/abi/ReceiptAnchorRegistry.json +193 -0
  45. package/dist/abi/RelationshipTypeRegistry.json +211 -0
  46. package/dist/abi/ShapeRegistry.json +211 -0
  47. package/dist/abi/SignatureVerifier.json +196 -0
  48. package/dist/abi/SkillDefinitionRegistry.json +193 -0
  49. package/dist/abi/SmartAgentPaymaster.json +236 -1
  50. package/dist/abi/StableProxyGoverned.json +190 -0
  51. package/dist/abi/StableProxyGovernedOneShot.json +172 -0
  52. package/dist/abi/TimestampEnforcer.json +193 -0
  53. package/dist/abi/TreasurySpendPolicy.json +193 -0
  54. package/dist/abi/UpgradeVoucher.json +156 -4
  55. package/dist/abi/ValueEnforcer.json +193 -0
  56. package/dist/abi/index.d.ts +14 -0
  57. package/dist/abi/index.js +14 -0
  58. package/dist/deployments/faithchain.d.ts +34 -14
  59. package/dist/deployments/faithchain.js +93 -69
  60. package/dist/deployments/hopechain.d.ts +20 -7
  61. package/dist/deployments/hopechain.js +72 -55
  62. package/package.json +1 -1
  63. package/src/AccountBootstrap.sol +38 -0
  64. package/src/AgentAccount.sol +149 -41
  65. package/src/AgentAccountFactory.sol +52 -13
  66. package/src/ApprovedHashRegistry.sol +98 -9
  67. package/src/SmartAgentPaymaster.sol +96 -12
  68. package/src/UniversalSignatureValidator.sol +7 -0
  69. package/src/UpgradeVoucher.sol +16 -3
  70. package/src/agency/DelegationManager.sol +106 -32
  71. package/src/agency/IDelegationManager.sol +28 -0
  72. package/src/agreement/AgreementRegistry.sol +16 -15
  73. package/src/attestation/AttestationRegistry.sol +39 -16
  74. package/src/custody/CustodyPolicy.sol +36 -35
  75. package/src/custody/TreasurySpendPolicy.sol +10 -1
  76. package/src/enforcers/AllowedMethodsEnforcer.sol +7 -1
  77. package/src/enforcers/AllowedTargetsEnforcer.sol +7 -1
  78. package/src/enforcers/CallDataHashEnforcer.sol +7 -1
  79. package/src/enforcers/DigestBindingEnforcer.sol +5 -2
  80. package/src/enforcers/PayloadClassesEnforcer.sol +7 -1
  81. package/src/enforcers/PaymentEnforcer.sol +5 -2
  82. package/src/enforcers/QuorumEnforcer.sol +7 -1
  83. package/src/enforcers/TimestampEnforcer.sol +7 -1
  84. package/src/enforcers/ValueEnforcer.sol +7 -1
  85. package/src/geo/GeoFeatureRegistry.sol +15 -1
  86. package/src/governance/AgenticGovernance.sol +145 -0
  87. package/src/governance/GovernanceManaged.sol +2 -0
  88. package/src/governance/StableProxyGoverned.sol +79 -0
  89. package/src/governance/StableProxyGovernedOneShot.sol +93 -0
  90. package/src/identity/AgentProfileResolver.sol +11 -2
  91. package/src/libraries/Eip7702.sol +36 -0
  92. package/src/libraries/SignatureSlotRecovery.sol +4 -0
  93. package/src/libraries/SignatureVerifier.sol +52 -0
  94. package/src/libraries/WebAuthnLib.sol +3 -0
  95. package/src/migration/Generation5Bridge.sol +364 -0
  96. package/src/naming/AgentNameAttributeResolver.sol +12 -2
  97. package/src/naming/AgentNameRegistry.sol +84 -10
  98. package/src/naming/AgentNameUniversalResolver.sol +9 -2
  99. package/src/naming/PermissionlessSubregistry.sol +13 -2
  100. package/src/naming/PricedSubregistry.sol +59 -3
  101. package/src/ontology/OntologyTermRegistry.sol +30 -2
  102. package/src/ontology/ShapeRegistry.sol +30 -2
  103. package/src/payments/PaymentEscrow.sol +16 -1
  104. package/src/payments/PaymentReceiptRegistry.sol +28 -3
  105. package/src/provenance/ReceiptAnchorRegistry.sol +13 -1
  106. package/src/registry/AgentRegistryBase.sol +21 -1
  107. package/src/registry/EstateProjectionRegistry.sol +15 -1
  108. package/src/relationships/AgentRelationship.sol +17 -1
  109. package/src/relationships/RelationshipTypeRegistry.sol +30 -2
  110. package/src/skills/SkillDefinitionRegistry.sol +15 -1
@@ -0,0 +1,93 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ import "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
5
+ import {Eip7702} from "../libraries/Eip7702.sol";
6
+
7
+ /**
8
+ * @title StableProxyGovernedOneShot
9
+ * @notice Spec 447 — {StableProxyGoverned} for a contract that cannot inherit OpenZeppelin's `Initializable`.
10
+ * `AgentNameRegistry` publishes an `initializer()` role getter (the root initializer, spec 445), and that
11
+ * name collides with `Initializable`'s `initializer` modifier; renaming the getter would break every
12
+ * client of the published ABI.
13
+ *
14
+ * Same upgrade authority as {StableProxyGoverned}, in the SAME ERC-7201 slot
15
+ * (`agenticprimitives.stable-proxy-governed.v1`), with the same error/event names. Initialization is a
16
+ * one-shot guard, `_initOnce()`, kept in `Initializable`'s own ERC-7201 slot with its `InvalidInitialization`
17
+ * error and `Initialized` event: it leaves that slot exactly as `Initializable.initializer` would, so a later
18
+ * implementation may still run a `reinitializer(2)`.
19
+ *
20
+ * - A DIRECT deployment calls `_initOnce()` in its constructor: the implementation can never be initialized
21
+ * afterwards, and UUPS's `onlyProxy` refuses to upgrade it.
22
+ * - Behind a proxy, the inheritor's own `initialize(governance_, ...)` calls `_initOnce()`, once.
23
+ * - A contract with no governance is never upgraded.
24
+ */
25
+ abstract contract StableProxyGovernedOneShot is UUPSUpgradeable {
26
+ /// @custom:storage-location erc7201:agenticprimitives.stable-proxy-governed.v1
27
+ struct StableProxyGovernedStorage {
28
+ address governance;
29
+ }
30
+
31
+ // keccak256(abi.encode(uint256(keccak256("agenticprimitives.stable-proxy-governed.v1")) - 1)) & ~bytes32(uint256(0xff))
32
+ bytes32 private constant STABLE_PROXY_GOVERNED_SLOT =
33
+ 0x775756232dfd963ad243ed4c7335d3b32889ad6784e2c9e947c9804ba981fb00;
34
+
35
+ // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
36
+ bytes32 private constant INITIALIZABLE_STORAGE =
37
+ 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
38
+
39
+ error NotGovernance();
40
+ error UpgradeWithoutGovernance();
41
+ /// @dev Same selector as OpenZeppelin `Initializable.InvalidInitialization`.
42
+ error InvalidInitialization();
43
+
44
+ event GovernanceSet(address indexed governance);
45
+ /// @dev Same signature as OpenZeppelin `Initializable.Initialized`.
46
+ event Initialized(uint64 version);
47
+
48
+ function _stableProxyGovernedStorage() private pure returns (StableProxyGovernedStorage storage $) {
49
+ bytes32 slot = STABLE_PROXY_GOVERNED_SLOT;
50
+ assembly {
51
+ $.slot := slot
52
+ }
53
+ }
54
+
55
+ /// @notice The upgrade authority (zero = none: the code is frozen).
56
+ function governance() public view returns (address) {
57
+ return _stableProxyGovernedStorage().governance;
58
+ }
59
+
60
+ /// @dev Runs once per storage (a direct deployment's constructor, or a proxy's initializer). Writes
61
+ /// `_initialized = 1, _initializing = false` into `Initializable`'s slot.
62
+ function _initOnce() internal {
63
+ bytes32 slot = INITIALIZABLE_STORAGE;
64
+ uint256 v;
65
+ assembly {
66
+ v := sload(slot)
67
+ }
68
+ if (v != 0) revert InvalidInitialization();
69
+ assembly {
70
+ sstore(slot, 1)
71
+ }
72
+ emit Initialized(1);
73
+ }
74
+
75
+ /// @dev Records `governance_`. An inheritor that needs a non-zero governance overrides this to refuse zero.
76
+ function _initializeGovernance(address governance_) internal virtual {
77
+ _stableProxyGovernedStorage().governance = governance_;
78
+ emit GovernanceSet(governance_);
79
+ }
80
+
81
+ modifier onlyGovernance() {
82
+ Eip7702.refuseDelegatedEOA(msg.sender); // spec 448 §0 (EIP-7702)
83
+ if (msg.sender != governance()) revert NotGovernance();
84
+ _;
85
+ }
86
+
87
+ function _authorizeUpgrade(address) internal view override {
88
+ address gov = governance();
89
+ if (gov == address(0)) revert UpgradeWithoutGovernance();
90
+ Eip7702.refuseDelegatedEOA(msg.sender); // spec 448 §0 (EIP-7702)
91
+ if (msg.sender != gov) revert NotGovernance();
92
+ }
93
+ }
@@ -2,7 +2,9 @@
2
2
  pragma solidity ^0.8.28;
3
3
 
4
4
  import "../ontology/AttributeStorage.sol";
5
+ import {Eip7702} from "../libraries/Eip7702.sol";
5
6
  import "./AgentProfilePredicates.sol";
7
+ import "../governance/StableProxyGoverned.sol";
6
8
 
7
9
  /**
8
10
  * @title AgentProfileResolver
@@ -31,7 +33,7 @@ import "./AgentProfilePredicates.sol";
31
33
  * - Off-chain `AgentCard` JSON is the source of truth; this
32
34
  * resolver stores the content-hash anchor + typed metadata only.
33
35
  */
34
- contract AgentProfileResolver is AttributeStorage {
36
+ contract AgentProfileResolver is AttributeStorage, StableProxyGoverned {
35
37
  address[] private _agents;
36
38
  mapping(address => bool) private _registered;
37
39
 
@@ -47,6 +49,7 @@ contract AgentProfileResolver is AttributeStorage {
47
49
  /// other principal, callers must route through their own
48
50
  /// CustodyPolicy / AgentAccount execute path.
49
51
  modifier onlyAgent(address agent) {
52
+ Eip7702.refuseDelegatedEOA(msg.sender); // spec 448 §0 (EIP-7702)
50
53
  if (msg.sender != agent) revert NotAgentOwner();
51
54
  _;
52
55
  }
@@ -56,7 +59,10 @@ contract AgentProfileResolver is AttributeStorage {
56
59
  _;
57
60
  }
58
61
 
59
- constructor(address ontologyRegistry) AttributeStorage(ontologyRegistry) {}
62
+ /// @notice A DIRECT deployment, with no upgrade governance (frozen code, as before). Spec 447 — behind a stable
63
+ /// proxy, `initialize(governance_)` instead. `ONTOLOGY` stays an immutable: it is the ontology
64
+ /// registry's stable proxy address, which never changes.
65
+ constructor(address ontologyRegistry) AttributeStorage(ontologyRegistry) initializer {}
60
66
 
61
67
  function _subject(address agent) internal pure returns (bytes32) {
62
68
  return bytes32(uint256(uint160(agent)));
@@ -202,4 +208,7 @@ contract AgentProfileResolver is AttributeStorage {
202
208
  function subjectFor(address agent) external pure returns (bytes32) {
203
209
  return bytes32(uint256(uint160(agent)));
204
210
  }
211
+
212
+ /// @dev Spec 447 — storage gap: the contract may sit behind a stable proxy; layout gated by `check:storage-layouts`.
213
+ uint256[33] private __gap;
205
214
  }
@@ -0,0 +1,36 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ /**
5
+ * @title Eip7702
6
+ * @notice The one test for "this address is an EOA that has attached code with an EIP-7702 delegation".
7
+ *
8
+ * @dev Such an address's code is exactly the 23-byte designator `0xef0100 ‖ delegate` (EXTCODESIZE and
9
+ * EXTCODECOPY read the designator, not the delegate's code). No deployed contract can match it: EIP-3541
10
+ * refuses new code that starts with `0xef`.
11
+ *
12
+ * The rule this library serves (spec 448 §0, 2026-12-02 EIP-7702): an address whose code is a delegation
13
+ * designator is an EOA for every authority purpose — it signs by ECDSA, or it has no voice. Its attached
14
+ * code is chosen by whoever obtained one authorization signature from the key, so it is never asked
15
+ * "is this signature yours?" (ERC-1271) and is never trusted as `msg.sender` where a role is decided.
16
+ */
17
+ library Eip7702 {
18
+ /// @notice A delegated-EOA caller was refused where a role is decided by `msg.sender`.
19
+ error DelegatedEOA(address account);
20
+
21
+ /// @notice True iff `account`'s code is an EIP-7702 delegation designator.
22
+ function isDelegatedEOA(address account) internal view returns (bool delegated) {
23
+ assembly ("memory-safe") {
24
+ if eq(extcodesize(account), 23) {
25
+ // Scratch space: copy the first 3 bytes of code to memory 0 and compare the top 24 bits.
26
+ extcodecopy(account, 0, 0, 3)
27
+ delegated := eq(shr(232, mload(0)), 0xef0100)
28
+ }
29
+ }
30
+ }
31
+
32
+ /// @notice Reverts `DelegatedEOA(account)` when `account` is a delegated EOA.
33
+ function refuseDelegatedEOA(address account) internal view {
34
+ if (isDelegatedEOA(account)) revert DelegatedEOA(account);
35
+ }
36
+ }
@@ -4,6 +4,7 @@ pragma solidity ^0.8.28;
4
4
  import "../ApprovedHashRegistry.sol";
5
5
  import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol";
6
6
  import {WebAuthnLib} from "./WebAuthnLib.sol";
7
+ import {Eip7702} from "./Eip7702.sol";
7
8
 
8
9
  /**
9
10
  * @title SignatureSlotRecovery
@@ -111,6 +112,9 @@ library SignatureSlotRecovery {
111
112
  // (left-padded); s holds the offset into `signatures` to a
112
113
  // (length, blob) tail.
113
114
  signer = address(uint160(uint256(r)));
115
+ // Spec 448 §0 (EIP-7702): a delegated EOA's code was chosen by whoever got one authorization
116
+ // signature from its key, so it is never asked to vouch for a vote. Its vote is v = 27/28 or none.
117
+ Eip7702.refuseDelegatedEOA(signer);
114
118
  uint256 sigOffset = uint256(s);
115
119
  // H7-C.3 / CON-SIG-SLOT-001: bound the length-prefix read.
116
120
  // sigOffset must leave room for the 32-byte length word.
@@ -0,0 +1,52 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ import {WebAuthnLib} from "./WebAuthnLib.sol";
5
+ import {SignatureSlotRecovery} from "./SignatureSlotRecovery.sol";
6
+
7
+ /**
8
+ * @title SignatureVerifier
9
+ * @notice Spec 449 — the pure signature arithmetic of `AgentAccount` and `CustodyPolicy`, moved out of their
10
+ * bytecode so both keep room under EIP-170. Nothing here is new: each function is the library code the
11
+ * two contracts ran inline before, behind an external entry point.
12
+ *
13
+ * STATELESS. It has no storage, no owner, no constructor argument and no upgrade path. Every input comes
14
+ * from its caller; it reads nothing of anyone's except through the view calls the moved library code
15
+ * already made (the RIP-7212 precompile; for a quorum slot, the approved-hash registry the caller names
16
+ * and an ERC-1271 signer's `isValidSignature`). Its callers reach it by STATICCALL (their verifying
17
+ * functions are `view`), so nothing it runs can write.
18
+ *
19
+ * WHO TRUSTS IT. Only the contract that created it: `AgentAccount` and `CustodyPolicy` each create their
20
+ * own instance in their constructor and keep its address as an immutable. The address is therefore a
21
+ * function of the implementation's own address (CREATE, nonce 1) and part of the implementation's runtime
22
+ * code — what the upgrade voucher (an account implementation) or governance (the policy proxy's
23
+ * implementation) vouched. No caller, custodian or governance action can point either at another verifier.
24
+ * It grants nothing: it answers true/false or a recovered address, and the caller decides.
25
+ */
26
+ contract SignatureVerifier {
27
+ /// @notice The credential an `AgentAccount` WebAuthn signature payload (`abi.encode(WebAuthnLib.Assertion)`)
28
+ /// names. Reverts on a payload that does not decode (the caller treats a revert as "invalid").
29
+ function credentialOf(bytes calldata payload) external pure returns (bytes32) {
30
+ return abi.decode(payload, (WebAuthnLib.Assertion)).credentialIdDigest;
31
+ }
32
+
33
+ /// @notice `WebAuthnLib.verify` over a decoded `payload`, with User Verification required.
34
+ function verifyWebAuthn(bytes calldata payload, bytes32 hash, uint256 x, uint256 y, bytes32 rpIdHash)
35
+ external
36
+ view
37
+ returns (bool)
38
+ {
39
+ return WebAuthnLib.verify(abi.decode(payload, (WebAuthnLib.Assertion)), hash, x, y, rpIdHash, true);
40
+ }
41
+
42
+ /// @notice `SignatureSlotRecovery.recoverFromSlot`, unchanged; its errors revert through this call verbatim.
43
+ function recoverFromSlot(
44
+ bytes32 payloadHash,
45
+ bytes calldata signatures,
46
+ uint256 index,
47
+ address approvedHashRegistry,
48
+ address passkeyScope
49
+ ) external view returns (address) {
50
+ return SignatureSlotRecovery.recoverFromSlot(payloadHash, signatures, index, approvedHashRegistry, passkeyScope);
51
+ }
52
+ }
@@ -126,6 +126,9 @@ library WebAuthnLib {
126
126
  ) private pure returns (bool) {
127
127
  bytes memory buf = bytes(cdj);
128
128
  bytes memory typeExpected = bytes('"type":"webauthn.get"');
129
+ // Audit 2026-12-02 C1-8 (ACCT-8): an index past the buffer is a malformed assertion — false, never an
130
+ // arithmetic panic (the sums below cannot overflow once each index is bounded by `buf.length`).
131
+ if (typeIndex > buf.length || challengeIndex > buf.length) return false;
129
132
  if (typeIndex + typeExpected.length > buf.length) return false;
130
133
  for (uint256 i; i < typeExpected.length; i++) {
131
134
  if (buf[typeIndex + i] != typeExpected[i]) return false;
@@ -0,0 +1,364 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
5
+
6
+ interface IGeneration5Account {
7
+ function migrateFactory(address newFactory, bytes calldata custodyInit) external;
8
+ function upgradeVoucher() external view returns (address);
9
+ }
10
+
11
+ interface IGeneration5Voucher {
12
+ function isVouched(address implementation, bytes32 dataHash) external view returns (bool);
13
+ }
14
+
15
+ interface IMoveFactoryView {
16
+ function accountImplementation() external view returns (address);
17
+ function custodyPolicy() external view returns (address);
18
+ function approvedHashRegistry() external view returns (address);
19
+ }
20
+
21
+ interface IMoveAccountView {
22
+ function factory() external view returns (address);
23
+ function isModuleInstalled(uint256 moduleTypeId, address module, bytes calldata additionalContext)
24
+ external
25
+ view
26
+ returns (bool);
27
+ function custodianCount() external view returns (uint256);
28
+ }
29
+
30
+ /// @dev The generation-4 account reads a bridged account still answers (its generation-4 policy makes them).
31
+ interface IGeneration4Reads {
32
+ function custodianCount() external view returns (uint256);
33
+ function isCustodian(address account) external view returns (bool);
34
+ function factory() external view returns (address);
35
+ function isModuleInstalled(uint256 moduleTypeId, address module, bytes calldata additionalContext)
36
+ external
37
+ view
38
+ returns (bool);
39
+ function getPasskey(bytes32 credentialIdDigest) external view returns (uint256 x, uint256 y);
40
+ function getPasskeyRpIdHash(bytes32 credentialIdDigest) external view returns (bytes32);
41
+ function passkeyIdentity(uint256 x, uint256 y) external view returns (address);
42
+ }
43
+
44
+ interface IMoveCustodyView {
45
+ function custodyMode(address account) external view returns (uint8);
46
+ function approvalsRequired(address account, uint8 tier) external view returns (uint8);
47
+ function recoveryApprovals(address account) external view returns (uint8);
48
+ function isTrustee(address account, address signer) external view returns (bool);
49
+ function trusteeCount(address account) external view returns (uint256);
50
+ function safetyDelay(address account, uint8 tier) external view returns (uint32);
51
+ function approvedHashRegistry(address account) external view returns (address);
52
+ function t3HighValueCeiling(address account) external view returns (uint256);
53
+ }
54
+
55
+ /**
56
+ * @title Generation5Bridge — the implementation a generation-4 account passes through on its way to generation 5.
57
+ * @notice Spec 447 §3.4 / §4.1 (audit H-1). WHY IT EXISTS. An account's upgrade is executed by the code it runs
58
+ * NOW. Generation-4 code can deliver a migration call only from a self-governed account; a
59
+ * custody-governed account (every treasury) upgrades through the generation-4 `CustodyPolicy`, a plain
60
+ * deployment whose `ApplySystemUpdate` always sends EMPTY migration data. The one thing every generation-4
61
+ * account can do, in every custody mode, is a PLAIN vouched upgrade. This contract is the target of that
62
+ * plain upgrade, and it does one thing: finish the move.
63
+ *
64
+ * THE MOVE, any custody mode, two steps:
65
+ * 1. the account's own custody (a credential's user operation; the quorum's `ApplySystemUpdate`; a
66
+ * matured queued upgrade) upgrades it to this bridge — `(bridge, keccak256(""))` vouched on the
67
+ * GENERATION-4 voucher;
68
+ * 2. anyone calls `completeMove(custodyInit)` on the account. The bridge switches the account to the
69
+ * generation-5 implementation and runs its `migrateFactory(factory5, custodyInit)` — the same
70
+ * function, with the same checks, a vouched generation-5 migration runs. Inside that one call the
71
+ * account's factory moves, a governed account's custody is installed on the stable policy, and
72
+ * every digest approved for it in the generation-5 registry is revoked (audit H-2).
73
+ * Run both in one transaction (step 1 is `applyCustodyChange`, callable by anyone holding the quorum's
74
+ * signatures): if step 2 would fail, nothing happened.
75
+ *
76
+ * ENTERING IS REFUSED, NOT RECOVERED FROM (audit 2026-12-02 review, item 2). Step 1 runs this bridge's
77
+ * `proxiableUUID()` with the account as caller; it answers only for an account of `factory4` whose
78
+ * generation-4 custody the stable policy can install — unchanged or made stricter by a vouch: per-mode
79
+ * trustee bounds (≥ mode, ≤ 32), a recovery quorum the trustees can reach, every tier reachable by the
80
+ * custodians (and, in mode 3, two custodians and the separation-of-duties cap). Generation 4 permits
81
+ * states outside these (a trustee removed below the mode's bound; more than 32 trustees), and the trustee
82
+ * set cannot be changed by the move, so such an account would otherwise wait on the bridge for good. Its
83
+ * upgrade to the bridge reverts instead — whoever submits it, the quorum's runner or a front-runner
84
+ * holding the apply signatures.
85
+ *
86
+ * THE EXIT. A custody-governed account on the bridge whose completion cannot happen (its vouch was never
87
+ * made, or its quorum changed its generation-4 policy after entering) goes back: its quorum applies
88
+ * `ApplySystemUpdate(implementation4)` on the GENERATION-4 policy, under that policy's tier, delay and
89
+ * pause rules. The bridge answers that one module call (`executeFromModule`) by restoring the
90
+ * generation-4 implementation — nothing else of the account was touched while it was here, so its
91
+ * custody is exactly what it was. A self-governed account needs no exit: its completion has no input
92
+ * that can be missing.
93
+ *
94
+ * WHAT AN ACCOUNT ON THE BRIDGE CAN DO: step 2, or the exit. The bridge has no `execute`, no
95
+ * `validateUserOp`, no `isValidSignature`, no `custodyEpoch`, no `receive`: between the two steps the
96
+ * account moves no value, validates no signature, honours no approval and can approve none (the
97
+ * generation-5 registry reads the epoch of an account signer). It answers the generation-4 READS its
98
+ * generation-4 policy makes of it (`custodianCount`, `isCustodian`, `factory`, `isModuleInstalled`, the
99
+ * passkey views) — the generation-4 implementation's own answers over the account's storage. Through the
100
+ * fallback they run under STATICCALL; `readAsGeneration4` also refuses any selector but those seven, so the
101
+ * generation-4 frame that upgraded the account (still running in the move's transaction) cannot use it to
102
+ * write — so the quorum can still schedule and apply on that policy (the
103
+ * exit). That is the point — the account never runs generation-5 code against generation-4 system
104
+ * contracts, and a digest planted in the generation-5 registry is never live, not even for one block.
105
+ *
106
+ * WHO DECIDES WHAT. Where the account goes is fixed in this bytecode (`implementation5`, `factory5`), and
107
+ * governance vouched this bytecode. A self-governed account carries no custody configuration, so its
108
+ * completion needs nothing more. A CUSTODY-GOVERNED account's configuration on the stable policy
109
+ * (`custodyInit`: mode, trustees, thresholds, delays) is taken only from a vouch that names THAT ACCOUNT:
110
+ * `voucher5.isVouched(implementation5, moveVouchHash(account, custodyInit))`. One account's vouched
111
+ * configuration cannot be applied to another, and a caller cannot supply its own. The account's quorum
112
+ * consents by upgrading to the bridge. An account upgraded to the bridge before its vouch exists waits,
113
+ * frozen, until governance vouches — vouch first.
114
+ *
115
+ * A VOUCH CANNOT WEAKEN CUSTODY. After the stable policy is installed the bridge compares it, view by
116
+ * view, with the account's generation-4 policy and reverts the whole move unless every field of the
117
+ * generation-4 `CustodyPolicy.Config` is carried or deliberately dropped, as follows:
118
+ * mode — the same;
119
+ * trustees, trusteeCount — the same set;
120
+ * recoveryApprovals — not lower;
121
+ * approvalsRequiredByTier 1–5 — not lower;
122
+ * approvalsRequiredByTier 6 — not compared: no action is authorized by it (T6 is recovery, whose
123
+ * quorum is `recoveryApprovals`);
124
+ * safetyDelayByTier 1–6 — not shorter;
125
+ * t3HighValueCeiling — the same (neither direction is "stricter" for every reader);
126
+ * approvedHashRegistry — the generation-5 registry, or none;
127
+ * installed — true by construction (the install is what just ran);
128
+ * permanentlyUninstalled — false by construction (a fresh install); an account whose generation-4
129
+ * policy was uninstalled is not custody-governed and carries no
130
+ * configuration;
131
+ * nextChangeId, pending, proposerCustodians — DROPPED: changes scheduled in the generation-4 policy (a
132
+ * recovery in flight included) do not apply after the move.
133
+ * Governance may vouch a STRICTER configuration (generation 5 refuses some delays generation 4 accepted);
134
+ * it cannot vouch a looser one, another trustee or another ceiling.
135
+ *
136
+ * WHAT ELSE IS NOT CARRIED. The account's delegation manager slot is untouched (a governed account
137
+ * rotates to the stable manager through its new policy).
138
+ *
139
+ * @dev LAYOUT COUPLING, STATED. `migrateFactory` runs only while the account implementation's transient
140
+ * `_upgradeMigrationCtx` flag is set. The bridge executes as the account (delegatecall), so it sets that
141
+ * flag itself: the transient variables below mirror `AgentAccount`'s, in order. After the move it also sets
142
+ * `_epochBumpedThisTx`, which the generation-5 code reads for the rest of the transaction. If the layouts
143
+ * ever disagreed `migrateFactory` would revert `MigrationOnly` and the move with it (fail closed);
144
+ * `Generation5Move448` runs the move on generation-4 bytecode and `check:storage-layouts` gates both
145
+ * transient layouts (offsets 0–5 identical).
146
+ */
147
+ contract Generation5Bridge {
148
+ /// @dev Domain tag of a per-account move vouch; keeps it disjoint from every `keccak256(migration data)`.
149
+ bytes32 private constant MOVE_VOUCH_TAG = keccak256("agenticprimitives.generation-5-move.v1");
150
+
151
+ address private immutable __self = address(this);
152
+
153
+ /// @notice The generation-5 account implementation every account leaves the bridge for.
154
+ address public immutable implementation5;
155
+ /// @notice The stable factory every account is moved to.
156
+ address public immutable factory5;
157
+ /// @notice The generation-5 voucher (the one `implementation5` carries) that holds per-account move vouches.
158
+ address public immutable voucher5;
159
+ /// @notice The generation-4 account implementation (the code the accounts leave).
160
+ address public immutable implementation4;
161
+ /// @notice The generation-4 custody policy (the canonical policy of the factory the accounts leave).
162
+ address public immutable policy4;
163
+ /// @notice The stable custody policy (`factory5`'s).
164
+ address public immutable policy5;
165
+ /// @notice The generation-5 approved-hash registry (`factory5`'s).
166
+ address public immutable registry5;
167
+ /// @notice The generation-4 factory: the only factory whose accounts may enter.
168
+ address public immutable factory4;
169
+
170
+ // Mirror of `AgentAccount`'s transient layout (see @dev above). Only `_upgradeMigrationCtx` and
171
+ // `_epochBumpedThisTx` are written.
172
+ bool private transient _upgradeAuthorizedCtx;
173
+ bool private transient _custodyGovCtx;
174
+ bool private transient _delegationExecCtx;
175
+ bool private transient _upgradeMigrationCtx;
176
+ bool private transient _initializedThisTx;
177
+ bool private transient _epochBumpedThisTx;
178
+
179
+ /// @dev The largest trustee set the stable policy installs (`CustodyPolicy.MAX_INSTALL_TRUSTEES`).
180
+ uint256 private constant MAX_INSTALL_TRUSTEES = 32;
181
+ uint256 private constant MODULE_TYPE_EXECUTOR = 2;
182
+
183
+ error ZeroAddress();
184
+ /// @dev Called on the bridge itself, or on a proxy whose implementation is not the bridge.
185
+ error NotAnAccountOnTheBridge();
186
+ /// @dev `readAsGeneration4` was asked for a selector outside the seven generation-4 reads.
187
+ error NotAGeneration4Read();
188
+ /// @dev A custody-governed account's configuration was not vouched for this account.
189
+ error MoveNotVouched(address account, bytes32 vouchHash);
190
+ /// @dev The vouched configuration is not the account's generation-4 custody, or is weaker. `check` names the
191
+ /// comparison that failed: 1 mode, 2 trustee count, 3 a trustee, 4 recovery quorum, 5 a tier's approvals,
192
+ /// 6 a tier's delay, 7 the approved-hash registry, 8 the T3 high-value ceiling.
193
+ error CustodyNotCarried(address account, uint8 check);
194
+ /// @dev The account cannot enter the bridge: its move could never complete. `check` names why: 1 not an
195
+ /// account of `factory4`, 2 trustees outside the stable policy's bounds for its mode, 3 a recovery quorum
196
+ /// its trustees cannot reach, 4 a tier its custodians cannot reach (or mode 3 with fewer than two).
197
+ error NotMovable(address account, uint8 check);
198
+ /// @dev A module call on a bridged account other than its generation-4 policy restoring `implementation4`.
199
+ error NotTheExit();
200
+
201
+ /// @notice A custody-governed account left the bridge for the generation-4 implementation, unchanged.
202
+ event MoveAborted(address indexed account);
203
+
204
+ constructor(address implementation5_, address factory5_, address factory4_) {
205
+ if (implementation5_.code.length == 0 || factory5_.code.length == 0 || factory4_.code.length == 0) {
206
+ revert ZeroAddress();
207
+ }
208
+ address v = IGeneration5Account(implementation5_).upgradeVoucher();
209
+ address p4 = IMoveFactoryView(factory4_).custodyPolicy();
210
+ address p5 = IMoveFactoryView(factory5_).custodyPolicy();
211
+ address i4 = IMoveFactoryView(factory4_).accountImplementation();
212
+ if (v.code.length == 0 || p4.code.length == 0 || p5.code.length == 0 || i4.code.length == 0) revert ZeroAddress();
213
+ implementation4 = i4;
214
+ implementation5 = implementation5_;
215
+ factory5 = factory5_;
216
+ voucher5 = v;
217
+ policy4 = p4;
218
+ policy5 = p5;
219
+ registry5 = IMoveFactoryView(factory5_).approvedHashRegistry();
220
+ factory4 = factory4_;
221
+ }
222
+
223
+ /// @notice ERC-1822: what the generation-4 `upgradeToAndCall` asks of its target, with the upgrading account
224
+ /// as caller. Answered only by the bridge itself, never through an account, and only for an account
225
+ /// whose move can complete (see ENTERING above) — so an account that could not leave is never let in.
226
+ function proxiableUUID() external view returns (bytes32) {
227
+ if (address(this) != __self) revert NotAnAccountOnTheBridge();
228
+ _requireMovable(msg.sender);
229
+ return ERC1967Utils.IMPLEMENTATION_SLOT;
230
+ }
231
+
232
+ /// @dev What the stable policy's `onInstall` would refuse in the account's generation-4 custody that no vouch
233
+ /// can repair (a vouch may raise thresholds, quorums and delays; it cannot change the mode or the trustee
234
+ /// set, or lower anything). Read while the account still runs generation-4 code.
235
+ function _requireMovable(address a) private view {
236
+ if (IMoveAccountView(a).factory() != factory4) revert NotMovable(a, 1);
237
+ if (!IMoveAccountView(a).isModuleInstalled(MODULE_TYPE_EXECUTOR, policy4, "")) return; // self-governed
238
+ IMoveCustodyView p = IMoveCustodyView(policy4);
239
+ uint8 mode = p.custodyMode(a);
240
+ uint256 trustees = p.trusteeCount(a);
241
+ if (mode >= 1 && (trustees < mode || trustees > MAX_INSTALL_TRUSTEES)) revert NotMovable(a, 2);
242
+ if (p.recoveryApprovals(a) > trustees) revert NotMovable(a, 3);
243
+ uint256 n = IMoveAccountView(a).custodianCount();
244
+ if (mode == 3 && n < 2) revert NotMovable(a, 4);
245
+ for (uint8 tier = 1; tier <= 5; tier++) {
246
+ if (p.approvalsRequired(a, tier) > ((mode == 3 && tier >= 4) ? n / 2 : n)) revert NotMovable(a, 4);
247
+ }
248
+ }
249
+
250
+ /// @notice The generation-4 READS a bridged account still answers (see WHAT AN ACCOUNT ON THE BRIDGE CAN DO):
251
+ /// `custodianCount()`, `isCustodian(address)`, `factory()`, `isModuleInstalled(uint256,address,bytes)`,
252
+ /// `getPasskey(bytes32)`, `getPasskeyRpIdHash(bytes32)`, `passkeyIdentity(uint256,uint256)`. Every other
253
+ /// selector, and any call carrying value, reverts.
254
+ // Deliberately non-trivial: a bridged account answers a fixed allowlist of generation-4 reads by staticcall to itself.
255
+ // solhint-disable-next-line no-complex-fallback
256
+ fallback() external {
257
+ if (address(this) == __self || !_isGeneration4Read(msg.sig)) revert NotAnAccountOnTheBridge();
258
+ (bool ok, bytes memory ret) = address(this).staticcall(abi.encodeCall(this.readAsGeneration4, (msg.data)));
259
+ if (!ok) revert NotAnAccountOnTheBridge();
260
+ ret = abi.decode(ret, (bytes));
261
+ assembly {
262
+ return(add(ret, 0x20), mload(ret))
263
+ }
264
+ }
265
+
266
+ /// @dev The seven generation-4 reads a bridged account answers: the ONE allowlist, used by the fallback and by
267
+ /// `readAsGeneration4`. Every one is a `view` of the generation-4 implementation, so a call that carries
268
+ /// only these selectors cannot write, static or not.
269
+ function _isGeneration4Read(bytes4 s) private pure returns (bool) {
270
+ return s == IGeneration4Reads.custodianCount.selector || s == IGeneration4Reads.isCustodian.selector
271
+ || s == IGeneration4Reads.factory.selector || s == IGeneration4Reads.isModuleInstalled.selector
272
+ || s == IGeneration4Reads.getPasskey.selector || s == IGeneration4Reads.getPasskeyRpIdHash.selector
273
+ || s == IGeneration4Reads.passkeyIdentity.selector;
274
+ }
275
+
276
+ /// @notice The body of a forwarded read: `implementation4` delegatecalled over the account's storage. Only the
277
+ /// account itself may call it, and only with one of the seven generation-4 reads (`NotAGeneration4Read`
278
+ /// otherwise). The fallback reaches it by STATICCALL; generation-4 code still running in the move's own
279
+ /// transaction can reach it by an ordinary self-call, which the allowlist alone confines to views.
280
+ function readAsGeneration4(bytes calldata data) external returns (bytes memory) {
281
+ if (msg.sender != address(this) || address(this) == __self) revert NotAnAccountOnTheBridge();
282
+ if (data.length < 4 || !_isGeneration4Read(bytes4(data[0:4]))) revert NotAGeneration4Read();
283
+ // Reviewed: the target is an immutable fixed at construction (never caller-chosen); only the account itself may
284
+ // reach this; and the selector is checked against the seven-read allowlist just above, every one a `view`.
285
+ // Slither sees "input-controlled function id" and cannot see that gate.
286
+ // slither-disable-next-line controlled-delegatecall
287
+ (bool ok, bytes memory ret) = implementation4.delegatecall(data);
288
+ if (!ok) revert NotAnAccountOnTheBridge();
289
+ return ret;
290
+ }
291
+
292
+ /// @notice THE EXIT. The generation-4 policy's `ApplySystemUpdate(implementation4)` — scheduled and applied by
293
+ /// the account's quorum on that policy, under its tier, delay and pause rules — reaches the account as
294
+ /// `executeFromModule(account, 0, upgradeToAndCall(implementation4, ""))`. The bridge accepts that one
295
+ /// call, from that one module, on an account that has it installed, and restores the generation-4
296
+ /// implementation. Nothing else is a module call here.
297
+ function executeFromModule(address target, uint256 value, bytes calldata data) external returns (bytes memory) {
298
+ if (address(this) == __self || ERC1967Utils.getImplementation() != __self) revert NotAnAccountOnTheBridge();
299
+ if (
300
+ msg.sender != policy4 || target != address(this) || value != 0
301
+ || keccak256(data) != keccak256(abi.encodeWithSignature("upgradeToAndCall(address,bytes)", implementation4, ""))
302
+ || !IMoveAccountView(address(this)).isModuleInstalled(MODULE_TYPE_EXECUTOR, policy4, "")
303
+ ) revert NotTheExit();
304
+ ERC1967Utils.upgradeToAndCall(implementation4, "");
305
+ emit MoveAborted(address(this));
306
+ return "";
307
+ }
308
+
309
+ /// @notice What governance vouches (on `voucher5`, for `implementation5`) so that the custody-governed
310
+ /// `account` can complete its move with exactly `custodyInit`.
311
+ function moveVouchHash(address account, bytes calldata custodyInit) public view returns (bytes32) {
312
+ return keccak256(abi.encode(MOVE_VOUCH_TAG, account, factory5, custodyInit));
313
+ }
314
+
315
+ /// @notice Finish the move of the account this is called on. Callable by anyone: every input that matters is
316
+ /// fixed in this bytecode or vouched for this account. `custodyInit` is empty for a self-governed
317
+ /// account and the vouched `CustodyPolicy.onInstall` encoding for a custody-governed one
318
+ /// (`migrateFactory` refuses the wrong one of the two).
319
+ function completeMove(bytes calldata custodyInit) external {
320
+ if (address(this) == __self || ERC1967Utils.getImplementation() != __self) revert NotAnAccountOnTheBridge();
321
+ if (custodyInit.length != 0) {
322
+ bytes32 h = moveVouchHash(address(this), custodyInit);
323
+ if (!IGeneration5Voucher(voucher5).isVouched(implementation5, h)) revert MoveNotVouched(address(this), h);
324
+ }
325
+ _upgradeMigrationCtx = true;
326
+ ERC1967Utils.upgradeToAndCall(
327
+ implementation5, abi.encodeCall(IGeneration5Account.migrateFactory, (factory5, custodyInit))
328
+ );
329
+ _upgradeMigrationCtx = false;
330
+ // The generation-4 code that ran before this call bumps no generation-5 flag, so a custodian retired by a
331
+ // generation-4 change applied earlier in this transaction could otherwise approve under the new epoch
332
+ // after the move. Marked here: for the rest of the transaction a governed account approves nothing except
333
+ // through its custody policy (`AgentAccount.approvalRefused`; audit 2026-12-02 H-2).
334
+ _epochBumpedThisTx = true;
335
+ if (custodyInit.length != 0) _requireCustodyCarried(custodyInit);
336
+ }
337
+
338
+ /// @dev Runs after `migrateFactory` installed the stable policy with `custodyInit` (which it does only for an
339
+ /// account governed by its old factory's policy). Trustees: the stable policy refuses a duplicate, so
340
+ /// "same count, and each one a generation-4 trustee" is "the same set".
341
+ function _requireCustodyCarried(bytes calldata custodyInit) private view {
342
+ address a = address(this);
343
+ IMoveCustodyView old = IMoveCustodyView(policy4);
344
+ IMoveCustodyView nu = IMoveCustodyView(policy5);
345
+ if (nu.custodyMode(a) != old.custodyMode(a)) revert CustodyNotCarried(a, 1);
346
+ if (nu.trusteeCount(a) != old.trusteeCount(a)) revert CustodyNotCarried(a, 2);
347
+ (,, address[] memory trustees,,,,) =
348
+ abi.decode(custodyInit, (uint8, uint8, address[], uint8[7], uint32[7], uint256, address));
349
+ for (uint256 i; i < trustees.length; i++) {
350
+ if (!old.isTrustee(a, trustees[i])) revert CustodyNotCarried(a, 3);
351
+ }
352
+ if (nu.recoveryApprovals(a) < old.recoveryApprovals(a)) revert CustodyNotCarried(a, 4);
353
+ // Tier 6 (recovery) has its quorum in `recoveryApprovals` (above); its delay is in the per-tier table.
354
+ for (uint8 tier = 1; tier <= 6; tier++) {
355
+ if (tier != 6 && nu.approvalsRequired(a, tier) < old.approvalsRequired(a, tier)) {
356
+ revert CustodyNotCarried(a, 5);
357
+ }
358
+ if (nu.safetyDelay(a, tier) < old.safetyDelay(a, tier)) revert CustodyNotCarried(a, 6);
359
+ }
360
+ address reg = nu.approvedHashRegistry(a);
361
+ if (reg != address(0) && reg != registry5) revert CustodyNotCarried(a, 7);
362
+ if (nu.t3HighValueCeiling(a) != old.t3HighValueCeiling(a)) revert CustodyNotCarried(a, 8);
363
+ }
364
+ }