@agenticprimitives/contracts 1.0.0-alpha.5 → 1.0.0-alpha.50

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 (145) hide show
  1. package/AUDIT.md +119 -27
  2. package/README.md +47 -12
  3. package/deployments-base-sepolia.json +52 -1
  4. package/deployments-faithchain.json +103 -0
  5. package/deployments-hopechain.json +78 -0
  6. package/deployments-paymaster-anvil.json +1 -0
  7. package/deployments-registries-base-sepolia.json +1 -0
  8. package/deployments-registries-hopechain.json +1 -0
  9. package/dist/abi/AccountBootstrap.json +99 -0
  10. package/dist/abi/AgentAccount.json +461 -67
  11. package/dist/abi/AgentAccountFactory.json +309 -0
  12. package/dist/abi/AgentNameAttributeResolver.json +212 -0
  13. package/dist/abi/AgentNameRegistry.json +544 -0
  14. package/dist/abi/AgentNameUniversalResolver.json +222 -0
  15. package/dist/abi/AgentProfileResolver.json +236 -0
  16. package/dist/abi/AgentRegistryBase.json +1003 -0
  17. package/dist/abi/AgentRelationship.json +405 -0
  18. package/dist/abi/AgenticGovernance.json +155 -0
  19. package/dist/abi/AgreementRegistry.json +203 -5
  20. package/dist/abi/AllowedMethodsEnforcer.json +193 -0
  21. package/dist/abi/AllowedTargetsEnforcer.json +193 -0
  22. package/dist/abi/ApprovedHashRegistry.json +267 -2
  23. package/dist/abi/AttestationRegistry.json +242 -0
  24. package/dist/abi/AttributeStorage.json +24 -0
  25. package/dist/abi/CallDataHashEnforcer.json +193 -0
  26. package/dist/abi/CustodyPolicy.json +422 -55
  27. package/dist/abi/DelegationManager.json +292 -0
  28. package/dist/abi/DigestBindingEnforcer.json +541 -0
  29. package/dist/abi/Eip7702.json +13 -0
  30. package/dist/abi/EstateProjectionRegistry.json +599 -0
  31. package/dist/abi/Generation5Bridge.json +355 -0
  32. package/dist/abi/GeoFeatureRegistry.json +235 -0
  33. package/dist/abi/IAgentAccountFactoryView.json +26 -0
  34. package/dist/abi/IAgentAccountGovernanceTimelockView.json +15 -0
  35. package/dist/abi/IApprovedHashRegistryWrite.json +35 -0
  36. package/dist/abi/ICustodyEpochView.json +28 -0
  37. package/dist/abi/ICustodyPolicyAccountModuleView.json +31 -0
  38. package/dist/abi/ICustodyPolicyFactoryView.json +13 -0
  39. package/dist/abi/ICustodyPolicyPasskeyView.json +50 -0
  40. package/dist/abi/IDelegationManager.json +18 -0
  41. package/dist/abi/IGeneration4Reads.json +143 -0
  42. package/dist/abi/IGeneration5Account.json +33 -0
  43. package/dist/abi/IGeneration5Voucher.json +26 -0
  44. package/dist/abi/IMoveAccountView.json +57 -0
  45. package/dist/abi/IMoveCustodyView.json +169 -0
  46. package/dist/abi/IMoveFactoryView.json +41 -0
  47. package/dist/abi/IPaymentReceiptRegistry.json +50 -0
  48. package/dist/abi/IRedemptionContext.json +15 -0
  49. package/dist/abi/IRegistryMembershipPolicy.json +70 -0
  50. package/dist/abi/ITimelockVeto.json +93 -0
  51. package/dist/abi/ITreasurySpendPolicyAccountView.json +44 -0
  52. package/dist/abi/IUpgradeVoucherView.json +26 -0
  53. package/dist/abi/MockUSDC.json +621 -0
  54. package/dist/abi/OntologyTermRegistry.json +268 -0
  55. package/dist/abi/PayloadClassesEnforcer.json +310 -0
  56. package/dist/abi/PaymentEnforcer.json +639 -0
  57. package/dist/abi/PaymentEscrow.json +501 -0
  58. package/dist/abi/PaymentReceiptRegistry.json +388 -0
  59. package/dist/abi/PermissionlessSubregistry.json +353 -0
  60. package/dist/abi/PricedSubregistry.json +1141 -0
  61. package/dist/abi/QuorumEnforcer.json +209 -0
  62. package/dist/abi/ReceiptAnchorRegistry.json +346 -0
  63. package/dist/abi/RelationshipTypeRegistry.json +268 -0
  64. package/dist/abi/ShapeRegistry.json +268 -0
  65. package/dist/abi/SignatureVerifier.json +196 -0
  66. package/dist/abi/SkillDefinitionRegistry.json +235 -0
  67. package/dist/abi/SmartAgentPaymaster.json +445 -1
  68. package/dist/abi/StableProxyGoverned.json +190 -0
  69. package/dist/abi/StableProxyGovernedOneShot.json +172 -0
  70. package/dist/abi/TimestampEnforcer.json +193 -0
  71. package/dist/abi/TreasurySpendPolicy.json +667 -0
  72. package/dist/abi/UpgradeVoucher.json +328 -0
  73. package/dist/abi/ValueEnforcer.json +193 -0
  74. package/dist/abi/index.d.ts +35 -0
  75. package/dist/abi/index.js +35 -0
  76. package/dist/deployments/base-sepolia.d.ts +11 -0
  77. package/dist/deployments/base-sepolia.js +51 -28
  78. package/dist/deployments/faithchain.d.ts +77 -0
  79. package/dist/deployments/faithchain.js +107 -0
  80. package/dist/deployments/hopechain.d.ts +68 -0
  81. package/dist/deployments/hopechain.js +82 -0
  82. package/dist/deployments/index.d.ts +7 -2
  83. package/dist/deployments/index.js +15 -0
  84. package/dist/deployments/paymaster-anvil.d.ts +11 -0
  85. package/dist/deployments/paymaster-anvil.js +9 -0
  86. package/dist/deployments/registries-base-sepolia.d.ts +10 -0
  87. package/dist/deployments/registries-base-sepolia.js +8 -0
  88. package/dist/deployments/registries-hopechain.d.ts +10 -0
  89. package/dist/deployments/registries-hopechain.js +8 -0
  90. package/package.json +37 -7
  91. package/src/AccountBootstrap.sol +38 -0
  92. package/src/AgentAccount.sol +1091 -134
  93. package/src/AgentAccountFactory.sol +198 -21
  94. package/src/ApprovedHashRegistry.sol +134 -10
  95. package/src/IAgentAccount.sol +37 -0
  96. package/src/SmartAgentPaymaster.sol +275 -22
  97. package/src/UniversalSignatureValidator.sol +7 -0
  98. package/src/UpgradeVoucher.sol +87 -0
  99. package/src/agency/DelegationManager.sol +299 -76
  100. package/src/agency/ICaveatEnforcer.sol +10 -0
  101. package/src/agency/IDelegationManager.sol +37 -5
  102. package/src/agreement/AgreementRegistry.sol +105 -35
  103. package/src/attestation/AttestationRegistry.sol +220 -40
  104. package/src/custody/CustodyPolicy.sol +588 -70
  105. package/src/custody/TreasurySpendPolicy.sol +338 -0
  106. package/src/enforcers/AllowedMethodsEnforcer.sol +13 -2
  107. package/src/enforcers/AllowedTargetsEnforcer.sol +13 -2
  108. package/src/enforcers/CallDataHashEnforcer.sol +7 -1
  109. package/src/enforcers/DigestBindingEnforcer.sol +182 -0
  110. package/src/enforcers/PayloadClassesEnforcer.sol +36 -0
  111. package/src/enforcers/PaymentEnforcer.sol +291 -0
  112. package/src/enforcers/QuorumEnforcer.sol +24 -3
  113. package/src/enforcers/TimestampEnforcer.sol +7 -1
  114. package/src/enforcers/ValueEnforcer.sol +13 -2
  115. package/src/geo/GeoFeatureRegistry.sol +67 -22
  116. package/src/governance/AgenticGovernance.sol +187 -4
  117. package/src/governance/GovernanceManaged.sol +2 -0
  118. package/src/governance/StableProxyGoverned.sol +79 -0
  119. package/src/governance/StableProxyGovernedOneShot.sol +93 -0
  120. package/src/identity/AgentProfilePredicates.sol +23 -0
  121. package/src/identity/AgentProfileResolver.sol +22 -2
  122. package/src/libraries/Eip7702.sol +36 -0
  123. package/src/libraries/SignatureSlotRecovery.sol +28 -7
  124. package/src/libraries/SignatureVerifier.sol +52 -0
  125. package/src/libraries/WebAuthnLib.sol +16 -0
  126. package/src/migration/Generation5Bridge.sol +364 -0
  127. package/src/mocks/MockUSDC.sol +152 -0
  128. package/src/naming/AgentNameAttributeResolver.sol +29 -4
  129. package/src/naming/AgentNamePredicates.sol +89 -0
  130. package/src/naming/AgentNameRegistry.sol +324 -20
  131. package/src/naming/AgentNameUniversalResolver.sol +35 -2
  132. package/src/naming/PermissionlessSubregistry.sol +82 -25
  133. package/src/naming/PricedSubregistry.sol +293 -0
  134. package/src/ontology/AttributeStorage.sol +93 -80
  135. package/src/ontology/OntologyTermRegistry.sol +58 -2
  136. package/src/ontology/ShapeRegistry.sol +58 -2
  137. package/src/payments/PaymentEscrow.sol +187 -0
  138. package/src/payments/PaymentReceiptRegistry.sol +100 -0
  139. package/src/provenance/ReceiptAnchorRegistry.sol +67 -0
  140. package/src/registry/AgentRegistryBase.sol +372 -0
  141. package/src/registry/EstateProjectionRegistry.sol +177 -0
  142. package/src/registry/IRegistryMembershipPolicy.sol +30 -0
  143. package/src/relationships/AgentRelationship.sol +129 -8
  144. package/src/relationships/RelationshipTypeRegistry.sol +58 -2
  145. package/src/skills/SkillDefinitionRegistry.sol +61 -17
