@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
@@ -14,6 +14,7 @@ import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
14
14
  import "./IAgentAccount.sol";
15
15
  import "./libraries/SignatureSlotRecovery.sol";
16
16
  import "./libraries/WebAuthnLib.sol";
17
+ import {SignatureVerifier} from "./libraries/SignatureVerifier.sol";
17
18
 
18
19
  /// @dev Minimal subset of AgentAccountFactory's surface used by the
19
20
  /// account to look up factory-scoped capability roles. We avoid a
@@ -28,6 +29,27 @@ interface IAgentAccountFactoryView {
28
29
  /// this address to call `IGovernanceView.isPaused()` from
29
30
  /// `whenNotPaused`-guarded entrypoints.
30
31
  function governance() external view returns (address);
32
+ /// @dev Wave-1/ACCT-C1 — the canonical CustodyPolicy this factory installs
33
+ /// as the custody executor for `mode > 0` accounts. AgentAccount reads it
34
+ /// to decide whether IT is custody-governed (its CustodyPolicy is installed)
35
+ /// vs. merely hosting an unrelated utility executor.
36
+ function custodyPolicy() external view returns (address);
37
+ /// @dev Spec 445 §1.3 (ii) — the canonical DelegationManager this factory wires into every account it
38
+ /// creates. A delegation manager other than this one is honoured only under the custody epoch it
39
+ /// was set (or re-affirmed) in.
40
+ function delegationManager() external view returns (address);
41
+ }
42
+
43
+ /// @dev Spec 445 §1.2 (a) — the governance contract names its own timelock. Read through the same
44
+ /// `_factory → governance()` hop the pause flag is read through, so nothing an account (or whoever
45
+ /// controls it) can write decides which targets stay reachable under a pause.
46
+ interface IAgentAccountGovernanceTimelockView {
47
+ function timelock() external view returns (address);
48
+ }
49
+
50
+ /// @dev Spec 445 §1.3 (i) — the one read an account makes before it upgrades (`src/UpgradeVoucher.sol`).
51
+ interface IUpgradeVoucherView {
52
+ function isVouched(address implementation, bytes32 dataHash) external view returns (bool);
31
53
  }
32
54
 
33
55
  /// @dev R6.5 — minimal interface for the pause read. Mirrors the same
@@ -51,6 +73,16 @@ interface IApprovedHashRegistryView {
51
73
  function isApproved(address signer, bytes32 hash) external view returns (bool);
52
74
  }
53
75
 
