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

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 (82) hide show
  1. package/AUDIT.md +60 -26
  2. package/deployments-base-sepolia.json +2 -0
  3. package/deployments-faithchain.json +2 -0
  4. package/deployments-hopechain.json +2 -0
  5. package/dist/abi/AgentAccount.json +175 -0
  6. package/dist/abi/AgentAccountFactory.json +47 -0
  7. package/dist/abi/AgentNameAttributeResolver.json +24 -0
  8. package/dist/abi/AgentNameRegistry.json +369 -0
  9. package/dist/abi/AgentNameUniversalResolver.json +34 -0
  10. package/dist/abi/AgentProfileResolver.json +48 -0
  11. package/dist/abi/AgentRegistryBase.json +158 -0
  12. package/dist/abi/AgentRelationship.json +212 -0
  13. package/dist/abi/AgreementRegistry.json +10 -0
  14. package/dist/abi/AttestationRegistry.json +49 -0
  15. package/dist/abi/AttributeStorage.json +24 -0
  16. package/dist/abi/CustodyPolicy.json +184 -0
  17. package/dist/abi/DelegationManager.json +96 -0
  18. package/dist/abi/DigestBindingEnforcer.json +103 -1
  19. package/dist/abi/EstateProjectionRegistry.json +137 -24
  20. package/dist/abi/GeoFeatureRegistry.json +42 -0
  21. package/dist/abi/IAgentAccountFactoryView.json +13 -0
  22. package/dist/abi/IAgentAccountGovernanceTimelockView.json +15 -0
  23. package/dist/abi/ICustodyPolicyFactoryView.json +13 -0
  24. package/dist/abi/ICustodyPolicyPasskeyView.json +50 -0
  25. package/dist/abi/IRedemptionContext.json +15 -0
  26. package/dist/abi/ITreasurySpendPolicyAccountView.json +44 -0
  27. package/dist/abi/IUpgradeVoucherView.json +26 -0
  28. package/dist/abi/OntologyTermRegistry.json +57 -0
  29. package/dist/abi/PaymentEnforcer.json +10 -0
  30. package/dist/abi/PermissionlessSubregistry.json +165 -0
  31. package/dist/abi/PricedSubregistry.json +57 -0
  32. package/dist/abi/RelationshipTypeRegistry.json +57 -0
  33. package/dist/abi/ShapeRegistry.json +57 -0
  34. package/dist/abi/SkillDefinitionRegistry.json +42 -0
  35. package/dist/abi/TreasurySpendPolicy.json +106 -1
  36. package/dist/abi/UpgradeVoucher.json +176 -0
  37. package/dist/abi/index.d.ts +6 -0
  38. package/dist/abi/index.js +6 -0
  39. package/dist/deployments/base-sepolia.d.ts +2 -0
  40. package/dist/deployments/base-sepolia.js +4 -0
  41. package/dist/deployments/faithchain.d.ts +2 -0
  42. package/dist/deployments/faithchain.js +4 -0
  43. package/dist/deployments/hopechain.d.ts +2 -0
  44. package/dist/deployments/hopechain.js +4 -0
  45. package/package.json +1 -1
  46. package/src/AgentAccount.sol +531 -92
  47. package/src/AgentAccountFactory.sol +28 -2
  48. package/src/IAgentAccount.sol +14 -0
  49. package/src/SmartAgentPaymaster.sol +30 -3
  50. package/src/UpgradeVoucher.sol +74 -0
  51. package/src/agency/DelegationManager.sol +177 -52
  52. package/src/agency/ICaveatEnforcer.sol +10 -0
  53. package/src/agency/IDelegationManager.sol +6 -5
  54. package/src/agreement/AgreementRegistry.sol +61 -17
  55. package/src/attestation/AttestationRegistry.sol +115 -22
  56. package/src/custody/CustodyPolicy.sol +393 -47
  57. package/src/custody/TreasurySpendPolicy.sol +192 -29
  58. package/src/enforcers/AllowedMethodsEnforcer.sol +6 -1
  59. package/src/enforcers/AllowedTargetsEnforcer.sol +6 -1
  60. package/src/enforcers/DigestBindingEnforcer.sol +91 -19
  61. package/src/enforcers/PaymentEnforcer.sol +32 -1
  62. package/src/enforcers/QuorumEnforcer.sol +1 -1
  63. package/src/enforcers/ValueEnforcer.sol +6 -1
  64. package/src/geo/GeoFeatureRegistry.sol +25 -1
  65. package/src/governance/AgenticGovernance.sol +16 -0
  66. package/src/identity/AgentProfileResolver.sol +11 -0
  67. package/src/naming/AgentNameAttributeResolver.sol +17 -2
  68. package/src/naming/AgentNamePredicates.sol +1 -1
  69. package/src/naming/AgentNameRegistry.sol +205 -10
  70. package/src/naming/AgentNameUniversalResolver.sol +26 -0
  71. package/src/naming/PermissionlessSubregistry.sol +69 -23
  72. package/src/naming/PricedSubregistry.sol +28 -0
  73. package/src/ontology/AttributeStorage.sol +93 -80
  74. package/src/ontology/OntologyTermRegistry.sol +28 -0
  75. package/src/ontology/ShapeRegistry.sol +28 -0
  76. package/src/payments/PaymentEscrow.sol +23 -15
  77. package/src/payments/PaymentReceiptRegistry.sol +11 -3
  78. package/src/registry/AgentRegistryBase.sol +39 -0
  79. package/src/registry/EstateProjectionRegistry.sol +94 -40
  80. package/src/relationships/AgentRelationship.sol +112 -7
  81. package/src/relationships/RelationshipTypeRegistry.sol +28 -0
  82. package/src/skills/SkillDefinitionRegistry.sol +25 -1
@@ -33,6 +33,22 @@ interface IAgentAccountFactoryView {
33
33
  /// to decide whether IT is custody-governed (its CustodyPolicy is installed)
34
34
  /// vs. merely hosting an unrelated utility executor.
35
35
  function custodyPolicy() external view returns (address);
36
+ /// @dev Spec 445 §1.3 (ii) — the canonical DelegationManager this factory wires into every account it
37
+ /// creates. A delegation manager other than this one is honoured only under the custody epoch it
38
+ /// was set (or re-affirmed) in.
39
+ function delegationManager() external view returns (address);
40
+ }
41
+
42
+ /// @dev Spec 445 §1.2 (a) — the governance contract names its own timelock. Read through the same
43
+ /// `_factory → governance()` hop the pause flag is read through, so nothing an account (or whoever
44
+ /// controls it) can write decides which targets stay reachable under a pause.
45
+ interface IAgentAccountGovernanceTimelockView {
46
+ function timelock() external view returns (address);
47
+ }
48
+
49
+ /// @dev Spec 445 §1.3 (i) — the one read an account makes before it upgrades (`src/UpgradeVoucher.sol`).
50
+ interface IUpgradeVoucherView {
51
+ function isVouched(address implementation, bytes32 dataHash) external view returns (bool);
36
52
  }
37
53
 
38
54
  /// @dev R6.5 — minimal interface for the pause read. Mirrors the same
@@ -110,6 +126,14 @@ contract AgentAccount is
110
126
  /// sentinel fails CLOSED (see `isValidSignature`).
111
127
  address private immutable _approvedHashRegistry;
112
128
 
129
+ /// @dev Spec 445 §1.3 (i) (audit H-2 / ACCT-1) — the `UpgradeVoucher` THIS IMPLEMENTATION consults before
130
+ /// every upgrade. IMMUTABLE: it travels with the implementation, not with the factory, because an
131
+ /// account's `_factory` is set once and an account upgraded in place still names its original
132
+ /// factory. An account's next upgrade is therefore constrained by the voucher of the implementation
133
+ /// it is running NOW. Zero / no code ⇒ every upgrade is refused (fail closed) — see
134
+ /// `upgradeToAndCall` for the migration statement.
135
+ address private immutable _upgradeVoucher;
136
+
113
137
  /// @dev Authorized DelegationManager (ERC-7710 executor)
114
138
  address private _delegationManager;
115
139
 
@@ -187,8 +211,10 @@ contract AgentAccount is
187
211
 
188
212
  /// @dev Wave-1 / DM-3 (spec 300) — transient "this execution stack originated
189
213
  /// from the DelegationManager". Set at the outermost `execute`/`executeBatch`