@@ -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
@@ -28,8 +29,10 @@ import {WebAuthnLib} from "./WebAuthnLib.sol";
28
29
  * v == 2 → WebAuthn passkey sig (agenticprimitives
29
30
  * extension; NOT in Safe). r holds the
30
31
  * Passkey-Identity-Address (PIA, derived
31
- * from the P-256 pubkey via
32
- * `address(uint160(uint256(keccak256(abi.encode(x, y)))))`).
32
+ * from the P-256 pubkey + the account it is
33
+ * scoped to via
34
+ * `address(uint160(uint256(keccak256(abi.encode(x, y, passkeyScope)))))`
35
+ * — per-account since spec 302 W2).
33
36
  * s holds the byte offset into `signatures`
34
37
  * to a length-prefixed tail containing
35
38
  * `abi.encode(uint256 x, uint256 y, bytes32 rpIdHash, WebAuthnLib.Assertion assertion)`.
@@ -77,12 +80,21 @@ library SignatureSlotRecovery {
77
80
  * caller does not want to allow v=1 sigs
78
81
  * (e.g. quorum-of-owners admin paths
79
82
  * that don't accept pre-approved hashes).
83
+ * @param passkeyScope Spec 302 W2 — the AgentAccount the v=2
84
+ * slot's PIA is scoped to (the account
85
+ * whose custody the passkey signer claims:
86
+ * CustodyPolicy passes `account`, the
87
+ * QuorumEnforcer passes the `delegator`).
88
+ * The per-account derivation
89
+ * `keccak256(abi.encode(x, y, scope))`
90
+ * kills the cross-account PIA join key.
80
91
  */
81
92
  function recoverFromSlot(
82
93
  bytes32 payloadHash,
83
94
  bytes memory signatures,
84
95
  uint256 index,
85
- address approvedHashRegistry
96
+ address approvedHashRegistry,
97
+ address passkeyScope
86
98
  ) internal view returns (address signer) {
87
99
  bytes32 r;
88
100
  bytes32 s;
@@ -100,6 +112,9 @@ library SignatureSlotRecovery {
100
112
  // (left-padded); s holds the offset into `signatures` to a
101
113
  // (length, blob) tail.
102
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);
103
118
  uint256 sigOffset = uint256(s);
104
119
  // H7-C.3 / CON-SIG-SLOT-001: bound the length-prefix read.
105
120
  // sigOffset must leave room for the 32-byte length word.
@@ -171,11 +186,17 @@ library SignatureSlotRecovery {
171
186
  // WebAuthnLib.Assertion assertion).
172
187
  (uint256 pubX, uint256 pubY, bytes32 rpIdHash, WebAuthnLib.Assertion memory assertion) =
173
188
  abi.decode(dyn, (uint256, uint256, bytes32, WebAuthnLib.Assertion));
174
- address derived = address(uint160(uint256(keccak256(abi.encode(pubX, pubY)))));
189
+ // Spec 302 W2 — per-account PIA (mirrors AgentAccount._passkeyIdentity).
190
+ address derived = address(uint160(uint256(keccak256(abi.encode(pubX, pubY, passkeyScope)))));
175
191
  if (derived != signer) revert PasskeyPubKeyMismatch(signer, derived);
176
- // requireUv=false at the slot level; account policy can layer UV
177
- // requirement via a future policy module.
178
- if (!WebAuthnLib.verify(assertion, payloadHash, pubX, pubY, rpIdHash, false)) {
192
+ // WA-2: require UV at the slot level. This path verifies custody-COUNCIL
193
+ // passkey signatures (CustodyPolicy quorum: trustees/custodians authorizing
194
+ // a recovery or admin change) — the highest-assurance signatures in the
195
+ // system. Consistent with the native ERC-1271 path (AgentAccount, R8.2):
196
+ // a UP-only assertion is rejected; browser ceremonies for custody signers
197
+ // MUST use `userVerification: 'required'`. A lower-assurance flow that needs
198
+ // UP-only must install a separate validator module that relaxes this.
199
+ if (!WebAuthnLib.verify(assertion, payloadHash, pubX, pubY, rpIdHash, true)) {
179
200
  revert PasskeySigInvalid(signer);
180
201
  }
181
202
  } else if (v == 27 || v == 28) {
@@ -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
+ }
@@ -36,6 +36,13 @@ import "./P256Verifier.sol";
36
36
  * PasskeyValidator (for external 1271-style verification).
37
37
  */
38
38
  library WebAuthnLib {
39
+ /// @dev secp256r1 (P-256) curve order n ÷ 2 — the low-s malleability bound (WA-1).
40
+ /// RIP-7212 accepts BOTH (r, s) and (r, n−s) for the same message, so without
41
+ /// this bound a second valid signature always exists. Any path that treats a
42
+ /// signature as unique (quorum slot recovery, dedup) would be malleable.
43
+ uint256 internal constant P256_N_DIV_2 =
44
+ 0x7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a8;
45
+
39
46
  /// @notice A WebAuthn-wrapped P-256 signature bundle.
40
47
  struct Assertion {
41
48
  bytes authenticatorData;
@@ -74,6 +81,12 @@ library WebAuthnLib {
74
81
  if (!_checkClientData(assertion.clientDataJSON, assertion.typeIndex, assertion.challengeIndex, expectedChallengeHash)) {
75
82
  return false;
76
83
  }
84
+ // WA-1: enforce low-s. RIP-7212 verifies both (r, s) and (r, n−s); rejecting
85
+ // the high-s half makes the assertion signature canonical, closing P-256
86
+ // malleability for every caller (native ERC-1271 + custody-quorum slot recovery).
87
+ if (assertion.s > P256_N_DIV_2) {
88
+ return false;
89
+ }
77
90
  bytes32 cdjHash = sha256(bytes(assertion.clientDataJSON));
78
91
  bytes32 signingHash = sha256(abi.encodePacked(assertion.authenticatorData, cdjHash));
79
92
  return P256Verifier.verify(signingHash, assertion.r, assertion.s, pubX, pubY);
@@ -113,6 +126,9 @@ library WebAuthnLib {
113
126
  ) private pure returns (bool) {
114
127
  bytes memory buf = bytes(cdj);
115
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;
116
132
  if (typeIndex + typeExpected.length > buf.length) return false;
117
133
  for (uint256 i; i < typeExpected.length; i++) {
118
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
+ }