76
+ /// @dev Spec 410 §1 (THESIS-1a) — the ONLY write path from this account to its registry. The account
77
+ /// computes the epoch-bound key itself (`approveDigest`); `execute` / `executeBatch` /
78
+ /// `executeFromModule` refuse the registry as a target unconditionally, so no caller — custodian,
79
+ /// module or delegate — can approve a key under an epoch the account is not in.
80
+ interface IApprovedHashRegistryWrite {
81
+ function approveHash(bytes32 hash) external;
82
+ function revokeHash(bytes32 hash) external;
83
+ function revokeAll() external;
84
+ }
85
+
54
86
  /**
55
87
  * @title AgentAccount
56
88
  * @notice ERC-4337 + UUPS-upgradeable smart account — agent identity anchor.
@@ -95,6 +127,19 @@ contract AgentAccount is
95
127
  /// sentinel fails CLOSED (see `isValidSignature`).
96
128
  address private immutable _approvedHashRegistry;
97
129
 
130
+ /// @dev Spec 445 §1.3 (i) (audit H-2 / ACCT-1) — the `UpgradeVoucher` THIS IMPLEMENTATION consults before
131
+ /// every upgrade. IMMUTABLE: it travels with the implementation, not with the factory, because an
132
+ /// account's `_factory` is set once and an account upgraded in place still names its original
133
+ /// factory. An account's next upgrade is therefore constrained by the voucher of the implementation
134
+ /// it is running NOW. Zero / no code ⇒ every upgrade is refused (fail closed) — see
135
+ /// `upgradeToAndCall` for the migration statement.
136
+ address private immutable _upgradeVoucher;
137
+ /// @notice Spec 449: the stateless verifier that runs this implementation's WebAuthn assertion check (decode,
138
+ /// authenticator data, client data, low-s, P-256) — moved out of this bytecode for EIP-170 room. Created
139
+ /// by this implementation's constructor, so it is part of what the upgrade voucher vouched; reached by
140
+ /// STATICCALL from `_verifyWebAuthn` only, and it holds no state and no authority.
141
+ address public immutable signatureVerifier;
142
+
98
143
  /// @dev Authorized DelegationManager (ERC-7710 executor)
99
144
  address private _delegationManager;
100
145
 
@@ -143,20 +188,109 @@ contract AgentAccount is
143
188
  }
144
189
 
145
190
  /// @dev Spec 007 Phase A.5 — current pending upgrade (set by
146
- /// `upgradeToWithAuthorization` when `_upgradeTimelock > 0`).
191
+ /// `scheduleUpgrade` when `_upgradeTimelock > 0`).
147
192
  PendingUpgrade private _pendingUpgrade;
148
193
 
194
+ /// @dev CA-1 — transient "the current call stack is an authorized upgrade
195
+ /// context" flag. Set while (a) a module action executes
196
+ /// (custody-governed, e.g. `CustodyPolicy.ApplySystemUpdate`, which
197
+ /// carries its own T5 quorum + timelock) or (b) a matured owner-queued
198
+ /// upgrade fires (`executePendingUpgrade`). `_authorizeUpgrade` reads it
199
+ /// so that, once an account configures `_upgradeTimelock`, a DIRECT owner
200
+ /// `upgradeToAndCall` is refused (must `scheduleUpgrade` then
201
+ /// `executePendingUpgrade`), while the custody path keeps working with no
202
+ /// double delay. Transient ⇒ tx-global (visible in the nested
203
+ /// `_authorizeUpgrade` frame) AND absent from the storage layout.
204
+ bool private transient _upgradeAuthorizedCtx;
205
+
206
+ /// @dev Wave-1 / ACCT-C1 (spec 300) — transient "this call stack was entered
207
+ /// by the installed CustodyPolicy EXECUTOR via `executeFromModule`"
208
+ /// (custody-quorum authorized) flag. Set ONLY inside `executeFromModule`,
209
+ /// around the dispatched call, cleared after. Governance mutators require
210
+ /// it on a custody-governed account (`mode > 0`, a CustodyPolicy EXECUTOR
211
+ /// installed): a 1-of-N UserOp `execute(self, adminSelector)` self-call
212
+ /// leaves the flag unset and reverts, so the quorum+timelock can no longer
213
+ /// be bypassed by a single compromised key. Person accounts (`mode 0`, no
214
+ /// CustodyPolicy) self-govern and are exempt. Transient ⇒ tx-global +
215
+ /// absent from the storage layout.
216
+ bool private transient _custodyGovCtx;
217
+
218
+ /// @dev Wave-1 / DM-3 (spec 300) — transient "this execution stack originated
219
+ /// from the DelegationManager". Set at the outermost `execute`/`executeBatch`
220
+ /// frame whose `msg.sender == _delegationManager`, preserved across a
221
+ /// `DM → execute(self, executeBatch(...))` nest (no longer produced by the canonical manager:
222
+ /// generation 4 / DLG-2 refuses a redemption whose target is the root delegator; the nesting
223
+ /// logic stays as defence in depth for a non-canonical manager), cleared by the
224
+ /// frame that set it. While set, a self-targeted governance selector is
225
+ /// rejected — a delegation may never reach account governance (that is the
226
+ /// CustodyPolicy's job), regardless of custody mode.
227
+ bool private transient _delegationExecCtx;
228
+
229
+ /// @dev Spec 447 — transient "a vouched upgrade's migration call is running" flag. Set only inside
230
+ /// {upgradeToAndCall}, after the voucher accepted `(newImplementation, keccak256(data))`, around the
231
+ /// delegatecall of `data`. {migrateFactory} runs only while it is set, so the factory an account reads its
232
+ /// canonical custody policy, delegation manager, governance and roles from is moved only by migration data
233
+ /// governance vouched for — never by a standalone call a custodian could make later with any factory
234
+ /// (GC's upgrade rehearsal hazard: a migration also vouched with empty data).
235
+ ///
236
+ /// LAYOUT. Transient variables are APPENDED, never inserted: an upgrade runs old and new code in one
237
+ /// transaction, so the three flags above keep the positions generation 4 gave them and this one takes the
238
+ /// next (slot 0, offset 3). `Generation5Bridge` writes this position by name; `check:storage-layouts` gates
239
+ /// the transient layout.
240
+ bool private transient _upgradeMigrationCtx;
241
+
242
+ /// @dev Audit 2026-12-02 C1-4 — transient "this account was initialized in this transaction". The factory's
243
+ /// one-time module-install exception (`onlySelfOrFactoryInit`) exists only while it is set: the factory
244
+ /// installs a governed account's policy in the transaction that creates it, and a self-governed account —
245
+ /// which the factory never installs anything on — leaves that transaction with the exception gone, as does
246
+ /// an account that moved to a new factory. Appended after `_upgradeMigrationCtx` (slot 0, offset 4).
247
+ bool private transient _initializedThisTx;
248
+
249
+ /// @dev Transient "the custody epoch was bumped in this transaction" (set in `_bumpCustodyEpoch`). On a
250
+ /// custody-governed account `approveDigest` refuses while it is set, outside the custody policy's own
251
+ /// context — see `approveDigest`. Appended after `_initializedThisTx` (slot 0, offset 5).
252
+ bool private transient _epochBumpedThisTx;
253
+
149
254
  /// @dev Spec 007 Phase A.5 — maximum permitted upgrade timelock to
150
255
  /// protect against an owner accidentally setting an absurdly
151
256
  /// large delay that bricks future migrations.
152
257
  uint256 internal constant MAX_UPGRADE_TIMELOCK = 30 days;
153
258
 
259
+ /// @dev R917-C-2 (spec 408 §1.2) — THE CUSTODY EPOCH. Incremented by every path that RETIRES a
260
+ /// credential (`removeCustodian`, `removePasskey` — T6 recovery and a full rotation remove through
261
+ /// these). The `0x03` approved-hash sentinel keys every approval to the epoch it was made under
262
+ /// (`approvedHashKey`), so an approval planted by a custodian who is later removed is void the
263
+ /// moment the custody set no longer contains that custodian — an ECDSA signature dies with its key,
264
+ /// and an approved hash now dies with its custody set. Adding a credential does not bump it: an
265
+ /// added key cannot launder an approval a still-present key planted, and voiding a person's
266
+ /// standing wires every time she enrols a device would be the wrong invariant. Takes one slot
267
+ /// from the gap (49 remain).
268
+ uint64 private _custodyEpoch;
269
+
270
+ /// @dev Spec 445 §1.3 (ii) (audit H-2 / ACCT-1) — what a credential can INSTALL is stamped with the
271
+ /// custody epoch it was installed under, exactly as an approved hash is keyed to its epoch. A module
272
+ /// that can ACT as the account (an EXECUTOR; a validator is stamped too, though this generation never
273
+ /// consults one) is honoured by `executeFromModule` only while `stamp == _custodyEpoch + 1`. The
274
+ /// stored value is `epoch + 1` so an unstamped module (slot 0 — one installed before generation 4, or
275
+ /// written by anything other than `installModule` / `reaffirmModule`) is never current: fail closed.
276
+ /// The factory's canonical `custodyPolicy()` is exempt (it is the custody tier itself, and it is what
277
+ /// performs a recovery). HOOK modules are not stamped and never lapse: a hook is a protection, not a
278
+ /// power — a retirement that silently dropped a spend ceiling would hand the retired credential's
279
+ /// delegates an unbounded treasury. One slot from the gap.
280
+ mapping(address => uint64) private _moduleEpochStamp;
281
+
282
+ /// @dev Spec 445 §1.3 (ii) — the same stamp for the delegation manager: `epoch + 1` at the moment
283
+ /// `setDelegationManager` / `reaffirmDelegationManager` ran (or at `initialize` for a factory-less
284
+ /// account). A delegation manager other than the factory's canonical one may call `execute` /
285
+ /// `executeBatch` only while the stamp is current. One slot from the gap (47 remain).
286
+ uint64 private _delegationManagerEpochStamp;
287
+
154
288
  /// @dev Spec 007 Phase A.5 (SC7 § 3.1) — storage gap reserves 50
155
289
  /// slots after the last linear-layout state variable. Future
156
290
  /// additive upgrades shrink the gap by however many slots they
157
291
  /// add. ERC-7201 namespaced state (passkeys, modules) lives at
158
292
  /// keccak-computed slots and is NOT in this linear layout.
159
- uint256[50] private __gap;
293
+ uint256[47] private __gap;
160
294
 
161
295
  // ─── Errors ─────────────────────────────────────────────────────
162
296
 
@@ -198,12 +332,62 @@ contract AgentAccount is
198
332
  error UpgradeNotReady(uint64 readyAt, uint256 nowTs);
199
333
  error PendingUpgradeMismatch(address pending, address attempted);
200
334
  error UpgradePending();
335
+ /// @notice CA-1 — a direct `upgradeToAndCall` was attempted while a per-account
336
+ /// upgrade timelock is set; route through `scheduleUpgrade` +
337
+ /// `executePendingUpgrade` (or the custody module path) instead.
338
+ error DirectUpgradeBlocked();
339
+ /// @notice CA-1 — `scheduleUpgrade` called with no upgrade timelock configured
340
+ /// (nothing to queue against — upgrade directly).
341
+ error UpgradeTimelockNotSet();
201
342
 
202
343
  // Wave 2A — on-chain authority closure (contract audit C-1..C-3).
203
344
  error ValidatorRequired();
204
345
  error LegacyUpgradePathDisabled();
205
346
  error ModuleOperationNotAllowed();
206
347
 
348
+ // Wave 1 — account authorization boundary (spec 300 / ACCT-C1 + DM-3).
349
+ /// @notice A governance mutator was reached on a custody-governed account
350
+ /// (`mode > 0`) outside the CustodyPolicy `executeFromModule` path —
351
+ /// i.e. a single-signer UserOp `execute(self, adminSelector)` self-call.
352
+ error AdminRequiresCustodyQuorum();
353
+ /// @notice A delegation-originated execution stack tried to self-call an
354
+ /// account-governance selector. Delegations may never reach governance.
355
+ error DelegatedGovernanceForbidden();
356
+ /// @dev Spec 410 §1 (THESIS-1a): the approved-hash registry is reachable only through
357
+ /// `approveDigest` / `revokeDigest` / `revokeAllApprovedDigests`, never as an execute target.
358
+ error ApprovedHashRegistryOnlyViaAccount();
359
+ /// @dev Spec 447: {migrateFactory} outside a vouched upgrade's migration call.
360
+ error MigrationOnly();
361
+ error ApprovalAfterCustodyChange();
362
+ /// @dev Spec 447: the migration target is not a factory (no code, or no custody policy / delegation manager).
363
+ error NotAFactory(address target);
364
+ /// @dev Spec 447: `custodyInit` must be given exactly when the account is custody-governed.
365
+ error CustodyInitMismatch(bool governed);
366
+
367
+ // Spec 445 — generation 4.
368
+ /// @notice §1.3 (i): the implementation's `UpgradeVoucher` does not vouch for this
369
+ /// `(newImplementation, keccak256(data))` — or the voucher is unset / has no code / did not answer.
370
+ error UpgradeNotVouched(address newImplementation, bytes32 dataHash);
371
+ /// @notice §1.3 (ii): `module` was installed (or last re-affirmed) under a custody epoch that has since
372
+ /// retired a credential. Re-affirm it (`reaffirmModule`) or uninstall it.
373
+ error ModuleEpochLapsed(address module);
374
+ /// @notice §1.3 (ii): the non-canonical delegation manager was set under a retired custody epoch.
375
+ error DelegationManagerEpochLapsed(address delegationManager);
376
+ /// @notice §1.5 / ACCT-3: an installed module is never an `execute` / `executeBatch` target from below the
377
+ /// custody tier, from a delegation, or from another module. Its lifecycle callbacks are reached
378
+ /// only through `installModule` / `uninstallModule`.
379
+ error ModuleNotAnExecuteTarget(address module);
380
+
381
+ /// @notice §1.3 (ii): `module` re-stamped under `epoch` (it survives the retirement that bumped to it).
382
+ event ModuleReaffirmed(address indexed module, uint64 epoch);
383
+ /// @notice §1.3 (ii): the current delegation manager re-stamped under `epoch`.
384
+ event DelegationManagerReaffirmed(address indexed delegationManager, uint64 epoch);
385
+ /// @notice ACCT-13: a HOOK's `onUninstall` failed; the hook was removed anyway (a hook must not be able
386
+ /// to make its own removal impossible). The hook's own state for this account may be stale.
387
+ event ModuleUninstallCallbackFailed(address indexed module);
388
+ /// @notice ACCT-13: not enough gas to give a hook's `onUninstall` its guaranteed budget — resubmit with more.
389
+ error InsufficientGasForHookUninstall();
390
+
207
391
  /// @notice Emitted when `setDelegationManager` rotates the DM via a
208
392
  /// self-call (the only authorized path post-Wave-2A).
209
393
  event DelegationManagerRotated(address indexed newDelegationManager);
@@ -242,11 +426,15 @@ contract AgentAccount is
242
426
  //
243
427
  // When `AgenticGovernance.isPaused() == true`, every mutating
244
428
  // external entrypoint guarded by this modifier reverts with
245
- // `SystemPaused`. Recovery-shaped entrypoints
246
- // (`uninstallModule`, `cancelPendingUpgrade`, `removeCustodian`,
247
- // the three `onlySelf` ceremonies) are deliberately NOT guarded
248
- // — an operator must always be able to remove attack surface
249
- // even during an incident.
429
+ // `SystemPaused`.
430
+ //
431
+ // Spec 445 §1.2 (audit H-3 / CUST-1 / ACCT-2) — WHAT STAYS REACHABLE UNDER A PAUSE, and how. The
432
+ // recovery-shaped functions (`removeCustodian`, `removePasskey`, `uninstallModule`,
433
+ // `cancelPendingUpgrade`, `revokeDigest`, `revokeAllApprovedDigests`) carry no pause modifier, but
434
+ // all of them except `cancelPendingUpgrade` are `onlySelf`: an un-gated function nobody can call is
435
+ // not live. The account calls itself only through `execute` / `executeBatch` / `executeFromModule`,
436
+ // so the exemption has to be at THOSE doors — `_requireExecutableUnderPause` (for `execute`) and the
437
+ // canonical-custody-policy branch of `executeFromModule`. `executeBatch` has no exemption at all.
250
438
  //
251
439
  // Reads `governance()` through the factory at each check so a
252
440
  // factory-level governance rotation propagates to every account
@@ -264,27 +452,108 @@ contract AgentAccount is
264
452
  /// compatibility). Production deploys MUST pass a real
265
453
  /// `AgenticGovernance` to the factory; the production-deploy
266
454
  /// preflight enforces that invariant.
267
- function _systemPaused() internal view returns (bool) {
455
+ function _systemPaused() internal view returns (bool paused) {
456
+ (paused,) = _pauseState();
457
+ }
458
+
459
+ /// @dev The pause flag AND the governance contract it was read from, in one pass (spec 445 §1.2: the
460
+ /// exemption reads governance once per call). `gov` is meaningful only when `paused` is true.
461
+ ///
462
+ /// DECISION (audit DLG-7, as it concerns this read) — a governance read that FAILS is "not paused".
463
+ /// Considered and kept, for three reasons. (1) Failing closed would make a broken or non-conforming
464
+ /// governance a permanent, unliftable freeze of every account of the factory: the only thing that
465
+ /// can lift a pause is that same governance, and the factory's pointer to it is immutable. (2) The
466
+ /// caller cannot induce the failure: `factory.governance()` is an immutable getter and
467
+ /// `AgenticGovernance.isPaused()` a single storage read; starving the two staticcalls of gas (the
468
+ /// 63/64 rule) leaves the frame with too little gas to perform the call the pause would have
469
+ /// stopped. (3) Which governance a factory points at is a deployment fact, asserted where it can
470
+ /// be: `Deploy.s.sol::_assertProductionEndState` requires a real `AgenticGovernance` and proves the
471
+ /// pause both sets and lifts. What this does NOT give: an account with no factory, or a factory
472
+ /// whose governance is an EOA / has no `isPaused()`, is never paused — by construction, not by
473
+ /// accident; it is outside the kill switch and the manifest must not claim otherwise.
474
+ function _pauseState() internal view returns (bool paused, address gov) {
268
475
  address f = _factory;
269
- if (f == address(0)) return false;
476
+ if (f == address(0)) return (false, address(0));
270
477
  (bool okF, bytes memory dataF) = f.staticcall(
271
478
  abi.encodeWithSelector(IAgentAccountFactoryView.governance.selector)
272
479
  );
273
- if (!okF || dataF.length < 32) return false;
274
- address g = abi.decode(dataF, (address));
275
- if (g == address(0) || g.code.length == 0) return false;
276
- (bool okG, bytes memory dataG) = g.staticcall(
480
+ if (!okF || dataF.length < 32) return (false, address(0));
481
+ gov = abi.decode(dataF, (address));
482
+ if (gov == address(0) || gov.code.length == 0) return (false, address(0));
483
+ (bool okG, bytes memory dataG) = gov.staticcall(
277
484
  abi.encodeWithSelector(IAgentAccountPauseView.isPaused.selector)
278
485
  );
279
- if (!okG || dataG.length < 32) return false;
280
- return abi.decode(dataG, (bool));
486
+ if (!okG || dataG.length < 32) return (false, address(0));
487
+ paused = abi.decode(dataG, (bool));
488
+ }
489
+
490
+ /// @dev Spec 445 §1.2 (a) — the pause gate of `execute` (the single call; `executeBatch` is paused with
491
+ /// no exemption). Not paused ⇒ returns. Paused ⇒ reverts `SystemPaused` unless the call is a
492
+ /// VALIDATED USER OPERATION (`msg.sender` is the immutable EntryPoint — never the delegation manager,
493
+ /// never a self-nest) and its target is one of exactly three things:
494
+ ///
495
+ /// 1. the factory's governance contract;
496
+ /// 2. that governance contract's own `timelock()`;
497
+ /// 3. this account, with a selector on the recovery allow-list (`_isPauseRecoverySelector`).
498
+ ///
499
+ /// (1) and (2) are why a pause can always be lifted (H-3): `unpause()` needs the timelock, the
500
+ /// timelock needs its proposer and executor to call it, and those are AgentAccounts. Both
501
+ /// addresses are read from `_factory → governance() → timelock()` — an immutable getter on the
502
+ /// factory and an immutable on the governance — so no state the account (or whoever holds its
503
+ /// keys) can write selects them. The exemption grants nothing at the target: the timelock's own
504
+ /// role checks and the governance's own `NotTimelock` / `NotGuardian` checks still decide; an
505
+ /// account that holds no role there reaches a revert.
506
+ /// (3) is ACCT-2: under a pause an owner can still REMOVE attack surface through a real path.
507
+ /// Every function on the list keeps its own gates (`onlySelf`, `_requireCustodyGoverned`), so on a
508
+ /// custody-governed account a single custodian's user operation still reverts
509
+ /// `AdminRequiresCustodyQuorum`; the quorum's path is `executeFromModule`.
510
+ ///
511
+ /// Value: unchanged — whatever `value` the call carries is forwarded as before.
512
+ function _requireExecutableUnderPause(address target, bytes calldata data) internal view {
513
+ (bool paused, address gov) = _pauseState();
514
+ if (!paused) return;
515
+ if (msg.sender == address(_entryPoint)) {
516
+ if (target == address(this)) {
517
+ if (data.length >= 4 && _isPauseRecoverySelector(bytes4(data[0:4]))) return;
518
+ } else if (_isGovernanceTarget(target, gov)) {
519
+ return;
520
+ }
521
+ }
522
+ revert SystemPaused();
523
+ }
524
+
525
+ /// @dev True iff `target` is `gov` or `gov.timelock()` (`gov` non-zero) — the pause exemption's resolution:
526
+ /// `_factory → governance() → timelock()`, an immutable getter and an immutable — nothing the account can
527
+ /// write selects either address.
528
+ function _isGovernanceTarget(address target, address gov) internal view returns (bool) {
529
+ if (gov == address(0) || target == address(0)) return false;
530
+ if (target == gov) return true;
531
+ (bool ok, bytes memory ret) =
532
+ gov.staticcall(abi.encodeWithSelector(IAgentAccountGovernanceTimelockView.timelock.selector));
533
+ return ok && ret.length >= 32 && target == abi.decode(ret, (address));
534
+ }
535
+
536
+ /// @dev The recovery allow-list: self-calls that only REMOVE authority or attack surface, reachable
537
+ /// under a pause (spec 445 §1.2 / ACCT-2; `AUDIT.md` §3.4 is the matrix this implements). Nothing
538
+ /// here adds a credential, installs or re-affirms a module, sets a delegation manager, approves a
539
+ /// digest, upgrades, or moves value.
540
+ function _isPauseRecoverySelector(bytes4 s) internal pure returns (bool) {
541
+ return
542
+ s == IAgentAccount.removeCustodian.selector ||
543
+ s == this.removePasskey.selector ||
544
+ s == this.uninstallModule.selector ||
545
+ s == this.cancelPendingUpgrade.selector ||
546
+ s == this.revokeDigest.selector ||
547
+ s == this.revokeAllApprovedDigests.selector;
281
548
  }
282
549
 
283
550
  // ─── Constructor / Initializer ──────────────────────────────────
284
551
 
285
- constructor(IEntryPoint entryPoint_, address approvedHashRegistry_) {
552
+ constructor(IEntryPoint entryPoint_, address approvedHashRegistry_, address upgradeVoucher_) {
553
+ signatureVerifier = address(new SignatureVerifier());
286
554
  _entryPoint = entryPoint_;
287
555
  _approvedHashRegistry = approvedHashRegistry_;
556
+ _upgradeVoucher = upgradeVoucher_;
288
557
  _disableInitializers();
289
558
  }
290
559
 
@@ -359,6 +628,12 @@ contract AgentAccount is
359
628
 
360
629
  _delegationManager = dm;
361
630
  _factory = factory_;
631
+ _initializedThisTx = true; // audit C1-4: the factory's install exception lives in this transaction only
632
+ // Spec 445 §1.3 (ii): a factory-less (legacy / direct-deploy) account has no canonical delegation
633
+ // manager to compare against, so its initial one is stamped under epoch 0 — and lapses, like any
634
+ // other non-canonical manager, at the first retirement unless re-affirmed. A factory-born account
635
+ // needs no stamp: its initial manager is the factory's canonical one.
636
+ if (factory_ == address(0) && dm != address(0)) _delegationManagerEpochStamp = 1;
362
637
  }
363
638
 
364
639
  /// @dev H7-C.5 — passkey-init body extracted so `initialize` stays below
@@ -387,7 +662,7 @@ contract AgentAccount is
387
662
  $.piaToCredentialId[pia] = credIdDigest;
388
663
  $.rpIdHashOf[credIdDigest] = rpIdHash;
389
664
  $.count = 1;
390
- emit PasskeyAdded(credIdDigest, x, y, rpIdHash);
665
+ emit PasskeyAdded(credIdDigest);
391
666
  emit CustodianAdded(pia);
392
667
  }
393
668
 
@@ -412,7 +687,161 @@ contract AgentAccount is
412
687
  * will revert here. Master / bundler / session-issuer
413
688
  * therefore cannot upgrade even by submitting the tx.
414
689
  */