190
- /// frame whose `msg.sender == _delegationManager`, preserved across the
191
- /// legitimate `DM → execute(self, executeBatch(...))` nest, cleared by the
214
+ /// frame whose `msg.sender == _delegationManager`, preserved across a
215
+ /// `DM → execute(self, executeBatch(...))` nest (no longer produced by the canonical manager:
216
+ /// generation 4 / DLG-2 refuses a redemption whose target is the root delegator; the nesting
217
+ /// logic stays as defence in depth for a non-canonical manager), cleared by the
192
218
  /// frame that set it. While set, a self-targeted governance selector is
193
219
  /// rejected — a delegation may never reach account governance (that is the
194
220
  /// CustodyPolicy's job), regardless of custody mode.
@@ -210,12 +236,30 @@ contract AgentAccount is
210
236
  /// from the gap (49 remain).
211
237
  uint64 private _custodyEpoch;
212
238
 
239
+ /// @dev Spec 445 §1.3 (ii) (audit H-2 / ACCT-1) — what a credential can INSTALL is stamped with the
240
+ /// custody epoch it was installed under, exactly as an approved hash is keyed to its epoch. A module
241
+ /// that can ACT as the account (an EXECUTOR; a validator is stamped too, though this generation never
242
+ /// consults one) is honoured by `executeFromModule` only while `stamp == _custodyEpoch + 1`. The
243
+ /// stored value is `epoch + 1` so an unstamped module (slot 0 — one installed before generation 4, or
244
+ /// written by anything other than `installModule` / `reaffirmModule`) is never current: fail closed.
245
+ /// The factory's canonical `custodyPolicy()` is exempt (it is the custody tier itself, and it is what
246
+ /// performs a recovery). HOOK modules are not stamped and never lapse: a hook is a protection, not a
247
+ /// power — a retirement that silently dropped a spend ceiling would hand the retired credential's
248
+ /// delegates an unbounded treasury. One slot from the gap.
249
+ mapping(address => uint64) private _moduleEpochStamp;
250
+
251
+ /// @dev Spec 445 §1.3 (ii) — the same stamp for the delegation manager: `epoch + 1` at the moment
252
+ /// `setDelegationManager` / `reaffirmDelegationManager` ran (or at `initialize` for a factory-less
253
+ /// account). A delegation manager other than the factory's canonical one may call `execute` /
254
+ /// `executeBatch` only while the stamp is current. One slot from the gap (47 remain).
255
+ uint64 private _delegationManagerEpochStamp;
256
+
213
257
  /// @dev Spec 007 Phase A.5 (SC7 § 3.1) — storage gap reserves 50
214
258
  /// slots after the last linear-layout state variable. Future
215
259
  /// additive upgrades shrink the gap by however many slots they
216
260
  /// add. ERC-7201 namespaced state (passkeys, modules) lives at
217
261
  /// keccak-computed slots and is NOT in this linear layout.
218
- uint256[49] private __gap;
262
+ uint256[47] private __gap;
219
263
 
220
264
  // ─── Errors ─────────────────────────────────────────────────────
221
265
 
@@ -282,6 +326,30 @@ contract AgentAccount is
282
326
  /// `approveDigest` / `revokeDigest` / `revokeAllApprovedDigests`, never as an execute target.
283
327
  error ApprovedHashRegistryOnlyViaAccount();
284
328
 
329
+ // Spec 445 — generation 4.
330
+ /// @notice §1.3 (i): the implementation's `UpgradeVoucher` does not vouch for this
331
+ /// `(newImplementation, keccak256(data))` — or the voucher is unset / has no code / did not answer.
332
+ error UpgradeNotVouched(address newImplementation, bytes32 dataHash);
333
+ /// @notice §1.3 (ii): `module` was installed (or last re-affirmed) under a custody epoch that has since
334
+ /// retired a credential. Re-affirm it (`reaffirmModule`) or uninstall it.
335
+ error ModuleEpochLapsed(address module);
336
+ /// @notice §1.3 (ii): the non-canonical delegation manager was set under a retired custody epoch.
337
+ error DelegationManagerEpochLapsed(address delegationManager);
338
+ /// @notice §1.5 / ACCT-3: an installed module is never an `execute` / `executeBatch` target from below the
339
+ /// custody tier, from a delegation, or from another module. Its lifecycle callbacks are reached
340
+ /// only through `installModule` / `uninstallModule`.
341
+ error ModuleNotAnExecuteTarget(address module);
342
+
343
+ /// @notice §1.3 (ii): `module` re-stamped under `epoch` (it survives the retirement that bumped to it).
344
+ event ModuleReaffirmed(address indexed module, uint64 epoch);
345
+ /// @notice §1.3 (ii): the current delegation manager re-stamped under `epoch`.
346
+ event DelegationManagerReaffirmed(address indexed delegationManager, uint64 epoch);
347
+ /// @notice ACCT-13: a HOOK's `onUninstall` failed; the hook was removed anyway (a hook must not be able
348
+ /// to make its own removal impossible). The hook's own state for this account may be stale.
349
+ event ModuleUninstallCallbackFailed(address indexed module);
350
+ /// @notice ACCT-13: not enough gas to give a hook's `onUninstall` its guaranteed budget — resubmit with more.
351
+ error InsufficientGasForHookUninstall();
352
+
285
353
  /// @notice Emitted when `setDelegationManager` rotates the DM via a
286
354
  /// self-call (the only authorized path post-Wave-2A).
287
355
  event DelegationManagerRotated(address indexed newDelegationManager);
@@ -320,11 +388,15 @@ contract AgentAccount is
320
388
  //
321
389
  // When `AgenticGovernance.isPaused() == true`, every mutating
322
390
  // external entrypoint guarded by this modifier reverts with
323
- // `SystemPaused`. Recovery-shaped entrypoints
324
- // (`uninstallModule`, `cancelPendingUpgrade`, `removeCustodian`,
325
- // the three `onlySelf` ceremonies) are deliberately NOT guarded
326
- // — an operator must always be able to remove attack surface
327
- // even during an incident.
391
+ // `SystemPaused`.
392
+ //
393
+ // Spec 445 §1.2 (audit H-3 / CUST-1 / ACCT-2) — WHAT STAYS REACHABLE UNDER A PAUSE, and how. The
394
+ // recovery-shaped functions (`removeCustodian`, `removePasskey`, `uninstallModule`,
395
+ // `cancelPendingUpgrade`, `revokeDigest`, `revokeAllApprovedDigests`) carry no pause modifier, but
396
+ // all of them except `cancelPendingUpgrade` are `onlySelf`: an un-gated function nobody can call is
397
+ // not live. The account calls itself only through `execute` / `executeBatch` / `executeFromModule`,
398
+ // so the exemption has to be at THOSE doors — `_requireExecutableUnderPause` (for `execute`) and the
399
+ // canonical-custody-policy branch of `executeFromModule`. `executeBatch` has no exemption at all.
328
400
  //
329
401
  // Reads `governance()` through the factory at each check so a
330
402
  // factory-level governance rotation propagates to every account
@@ -342,27 +414,107 @@ contract AgentAccount is
342
414
  /// compatibility). Production deploys MUST pass a real
343
415
  /// `AgenticGovernance` to the factory; the production-deploy
344
416
  /// preflight enforces that invariant.