415
- function _authorizeUpgrade(address) internal view override onlySelf {}
690
+ function _authorizeUpgrade(address) internal view override onlySelf {
691
+ // CA-1: the per-account upgrade timelock is now ENFORCED here (it was
692
+ // previously dead code — set via `setUpgradeTimelock` but never consulted,
693
+ // so a direct `upgradeToAndCall` fired immediately). When a timelock is
694
+ // configured, a direct owner upgrade is refused; the owner must
695
+ // `scheduleUpgrade` then `executePendingUpgrade` after the delay. Authorized
696
+ // contexts — a custody-module action (its own T5 quorum + timelock) or the
697
+ // matured owner queue — set `_upgradeAuthorizedCtx` and pass through, so the
698
+ // custody path is not double-delayed. A zero timelock keeps the
699
+ // immediate-upgrade default (backward-compatible).
700
+ // Wave-1/ACCT-C1 + M-4 (spec 300): outside an authorized context, a
701
+ // custody-governed account (`mode>0`) may upgrade ONLY through the
702
+ // CustodyPolicy quorum — reject even when the per-account timelock is 0 (M-4
703
+ // floors it non-zero at the factory, but a quorum-set 0 must not re-open the
704
+ // direct path). A person account keeps the CA-1 behavior (timelock if set).
705
+ if (!_upgradeAuthorizedCtx) {
706
+ if (_hasCustodyGovernance()) revert AdminRequiresCustodyQuorum();
707
+ if (_upgradeTimelock != 0) revert DirectUpgradeBlocked();
708
+ }
709
+ }
710
+
711
+ /**
712
+ * @notice Upgrade this account's implementation. Spec 445 §1.3 (i) (audit H-2 / ACCT-1): on EVERY path —
713
+ * a self-governed account's own user operation, the custody quorum's `ApplySystemUpdate`, and a
714
+ * matured queued upgrade (`executePendingUpgrade`) — the pair
715
+ * `(newImplementation, keccak256(data))` must be vouched by this implementation's
716
+ * `UpgradeVoucher` AT THE MOMENT THE UPGRADE EXECUTES.
717
+ *
718
+ * @dev WHY. OZ's `upgradeToAndCall` delegatecalls `data` on `newImplementation` in this account's storage.
719
+ * With a caller-chosen implementation that is arbitrary code as the account: the audit's PoC upgraded
720
+ * to a throwaway contract whose migration call approved a hash for custody epoch + 1 in the
721
+ * `ApprovedHashRegistry` (as `msg.sender == account`), wrote `_externalCustodians[hidden] = true`
722
+ * with no event and no count change, and restored the real implementation — all in one user
723
+ * operation, all surviving the retirement of the credential that did it. A storage write under
724
+ * delegatecall cannot be detected afterwards, so it must be made impossible beforehand. A quorum
725
+ * should not be able to delegatecall arbitrary code either, so the custody path gets the same check.
726
+ *
727
+ * ORDER. `_authorizeUpgrade` (every pre-existing gate: `onlySelf`, the custody quorum on a governed
728
+ * account, the per-account timelock) runs first so the refusal a caller sees is the same as before;
729
+ * then the voucher; then OZ's `upgradeToAndCall`, which re-authorizes and performs the upgrade.
730
+ * `_authorizeUpgrade(address)` alone cannot make the check — it never sees `data`.
731
+ *
732
+ * FAIL CLOSED. A voucher that is zero, has no code, reverts, or answers anything but `true` refuses
733
+ * the upgrade. An implementation built without a voucher can never be upgraded away from.
734
+ *
735
+ * THE QUEUE. `scheduleUpgrade` binds only an implementation; `executePendingUpgrade` always runs it
736
+ * with EMPTY migration data, so a queued upgrade is bound to `dataHash == keccak256("")` by
737
+ * construction and is checked against the voucher when it executes, not when it was queued (an
738
+ * `unvouch` during the wait stops it). An upgrade that needs a migration call cannot be queued.
739
+ *
740
+ * MIGRATION OF AN EXISTING (generation ≤ 3) ACCOUNT — read this before claiming more than it gives.
741
+ * Such an account reaches generation 4 by upgrading through its OLD implementation's code, which
742
+ * has no voucher: nothing in this contract can constrain that last old-rules upgrade, nor anything
743
+ * done before it. From the moment the account runs a generation-4 implementation, its upgrades are
744
+ * constrained by the voucher immutable of the implementation it is running.
745
+ * GUARANTEED after migration: no credential, module, delegate or quorum can execute code as the
746
+ * account other than a governance-vouched implementation + migration call; a retirement expels
747
+ * non-canonical executor modules and a non-canonical delegation manager (§1.3 (ii)) and clears a
748
+ * queued upgrade.
749
+ * NOT GUARANTEED: that the account was clean when it migrated. A credential that was compromised
750
+ * BEFORE the migration may already have written a hidden custodian, planted approvals, or
751
+ * swapped the implementation for one of its own (which then never consults any voucher).
752
+ * Migrating does not undo any of that and does not detect it. For an account suspected of
753
+ * compromise before migration, the only sound remedies are off-chain review of its storage
754
+ * against its event history, or a new account.
755
+ * Also unchanged by an in-place upgrade: `_factory`. A migrated account's CANONICAL custody policy
756
+ * and delegation manager remain those of its ORIGINAL factory (generation ≤ 3 code). Pointing it at
757
+ * a generation-4 DelegationManager is a `setDelegationManager` — non-canonical for that account, so
758
+ * it must be re-affirmed at every rotation; its custody policy keeps the old action set.
759
+ */
760
+ /// @notice ERC-1822, asked of THIS implementation by an account about to upgrade to it. Answered only for an
761
+ /// account whose running implementation carries this implementation's voucher (spec 448 §0, audit
762
+ /// 2026-12-02 H-2): an account still running code with another voucher — every generation-4 account —
763
+ /// cannot upgrade to this implementation directly, whatever pair its own voucher vouches. Its one way in
764
+ /// is `Generation5Bridge`, whose completion runs `migrateFactory`.
765
+ function proxiableUUID() external view override notDelegated returns (bytes32) {
766
+ if (AgentAccount(payable(msg.sender)).upgradeVoucher() != _upgradeVoucher) revert UpgradeNotVouched(address(this), 0);
767
+ return ERC1967Utils.IMPLEMENTATION_SLOT;
768
+ }
769
+
770
+ function upgradeToAndCall(address newImplementation, bytes memory data) public payable override onlyProxy {
771
+ _authorizeUpgrade(newImplementation);
772
+ _requireVouchedUpgrade(newImplementation, keccak256(data));
773
+ _upgradeMigrationCtx = true;
774
+ super.upgradeToAndCall(newImplementation, data);
775
+ _upgradeMigrationCtx = false;
776
+ }
777
+
778
+ /// @notice Spec 447 §3.3 — move this account to a new factory, IN PLACE (same address, same custodians,
779
+ /// same storage). Callable only as a vouched upgrade's migration call: the generation-5 move is
780
+ /// `upgradeToAndCall(gen5Implementation, abi.encodeCall(this.migrateFactory, (stableFactory, custodyInit)))`
781
+ /// with that exact pair vouched by governance (and, on a custody-governed account, applied by its own
782
+ /// quorum through `ApplySystemUpdate`). From then on the account reads its canonical custody policy,
783
+ /// delegation manager, governance, bundler and session issuer from the new (stable) factory.
784
+ ///
785
+ /// A CUSTODY-GOVERNED account keeps its custody: when the new factory's canonical policy differs from
786
+ /// the installed one, the new policy is installed with `custodyInit` (the account's own configuration,
787
+ /// the `onInstall` encoding) and the old one is unlisted — it can no longer act on this account; its
788
+ /// stale state stays in the old contract. Without this the account would silently stop being
789
+ /// custody-governed (the old policy is no longer canonical). A self-governed account passes empty
790
+ /// `custodyInit`.
791
+ /// @dev Refused outside a migration (`MigrationOnly`), for a factory with no code or one that names no custody
792
+ /// policy or delegation manager (PR #751: a non-factory `_factory` bricks the account), for a governed
793
+ /// account with no `custodyInit`, and for `custodyInit` on an account that is not governed.
794
+ function migrateFactory(address newFactory, bytes calldata custodyInit) external {
795
+ if (!_upgradeMigrationCtx) revert MigrationOnly();
796
+ if (newFactory.code.length == 0) revert NotAFactory(newFactory);
797
+ address newPolicy = IAgentAccountFactoryView(newFactory).custodyPolicy();
798
+ if (newPolicy == address(0) || IAgentAccountFactoryView(newFactory).delegationManager() == address(0)) {
799
+ revert NotAFactory(newFactory);
800
+ }
801
+ address oldFactory = _factory;
802
+ address oldPolicy = oldFactory == address(0) ? address(0) : IAgentAccountFactoryView(oldFactory).custodyPolicy();
803
+ ModulesStorage storage $ = _modulesStorage();
804
+ bool governed = oldPolicy != address(0) && $.installed[MODULE_TYPE_EXECUTOR][oldPolicy];
805
+ if (governed != (custodyInit.length != 0)) revert CustodyInitMismatch(governed);
806
+
807
+ // Audit H-2 (C1-2 / C3-1): the registry this implementation reads was an ordinary call target for the
808
+ // code the account ran before, so anything approved there (for this or any later custody epoch) was
809
+ // approved outside `approveDigest`. The move voids all of it HERE, in every custody mode — not in a step
810
+ // of the mover's batch.
811
+ _revokeAllApproved();
812
+ emit FactoryMigrated(oldFactory, newFactory);
813
+ _factory = newFactory;
814
+ if (!governed || newPolicy == oldPolicy) return;
815
+
816
+ $.installed[MODULE_TYPE_EXECUTOR][oldPolicy] = false;
817
+ _removeFromList($.installedList[MODULE_TYPE_EXECUTOR], oldPolicy);
818
+ delete _moduleEpochStamp[oldPolicy];
819
+ emit ModuleUninstalled(MODULE_TYPE_EXECUTOR, oldPolicy);
820
+
821
+ $.installed[MODULE_TYPE_EXECUTOR][newPolicy] = true;
822
+ $.installedList[MODULE_TYPE_EXECUTOR].push(newPolicy);
823
+ _moduleEpochStamp[newPolicy] = _custodyEpoch + 1;
824
+ IERC7579ModuleLike(newPolicy).onInstall(custodyInit); // a refusal reverts the whole upgrade
825
+ emit ModuleInstalled(MODULE_TYPE_EXECUTOR, newPolicy);
826
+ }
827
+
828
+ /// @dev Spec 445 §1.3 (i). See `upgradeToAndCall`. Low-level staticcall so a voucher that reverts or
829
+ /// returns malformed data is a refusal, never a bubble-up the caller could mistake for another gate.
830
+ function _requireVouchedUpgrade(address newImplementation, bytes32 dataHash) internal view {
831
+ address v = _upgradeVoucher;
832
+ if (v.code.length != 0) {
833
+ (bool ok, bytes memory ret) = v.staticcall(
834
+ abi.encodeWithSelector(IUpgradeVoucherView.isVouched.selector, newImplementation, dataHash)
835
+ );
836
+ if (ok && ret.length == 32 && abi.decode(ret, (uint256)) == 1) return;
837
+ }
838
+ revert UpgradeNotVouched(newImplementation, dataHash);
839
+ }
840
+
841
+ /// @notice The `UpgradeVoucher` this implementation consults before every upgrade (immutable).
842
+ function upgradeVoucher() external view returns (address) {
843
+ return _upgradeVoucher;
844
+ }
416
845
 
417
846
  /**
418
847
  * @notice DEPRECATED — single-signature upgrade path (contract audit C-3).
@@ -439,6 +868,25 @@ contract AgentAccount is
439
868
  revert LegacyUpgradePathDisabled();
440
869
  }
441
870
 
871
+ /// @notice CA-1 — queue an implementation upgrade subject to the per-account
872
+ /// upgrade timelock. The owner signs a userOp that calls this
873
+ /// (`onlySelf`); the bound implementation can then be applied via
874
+ /// `executePendingUpgrade` once `_upgradeTimelock` has elapsed. Only
875
+ /// meaningful when a timelock is configured — with none set, upgrade
876
+ /// directly. Overwrites any existing pending upgrade.
877
+ /// @dev Spec 445 §1.3: the queued upgrade is bound to EMPTY migration data and is checked against the
878
+ /// `UpgradeVoucher` when it EXECUTES (see `upgradeToAndCall`); every credential retirement clears
879
+ /// the queue (`_bumpCustodyEpoch`), so an upgrade queued by a since-retired credential never fires.
880
+ function scheduleUpgrade(address newImplementation) external onlySelf {
881
+ _requireCustodyGoverned();
882
+ if (newImplementation == address(0)) revert ZeroAddress();
883
+ uint256 tl = _upgradeTimelock;
884
+ if (tl == 0) revert UpgradeTimelockNotSet();
885
+ uint64 readyAt = uint64(block.timestamp + tl);
886
+ _pendingUpgrade = PendingUpgrade({newImplementation: newImplementation, readyAt: readyAt});
887
+ emit UpgradeProposed(newImplementation, readyAt);
888
+ }
889
+
442
890
  /// @notice Execute a previously-queued upgrade. Permissionless once
443
891
  /// the timelock has expired — anyone can pay the gas, but
444
892
  /// the implementation address was bound at queue time.
@@ -450,28 +898,52 @@ contract AgentAccount is
450
898
  // impl can't replay this state.
451
899
  delete _pendingUpgrade;
452
900
  emit UpgradeAuthorized(p.newImplementation);
901
+ // CA-1: authorize the nested `_authorizeUpgrade` for this matured queue
902
+ // (transient, tx-global). Cleared after so a later same-tx direct upgrade
903
+ // isn't inadvertently authorized.
904
+ _upgradeAuthorizedCtx = true;
453
905
  this.upgradeToAndCall(p.newImplementation, "");
906
+ _upgradeAuthorizedCtx = false;
454
907
  }
455
908
 
456
- /// @notice Cancel a queued upgrade during the timelock window. Owner
457
- /// signs a digest that binds to the pending implementation
458
- /// AND `address(this)` + chain id, preventing cross-account
459
- /// replay of a cancel-grant.
909
+ /// @notice Cancel a queued upgrade during the timelock window.
910
+ /// @dev NEW-CANCEL-UPGRADE-1: cancel is a governance op. On a CUSTODY-GOVERNED
911
+ /// account (mode>0 / org) it MUST go through the custody quorum — routed via
912
+ /// the CustodyPolicy executor (`_custodyGovCtx`), exactly like `scheduleUpgrade`
913
+ /// and the other governance mutators — so a single compromised custodian's
914
+ /// ECDSA signature cannot perpetually cancel quorum-scheduled upgrades
915
+ /// (upgrade-liveness DoS). The lightweight ECDSA cancel-grant fast-path remains
916
+ /// ONLY for non-governed (mode-0) accounts, where the sole custodian IS the owner.
917
+ /// Spec 445 §1.2 / ACCT-2 (+ ACCT-9b): on a non-governed account a SELF-CALL is also accepted, with
918
+ /// no signature — it arrives only through a user operation one of the account's own credentials
919
+ /// signed (the same authority that could overwrite the queue with `scheduleUpgrade`). Without it a
920
+ /// passkey-only account had no way to cancel at all, and under a pause the recovery allow-list
921
+ /// entry for this selector would have named a path nobody could take.
460
922
  /// @param ownerSig Owner ECDSA signature over `keccak256(abi.encode(
461
923
  /// "UPGRADE_CANCEL", _pendingUpgrade.newImplementation,
462
- /// address(this), block.chainid))`.
924
+ /// address(this), block.chainid))`. Ignored on governed accounts
925
+ /// (the quorum context authorizes; no signature is consulted) and on a self-call.
463
926
  function cancelPendingUpgrade(bytes calldata ownerSig) external {
927
+ bool governed = _hasCustodyGovernance();
928
+ // Governed: authorize FIRST (fail-closed before revealing pending state). Only the custody quorum
929
+ // (executor self-call with the gov context set) may cancel — `_custodyGovCtx` is set solely by
930
+ // `executeFromModule` when the caller is the CustodyPolicy module, so this reverts
931
+ // AdminRequiresCustodyQuorum for any single-custodian / external attempt.
932
+ if (governed) _requireCustodyGoverned();
464
933
  PendingUpgrade memory p = _pendingUpgrade;
465
934
  if (p.readyAt == 0) revert NoPendingUpgrade();
466
- bytes32 digest = keccak256(
467
- abi.encode(
468
- bytes32("UPGRADE_CANCEL"),
469
- p.newImplementation,
470
- address(this),
471
- block.chainid
472
- )
473
- );
474
- if (!_verifyEcdsa(digest, ownerSig)) revert NotOwnerSig();
935
+ if (!governed && msg.sender != address(this)) {
936
+ // Non-governed (mode-0): the sole custodian's ECDSA cancel-grant authorizes.
937
+ bytes32 digest = keccak256(
938
+ abi.encode(
939
+ bytes32("UPGRADE_CANCEL"),
940
+ p.newImplementation,
941
+ address(this),
942
+ block.chainid
943
+ )
944
+ );
945
+ if (!_verifyEcdsa(digest, ownerSig)) revert NotOwnerSig();
946
+ }
475
947
  delete _pendingUpgrade;
476
948
  emit UpgradeCancelled(p.newImplementation);
477
949
  }
@@ -481,6 +953,7 @@ contract AgentAccount is
481
953
  /// (`onlySelf`). 0 == immediate upgrades (default,
482
954
  /// backward-compat).
483
955
  function setUpgradeTimelock(uint256 secs) external onlySelf {
956
+ _requireCustodyGoverned();
484
957
  if (secs > MAX_UPGRADE_TIMELOCK) {
485
958
  revert UpgradeTimelockTooLong(secs, MAX_UPGRADE_TIMELOCK);
486
959
  }
@@ -502,7 +975,7 @@ contract AgentAccount is
502
975
 
503
976
  /// @notice Returns the current implementation version.
504
977
  function version() external pure returns (string memory) {
505
- return "2.2.0";
978
+ return "2.3.0";
506
979
  }
507
980
 
508
981
  // ─── Delegation Manager (ERC-7710) ─────────────────────────────
@@ -524,16 +997,54 @@ contract AgentAccount is
524
997
  * a self-call into this function.
525
998
  */
526
999
  function setDelegationManager(address dm) external onlySelf {
1000
+ _requireCustodyGoverned();
527
1001
  if (dm.code.length == 0) revert ValidatorRequired();
528
1002
  _delegationManager = dm;
1003
+ // Spec 445 §1.3 (ii): stamped with the epoch it was set under. If `dm` is not the factory's canonical
1004
+ // manager it stops being honoured at the next credential retirement unless re-affirmed.
1005
+ _delegationManagerEpochStamp = _custodyEpoch + 1;
529
1006
  emit DelegationManagerRotated(dm);
530
1007
  }
531
1008
 
1009
+ /// @notice Spec 445 §1.3 (ii) — re-stamp the CURRENT delegation manager under the current custody epoch,
1010
+ /// so a non-canonical manager the person keeps survives the retirement that just bumped the
1011
+ /// epoch. Gated EXACTLY like `setDelegationManager` (`onlySelf` + the custody quorum on a governed
1012
+ /// account); unreachable from a delegation stack (`_isGovernanceSelector`). The rotation ceremony
1013
+ /// calls it after the retirement; a recovery never does.
1014
+ function reaffirmDelegationManager() external onlySelf {
1015
+ _requireCustodyGoverned();
1016
+ address dm = _delegationManager;
1017
+ if (dm.code.length == 0) revert ValidatorRequired();
1018
+ uint64 epoch = _custodyEpoch;
1019
+ _delegationManagerEpochStamp = epoch + 1;
1020
+ emit DelegationManagerReaffirmed(dm, epoch);
1021
+ }
1022
+
532
1023
  /// @notice Get the currently authorized DelegationManager.
533
1024
  function delegationManager() external view returns (address) {
534
1025
  return _delegationManager;
535
1026
  }
536
1027
 
1028
+ /// @notice Whether the delegation manager is honoured by `execute` / `executeBatch` RIGHT NOW: it is the
1029
+ /// factory's canonical one, or it was set / re-affirmed under the current custody epoch.
1030
+ function isDelegationManagerCurrent() external view returns (bool) {
1031
+ return _delegationManagerCurrent();
1032
+ }
1033
+
1034
+ /// @dev Spec 445 §1.3 (ii). The canonical manager is read from the factory (an immutable there); a
1035
+ /// factory that cannot answer names no canonical manager — fail closed.
1036
+ function _delegationManagerCurrent() internal view returns (bool) {
1037
+ if (_delegationManagerEpochStamp == _custodyEpoch + 1) return true;
1038
+ address f = _factory;
1039
+ if (f == address(0)) return false;
1040
+ (bool ok, bytes memory ret) = f.staticcall(
1041
+ abi.encodeWithSelector(IAgentAccountFactoryView.delegationManager.selector)
1042
+ );
1043
+ if (!ok || ret.length < 32) return false;
1044
+ address canonical = abi.decode(ret, (address));
1045
+ return canonical != address(0) && canonical == _delegationManager;
1046
+ }
1047
+
537
1048
  // ─── Phase A — capability roles (factory-scoped) ───────────────
538
1049
 
539
1050
  /// @notice Address of the factory that deployed this account.
@@ -587,6 +1098,7 @@ contract AgentAccount is
587
1098
  * delegation the owner has authorized.
588
1099
  */
589
1100
  function acceptSessionDelegation(bytes32 sessionDelegationHash) external onlySelf {
1101
+ _requireCustodyGoverned();
590
1102
  if (_acceptedSessionDelegations[sessionDelegationHash]) {
591
1103
  revert SessionDelegationAlreadyAccepted(sessionDelegationHash);
592
1104
  }
@@ -686,6 +1198,10 @@ contract AgentAccount is
686
1198
  /// an unbounded list would let a malicious owner brick their account.
687
1199
  uint256 internal constant MAX_HOOKS = 8;
688
1200
 
1201
+ /// @dev ACCT-13 — the fixed gas a HOOK's `onUninstall` callback is given (see `uninstallModule`). Ample for
1202
+ /// a hook that clears per-account state; a hook that needs more is not removable cleanly, by design.
1203
+ uint256 internal constant HOOK_UNINSTALL_CALLBACK_GAS = 200_000;
1204
+
689
1205
  /// @dev ERC-7201 namespaced storage slot for module state.
690
1206
  /// slot = keccak256(abi.encode(uint256(keccak256("smart-agent.account.modules.v1")) - 1)) & ~bytes32(uint256(0xff))
691
1207
  bytes32 private constant MODULES_STORAGE_SLOT =
@@ -751,7 +1267,7 @@ contract AgentAccount is
751
1267
  _;
752
1268
  return;
753
1269
  }
754
- if (msg.sender == _factory && !_factoryInitConsumed) {
1270
+ if (msg.sender == _factory && _initializedThisTx && !_factoryInitConsumed) {
755
1271
  _factoryInitConsumed = true;
756
1272
  _;
757
1273
  return;
@@ -771,6 +1287,10 @@ contract AgentAccount is
771
1287
  address module,
772
1288
  bytes calldata initData
773
1289
  ) external onlySelfOrFactoryInit whenNotPaused {
1290
+ // Wave-1/ACCT-C1: on a custody-governed account, module installs must route
1291
+ // through the CustodyPolicy quorum. Exempt by construction at factory-init
1292
+ // (no EXECUTOR installed yet ⇒ `_hasCustodyGovernance()` is false).
1293
+ _requireCustodyGoverned();
774
1294
  if (module == address(0)) revert ZeroAddress();
775
1295
  if (!_isSupportedModuleType(moduleTypeId)) revert UnsupportedModuleType(moduleTypeId);
776
1296
 
@@ -784,6 +1304,9 @@ contract AgentAccount is
784
1304
 
785
1305
  $.installed[moduleTypeId][module] = true;
786
1306
  $.installedList[moduleTypeId].push(module);
1307
+ // Spec 445 §1.3 (ii): a module that can act as the account is stamped with the custody epoch it was
1308
+ // installed under (see `_moduleEpochStamp`). A HOOK is not stamped — it never lapses.
1309
+ if (moduleTypeId != MODULE_TYPE_HOOK) _moduleEpochStamp[module] = _custodyEpoch + 1;
787
1310
 
788
1311
  // Notify the module — best-effort wrapped so a misbehaving module
789
1312
  // produces a typed error instead of bubbling raw bytes. We still
@@ -796,6 +1319,7 @@ contract AgentAccount is
796
1319
  $.installed[moduleTypeId][module] = false;
797
1320
  address[] storage list = $.installedList[moduleTypeId];
798
1321
  list.pop();
1322
+ // (the epoch stamp is rolled back by the revert itself)
799
1323
  revert ModuleOnInstallFailed(reason);
800
1324
  }
801
1325
 
@@ -820,6 +1344,7 @@ contract AgentAccount is
820
1344
  // at deploy time, and there's never a legitimate reason for
821
1345
  // the factory to do that.
822
1346
  if (msg.sender != address(this)) revert ModuleOperationNotAllowed();
1347
+ _requireCustodyGoverned();
823
1348
  if (!_isSupportedModuleType(moduleTypeId)) revert UnsupportedModuleType(moduleTypeId);
824
1349
 
825
1350
  ModulesStorage storage $ = _modulesStorage();
@@ -827,22 +1352,77 @@ contract AgentAccount is
827
1352
  revert ModuleNotInstalled(moduleTypeId, module);
828
1353
  }
829
1354
 