345
- function _systemPaused() internal view returns (bool) {
417
+ function _systemPaused() internal view returns (bool paused) {
418
+ (paused,) = _pauseState();
419
+ }
420
+
421
+ /// @dev The pause flag AND the governance contract it was read from, in one pass (spec 445 §1.2: the
422
+ /// exemption reads governance once per call). `gov` is meaningful only when `paused` is true.
423
+ ///
424
+ /// DECISION (audit DLG-7, as it concerns this read) — a governance read that FAILS is "not paused".
425
+ /// Considered and kept, for three reasons. (1) Failing closed would make a broken or non-conforming
426
+ /// governance a permanent, unliftable freeze of every account of the factory: the only thing that
427
+ /// can lift a pause is that same governance, and the factory's pointer to it is immutable. (2) The
428
+ /// caller cannot induce the failure: `factory.governance()` is an immutable getter and
429
+ /// `AgenticGovernance.isPaused()` a single storage read; starving the two staticcalls of gas (the
430
+ /// 63/64 rule) leaves the frame with too little gas to perform the call the pause would have
431
+ /// stopped. (3) Which governance a factory points at is a deployment fact, asserted where it can
432
+ /// be: `Deploy.s.sol::_assertProductionEndState` requires a real `AgenticGovernance` and proves the
433
+ /// pause both sets and lifts. What this does NOT give: an account with no factory, or a factory
434
+ /// whose governance is an EOA / has no `isPaused()`, is never paused — by construction, not by
435
+ /// accident; it is outside the kill switch and the manifest must not claim otherwise.
436
+ function _pauseState() internal view returns (bool paused, address gov) {
346
437
  address f = _factory;
347
- if (f == address(0)) return false;
438
+ if (f == address(0)) return (false, address(0));
348
439
  (bool okF, bytes memory dataF) = f.staticcall(
349
440
  abi.encodeWithSelector(IAgentAccountFactoryView.governance.selector)
350
441
  );
351
- if (!okF || dataF.length < 32) return false;
352
- address g = abi.decode(dataF, (address));
353
- if (g == address(0) || g.code.length == 0) return false;
354
- (bool okG, bytes memory dataG) = g.staticcall(
442
+ if (!okF || dataF.length < 32) return (false, address(0));
443
+ gov = abi.decode(dataF, (address));
444
+ if (gov == address(0) || gov.code.length == 0) return (false, address(0));
445
+ (bool okG, bytes memory dataG) = gov.staticcall(
355
446
  abi.encodeWithSelector(IAgentAccountPauseView.isPaused.selector)
356
447
  );
357
- if (!okG || dataG.length < 32) return false;
358
- return abi.decode(dataG, (bool));
448
+ if (!okG || dataG.length < 32) return (false, address(0));
449
+ paused = abi.decode(dataG, (bool));
450
+ }
451
+
452
+ /// @dev Spec 445 §1.2 (a) — the pause gate of `execute` (the single call; `executeBatch` is paused with
453
+ /// no exemption). Not paused ⇒ returns. Paused ⇒ reverts `SystemPaused` unless the call is a
454
+ /// VALIDATED USER OPERATION (`msg.sender` is the immutable EntryPoint — never the delegation manager,
455
+ /// never a self-nest) and its target is one of exactly three things:
456
+ ///
457
+ /// 1. the factory's governance contract;
458
+ /// 2. that governance contract's own `timelock()`;
459
+ /// 3. this account, with a selector on the recovery allow-list (`_isPauseRecoverySelector`).
460
+ ///
461
+ /// (1) and (2) are why a pause can always be lifted (H-3): `unpause()` needs the timelock, the
462
+ /// timelock needs its proposer and executor to call it, and those are AgentAccounts. Both
463
+ /// addresses are read from `_factory → governance() → timelock()` — an immutable getter on the
464
+ /// factory and an immutable on the governance — so no state the account (or whoever holds its
465
+ /// keys) can write selects them. The exemption grants nothing at the target: the timelock's own
466
+ /// role checks and the governance's own `NotTimelock` / `NotGuardian` checks still decide; an
467
+ /// account that holds no role there reaches a revert.
468
+ /// (3) is ACCT-2: under a pause an owner can still REMOVE attack surface through a real path.
469
+ /// Every function on the list keeps its own gates (`onlySelf`, `_requireCustodyGoverned`), so on a
470
+ /// custody-governed account a single custodian's user operation still reverts
471
+ /// `AdminRequiresCustodyQuorum`; the quorum's path is `executeFromModule`.
472
+ ///
473
+ /// Value: unchanged — whatever `value` the call carries is forwarded as before.
474
+ function _requireExecutableUnderPause(address target, bytes calldata data) internal view {
475
+ (bool paused, address gov) = _pauseState();
476
+ if (!paused) return;
477
+ if (msg.sender == address(_entryPoint)) {
478
+ if (target == address(this)) {
479
+ if (data.length >= 4 && _isPauseRecoverySelector(bytes4(data[0:4]))) return;
480
+ } else if (_isGovernanceTarget(target, gov)) {
481
+ return;
482
+ }
483
+ }
484
+ revert SystemPaused();
485
+ }
486
+
487
+ /// @dev True iff `target` is `gov` or `gov.timelock()` (`gov` non-zero) — the pause exemption's resolution:
488
+ /// `_factory → governance() → timelock()`, an immutable getter and an immutable — nothing the account can
489
+ /// write selects either address.
490
+ function _isGovernanceTarget(address target, address gov) internal view returns (bool) {
491
+ if (gov == address(0) || target == address(0)) return false;
492
+ if (target == gov) return true;
493
+ (bool ok, bytes memory ret) =
494
+ gov.staticcall(abi.encodeWithSelector(IAgentAccountGovernanceTimelockView.timelock.selector));
495
+ return ok && ret.length >= 32 && target == abi.decode(ret, (address));
496
+ }
497
+
498
+ /// @dev The recovery allow-list: self-calls that only REMOVE authority or attack surface, reachable
499
+ /// under a pause (spec 445 §1.2 / ACCT-2; `AUDIT.md` §3.4 is the matrix this implements). Nothing
500
+ /// here adds a credential, installs or re-affirms a module, sets a delegation manager, approves a
501
+ /// digest, upgrades, or moves value.
502
+ function _isPauseRecoverySelector(bytes4 s) internal pure returns (bool) {
503
+ return
504
+ s == IAgentAccount.removeCustodian.selector ||
505
+ s == this.removePasskey.selector ||
506
+ s == this.uninstallModule.selector ||
507
+ s == this.cancelPendingUpgrade.selector ||
508
+ s == this.revokeDigest.selector ||
509
+ s == this.revokeAllApprovedDigests.selector;
359
510
  }
360
511
 
361
512
  // ─── Constructor / Initializer ──────────────────────────────────
362
513
 
363
- constructor(IEntryPoint entryPoint_, address approvedHashRegistry_) {
514
+ constructor(IEntryPoint entryPoint_, address approvedHashRegistry_, address upgradeVoucher_) {
364
515
  _entryPoint = entryPoint_;
365
516
  _approvedHashRegistry = approvedHashRegistry_;
517
+ _upgradeVoucher = upgradeVoucher_;
366
518
  _disableInitializers();
367
519
  }
368
520
 
@@ -437,6 +589,11 @@ contract AgentAccount is
437
589
 
438
590
  _delegationManager = dm;
439
591
  _factory = factory_;
592
+ // Spec 445 §1.3 (ii): a factory-less (legacy / direct-deploy) account has no canonical delegation
593
+ // manager to compare against, so its initial one is stamped under epoch 0 — and lapses, like any
594
+ // other non-canonical manager, at the first retirement unless re-affirmed. A factory-born account
595
+ // needs no stamp: its initial manager is the factory's canonical one.
596
+ if (factory_ == address(0) && dm != address(0)) _delegationManagerEpochStamp = 1;
440
597
  }
441
598
 
442
599
  /// @dev H7-C.5 — passkey-init body extracted so `initialize` stays below
@@ -511,6 +668,79 @@ contract AgentAccount is
511
668
  }
512
669
  }
513
670
 