830
- // Loud uninstall — if the module reverts in onUninstall, we revert
831
- // too so the caller sees the failure. (Owner can force-uninstall
832
- // by passing deInitData the module can handle, or by re-deploying
833
- // the account proxy — UUPS is available.)
834
- try IERC7579ModuleLike(module).onUninstall(deInitData) {
835
- // ok
836
- } catch (bytes memory reason) {
837
- revert ModuleOnUninstallFailed(reason);
838
- }
839
-
1355
+ // R917-C-1: effects BEFORE the interaction. The module's `onUninstall` may verify that this account
1356
+ // no longer lists it (CustodyPolicy does — that is how it tells `uninstallModule` apart from a
1357
+ // custodian's `execute(custodyPolicy, onUninstall)`), so the flag is cleared first. A revert below
1358
+ // still rolls the whole call back.
840
1359
  $.installed[moduleTypeId][module] = false;
841
1360
  _removeFromList($.installedList[moduleTypeId], module);
1361
+ if (moduleTypeId != MODULE_TYPE_HOOK) delete _moduleEpochStamp[module];
1362
+
1363
+ if (moduleTypeId != MODULE_TYPE_HOOK) {
1364
+ // Loud uninstall — if an EXECUTOR / VALIDATOR reverts in onUninstall, we revert too so the caller
1365
+ // sees the failure (the custody policy's `onUninstall` must be able to refuse).
1366
+ try IERC7579ModuleLike(module).onUninstall(deInitData) {
1367
+ // ok
1368
+ } catch (bytes memory reason) {
1369
+ revert ModuleOnUninstallFailed(reason);
1370
+ }
1371
+ } else {
1372
+ // ACCT-13 (audit 2026-11-10): a HOOK is different. Hooks run before every `execute`; one whose
1373
+ // `onUninstall` (or `preCheck` — see `execute`) reverts or burns its gas would otherwise make its
1374
+ // own removal impossible and brick a self-governed account. The account has already decided, at
1375
+ // its custody tier, to drop the hook: the callback gets a FIXED gas budget and its failure is
1376
+ // recorded (`ModuleUninstallCallbackFailed`), not obeyed.
1377
+ // - The budget is guaranteed, not best-effort: the call reverts up front if it could not be
1378
+ // forwarded in full. Otherwise whoever submits the transaction (anyone can submit a quorum's
1379
+ // `applyCustodyChange`) could starve an HONEST hook's cleanup with a tuned gas limit and
1380
+ // leave its per-account state stale.
1381
+ // - The revert data is not copied (no return-bomb, no unbounded log).
1382
+ // Consequence for a hook that does fail: its own state for this account may still say
1383
+ // "installed" — `TreasurySpendPolicy` then refuses a fresh `onInstall`, so a NEW hook instance is
1384
+ // needed. That is the hook's cost of having failed, never the account's.
1385
+ if (gasleft() < HOOK_UNINSTALL_CALLBACK_GAS + HOOK_UNINSTALL_CALLBACK_GAS / 32) {
1386
+ revert InsufficientGasForHookUninstall();
1387
+ }
1388
+ try IERC7579ModuleLike(module).onUninstall{gas: HOOK_UNINSTALL_CALLBACK_GAS}(deInitData) {
1389
+ // ok
1390
+ } catch {
1391
+ emit ModuleUninstallCallbackFailed(module);
1392
+ }
1393
+ }
842
1394
 
843
1395
  emit ModuleUninstalled(moduleTypeId, module);
844
1396
  }
845
1397
 
1398
+ /// @notice Spec 445 §1.3 (ii) — re-stamp an installed EXECUTOR (or validator) module under the current
1399
+ /// custody epoch, so a module the person KEEPS survives the retirement that just bumped the
1400
+ /// epoch. Gated EXACTLY like `installModule` after birth: `onlySelf`, pause-gated, and — on a
1401
+ /// custody-governed account — only inside the custody quorum's `executeFromModule`. Unreachable
1402
+ /// from a delegation stack (`_isGovernanceSelector`). The rotation ceremony calls it after the
1403
+ /// retirement (`add → retire → approveDigest×N → reaffirm×M`); a recovery never does — whatever a
1404
+ /// lost or stolen credential installed stays expelled until the person re-installs it knowingly.
1405
+ /// A hook needs no re-affirmation and is refused here (it never lapses).
1406
+ function reaffirmModule(address module) external onlySelf whenNotPaused {
1407
+ _requireCustodyGoverned();
1408
+ ModulesStorage storage $ = _modulesStorage();
1409
+ if (!$.installed[MODULE_TYPE_EXECUTOR][module] && !$.installed[MODULE_TYPE_VALIDATOR][module]) {
1410
+ revert ModuleNotInstalled(MODULE_TYPE_EXECUTOR, module);
1411
+ }
1412
+ uint64 epoch = _custodyEpoch;
1413
+ _moduleEpochStamp[module] = epoch + 1;
1414
+ emit ModuleReaffirmed(module, epoch);
1415
+ }
1416
+
1417
+ /// @notice Whether `module` may act through `executeFromModule` RIGHT NOW: it is the factory's canonical
1418
+ /// custody policy, or it was installed / re-affirmed under the current custody epoch. (Says
1419
+ /// nothing about whether it is installed — pair with `isModuleInstalled`.)
1420
+ function isModuleCurrent(address module) external view returns (bool) {
1421
+ if (_moduleEpochStamp[module] == _custodyEpoch + 1) return true;
1422
+ address f = _factory;
1423
+ return f != address(0) && module == IAgentAccountFactoryView(f).custodyPolicy();
1424
+ }
1425
+
846
1426
  /// @notice Returns true iff the given module is installed for the given type.
847
1427
  /// @dev `additionalContext` accepted for ERC-7579 conformance; unused here.