671
+ /**
672
+ * @notice Upgrade this account's implementation. Spec 445 §1.3 (i) (audit H-2 / ACCT-1): on EVERY path —
673
+ * a self-governed account's own user operation, the custody quorum's `ApplySystemUpdate`, and a
674
+ * matured queued upgrade (`executePendingUpgrade`) — the pair
675
+ * `(newImplementation, keccak256(data))` must be vouched by this implementation's
676
+ * `UpgradeVoucher` AT THE MOMENT THE UPGRADE EXECUTES.
677
+ *
678
+ * @dev WHY. OZ's `upgradeToAndCall` delegatecalls `data` on `newImplementation` in this account's storage.
679
+ * With a caller-chosen implementation that is arbitrary code as the account: the audit's PoC upgraded
680
+ * to a throwaway contract whose migration call approved a hash for custody epoch + 1 in the
681
+ * `ApprovedHashRegistry` (as `msg.sender == account`), wrote `_externalCustodians[hidden] = true`
682
+ * with no event and no count change, and restored the real implementation — all in one user
683
+ * operation, all surviving the retirement of the credential that did it. A storage write under
684
+ * delegatecall cannot be detected afterwards, so it must be made impossible beforehand. A quorum
685
+ * should not be able to delegatecall arbitrary code either, so the custody path gets the same check.
686
+ *
687
+ * ORDER. `_authorizeUpgrade` (every pre-existing gate: `onlySelf`, the custody quorum on a governed
688
+ * account, the per-account timelock) runs first so the refusal a caller sees is the same as before;
689
+ * then the voucher; then OZ's `upgradeToAndCall`, which re-authorizes and performs the upgrade.
690
+ * `_authorizeUpgrade(address)` alone cannot make the check — it never sees `data`.
691
+ *
692
+ * FAIL CLOSED. A voucher that is zero, has no code, reverts, or answers anything but `true` refuses
693
+ * the upgrade. An implementation built without a voucher can never be upgraded away from.
694
+ *
695
+ * THE QUEUE. `scheduleUpgrade` binds only an implementation; `executePendingUpgrade` always runs it
696
+ * with EMPTY migration data, so a queued upgrade is bound to `dataHash == keccak256("")` by
697
+ * construction and is checked against the voucher when it executes, not when it was queued (an
698
+ * `unvouch` during the wait stops it). An upgrade that needs a migration call cannot be queued.
699
+ *
700
+ * MIGRATION OF AN EXISTING (generation ≤ 3) ACCOUNT — read this before claiming more than it gives.
701
+ * Such an account reaches generation 4 by upgrading through its OLD implementation's code, which
702
+ * has no voucher: nothing in this contract can constrain that last old-rules upgrade, nor anything
703
+ * done before it. From the moment the account runs a generation-4 implementation, its upgrades are
704
+ * constrained by the voucher immutable of the implementation it is running.
705
+ * GUARANTEED after migration: no credential, module, delegate or quorum can execute code as the
706
+ * account other than a governance-vouched implementation + migration call; a retirement expels
707
+ * non-canonical executor modules and a non-canonical delegation manager (§1.3 (ii)) and clears a
708
+ * queued upgrade.
709
+ * NOT GUARANTEED: that the account was clean when it migrated. A credential that was compromised
710
+ * BEFORE the migration may already have written a hidden custodian, planted approvals, or
711
+ * swapped the implementation for one of its own (which then never consults any voucher).
712
+ * Migrating does not undo any of that and does not detect it. For an account suspected of
713
+ * compromise before migration, the only sound remedies are off-chain review of its storage
714
+ * against its event history, or a new account.
715
+ * Also unchanged by an in-place upgrade: `_factory`. A migrated account's CANONICAL custody policy
716
+ * and delegation manager remain those of its ORIGINAL factory (generation ≤ 3 code). Pointing it at
717
+ * a generation-4 DelegationManager is a `setDelegationManager` — non-canonical for that account, so
718
+ * it must be re-affirmed at every rotation; its custody policy keeps the old action set.
719
+ */
720
+ function upgradeToAndCall(address newImplementation, bytes memory data) public payable override onlyProxy {
721
+ _authorizeUpgrade(newImplementation);
722
+ _requireVouchedUpgrade(newImplementation, keccak256(data));
723
+ super.upgradeToAndCall(newImplementation, data);
724
+ }
725
+
726
+ /// @dev Spec 445 §1.3 (i). See `upgradeToAndCall`. Low-level staticcall so a voucher that reverts or
727
+ /// returns malformed data is a refusal, never a bubble-up the caller could mistake for another gate.
728
+ function _requireVouchedUpgrade(address newImplementation, bytes32 dataHash) internal view {
729
+ address v = _upgradeVoucher;
730
+ if (v.code.length != 0) {
731
+ (bool ok, bytes memory ret) = v.staticcall(
732
+ abi.encodeWithSelector(IUpgradeVoucherView.isVouched.selector, newImplementation, dataHash)
733
+ );
734
+ if (ok && ret.length == 32 && abi.decode(ret, (uint256)) == 1) return;
735
+ }
736
+ revert UpgradeNotVouched(newImplementation, dataHash);
737
+ }
738
+
739
+ /// @notice The `UpgradeVoucher` this implementation consults before every upgrade (immutable).
740
+ function upgradeVoucher() external view returns (address) {
741
+ return _upgradeVoucher;
742
+ }
743
+
514
744
  /**
515
745
  * @notice DEPRECATED — single-signature upgrade path (contract audit C-3).
516
746
  *
@@ -542,6 +772,9 @@ contract AgentAccount is
542
772
  /// `executePendingUpgrade` once `_upgradeTimelock` has elapsed. Only
543
773
  /// meaningful when a timelock is configured — with none set, upgrade
544
774
  /// directly. Overwrites any existing pending upgrade.
775
+ /// @dev Spec 445 §1.3: the queued upgrade is bound to EMPTY migration data and is checked against the
776
+ /// `UpgradeVoucher` when it EXECUTES (see `upgradeToAndCall`); every credential retirement clears
777
+ /// the queue (`_bumpCustodyEpoch`), so an upgrade queued by a since-retired credential never fires.
545
778
  function scheduleUpgrade(address newImplementation) external onlySelf {
546
779
  _requireCustodyGoverned();
547
780
  if (newImplementation == address(0)) revert ZeroAddress();
@@ -579,10 +812,15 @@ contract AgentAccount is
579
812
  /// ECDSA signature cannot perpetually cancel quorum-scheduled upgrades
580
813
  /// (upgrade-liveness DoS). The lightweight ECDSA cancel-grant fast-path remains
581
814
  /// ONLY for non-governed (mode-0) accounts, where the sole custodian IS the owner.
815
+ /// Spec 445 §1.2 / ACCT-2 (+ ACCT-9b): on a non-governed account a SELF-CALL is also accepted, with
816
+ /// no signature — it arrives only through a user operation one of the account's own credentials
817
+ /// signed (the same authority that could overwrite the queue with `scheduleUpgrade`). Without it a
818
+ /// passkey-only account had no way to cancel at all, and under a pause the recovery allow-list
819
+ /// entry for this selector would have named a path nobody could take.
582
820
  /// @param ownerSig Owner ECDSA signature over `keccak256(abi.encode(
583
821
  /// "UPGRADE_CANCEL", _pendingUpgrade.newImplementation,
584
822
  /// address(this), block.chainid))`. Ignored on governed accounts
585
- /// (the quorum context authorizes; no signature is consulted).
823
+ /// (the quorum context authorizes; no signature is consulted) and on a self-call.
586
824
  function cancelPendingUpgrade(bytes calldata ownerSig) external {
587
825
  bool governed = _hasCustodyGovernance();
588
826
  // Governed: authorize FIRST (fail-closed before revealing pending state). Only the custody quorum
@@ -592,7 +830,7 @@ contract AgentAccount is
592
830
  if (governed) _requireCustodyGoverned();
593
831
  PendingUpgrade memory p = _pendingUpgrade;
594
832
  if (p.readyAt == 0) revert NoPendingUpgrade();
595
- if (!governed) {
833
+ if (!governed && msg.sender != address(this)) {
596
834
  // Non-governed (mode-0): the sole custodian's ECDSA cancel-grant authorizes.
597
835
  bytes32 digest = keccak256(
598
836
  abi.encode(
@@ -635,7 +873,7 @@ contract AgentAccount is
635
873
 
636
874
  /// @notice Returns the current implementation version.
637
875
  function version() external pure returns (string memory) {
638
- return "2.2.0";
876
+ return "2.3.0";
639
877
  }
640
878
 
641
879
  // ─── Delegation Manager (ERC-7710) ─────────────────────────────
@@ -660,14 +898,51 @@ contract AgentAccount is
660
898
  _requireCustodyGoverned();
661
899
  if (dm.code.length == 0) revert ValidatorRequired();
662
900
  _delegationManager = dm;
901
+ // Spec 445 §1.3 (ii): stamped with the epoch it was set under. If `dm` is not the factory's canonical
902
+ // manager it stops being honoured at the next credential retirement unless re-affirmed.
903
+ _delegationManagerEpochStamp = _custodyEpoch + 1;
663
904
  emit DelegationManagerRotated(dm);
664
905
  }
665
906
 
907
+ /// @notice Spec 445 §1.3 (ii) — re-stamp the CURRENT delegation manager under the current custody epoch,
908
+ /// so a non-canonical manager the person keeps survives the retirement that just bumped the
909
+ /// epoch. Gated EXACTLY like `setDelegationManager` (`onlySelf` + the custody quorum on a governed
910
+ /// account); unreachable from a delegation stack (`_isGovernanceSelector`). The rotation ceremony
911
+ /// calls it after the retirement; a recovery never does.
912
+ function reaffirmDelegationManager() external onlySelf {
913
+ _requireCustodyGoverned();
914
+ address dm = _delegationManager;
915
+ if (dm.code.length == 0) revert ValidatorRequired();
916
+ uint64 epoch = _custodyEpoch;
917
+ _delegationManagerEpochStamp = epoch + 1;
918
+ emit DelegationManagerReaffirmed(dm, epoch);
919
+ }
920
+
666
921
  /// @notice Get the currently authorized DelegationManager.
667
922
  function delegationManager() external view returns (address) {
668
923
  return _delegationManager;
669
924
  }
670
925
 
926
+ /// @notice Whether the delegation manager is honoured by `execute` / `executeBatch` RIGHT NOW: it is the
927
+ /// factory's canonical one, or it was set / re-affirmed under the current custody epoch.
928
+ function isDelegationManagerCurrent() external view returns (bool) {
929
+ return _delegationManagerCurrent();
930
+ }
931
+
932
+ /// @dev Spec 445 §1.3 (ii). The canonical manager is read from the factory (an immutable there); a
933
+ /// factory that cannot answer names no canonical manager — fail closed.
934
+ function _delegationManagerCurrent() internal view returns (bool) {
935
+ if (_delegationManagerEpochStamp == _custodyEpoch + 1) return true;
936
+ address f = _factory;
937
+ if (f == address(0)) return false;
938
+ (bool ok, bytes memory ret) = f.staticcall(
939
+ abi.encodeWithSelector(IAgentAccountFactoryView.delegationManager.selector)
940
+ );
941
+ if (!ok || ret.length < 32) return false;
942
+ address canonical = abi.decode(ret, (address));
943
+ return canonical != address(0) && canonical == _delegationManager;
944
+ }
945
+
671
946
  // ─── Phase A — capability roles (factory-scoped) ───────────────
672
947
 
673
948
  /// @notice Address of the factory that deployed this account.
@@ -821,6 +1096,10 @@ contract AgentAccount is
821
1096
  /// an unbounded list would let a malicious owner brick their account.
822
1097
  uint256 internal constant MAX_HOOKS = 8;
823
1098
 
1099
+ /// @dev ACCT-13 — the fixed gas a HOOK's `onUninstall` callback is given (see `uninstallModule`). Ample for
1100
+ /// a hook that clears per-account state; a hook that needs more is not removable cleanly, by design.
1101
+ uint256 internal constant HOOK_UNINSTALL_CALLBACK_GAS = 200_000;
1102
+
824
1103
  /// @dev ERC-7201 namespaced storage slot for module state.
825
1104
  /// slot = keccak256(abi.encode(uint256(keccak256("smart-agent.account.modules.v1")) - 1)) & ~bytes32(uint256(0xff))
826
1105
  bytes32 private constant MODULES_STORAGE_SLOT =
@@ -923,6 +1202,9 @@ contract AgentAccount is
923
1202
 
924
1203
  $.installed[moduleTypeId][module] = true;
925
1204
  $.installedList[moduleTypeId].push(module);
1205
+ // Spec 445 §1.3 (ii): a module that can act as the account is stamped with the custody epoch it was
1206
+ // installed under (see `_moduleEpochStamp`). A HOOK is not stamped — it never lapses.
1207
+ if (moduleTypeId != MODULE_TYPE_HOOK) _moduleEpochStamp[module] = _custodyEpoch + 1;
926
1208
 
927
1209
  // Notify the module — best-effort wrapped so a misbehaving module
928
1210
  // produces a typed error instead of bubbling raw bytes. We still
@@ -935,6 +1217,7 @@ contract AgentAccount is
935
1217
  $.installed[moduleTypeId][module] = false;
936
1218
  address[] storage list = $.installedList[moduleTypeId];
937
1219
  list.pop();
1220
+ // (the epoch stamp is rolled back by the revert itself)
938
1221
  revert ModuleOnInstallFailed(reason);
939
1222
  }
940
1223
 
@@ -973,20 +1256,71 @@ contract AgentAccount is
973
1256
  // still rolls the whole call back.
974
1257
  $.installed[moduleTypeId][module] = false;
975
1258
  _removeFromList($.installedList[moduleTypeId], module);
976
-
977
- // Loud uninstall — if the module reverts in onUninstall, we revert
978
- // too so the caller sees the failure. (Owner can force-uninstall
979
- // by passing deInitData the module can handle, or by re-deploying
980
- // the account proxy — UUPS is available.)
981
- try IERC7579ModuleLike(module).onUninstall(deInitData) {
982
- // ok
983
- } catch (bytes memory reason) {
984
- revert ModuleOnUninstallFailed(reason);
1259
+ if (moduleTypeId != MODULE_TYPE_HOOK) delete _moduleEpochStamp[module];
1260
+
1261
+ if (moduleTypeId != MODULE_TYPE_HOOK) {
1262
+ // Loud uninstall — if an EXECUTOR / VALIDATOR reverts in onUninstall, we revert too so the caller
1263
+ // sees the failure (the custody policy's `onUninstall` must be able to refuse).
1264
+ try IERC7579ModuleLike(module).onUninstall(deInitData) {
1265
+ // ok
1266
+ } catch (bytes memory reason) {
1267
+ revert ModuleOnUninstallFailed(reason);
1268
+ }
1269
+ } else {
1270
+ // ACCT-13 (audit 2026-11-10): a HOOK is different. Hooks run before every `execute`; one whose
1271
+ // `onUninstall` (or `preCheck` — see `execute`) reverts or burns its gas would otherwise make its
1272
+ // own removal impossible and brick a self-governed account. The account has already decided, at
1273
+ // its custody tier, to drop the hook: the callback gets a FIXED gas budget and its failure is
1274
+ // recorded (`ModuleUninstallCallbackFailed`), not obeyed.
1275
+ // - The budget is guaranteed, not best-effort: the call reverts up front if it could not be
1276
+ // forwarded in full. Otherwise whoever submits the transaction (anyone can submit a quorum's
1277
+ // `applyCustodyChange`) could starve an HONEST hook's cleanup with a tuned gas limit and
1278
+ // leave its per-account state stale.
1279
+ // - The revert data is not copied (no return-bomb, no unbounded log).
1280
+ // Consequence for a hook that does fail: its own state for this account may still say
1281
+ // "installed" — `TreasurySpendPolicy` then refuses a fresh `onInstall`, so a NEW hook instance is
1282
+ // needed. That is the hook's cost of having failed, never the account's.
1283
+ if (gasleft() < HOOK_UNINSTALL_CALLBACK_GAS + HOOK_UNINSTALL_CALLBACK_GAS / 32) {
1284
+ revert InsufficientGasForHookUninstall();
1285
+ }
1286
+ try IERC7579ModuleLike(module).onUninstall{gas: HOOK_UNINSTALL_CALLBACK_GAS}(deInitData) {
1287
+ // ok
1288
+ } catch {
1289
+ emit ModuleUninstallCallbackFailed(module);
1290
+ }
985
1291
  }
986
1292
 
987
1293
  emit ModuleUninstalled(moduleTypeId, module);
988
1294
  }
989
1295
 
1296
+ /// @notice Spec 445 §1.3 (ii) — re-stamp an installed EXECUTOR (or validator) module under the current
1297
+ /// custody epoch, so a module the person KEEPS survives the retirement that just bumped the
1298
+ /// epoch. Gated EXACTLY like `installModule` after birth: `onlySelf`, pause-gated, and — on a
1299
+ /// custody-governed account — only inside the custody quorum's `executeFromModule`. Unreachable
1300
+ /// from a delegation stack (`_isGovernanceSelector`). The rotation ceremony calls it after the
1301
+ /// retirement (`add → retire → approveDigest×N → reaffirm×M`); a recovery never does — whatever a
1302
+ /// lost or stolen credential installed stays expelled until the person re-installs it knowingly.
1303
+ /// A hook needs no re-affirmation and is refused here (it never lapses).
1304
+ function reaffirmModule(address module) external onlySelf whenNotPaused {
1305
+ _requireCustodyGoverned();
1306
+ ModulesStorage storage $ = _modulesStorage();
1307
+ if (!$.installed[MODULE_TYPE_EXECUTOR][module] && !$.installed[MODULE_TYPE_VALIDATOR][module]) {
1308
+ revert ModuleNotInstalled(MODULE_TYPE_EXECUTOR, module);
1309
+ }
1310
+ uint64 epoch = _custodyEpoch;
1311
+ _moduleEpochStamp[module] = epoch + 1;
1312
+ emit ModuleReaffirmed(module, epoch);
1313
+ }
1314
+
1315
+ /// @notice Whether `module` may act through `executeFromModule` RIGHT NOW: it is the factory's canonical
1316
+ /// custody policy, or it was installed / re-affirmed under the current custody epoch. (Says
1317
+ /// nothing about whether it is installed — pair with `isModuleInstalled`.)
1318
+ function isModuleCurrent(address module) external view returns (bool) {
1319
+ if (_moduleEpochStamp[module] == _custodyEpoch + 1) return true;
1320
+ address f = _factory;
1321
+ return f != address(0) && module == IAgentAccountFactoryView(f).custodyPolicy();
1322
+ }
1323
+
990
1324
  /// @notice Returns true iff the given module is installed for the given type.
991
1325
  /// @dev `additionalContext` accepted for ERC-7579 conformance; unused here.
992
1326
  function isModuleInstalled(
@@ -1062,15 +1396,8 @@ contract AgentAccount is
1062
1396
  function executeFromModule(address target, uint256 value, bytes calldata data)
1063
1397
  external
1064
1398
  nonReentrant
1065
- whenNotPaused
1066
1399
  returns (bytes memory)
1067
1400
  {
1068
- ModulesStorage storage $ = _modulesStorage();
1069
- if (!$.installed[MODULE_TYPE_EXECUTOR][msg.sender]) {
1070
- revert NotInstalledExecutor(msg.sender);
1071
- }
1072
- emit ModuleExecuted(msg.sender, target, value);
1073
- _rejectDirectRegistryCall(target);
1074
1401
  // CA-1 + Wave-1/ACCT-C1 (spec 300): a module action from the CANONICAL CustodyPolicy is a
1075
1402
  // custody-governed context (gated upstream by its own T5 quorum + timelock). `_custodyGovCtx`
1076
1403
  // authorizes every governance mutator this call dispatches (the ONLY way past
@@ -1082,25 +1409,94 @@ contract AgentAccount is
1082
1409
  // (utility / automation) executor a quorum installs believing it unprivileged would silently inherit
1083
1410
  // full authority to mutate custody / DM / upgrade / modules, bypassing quorum+timelock. Matching the
1084
1411
  // specific policy address is the same check `_hasCustodyGovernance` uses. A non-canonical executor
1085
- // runs WITHOUT the context, so `_requireCustodyGoverned` rejects any governance mutator it dispatches
1086
- // (defense-in-depth: not reachable at v1 since the factory installs only CustodyPolicy).
1412
+ // runs WITHOUT the context, so `_requireCustodyGoverned` rejects any governance mutator it dispatches.
1087
1413
  address f = _factory;
1088
1414
  bool custodyGoverned = f != address(0) && msg.sender == IAgentAccountFactoryView(f).custodyPolicy();
1089
- if (custodyGoverned) {
1415
+
1416
+ // R6.5 pause gate, with the spec 445 §1.2 / ACCT-2 exemption: under a pause the ONLY module call that
1417
+ // still lands is the canonical custody policy dispatching a recovery-allow-list self-call (a quorum
1418
+ // removing a credential or uninstalling a module). The policy decides which of its actions it will
1419
+ // schedule/apply under a pause; this is the account's half of the same rule. (A pause is lifted through
1420
+ // `execute` from a validated user operation — `_requireExecutableUnderPause`, H-3.)
1421
+ if (_systemPaused()) {
1422
+ if (
1423
+ !(custodyGoverned && target == address(this)
1424
+ && data.length >= 4 && _isPauseRecoverySelector(bytes4(data[0:4])))
1425
+ ) revert SystemPaused();
1426
+ }
1427
+
1428
+ ModulesStorage storage $ = _modulesStorage();
1429
+ if (!$.installed[MODULE_TYPE_EXECUTOR][msg.sender]) {
1430
+ revert NotInstalledExecutor(msg.sender);
1431
+ }
1432
+ if (!custodyGoverned) {
1433
+ // Spec 445 §1.3 (ii) (audit H-2 / ACCT-1): an executor installed by a credential that has since
1434
+ // been retired is retired with it. Only the canonical custody policy is exempt — it IS the
1435
+ // custody tier, and it is what performs the recovery that bumps the epoch.
1436
+ if (_moduleEpochStamp[msg.sender] != _custodyEpoch + 1) revert ModuleEpochLapsed(msg.sender);
1437
+ // ACCT-3: a module never speaks as the account to another installed module (it could drop a
1438
+ // hook's budget, or drive the custody policy).
1439
+ if (_isInstalledModule(target)) revert ModuleNotAnExecuteTarget(target);
1440
+ }
1441
+ emit ModuleExecuted(msg.sender, target, value);
1442
+ _rejectDirectRegistryCall(target);
1443
+
1444
+ // Spec 445 §1.5 (CUST-2 / ACCT-3): HOOKS RUN ON A MODULE'S CALL TOO. Before generation 4 they ran only
1445
+ // in `execute` / `executeBatch`, so any installed executor moved value with no hook consulted — the
1446
+ // treasury ceiling bounded delegates and user operations and nothing else. The canonical custody
1447
+ // policy is not hooked: it dispatches account governance (never value), and a reverting hook must
1448
+ // not be able to stop the quorum from removing that very hook.
1449
+ address[] memory hooks;
1450
+ bytes[] memory hookData;
1451
+ if (!custodyGoverned) (hooks, hookData) = _preHooks(value, abi.encode(target, value, data));
1452
+
1453
+ // The custody context is granted only around a SELF-call — the shape of every governance action the
1454
+ // policy dispatches. Its one other dispatch (spec 445 §1.5: a ceiling change on an installed hook)
1455
+ // is a call OUT to the hook; an external contract never runs with this account's governance flags set.
1456
+ bool grantCtx = custodyGoverned && target == address(this);
1457
+ if (grantCtx) {
1090
1458
  _custodyGovCtx = true;
1091
1459
  _upgradeAuthorizedCtx = true;
1092
1460
  }
1093
1461
  (bool ok, bytes memory ret) = target.call{value: value}(data);
1094
- if (custodyGoverned) {
1462
+ if (grantCtx) {
1095
1463
  _upgradeAuthorizedCtx = false;
1096
1464
  _custodyGovCtx = false;
1097
1465
  }
1098
1466
  if (!ok) {
1099
1467
  assembly { revert(add(ret, 32), mload(ret)) }
1100
1468
  }
1469
+ _postHooks(hooks, hookData);
1101
1470
  return ret;
1102
1471
  }
1103
1472
 
1473
+ /// @dev Run every installed hook's `preCheck`, in install order. `hookMsgData` is
1474
+ /// `abi.encode(target, value, data)` for a single call and `abi.encode(Call[])` for a batch.
1475
+ function _preHooks(uint256 value, bytes memory hookMsgData)
1476
+ internal
1477
+ returns (address[] memory hooks, bytes[] memory hookData)
1478
+ {
1479
+ hooks = _modulesStorage().installedList[MODULE_TYPE_HOOK];
1480
+ hookData = new bytes[](hooks.length);
1481
+ for (uint256 i = 0; i < hooks.length; i++) {
1482
+ hookData[i] = IERC7579HookLike(hooks[i]).preCheck(msg.sender, value, hookMsgData);
1483
+ }
1484
+ }
1485
+
1486
+ function _postHooks(address[] memory hooks, bytes[] memory hookData) internal {
1487
+ for (uint256 i = 0; i < hooks.length; i++) {
1488
+ IERC7579HookLike(hooks[i]).postCheck(hookData[i]);
1489
+ }
1490
+ }
1491
+
1492
+ /// @dev True iff `target` is installed on this account as a module of ANY supported type.
1493
+ function _isInstalledModule(address target) internal view returns (bool) {
1494
+ ModulesStorage storage $ = _modulesStorage();
1495
+ return $.installed[MODULE_TYPE_EXECUTOR][target]
1496
+ || $.installed[MODULE_TYPE_HOOK][target]
1497
+ || $.installed[MODULE_TYPE_VALIDATOR][target];
1498
+ }
1499
+
1104
1500
  function _isSupportedModuleType(uint256 moduleTypeId) internal pure returns (bool) {
1105
1501
  return moduleTypeId == MODULE_TYPE_VALIDATOR
1106
1502
  || moduleTypeId == MODULE_TYPE_EXECUTOR
@@ -1152,30 +1548,37 @@ contract AgentAccount is
1152
1548
  /// exemption is justified at its declaration. The flag is transient
1153
1549
  /// (EIP-1153), so it cannot survive the transaction either.
1154
1550
  // slither-disable-next-line reentrancy-eth
1155
- function execute(address target, uint256 value, bytes calldata data) external override nonReentrant whenNotPaused {
1551
+ function execute(address target, uint256 value, bytes calldata data) external override nonReentrant {
1552
+ // R6.5 pause gate, with the spec 445 §1.2 exemptions (governance, its timelock, the recovery
1553
+ // allow-list on self) — see `_requireExecutableUnderPause`. Runs first, as the modifier did.
1554
+ _requireExecutableUnderPause(target, data);
1156
1555
  _requireForExecute();
1157
1556
 
1158
1557
  // DM-3 (spec 300): mark a delegation-originated stack (set once at the
1159
- // outermost DM frame; preserved across the legitimate DM → execute(self,
1160
- // executeBatch(...)) nest) and forbid it from self-calling governance.
1558
+ // outermost DM frame; preserved across a DM → execute(self, executeBatch(...))
1559
+ // nest — which the canonical manager no longer produces (DLG-2 refuses a
1560
+ // self-targeted redemption); kept as defence in depth) and forbid it from
1561
+ // self-calling governance.
1161
1562
  bool setDelCtx = (msg.sender == _delegationManager && !_delegationExecCtx);
1162
1563
  if (setDelCtx) _delegationExecCtx = true;
1163
1564
  _rejectDirectRegistryCall(target);
1164
1565
  _rejectDelegatedGovernance(target, data);
1566
+ _rejectModuleTarget(target);
1165
1567
 
1166
- ModulesStorage storage $ = _modulesStorage();
1167
- address[] memory hooks = $.installedList[MODULE_TYPE_HOOK];
1168
- bytes[] memory hookData = new bytes[](hooks.length);
1169
-
1170
- // Compose msgData = abi.encodeWithSignature("execute(address,uint256,bytes)", ...)
1171
- // so hook policy can decode the inner call. Easier and cheaper than
1172
- // forwarding msg.data which includes the selector + ABI tail; we
1173
- // rebuild the encoded inner call directly here.
1174
- bytes memory hookMsgData = abi.encode(target, value, data);
1175
-
1176
- for (uint256 i = 0; i < hooks.length; i++) {
1177
- hookData[i] = IERC7579HookLike(hooks[i]).preCheck(msg.sender, value, hookMsgData);
1178
- }
1568
+ // Hook policy sees the inner call as `abi.encode(target, value, data)`.
1569
+ //
1570
+ // ACCT-13: the ONE call that runs no hook is this account uninstalling a HOOK
1571
+ // (`execute(self, uninstallModule(4, hook, …))`). Hooks run before every call, so a hook whose
1572
+ // `preCheck` reverts (a bug, a dead dependency) would otherwise block the only call that removes it
1573
+ // and brick a self-governed account for good. The skipped call moves nothing: a value-carrying
1574
+ // self-call to a non-payable function reverts.
1575
+ address[] memory hooks;
1576
+ bytes[] memory hookData;
1577
+ if (
1578
+ !(target == address(this) && data.length >= 36
1579
+ && bytes4(data[0:4]) == this.uninstallModule.selector
1580
+ && uint256(bytes32(data[4:36])) == MODULE_TYPE_HOOK)
1581
+ ) (hooks, hookData) = _preHooks(value, abi.encode(target, value, data));
1179
1582
 
1180
1583
  // Perform the actual call (mirrors BaseAccount.execute body).
1181
1584
  (bool ok, bytes memory ret) = target.call{value: value}(data);
@@ -1187,31 +1590,29 @@ contract AgentAccount is
1187
1590
  }
1188
1591
  }
1189
1592
 
1190
- for (uint256 i = 0; i < hooks.length; i++) {
1191
- IERC7579HookLike(hooks[i]).postCheck(hookData[i]);
1192
- }
1593
+ _postHooks(hooks, hookData);
1193
1594
 
1194
1595
  if (setDelCtx) _delegationExecCtx = false;
1195
1596
  }
1196
1597
 
1197
1598
  /// @notice Atomically execute multiple calls from this account.
1198
1599
  /// @dev Overrides BaseAccount.executeBatch to layer the module-hook
1199
- /// pre/post-check semantics already used by `execute`. Spec 005 —
1200
- /// pledge honor needs `USDC.transfer(pool, amount)` +
1201
- /// `PledgeRegistry.recordHonor(...)` in one atomic operation,
1202
- /// pinned by a `CallDataHashEnforcer` on the redeem path so the
1203
- /// donor's sub-delegation authorises exactly this calldata.
1600
+ /// pre/post-check semantics already used by `execute`. (Spec 005 once
1601
+ /// reached this under a delegation as `execute(self, executeBatch(...))`
1602
+ /// pinned by a `CallDataHashEnforcer`; generation 4 / DLG-2 refuses any
1603
+ /// redemption that targets the root delegator, so a batch is a user
1604
+ /// operation's (or a self-call's) shape only — no caller relied on it.)
1204
1605
  ///
1205
1606
  /// Auth: identical to `execute` — EntryPoint / self / DelegationManager.
1206
1607
  /// Inner calls run with `msg.sender == address(this)`.
1207
1608
  /// All-or-nothing: any inner revert bubbles and reverts the batch.
1208
1609
  /// Pre-hooks run once on the whole batch; post-hooks run on success.
1209
1610
  ///
1210
- /// Spec 007 Phase A.5 — intentionally NOT `nonReentrant`. The
1211
- /// DM redeem flow legitimately calls `account.execute(target=self,
1212
- /// data=executeBatch_calldata)`, which then self-calls into
1213
- /// `executeBatch`. If both functions held the guard, that
1214
- /// pattern would revert with `ReentrancyGuardReentrantCall`. The
1611
+ /// Spec 007 Phase A.5 — intentionally NOT `nonReentrant`. A user
1612
+ /// operation may call `account.execute(target=self,
1613
+ /// data=executeBatch_calldata)` (the DM redeem flow no longer can —
1614
+ /// DLG-2), which then self-calls into `executeBatch`. If both functions
1615
+ /// held the guard, that pattern would revert with `ReentrancyGuardReentrantCall`. The
1215
1616
  /// OUTER `execute` already holds the guard, so external re-entry
1216
1617
  /// is blocked; `_requireForExecute` restricts entry to
1217
1618
  /// EntryPoint / self / DM (DM has its own `nonReentrant`).
@@ -1228,27 +1629,20 @@ contract AgentAccount is
1228
1629
  _requireForExecute();
1229
1630
 
1230
1631
  // DM-3 (spec 300): same delegation-origin marking as `execute`. Preserved
1231
- // across the DM → execute(self, executeBatch(...)) nest so a governance
1632
+ // across a DM → execute(self, executeBatch(...)) nest (defence in depth: the
1633
+ // canonical manager refuses that redemption, DLG-2) so a governance
1232
1634
  // self-call in ANY inner call is caught even though this frame's
1233
1635
  // msg.sender is address(this).
1234
1636
  bool setDelCtx = (msg.sender == _delegationManager && !_delegationExecCtx);
1235
1637
  if (setDelCtx) _delegationExecCtx = true;
1236
1638
 
1237
- ModulesStorage storage $ = _modulesStorage();
1238
- address[] memory hooks = $.installedList[MODULE_TYPE_HOOK];
1239
- bytes[] memory hookData = new bytes[](hooks.length);
1240
-
1241
- // hookMsgData encodes the full batch so hook policy can inspect
1242
- // every inner call.
1243
- bytes memory hookMsgData = abi.encode(calls);
1244
-
1245
- for (uint256 i = 0; i < hooks.length; i++) {
1246
- hookData[i] = IERC7579HookLike(hooks[i]).preCheck(msg.sender, 0, hookMsgData);
1247
- }
1639
+ // hookMsgData encodes the full batch so hook policy can inspect every inner call.
1640
+ (address[] memory hooks, bytes[] memory hookData) = _preHooks(0, abi.encode(calls));
1248
1641
 
1249
1642
  for (uint256 i = 0; i < calls.length; i++) {
1250
1643
  _rejectDirectRegistryCall(calls[i].target);
1251
1644
  _rejectDelegatedGovernance(calls[i].target, calls[i].data);
1645
+ _rejectModuleTarget(calls[i].target);
1252
1646
  (bool ok, bytes memory ret) = calls[i].target.call{ value: calls[i].value }(calls[i].data);
1253
1647
  if (!ok) {
1254
1648
  assembly {
@@ -1258,9 +1652,7 @@ contract AgentAccount is
1258
1652
  }
1259
1653
  }
1260
1654
 
1261
- for (uint256 i = 0; i < hooks.length; i++) {
1262
- IERC7579HookLike(hooks[i]).postCheck(hookData[i]);
1263
- }
1655
+ _postHooks(hooks, hookData);
1264
1656
 
1265
1657
  if (setDelCtx) _delegationExecCtx = false;
1266
1658
  }
@@ -1286,14 +1678,17 @@ contract AgentAccount is
1286
1678
  }
1287
1679
 
1288
1680
  /// @dev Allow execution from EntryPoint, account itself (via UserOp), or DelegationManager (ERC-7710)
1681
+ /// @dev Spec 445 §1.3 (ii) (audit H-2 / ACCT-1): the delegation manager is honoured only while it is
1682
+ /// CURRENT — the factory's canonical one, or one set / re-affirmed under the current custody epoch.
1683
+ /// A manager a since-retired credential swapped in is refused here, on both `execute` and
1684
+ /// `executeBatch`, with no further state to clear.
1289
1685
  function _requireForExecute() internal view override {
1290
- if (
1291
- msg.sender != address(entryPoint()) &&
1292
- msg.sender != address(this) &&
1293
- msg.sender != _delegationManager
1294
- ) {
1295
- revert NotFromEntryPoint(msg.sender, address(this), address(entryPoint()));
1686
+ if (msg.sender == address(entryPoint()) || msg.sender == address(this)) return;
1687
+ if (msg.sender == _delegationManager) {
1688
+ if (!_delegationManagerCurrent()) revert DelegationManagerEpochLapsed(msg.sender);
1689
+ return;
1296
1690
  }
1691
+ revert NotFromEntryPoint(msg.sender, address(this), address(entryPoint()));
1297
1692
  }
1298
1693
 
1299
1694
  // ─── Wave 1 — account authorization boundary (spec 300) ─────────
@@ -1324,8 +1719,9 @@ contract AgentAccount is
1324
1719
 
1325
1720
  /// @dev DM-3 gate: a delegation-originated stack may never self-call an account
1326
1721
  /// governance selector. `_delegationExecCtx` is set at the outermost
1327
- /// DM-driven `execute`/`executeBatch` and persists across the legitimate
1328
- /// `DM → execute(self, executeBatch(...))` nest, so a nested governance
1722
+ /// DM-driven `execute`/`executeBatch` and persists across a
1723
+ /// `DM → execute(self, executeBatch(...))` nest (refused by the canonical manager since
1724
+ /// generation 4 / DLG-2; kept as defence in depth), so a nested governance
1329
1725
  /// self-call is caught regardless of mode.
1330
1726
  function _rejectDelegatedGovernance(address target, bytes calldata data) internal view {
1331
1727
  if (!_delegationExecCtx) return;
@@ -1341,9 +1737,38 @@ contract AgentAccount is
1341
1737
  // the principal — a delegate reaching them through `execute` would uninstall the custody policy
1342
1738
  // (bricking the account) or plant approved-hash root delegations that outlive the delegate's own
1343
1739
  // caveats. Any selector: there is no legitimate delegated call to either.
1740
+ // Spec 445 §1.5 / ACCT-3: the same holds for EVERY installed module — a hook keys its state by
1741
+ // `msg.sender == account` exactly as the custody policy does (a delegate that could call
1742
+ // `TreasurySpendPolicy.onUninstall` as the treasury removed the treasury's ceiling).
1344
1743
  if (_isAccountTrustedTarget(target)) revert DelegatedGovernanceForbidden();
1345
1744
  }
1346
1745
 
1746
+ /// @dev Spec 445 §1.5 / ACCT-3 — outside a delegation (that case is `_rejectDelegatedGovernance`): on a
1747
+ /// CUSTODY-GOVERNED account an installed module is never an `execute` / `executeBatch` target. Those
1748
+ /// two doors open to a single custodian's user operation, which is below the custody tier there;
1749
+ /// the quorum reaches a module through the custody policy's own actions (`executeFromModule`) and
1750
+ /// a module's lifecycle callbacks only through `installModule` / `uninstallModule`.
1751
+ ///
1752
+ /// ONE EXCEPTION, deliberate: the canonical custody policy itself stays a valid target. Its
1753
+ /// `scheduleCustodyChange` / `applyCustodyChange` / `cancelScheduledChange` are authorized by the
1754
+ /// quorum signatures they carry and do not care who submits them — a passkey-only person submits
1755
+ /// them as a user operation from the very account they govern, and refusing that would leave her
1756
+ /// dependent on a relayer to change her own custody. The two entry points where the policy DOES
1757
+ /// take `msg.sender == account` as principal defend themselves (`onInstall`: NotInstalledAsExecutorOn
1758
+ /// / AlreadyInstalledOn; `onUninstall`: StillInstalledOn, R917-C-1).
1759
+ ///
1760
+ /// A self-governed (mode-0) account's one credential IS its custody tier — it can install and
1761
+ /// uninstall — so the rule adds nothing there and is not applied; a hook defends its own
1762
+ /// `onInstall` / `onUninstall` on every mode.
1763
+ function _rejectModuleTarget(address target) internal view {
1764
+ if (_delegationExecCtx || _custodyGovCtx) return; // refused already (delegation) / the quorum itself
1765
+ address f = _factory;
1766
+ if (f == address(0)) return;
1767
+ address cp = IAgentAccountFactoryView(f).custodyPolicy();
1768
+ if (cp == address(0) || !_modulesStorage().installed[MODULE_TYPE_EXECUTOR][cp]) return; // self-governed
1769
+ if (target != cp && _isInstalledModule(target)) revert ModuleNotAnExecuteTarget(target);
1770
+ }
1771
+
1347
1772
  /// @dev Spec 410 §1 (THESIS-1a). `ApprovedHashRegistry.approveHash` stores whatever 32 bytes the account
1348
1773
  /// sends, and the custody epoch is public — so a custodian who could reach the registry through
1349
1774
  /// `execute` could approve `keccak256(abi.encode(h, epoch + 1))`: inert now, live the moment a
@@ -1360,6 +1785,7 @@ contract AgentAccount is
1360
1785
  /// deploy with no factory has none); the registry is the immutable this account was built with.
1361
1786
  function _isAccountTrustedTarget(address target) internal view returns (bool) {
1362
1787
  if (target == _approvedHashRegistry && target != address(0)) return true;
1788
+ if (_isInstalledModule(target)) return true;
1363
1789
  address f = _factory;
1364
1790
  if (f == address(0)) return false;
1365
1791
  address cp = IAgentAccountFactoryView(f).custodyPolicy();
@@ -1379,6 +1805,8 @@ contract AgentAccount is
1379
1805
  s == this.cancelPendingUpgrade.selector ||
1380
1806
  s == this.installModule.selector ||
1381
1807
  s == this.uninstallModule.selector ||
1808
+ s == this.reaffirmModule.selector ||
1809
+ s == this.reaffirmDelegationManager.selector ||
1382
1810
  s == IAgentAccount.addCustodian.selector ||
1383
1811
  s == IAgentAccount.removeCustodian.selector ||
1384
1812
  s == this.addPasskey.selector ||
@@ -1830,10 +2258,21 @@ contract AgentAccount is
1830
2258
  }
1831
2259
 
1832
2260
  /// @dev Retire-a-credential paths call this; see `_custodyEpoch`.
2261
+ /// Spec 445 §1.3 (ii): the bump is what expels everything a retired credential could have
2262
+ /// installed — approved hashes (R917-C-2), non-canonical executor modules (`_moduleEpochStamp`), a
2263
+ /// non-canonical delegation manager (`_delegationManagerEpochStamp`) — because each is honoured only
2264
+ /// under the epoch it was made in. The one thing not keyed to the epoch is the upgrade queue, so it
2265
+ /// is cleared here: `executePendingUpgrade` is permissionless once matured, and an upgrade queued by
2266
+ /// the credential being retired must not fire after it is gone. The owner re-queues if she wants it.
1833
2267
  function _bumpCustodyEpoch() internal {
1834
2268
  uint64 next = _custodyEpoch + 1;
1835
2269
  _custodyEpoch = next;
1836
2270
  emit CustodyEpochBumped(next);
2271
+ address pending = _pendingUpgrade.newImplementation;
2272
+ if (_pendingUpgrade.readyAt != 0) {
2273
+ delete _pendingUpgrade;
2274
+ emit UpgradeCancelled(pending);
2275
+ }
1837
2276
  }
1838
2277
 
1839
2278
  // ─── Approved digests (spec 410 §1, THESIS-1a) ───────────────────