848
1428
  function isModuleInstalled(
@@ -918,21 +1498,107 @@ contract AgentAccount is
918
1498
  function executeFromModule(address target, uint256 value, bytes calldata data)
919
1499
  external
920
1500
  nonReentrant
921
- whenNotPaused
922
1501
  returns (bytes memory)
923
1502
  {
1503
+ // CA-1 + Wave-1/ACCT-C1 (spec 300): a module action from the CANONICAL CustodyPolicy is a
1504
+ // custody-governed context (gated upstream by its own T5 quorum + timelock). `_custodyGovCtx`
1505
+ // authorizes every governance mutator this call dispatches (the ONLY way past
1506
+ // `_requireCustodyGoverned` on a `mode>0` account); `_upgradeAuthorizedCtx` additionally exempts a
1507
+ // dispatched upgrade from the per-account timelock (no double delay). Both transient.
1508
+ //
1509
+ // NEW-EXEC-MODULE-1 (2026-07-05 audit, internal + external): grant that context ONLY to the
1510
+ // canonical CustodyPolicy the factory installs — NOT to any installed executor. Otherwise a second
1511
+ // (utility / automation) executor a quorum installs believing it unprivileged would silently inherit
1512
+ // full authority to mutate custody / DM / upgrade / modules, bypassing quorum+timelock. Matching the
1513
+ // specific policy address is the same check `_hasCustodyGovernance` uses. A non-canonical executor
1514
+ // runs WITHOUT the context, so `_requireCustodyGoverned` rejects any governance mutator it dispatches.
1515
+ address f = _factory;
1516
+ bool custodyGoverned = f != address(0) && msg.sender == IAgentAccountFactoryView(f).custodyPolicy();
1517
+
1518
+ // R6.5 pause gate, with the spec 445 §1.2 / ACCT-2 exemption: under a pause the ONLY module call that
1519
+ // still lands is the canonical custody policy dispatching a recovery-allow-list self-call (a quorum
1520
+ // removing a credential or uninstalling a module). The policy decides which of its actions it will
1521
+ // schedule/apply under a pause; this is the account's half of the same rule. (A pause is lifted through
1522
+ // `execute` from a validated user operation — `_requireExecutableUnderPause`, H-3.)
1523
+ if (_systemPaused()) {
1524
+ if (
1525
+ !(custodyGoverned && target == address(this)
1526
+ && data.length >= 4 && _isPauseRecoverySelector(bytes4(data[0:4])))
1527
+ ) revert SystemPaused();
1528
+ }
1529
+
924
1530
  ModulesStorage storage $ = _modulesStorage();
925
1531
  if (!$.installed[MODULE_TYPE_EXECUTOR][msg.sender]) {
926
1532
  revert NotInstalledExecutor(msg.sender);
927
1533
  }
1534
+ if (!custodyGoverned) {
1535
+ // Spec 445 §1.3 (ii) (audit H-2 / ACCT-1): an executor installed by a credential that has since
1536
+ // been retired is retired with it. Only the canonical custody policy is exempt — it IS the
1537
+ // custody tier, and it is what performs the recovery that bumps the epoch.
1538
+ if (_moduleEpochStamp[msg.sender] != _custodyEpoch + 1) revert ModuleEpochLapsed(msg.sender);
1539
+ // ACCT-3: a module never speaks as the account to another installed module (it could drop a
1540
+ // hook's budget, or drive the custody policy).
1541
+ if (_isInstalledModule(target)) revert ModuleNotAnExecuteTarget(target);
1542
+ }
928
1543
  emit ModuleExecuted(msg.sender, target, value);
1544
+ _rejectDirectRegistryCall(target);
1545
+
1546
+ // Spec 445 §1.5 (CUST-2 / ACCT-3): HOOKS RUN ON A MODULE'S CALL TOO. Before generation 4 they ran only
1547
+ // in `execute` / `executeBatch`, so any installed executor moved value with no hook consulted — the
1548
+ // treasury ceiling bounded delegates and user operations and nothing else. The canonical custody
1549
+ // policy is not hooked: it dispatches account governance (never value), and a reverting hook must
1550
+ // not be able to stop the quorum from removing that very hook.
1551
+ address[] memory hooks;
1552
+ bytes[] memory hookData;
1553
+ if (!custodyGoverned) (hooks, hookData) = _preHooks(value, abi.encode(target, value, data));
1554
+
1555
+ // The custody context is granted only around a SELF-call — the shape of every governance action the
1556
+ // policy dispatches. Its one other dispatch (spec 445 §1.5: a ceiling change on an installed hook)
1557
+ // is a call OUT to the hook; an external contract never runs with this account's governance flags set.
1558
+ bool grantCtx = custodyGoverned && target == address(this);
1559
+ if (grantCtx) {
1560
+ _custodyGovCtx = true;
1561
+ _upgradeAuthorizedCtx = true;
1562
+ }
929
1563
  (bool ok, bytes memory ret) = target.call{value: value}(data);
1564
+ if (grantCtx) {
1565
+ _upgradeAuthorizedCtx = false;
1566
+ _custodyGovCtx = false;
1567
+ }
930
1568
  if (!ok) {
931
1569
  assembly { revert(add(ret, 32), mload(ret)) }
932
1570
  }
1571
+ _postHooks(hooks, hookData);
933
1572
  return ret;
934
1573
  }
935
1574
 
1575
+ /// @dev Run every installed hook's `preCheck`, in install order. `hookMsgData` is
1576
+ /// `abi.encode(target, value, data)` for a single call and `abi.encode(Call[])` for a batch.
1577
+ function _preHooks(uint256 value, bytes memory hookMsgData)
1578
+ internal
1579
+ returns (address[] memory hooks, bytes[] memory hookData)
1580
+ {
1581
+ hooks = _modulesStorage().installedList[MODULE_TYPE_HOOK];
1582
+ hookData = new bytes[](hooks.length);
1583
+ for (uint256 i = 0; i < hooks.length; i++) {
1584
+ hookData[i] = IERC7579HookLike(hooks[i]).preCheck(msg.sender, value, hookMsgData);
1585
+ }
1586
+ }
1587
+
1588
+ function _postHooks(address[] memory hooks, bytes[] memory hookData) internal {
1589
+ for (uint256 i = 0; i < hooks.length; i++) {
1590
+ IERC7579HookLike(hooks[i]).postCheck(hookData[i]);
1591
+ }
1592
+ }
1593
+
1594
+ /// @dev True iff `target` is installed on this account as a module of ANY supported type.
1595
+ function _isInstalledModule(address target) internal view returns (bool) {
1596
+ ModulesStorage storage $ = _modulesStorage();
1597
+ return $.installed[MODULE_TYPE_EXECUTOR][target]
1598
+ || $.installed[MODULE_TYPE_HOOK][target]
1599
+ || $.installed[MODULE_TYPE_VALIDATOR][target];
1600
+ }
1601
+
936
1602
  function _isSupportedModuleType(uint256 moduleTypeId) internal pure returns (bool) {
937
1603
  return moduleTypeId == MODULE_TYPE_VALIDATOR
938
1604
  || moduleTypeId == MODULE_TYPE_EXECUTOR
@@ -973,22 +1639,48 @@ contract AgentAccount is
973
1639
  /// EntryPoint / self / DelegationManager; the guard hardens
974
1640
  /// against a malicious target re-entering through one of those
975
1641
  /// callers.
976
- function execute(address target, uint256 value, bytes calldata data) external override nonReentrant whenNotPaused {
1642
+ ///
1643
+ /// Slither reports `reentrancy-eth` here because `_delegationExecCtx`
1644
+ /// is written after the external calls. The write is `= false`, and the
1645
+ /// flag is RESTRICTIVE while set: `_rejectDelegatedGovernance` reverts a
1646
+ /// delegation-originated governance self-call only when it is true. A
1647
+ /// reentrant frame therefore observes the *more* restricted state, never
1648
+ /// a bypass — and the only readers of the flag are `execute` (guarded by
1649
+ /// `nonReentrant` on this very function) and `executeBatch`, whose own
1650
+ /// exemption is justified at its declaration. The flag is transient
1651
+ /// (EIP-1153), so it cannot survive the transaction either.
1652
+ // slither-disable-next-line reentrancy-eth
1653
+ function execute(address target, uint256 value, bytes calldata data) external override nonReentrant {
1654
+ // R6.5 pause gate, with the spec 445 §1.2 exemptions (governance, its timelock, the recovery
1655
+ // allow-list on self) — see `_requireExecutableUnderPause`. Runs first, as the modifier did.
1656
+ _requireExecutableUnderPause(target, data);
977
1657
  _requireForExecute();
978
1658
 
979
- ModulesStorage storage $ = _modulesStorage();
980
- address[] memory hooks = $.installedList[MODULE_TYPE_HOOK];
981
- bytes[] memory hookData = new bytes[](hooks.length);
982
-
983
- // Compose msgData = abi.encodeWithSignature("execute(address,uint256,bytes)", ...)
984
- // so hook policy can decode the inner call. Easier and cheaper than
985
- // forwarding msg.data which includes the selector + ABI tail; we
986
- // rebuild the encoded inner call directly here.
987
- bytes memory hookMsgData = abi.encode(target, value, data);
988
-
989
- for (uint256 i = 0; i < hooks.length; i++) {
990
- hookData[i] = IERC7579HookLike(hooks[i]).preCheck(msg.sender, value, hookMsgData);
991
- }
1659
+ // DM-3 (spec 300): mark a delegation-originated stack (set once at the
1660
+ // outermost DM frame; preserved across a DM → execute(self, executeBatch(...))
1661
+ // nest — which the canonical manager no longer produces (DLG-2 refuses a
1662
+ // self-targeted redemption); kept as defence in depth) and forbid it from
1663
+ // self-calling governance.
1664
+ bool setDelCtx = (msg.sender == _delegationManager && !_delegationExecCtx);
1665
+ if (setDelCtx) _delegationExecCtx = true;
1666
+ _rejectDirectRegistryCall(target);
1667
+ _rejectDelegatedGovernance(target, data);
1668
+ _rejectModuleTarget(target);
1669
+
1670
+ // Hook policy sees the inner call as `abi.encode(target, value, data)`.
1671
+ //
1672
+ // ACCT-13: the ONE call that runs no hook is this account uninstalling a HOOK
1673
+ // (`execute(self, uninstallModule(4, hook, …))`). Hooks run before every call, so a hook whose
1674
+ // `preCheck` reverts (a bug, a dead dependency) would otherwise block the only call that removes it
1675
+ // and brick a self-governed account for good. The skipped call moves nothing: a value-carrying
1676
+ // self-call to a non-payable function reverts.
1677
+ address[] memory hooks;
1678
+ bytes[] memory hookData;
1679
+ if (
1680
+ !(target == address(this) && data.length >= 36
1681
+ && bytes4(data[0:4]) == this.uninstallModule.selector
1682
+ && uint256(bytes32(data[4:36])) == MODULE_TYPE_HOOK)
1683
+ ) (hooks, hookData) = _preHooks(value, abi.encode(target, value, data));
992
1684
 
993
1685
  // Perform the actual call (mirrors BaseAccount.execute body).
994
1686
  (bool ok, bytes memory ret) = target.call{value: value}(data);
@@ -1000,48 +1692,59 @@ contract AgentAccount is
1000
1692
  }
1001
1693
  }
1002
1694
 
1003
- for (uint256 i = 0; i < hooks.length; i++) {
1004
- IERC7579HookLike(hooks[i]).postCheck(hookData[i]);
1005
- }
1695
+ _postHooks(hooks, hookData);
1696
+
1697
+ if (setDelCtx) _delegationExecCtx = false;
1006
1698
  }
1007
1699
 
1008
1700
  /// @notice Atomically execute multiple calls from this account.
1009
1701
  /// @dev Overrides BaseAccount.executeBatch to layer the module-hook
1010
- /// pre/post-check semantics already used by `execute`. Spec 005 —
1011
- /// pledge honor needs `USDC.transfer(pool, amount)` +
1012
- /// `PledgeRegistry.recordHonor(...)` in one atomic operation,
1013
- /// pinned by a `CallDataHashEnforcer` on the redeem path so the
1014
- /// donor's sub-delegation authorises exactly this calldata.
1702
+ /// pre/post-check semantics already used by `execute`. (Spec 005 once
1703
+ /// reached this under a delegation as `execute(self, executeBatch(...))`
1704
+ /// pinned by a `CallDataHashEnforcer`; generation 4 / DLG-2 refuses any
1705
+ /// redemption that targets the root delegator, so a batch is a user
1706
+ /// operation's (or a self-call's) shape only — no caller relied on it.)
1015
1707
  ///
1016
1708
  /// Auth: identical to `execute` — EntryPoint / self / DelegationManager.
1017
1709
  /// Inner calls run with `msg.sender == address(this)`.
1018
1710
  /// All-or-nothing: any inner revert bubbles and reverts the batch.
1019
1711
  /// Pre-hooks run once on the whole batch; post-hooks run on success.
1020
1712
  ///
1021
- /// Spec 007 Phase A.5 — intentionally NOT `nonReentrant`. The
1022
- /// DM redeem flow legitimately calls `account.execute(target=self,
1023
- /// data=executeBatch_calldata)`, which then self-calls into
1024
- /// `executeBatch`. If both functions held the guard, that
1025
- /// pattern would revert with `ReentrancyGuardReentrantCall`. The
1713
+ /// Spec 007 Phase A.5 — intentionally NOT `nonReentrant`. A user
1714
+ /// operation may call `account.execute(target=self,
1715
+ /// data=executeBatch_calldata)` (the DM redeem flow no longer can —
1716
+ /// DLG-2), which then self-calls into `executeBatch`. If both functions
1717
+ /// held the guard, that pattern would revert with `ReentrancyGuardReentrantCall`. The
1026
1718
  /// OUTER `execute` already holds the guard, so external re-entry
1027
1719
  /// is blocked; `_requireForExecute` restricts entry to
1028
1720
  /// EntryPoint / self / DM (DM has its own `nonReentrant`).
1721
+ ///
1722
+ /// Slither reports `reentrancy-eth` here for the same reason as
1723
+ /// `execute`, and it is a false positive for the same reason: the
1724
+ /// post-call write clears `_delegationExecCtx`, a transient flag that
1725
+ /// only ever *adds* a restriction while set. Note this function is
1726
+ /// deliberately un-guarded (see above), so the suppression is scoped to
1727
+ /// this detector on this declaration only — any other high-severity
1728
+ /// finding here still fails the build.
1729
+ // slither-disable-next-line reentrancy-eth
1029
1730
  function executeBatch(Call[] calldata calls) external override whenNotPaused {
1030
1731
  _requireForExecute();
1031
1732
 
1032
- ModulesStorage storage $ = _modulesStorage();
1033
- address[] memory hooks = $.installedList[MODULE_TYPE_HOOK];
1034
- bytes[] memory hookData = new bytes[](hooks.length);
1035
-
1036
- // hookMsgData encodes the full batch so hook policy can inspect
1037
- // every inner call.
1038
- bytes memory hookMsgData = abi.encode(calls);
1733
+ // DM-3 (spec 300): same delegation-origin marking as `execute`. Preserved
1734
+ // across a DM → execute(self, executeBatch(...)) nest (defence in depth: the
1735
+ // canonical manager refuses that redemption, DLG-2) so a governance
1736
+ // self-call in ANY inner call is caught even though this frame's
1737
+ // msg.sender is address(this).
1738
+ bool setDelCtx = (msg.sender == _delegationManager && !_delegationExecCtx);
1739
+ if (setDelCtx) _delegationExecCtx = true;
1039
1740
 
1040
- for (uint256 i = 0; i < hooks.length; i++) {
1041
- hookData[i] = IERC7579HookLike(hooks[i]).preCheck(msg.sender, 0, hookMsgData);
1042
- }
1741
+ // hookMsgData encodes the full batch so hook policy can inspect every inner call.
1742
+ (address[] memory hooks, bytes[] memory hookData) = _preHooks(0, abi.encode(calls));
1043
1743
 
1044
1744
  for (uint256 i = 0; i < calls.length; i++) {
1745
+ _rejectDirectRegistryCall(calls[i].target);
1746
+ _rejectDelegatedGovernance(calls[i].target, calls[i].data);
1747
+ _rejectModuleTarget(calls[i].target);
1045
1748
  (bool ok, bytes memory ret) = calls[i].target.call{ value: calls[i].value }(calls[i].data);
1046
1749
  if (!ok) {
1047
1750
  assembly {
@@ -1051,9 +1754,9 @@ contract AgentAccount is
1051
1754
  }
1052
1755
  }
1053
1756
 
1054
- for (uint256 i = 0; i < hooks.length; i++) {
1055
- IERC7579HookLike(hooks[i]).postCheck(hookData[i]);
1056
- }
1757
+ _postHooks(hooks, hookData);
1758
+
1759
+ if (setDelCtx) _delegationExecCtx = false;
1057
1760
  }
1058
1761
 
1059
1762
  // ─── ERC-4337 ───────────────────────────────────────────────────
@@ -1077,14 +1780,143 @@ contract AgentAccount is
1077
1780
  }
1078
1781
 
1079
1782
  /// @dev Allow execution from EntryPoint, account itself (via UserOp), or DelegationManager (ERC-7710)
1783
+ /// @dev Spec 445 §1.3 (ii) (audit H-2 / ACCT-1): the delegation manager is honoured only while it is
1784
+ /// CURRENT — the factory's canonical one, or one set / re-affirmed under the current custody epoch.
1785
+ /// A manager a since-retired credential swapped in is refused here, on both `execute` and
1786
+ /// `executeBatch`, with no further state to clear.
1080
1787
  function _requireForExecute() internal view override {
1788
+ if (msg.sender == address(entryPoint()) || msg.sender == address(this)) return;
1789
+ if (msg.sender == _delegationManager) {
1790
+ if (!_delegationManagerCurrent()) revert DelegationManagerEpochLapsed(msg.sender);
1791
+ return;
1792
+ }
1793
+ revert NotFromEntryPoint(msg.sender, address(this), address(entryPoint()));
1794
+ }
1795
+
1796
+ // ─── Wave 1 — account authorization boundary (spec 300) ─────────
1797
+
1798
+ /// @dev True when this account is custody-governed — i.e. the canonical
1799
+ /// CustodyPolicy the factory installs for `mode > 0` accounts is installed
1800
+ /// as an EXECUTOR here. Governance mutators then require the
1801
+ /// `executeFromModule` (quorum+timelock) path. A `mode 0` person account
1802
+ /// (no CustodyPolicy) self-governs; installing an UNRELATED utility executor
1803
+ /// does NOT make it custody-governed (we check the specific policy address,
1804
+ /// not "any executor"). If the factory is unknown (legacy direct deploy),
1805
+ /// fall back to person semantics.
1806
+ function _hasCustodyGovernance() internal view returns (bool) {
1807
+ address f = _factory;
1808
+ if (f == address(0)) return false;
1809
+ address cp = IAgentAccountFactoryView(f).custodyPolicy();
1810
+ if (cp == address(0)) return false;
1811
+ return _modulesStorage().installed[MODULE_TYPE_EXECUTOR][cp];
1812
+ }
1813
+
1814
+ /// @dev ACCT-C1 gate: on a custody-governed account, a governance mutator is
1815
+ /// reachable only through `executeFromModule` (which sets `_custodyGovCtx`).
1816
+ /// A single-signer UserOp `execute(self, adminSelector)` self-call leaves the
1817
+ /// flag unset and reverts here, so the custody quorum can no longer be bypassed.
1818
+ function _requireCustodyGoverned() internal view {
1819
+ if (_hasCustodyGovernance() && !_custodyGovCtx) revert AdminRequiresCustodyQuorum();
1820
+ }
1821
+
1822
+ /// @dev DM-3 gate: a delegation-originated stack may never self-call an account
1823
+ /// governance selector. `_delegationExecCtx` is set at the outermost
1824
+ /// DM-driven `execute`/`executeBatch` and persists across a
1825
+ /// `DM → execute(self, executeBatch(...))` nest (refused by the canonical manager since
1826
+ /// generation 4 / DLG-2; kept as defence in depth), so a nested governance
1827
+ /// self-call is caught regardless of mode.
1828
+ function _rejectDelegatedGovernance(address target, bytes calldata data) internal view {
1829
+ if (!_delegationExecCtx) return;
1081
1830
  if (
1082
- msg.sender != address(entryPoint()) &&
1083
- msg.sender != address(this) &&
1084
- msg.sender != _delegationManager
1831
+ target == address(this) &&
1832
+ data.length >= 4 &&
1833
+ _isGovernanceSelector(bytes4(data[0:4]))
1085
1834
  ) {
1086
- revert NotFromEntryPoint(msg.sender, address(this), address(entryPoint()));
1835
+ revert DelegatedGovernanceForbidden();
1087
1836
  }
1837
+ // R917-C-1/C-2 (spec 408 §1.1): a delegation stack may not speak AS THE ACCOUNT to the account's own
1838
+ // custody-tier contracts. `CustodyPolicy` and `ApprovedHashRegistry` treat `msg.sender == account` as
1839
+ // the principal — a delegate reaching them through `execute` would uninstall the custody policy
1840
+ // (bricking the account) or plant approved-hash root delegations that outlive the delegate's own
1841
+ // caveats. Any selector: there is no legitimate delegated call to either.
1842
+ // Spec 445 §1.5 / ACCT-3: the same holds for EVERY installed module — a hook keys its state by
1843
+ // `msg.sender == account` exactly as the custody policy does (a delegate that could call
1844
+ // `TreasurySpendPolicy.onUninstall` as the treasury removed the treasury's ceiling).
1845
+ if (_isAccountTrustedTarget(target)) revert DelegatedGovernanceForbidden();
1846
+ }
1847
+
1848
+ /// @dev Spec 445 §1.5 / ACCT-3 — outside a delegation (that case is `_rejectDelegatedGovernance`): on a
1849
+ /// CUSTODY-GOVERNED account an installed module is never an `execute` / `executeBatch` target. Those
1850
+ /// two doors open to a single custodian's user operation, which is below the custody tier there;
1851
+ /// the quorum reaches a module through the custody policy's own actions (`executeFromModule`) and
1852
+ /// a module's lifecycle callbacks only through `installModule` / `uninstallModule`.
1853
+ ///
1854
+ /// ONE EXCEPTION, deliberate: the canonical custody policy itself stays a valid target. Its
1855
+ /// `scheduleCustodyChange` / `applyCustodyChange` / `cancelScheduledChange` are authorized by the
1856
+ /// quorum signatures they carry and do not care who submits them — a passkey-only person submits
1857
+ /// them as a user operation from the very account they govern, and refusing that would leave her
1858
+ /// dependent on a relayer to change her own custody. The two entry points where the policy DOES
1859
+ /// take `msg.sender == account` as principal defend themselves (`onInstall`: NotInstalledAsExecutorOn
1860
+ /// / AlreadyInstalledOn; `onUninstall`: StillInstalledOn, R917-C-1).
1861
+ ///
1862
+ /// A self-governed (mode-0) account's one credential IS its custody tier — it can install and
1863
+ /// uninstall — so the rule adds nothing there and is not applied; a hook defends its own
1864
+ /// `onInstall` / `onUninstall` on every mode.
1865
+ function _rejectModuleTarget(address target) internal view {
1866
+ if (_delegationExecCtx || _custodyGovCtx) return; // refused already (delegation) / the quorum itself
1867
+ address f = _factory;
1868
+ if (f == address(0)) return;
1869
+ address cp = IAgentAccountFactoryView(f).custodyPolicy();
1870
+ if (cp == address(0) || !_modulesStorage().installed[MODULE_TYPE_EXECUTOR][cp]) return; // self-governed
1871
+ if (target != cp && _isInstalledModule(target)) revert ModuleNotAnExecuteTarget(target);
1872
+ }
1873
+
1874
+ /// @dev Spec 410 §1 (THESIS-1a). `ApprovedHashRegistry.approveHash` stores whatever 32 bytes the account
1875
+ /// sends, and the custody epoch is public — so a custodian who could reach the registry through
1876
+ /// `execute` could approve `keccak256(abi.encode(h, epoch + 1))`: inert now, live the moment a
1877
+ /// recovery bumps the epoch to expel that very custodian. Closing it: the registry is never an
1878
+ /// execute target; the account derives the key on chain in `approveDigest`, under the epoch it is
1879
+ /// in, and nowhere else. Unconditional — not only under the delegation context (R917-C-1/C-2).
1880
+ function _rejectDirectRegistryCall(address target) internal view {
1881
+ if (target == _approvedHashRegistry && target != address(0)) revert ApprovedHashRegistryOnlyViaAccount();
1882
+ }
1883
+
1884
+ /// @dev The contracts that take THIS ACCOUNT as principal when it is `msg.sender` — reachable only from
1885
+ /// the account's own governance paths (`uninstallModule`, a custodian-signed userOp), never from a
1886
+ /// delegation. The custody policy is read from the factory (the canonical one; a legacy direct
1887
+ /// deploy with no factory has none); the registry is the immutable this account was built with.
1888
+ function _isAccountTrustedTarget(address target) internal view returns (bool) {
1889
+ if (target == _approvedHashRegistry && target != address(0)) return true;
1890
+ if (_isInstalledModule(target)) return true;
1891
+ address f = _factory;
1892
+ if (f == address(0)) return false;
1893
+ address cp = IAgentAccountFactoryView(f).custodyPolicy();
1894
+ return cp != address(0) && target == cp;
1895
+ }
1896
+
1897
+ /// @dev The account-governance selector set — mutators that change custody,
1898
+ /// the DelegationManager, installed modules, or the upgrade path. Kept in
1899
+ /// sync with the `_requireCustodyGoverned`-gated functions above.
1900
+ function _isGovernanceSelector(bytes4 s) internal pure returns (bool) {
1901
+ return
1902
+ s == this.setDelegationManager.selector ||
1903
+ s == UUPSUpgradeable.upgradeToAndCall.selector ||
1904
+ s == this.setUpgradeTimelock.selector ||
1905
+ s == this.scheduleUpgrade.selector ||
1906
+ s == this.executePendingUpgrade.selector ||
1907
+ s == this.cancelPendingUpgrade.selector ||
1908
+ s == this.installModule.selector ||
1909
+ s == this.uninstallModule.selector ||
1910
+ s == this.reaffirmModule.selector ||
1911
+ s == this.reaffirmDelegationManager.selector ||
1912
+ s == IAgentAccount.addCustodian.selector ||
1913
+ s == IAgentAccount.removeCustodian.selector ||
1914
+ s == this.addPasskey.selector ||
1915
+ s == this.removePasskey.selector ||
1916
+ s == this.acceptSessionDelegation.selector ||
1917
+ s == this.approveDigest.selector ||
1918
+ s == this.revokeDigest.selector ||
1919
+ s == this.revokeAllApprovedDigests.selector;
1088
1920
  }
1089
1921
 
1090
1922
  // ─── ERC-1271 ───────────────────────────────────────────────────
@@ -1109,9 +1941,11 @@ contract AgentAccount is
1109
1941
  // branch is unreachable from `_validateSignature`/`_validateSig`
1110
1942
  // (the userOp-auth path), where 0x03 is an unknown type → false.
1111
1943
  // Fails CLOSED if the registry is unset/not-a-contract (ADR-0013).
1944
+ // R917-C-2: the registry is consulted for the EPOCH-BOUND key, never the raw hash — an approval
1945
+ // made under a custody set that has since retired a credential is not this account's approval.
1112
1946
  if (signature.length == 1 && uint8(signature[0]) == SIG_TYPE_APPROVED_HASH) {
1113
1947
  if (_approvedHashRegistry.code.length == 0) return bytes4(0xffffffff);
1114
- return IApprovedHashRegistryView(_approvedHashRegistry).isApproved(address(this), hash)
1948
+ return IApprovedHashRegistryView(_approvedHashRegistry).isApproved(address(this), approvedHashKey(hash))
1115
1949
  ? ERC1271_MAGIC_VALUE
1116
1950
  : bytes4(0xffffffff);
1117
1951
  }
@@ -1203,53 +2037,35 @@ contract AgentAccount is
1203
2037
  * revert during validation as a banned account — much worse
1204
2038
  * than a clean "this sig is invalid" return.
1205
2039
  *
1206
- * Solidity can't try/catch an internal `abi.decode`, so we
1207
- * route the decode through an external self-call (which CAN
1208
- * be try/catch'd). Gas overhead is ~700 in the success path;
1209
- * the security win is bounded reverts.
2040
+ * The decode runs in an external call (which CAN be
2041
+ * try/catch'd) — since spec 449 the call is to
2042
+ * `signatureVerifier`, which replaced the self-call
2043
+ * `decodeWebAuthnAssertion`.
1210
2044
  */
1211
2045
  function _verifyWebAuthn(bytes32 hash, bytes memory payload) internal view returns (bool) {
1212
- try this.decodeWebAuthnAssertion(payload) returns (WebAuthnLib.Assertion memory a) {
2046
+ // Spec 449: decoding and verification run in `signatureVerifier` (stateless; this implementation's own).
2047
+ // Any revert there — a payload that does not decode, or anything else — is "invalid", never a revert out
2048
+ // of validation (audit C-7; C1-8).
2049
+ SignatureVerifier v = SignatureVerifier(signatureVerifier);
2050
+ try v.credentialOf(payload) returns (bytes32 cid) {
1213
2051
  PasskeyStorage storage $ = _passkeyStorage();
1214
- PasskeyEntry storage key = $.keys[a.credentialIdDigest];
2052
+ PasskeyEntry storage key = $.keys[cid];
1215
2053
  if (key.x == 0 && key.y == 0) return false;
1216
2054
  // H7-C.1 / CON-WEBAUTHN-001: pin per-credential rpIdHash + require UP.
1217
- // R8.2 / ATL-SEC-03: require UV (User Verification) at the library
1218
- // layer. Wave H1 made the JS-side ceremony pass
1219
- // `userVerification: 'required'` for custody-grade flows
1220
- // (demo-sso, demo-sso-next, demo-org, demo-web-recovery); the
1221
- // third-party audit (2026-05-31) correctly observed that the
1222
- // contract still passed `requireUv: false` here. That meant a
1223
- // permissive authenticator could produce a UP-only assertion
1224
- // and we'd accept it. R8.2 makes UV strictly required on every
1225
- // ERC-1271 verify. Browser ceremonies that pass
1226
- // `userVerification: 'preferred'` will be REJECTED at the
1227
- // signature step — those apps (demo-web, demo-web-pro) MUST
1228
- // upgrade to `'required'` for production deployments. Tests
1229
- // exercising lower-assurance flows can install a separate
1230
- // passkey-validator module that relaxes this check.
1231
- bytes32 rpIdHash = $.rpIdHashOf[a.credentialIdDigest];
2055
+ // R8.2 / ATL-SEC-03: User Verification is required on every verify (`verifyWebAuthn` passes
2056
+ // `requireUv = true`); a lower-assurance flow installs a separate validator module.
2057
+ bytes32 rpIdHash = $.rpIdHashOf[cid];
1232
2058
  if (rpIdHash == bytes32(0)) return false;
1233
- return WebAuthnLib.verify(a, hash, key.x, key.y, rpIdHash, /*requireUv*/ true);
2059
+ try v.verifyWebAuthn(payload, hash, key.x, key.y, rpIdHash) returns (bool ok) {
2060
+ return ok;
2061
+ } catch {
2062
+ return false;
2063
+ }
1234
2064
  } catch {
1235
2065
  return false;
1236
2066
  }
1237
2067
  }
1238
2068
 
1239
- /**
1240
- * @notice External decoder wrapper used by `_verifyWebAuthn` to
1241
- * bound `abi.decode` reverts. MUST stay `external` so the
1242
- * caller can wrap it in `try { … } catch { … }`. Marked
1243
- * pure — no state access, just decode.
1244
- */
1245
- function decodeWebAuthnAssertion(bytes calldata payload)
1246
- external
1247
- pure
1248
- returns (WebAuthnLib.Assertion memory)
1249
- {
1250
- return abi.decode(payload, (WebAuthnLib.Assertion));
1251
- }
1252
-
1253
2069
  // ─── Owner Management ───────────────────────────────────────────
1254
2070
 
1255
2071
  /// @inheritdoc IAgentAccount
@@ -1271,6 +2087,19 @@ contract AgentAccount is
1271
2087
  return _passkeyStorage().piaToCredentialId[account] != bytes32(0);
1272
2088
  }
1273
2089
 
2090
+ /// @notice EXT-ISCUSTODIAN-1 (2026-07-05 audit): like `isCustodian` but EXCLUDES the account itself.
2091
+ /// @dev `isCustodian(address(this)) == true` is deliberate (account-actor compatibility), but that
2092
+ /// footgun can recreate the ACCT-C2 quorum-collapse class in a FUTURE consumer that reuses
2093
+ /// `isCustodian` as if it meant "external signer." Any quorum / authority consumer that must count
2094
+ /// only real external custodians / passkeys (never the account) should use THIS view. ACCT-C2 fixed
2095
+ /// the current CustodyPolicy quorum at the counting site (reject signer==account); this gives new
2096
+ /// consumers the safe primitive so the class can't reappear off-path.
2097
+ function isExternalCustodianOrPasskey(address account) external view returns (bool) {
2098
+ if (account == address(this)) return false;
2099
+ if (_externalCustodians[account]) return true;
2100
+ return _passkeyStorage().piaToCredentialId[account] != bytes32(0);
2101
+ }
2102
+
1274
2103
  /// @inheritdoc IAgentAccount
1275
2104
  /// @dev Counts EOA/contract custodians PLUS registered passkeys —
1276
2105
  /// each passkey contributes one PIA-custodian. Matches the
@@ -1282,15 +2111,23 @@ contract AgentAccount is
1282
2111
  }
1283
2112
 
1284
2113
  /// @notice Deterministically derive the Passkey-Identity-Address for
1285
- /// a P-256 public key. Exposed as `pure` so off-chain code +
1286
- /// other contracts (CustodyPolicy, factory) can recompute it
1287
- /// without reading account state.
1288
- function passkeyIdentity(uint256 x, uint256 y) public pure returns (address) {
2114
+ /// a P-256 public key ON THIS ACCOUNT. Spec 302 W2: the PIA is
2115
+ /// account-scoped — `keccak256(abi.encode(x, y, address(this)))` —
2116
+ /// so the same physical passkey yields a DIFFERENT custodian
2117
+ /// address on every account it custodies. The pre-302 global
2118
+ /// derivation (`keccak256(abi.encode(x, y))`) made the PIA a
2119
+ /// public cross-account join key: one `CustodianAdded(pia)` log
2120
+ /// scan clustered a person's SA with every org/treasury SA their
2121
+ /// root passkey controls. Off-chain mirror: account-custody
2122
+ /// `passkeyIdentity(x, y, account)`; the v=2 signature slot
2123
+ /// verifier (SignatureSlotRecovery) re-derives with the same
2124
+ /// account scope.
2125
+ function passkeyIdentity(uint256 x, uint256 y) public view returns (address) {
1289
2126
  return _passkeyIdentity(x, y);
1290
2127
  }
1291
2128
 
1292
- function _passkeyIdentity(uint256 x, uint256 y) internal pure returns (address) {
1293
- return address(uint160(uint256(keccak256(abi.encode(x, y)))));
2129
+ function _passkeyIdentity(uint256 x, uint256 y) internal view returns (address) {
2130
+ return address(uint160(uint256(keccak256(abi.encode(x, y, address(this))))));
1294
2131
  }
1295
2132
 
1296
2133
  /// @inheritdoc IAgentAccount
@@ -1300,6 +2137,7 @@ contract AgentAccount is
1300
2137
  /// the ERC-165 marker. Passkey custodians are not added here;
1301
2138
  /// use `addPasskey` instead.
1302
2139
  function addCustodian(address owner) external override onlySelf whenNotPaused {
2140
+ _requireCustodyGoverned();
1303
2141
  if (owner == address(0)) revert ZeroAddress();
1304
2142
  if (_externalCustodians[owner]) revert CustodianAlreadyExists(owner);
1305
2143
  if (_isAgenticPrimitivesAgent(owner)) {
@@ -1343,11 +2181,13 @@ contract AgentAccount is
1343
2181
  /// owner if there are also no registered passkeys. A passkey-only
1344
2182
  /// account is allowed, but a zero-signer account is not.
1345
2183
  function removeCustodian(address owner) external override onlySelf {
2184
+ _requireCustodyGoverned();
1346
2185
  if (!_externalCustodians[owner]) revert CustodianDoesNotExist(owner);
1347
2186
  if (_externalCustodianCount == 1 && _passkeyStorage().count == 0) revert CannotRemoveLastCustodian();
1348
2187
  _externalCustodians[owner] = false;
1349
2188
  _externalCustodianCount--;
1350
2189
  emit CustodianRemoved(owner);
2190
+ _bumpCustodyEpoch();
1351
2191
  }
1352
2192
 
1353
2193
  // ─── Passkey (WebAuthn P-256) management ──────────────────────
@@ -1387,8 +2227,24 @@ contract AgentAccount is
1387
2227
  assembly { $.slot := slot }
1388
2228
  }
1389
2229
 
1390
- event PasskeyAdded(bytes32 indexed credentialIdDigest, uint256 x, uint256 y, bytes32 rpIdHash);
2230
+ /// @dev Spec 302 W1 — the event carries ONLY the credential digest. The raw
2231
+ /// P256 coordinates and rpIdHash were removed: identical (x, y) across
2232
+ /// accounts let any log indexer cluster every SA one physical passkey
2233
+ /// custodies (publicly defeating ADR-0025's person↔org privacy), and
2234
+ /// sha256(rpId) is a guessable-preimage domain disclosure. Coordinates
2235
+ /// remain in storage — the ONE read path is `getPasskey(credentialIdDigest)`
2236
+ /// (ADR-0012/0013; INV-302-3).
2237
+ event PasskeyAdded(bytes32 indexed credentialIdDigest);
1391
2238
  event PasskeyRemoved(bytes32 indexed credentialIdDigest);
2239
+ /// @dev R917-C-2 — a credential was retired; every approved hash keyed to the previous epoch is void.
2240
+ event CustodyEpochBumped(uint64 epoch);
2241
+ /// @dev Spec 410 §1 — `digest` approved under `epoch` through the account's own key derivation.
2242
+ event DigestApproved(bytes32 indexed digest, uint64 epoch);
2243
+ event DigestRevoked(bytes32 indexed digest, uint64 epoch);
2244
+ /// @dev Spec 410 §1 — every approval this account ever made is void (registry-side epoch bump).
2245
+ event AllDigestsRevoked();
2246
+ /// @notice Spec 447 — the account now reads its system addresses from `newFactory`.
2247
+ event FactoryMigrated(address indexed oldFactory, address indexed newFactory);
1392
2248
 
1393
2249
  /// @notice Register a new WebAuthn credential bound to a specific RP.
1394
2250
  /// `onlySelf` — callable via a UserOp signed by any existing signer
@@ -1407,6 +2263,7 @@ contract AgentAccount is
1407
2263
  uint256 y,
1408
2264
  bytes32 rpIdHash
1409
2265
  ) external onlySelf {
2266
+ _requireCustodyGoverned();
1410
2267
  if (x == 0 || y == 0) revert InvalidPasskeyPublicKey();
1411
2268
  // Audit C-6: zero digest poisons piaToCredentialId mapping.
1412
2269
  if (credentialIdDigest == bytes32(0)) revert InvalidCredentialIdDigest();
@@ -1422,7 +2279,7 @@ contract AgentAccount is
1422
2279
  $.piaToCredentialId[pia] = credentialIdDigest;
1423
2280
  $.rpIdHashOf[credentialIdDigest] = rpIdHash;
1424
2281
  $.count += 1;
1425
- emit PasskeyAdded(credentialIdDigest, x, y, rpIdHash);
2282
+ emit PasskeyAdded(credentialIdDigest);
1426
2283
  emit CustodianAdded(pia);
1427
2284
  }
1428
2285
 
@@ -1431,6 +2288,7 @@ contract AgentAccount is
1431
2288
  /// AND passkeys together. Also clears the credential's PIA
1432
2289
  /// entry so `isCustodian(pia)` flips back to false.
1433
2290
  function removePasskey(bytes32 credentialIdDigest) external onlySelf {
2291
+ _requireCustodyGoverned();
1434
2292
  PasskeyStorage storage $ = _passkeyStorage();
1435
2293
  if (!$.registered[credentialIdDigest]) revert PasskeyNotRegistered(credentialIdDigest);
1436
2294
  if (_externalCustodianCount + $.count == 1) revert CannotRemoveLastSigner();
@@ -1443,6 +2301,7 @@ contract AgentAccount is
1443
2301
  $.count -= 1;
1444
2302
  emit PasskeyRemoved(credentialIdDigest);
1445
2303
  emit CustodianRemoved(pia);
2304
+ _bumpCustodyEpoch();
1446
2305
  }
1447
2306
 
1448
2307
  /// @notice Whether a passkey is registered on this account.
@@ -1456,11 +2315,109 @@ contract AgentAccount is
1456
2315
  return (k.x, k.y);
1457
2316
  }
1458
2317
 
2318
+ /// @notice Read the RP-ID hash a credential was registered against.
2319
+ /// @dev Spec 302 W1 (INV-302-3): the slimmed `PasskeyAdded` event no longer
2320
+ /// carries `rpIdHash`; this getter is the ONE read path for it
2321
+ /// (ADR-0012/0013 — `readContract`, no log walking).
2322
+ function getPasskeyRpIdHash(bytes32 credentialIdDigest) external view returns (bytes32) {
2323
+ return _passkeyStorage().rpIdHashOf[credentialIdDigest];
2324
+ }
2325
+
1459
2326
  /// @notice Total count of registered passkeys.
1460
2327
  function passkeyCount() external view returns (uint256) {
1461
2328
  return _passkeyStorage().count;
1462
2329
  }
1463
2330
 
2331
+ // ─── Custody epoch (R917-C-2, spec 408 §1.2) ─────────────────────
2332
+
2333
+ /// @notice The current custody epoch — bumped whenever a credential is retired.
2334
+ function custodyEpoch() external view returns (uint64) {
2335
+ return _custodyEpoch;
2336
+ }
2337
+
2338
+ /// @notice THE KEY an SDK approves in the `ApprovedHashRegistry` for `hash` to validate through this
2339
+ /// account's `0x03` sentinel NOW: `keccak256(abi.encode(hash, custodyEpoch))`. A counterfactual
2340
+ /// account (not yet deployed) is at epoch 0, so its key is computable before deploy — which is
2341
+ /// what spec 253's batched deploy-and-approve relies on.
2342
+ function approvedHashKey(bytes32 hash) public view returns (bytes32) {
2343
+ return keccak256(abi.encode(hash, _custodyEpoch));
2344
+ }
2345
+
2346
+ /// @dev Retire-a-credential paths call this; see `_custodyEpoch`.
2347
+ /// Spec 445 §1.3 (ii): the bump is what expels everything a retired credential could have
2348
+ /// installed — approved hashes (R917-C-2), non-canonical executor modules (`_moduleEpochStamp`), a
2349
+ /// non-canonical delegation manager (`_delegationManagerEpochStamp`) — because each is honoured only
2350
+ /// under the epoch it was made in. The one thing not keyed to the epoch is the upgrade queue, so it
2351
+ /// is cleared here: `executePendingUpgrade` is permissionless once matured, and an upgrade queued by
2352
+ /// the credential being retired must not fire after it is gone. The owner re-queues if she wants it.
2353
+ function _bumpCustodyEpoch() internal {
2354
+ uint64 next = _custodyEpoch + 1;
2355
+ _custodyEpoch = next;
2356
+ _epochBumpedThisTx = true;
2357
+ emit CustodyEpochBumped(next);
2358
+ address pending = _pendingUpgrade.newImplementation;
2359
+ if (_pendingUpgrade.readyAt != 0) {
2360
+ delete _pendingUpgrade;
2361
+ emit UpgradeCancelled(pending);
2362
+ }
2363
+ }
2364
+
2365
+ // ─── Approved digests (spec 410 §1, THESIS-1a) ───────────────────
2366
+
2367
+ /// @notice Approve `digest` for this account's `0x03` sentinel under the epoch the account is IN. The
2368
+ /// only path to the registry (`execute` refuses it as a target), so the key is never computed
2369
+ /// by a caller and never for an epoch other than the current one. `onlySelf`, not
2370
+ /// custody-gated: spec 253's one-prompt org-create batches it into the deploy userOp under the
2371
+ /// creating custodian, and the epoch (R917-C-2) plus `revokeAllApprovedDigests` on every
2372
+ /// recovery path (spec 410 §1.2) close the persistence risk instead. A delegation stack cannot
2373
+ /// reach it (`_isGovernanceSelector`).
2374
+ /// On a custody-governed account no approval is made after a custody-epoch bump in the same
2375
+ /// transaction except by the custody policy itself (`RotateCredential`'s re-approval list): a user
2376
+ /// operation validates before it executes, so a custodian being retired or recovered away could
2377
+ /// otherwise wrap the quorum's applied change in her own batch and approve under the NEW epoch after
2378
+ /// she is out (audit 2026-12-02 H-2 / THESIS-1a). Transient, so it covers every later operation of
2379
+ /// the same bundle too. A mode-0 account rotates in its own batch and is not affected.
2380
+ function approveDigest(bytes32 digest) external onlySelf {
2381
+ if (_approvedHashRegistry == address(0)) revert ApprovedHashRegistryOnlyViaAccount();
2382
+ if (approvalRefused()) revert ApprovalAfterCustodyChange();
2383
+ // The registry derives the key under this account's current epoch itself (audit 2026-12-02 H-2).
2384
+ IApprovedHashRegistryWrite(_approvedHashRegistry).approveHash(digest);
2385
+ emit DigestApproved(digest, _custodyEpoch);
2386
+ }
2387
+
2388
+ /// @notice Whether an approval made by this account NOW would be refused: a custody-governed account whose
2389
+ /// custody epoch was bumped, or which completed its move to this generation, earlier in this
2390
+ /// transaction, outside the custody policy's own call. `approveDigest` refuses on it, and the
2391
+ /// `ApprovedHashRegistry` asks it of every account signer, so an approval sent to the registry
2392
+ /// directly (a still-running generation-4 call frame after the move) is refused the same way.
2393
+ function approvalRefused() public view returns (bool) {
2394
+ return _epochBumpedThisTx && !_custodyGovCtx && _hasCustodyGovernance();
2395
+ }
2396
+
2397
+ /// @notice Revoke one approval made under the current epoch.
2398
+ function revokeDigest(bytes32 digest) external onlySelf {
2399
+ if (_approvedHashRegistry == address(0)) revert ApprovedHashRegistryOnlyViaAccount();
2400
+ IApprovedHashRegistryWrite(_approvedHashRegistry).revokeHash(digest);
2401
+ emit DigestRevoked(digest, _custodyEpoch);
2402
+ }
2403
+
2404
+ /// @notice Void EVERY approval this account ever made, under any epoch — including one planted for a
2405
+ /// future epoch before this contract generation refused direct registry calls. `CustodyPolicy`
2406
+ /// calls it as the last step of every recovery path; a custody-governed account reaches it
2407
+ /// only through the module (`_requireCustodyGoverned`), a mode-0 person through her own userOp.
2408
+ /// Recovery re-approves nothing: the person re-issues from a reviewed list (spec 410 §1.2).
2409
+ function revokeAllApprovedDigests() external onlySelf {
2410
+ _requireCustodyGoverned();
2411
+ _revokeAllApproved();
2412
+ }
2413
+
2414
+ /// @dev No registry wired: nothing was ever approvable (the sentinel fails closed), so there is nothing to
2415
+ /// void — a no-op, never a revert, so a recovery or a move on such an account still completes.
2416
+ function _revokeAllApproved() internal {
2417
+ if (_approvedHashRegistry != address(0)) IApprovedHashRegistryWrite(_approvedHashRegistry).revokeAll();
2418
+ emit AllDigestsRevoked();
2419
+ }
2420
+
1464
2421
  // ─── Custody policy + scheduled changes ───────────────────────────
1465
2422
  //
1466
2423
  // The schedule / apply / cancel custody-change surface, CustodyAction