@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
@@ -1,8 +1,9 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  pragma solidity ^0.8.28;
3
3
 
4
- import {IAgentAccount, AgentAccountRecoveryArgs, AgentAccountRecoveryPasskeyAdd} from "../IAgentAccount.sol";
5
- import {SignatureSlotRecovery} from "../libraries/SignatureSlotRecovery.sol";
4
+ import {IAgentAccount, AgentAccountRecoveryArgs, AgentAccountRecoveryPasskeyAdd, AgentAccountRotateCredentialArgs} from "../IAgentAccount.sol";
5
+ import {SignatureVerifier} from "../libraries/SignatureVerifier.sol";
6
+ import {StableProxyGoverned} from "../governance/StableProxyGoverned.sol";
6
7
 
7
8
  /// @dev R6.6 — minimal interface for the `account → factory → governance.isPaused()`
8
9
  /// staticcall chain. Mirrors the same patterns introduced by R6.5
@@ -14,12 +15,28 @@ interface IAgentAccountFactoryAccessor {
14
15
 
15
16
  interface ICustodyPolicyFactoryView {
16
17
  function governance() external view returns (address);
18
+ /// @dev ACCT-11 — the deployment's T4-floor posture (R917-C-5), read when a policy is installed
19
+ /// post-deploy so `onInstall` applies the same floor the factory would have.
20
+ function relaxedT4Floor() external view returns (bool);
17
21
  }
18
22
 
19
23
  interface ICustodyPolicyPauseView {
20
24
  function isPaused() external view returns (bool);
21
25
  }
22
26
 
27
+ /// @dev R917-C-1 — the account's ERC-7579 module view. `onUninstall` refuses while the account still lists
28
+ /// this module as installed, so the only path to it is `AgentAccount.uninstallModule` (onlySelf +
29
+ /// custody-quorum), which clears the flag BEFORE calling out.
30
+ interface ICustodyPolicyAccountModuleView {
31
+ function isModuleInstalled(uint256 moduleTypeId, address module, bytes calldata additionalContext) external view returns (bool);
32
+ }
33
+
34
+ /// @dev Audit 2026-11-10 CUST-4 — a passkey's trustee seat is its per-account PIA; read before it is removed.
35
+ interface ICustodyPolicyPasskeyView {
36
+ function getPasskey(bytes32 credentialIdDigest) external view returns (uint256 x, uint256 y);
37
+ function passkeyIdentity(uint256 x, uint256 y) external view returns (address);
38
+ }
39
+
23
40
  /**
24
41
  * @title CustodyPolicy
25
42
  * @notice ERC-7579 module that owns the schedule / apply / cancel
@@ -51,9 +68,10 @@ interface ICustodyPolicyPauseView {
51
68
  * timelock → safetyDelay, guardian → trustee, owner → custodian),
52
69
  * and EIP-712 typehashes likewise.
53
70
  */
54
- contract CustodyPolicy {
71
+ contract CustodyPolicy is StableProxyGoverned {
55
72
  // ─── ERC-7579 marker constants (mirror of the account-side ids) ──
56
73
  uint256 internal constant MODULE_TYPE_EXECUTOR = 2;
74
+ uint256 internal constant MODULE_TYPE_HOOK = 4;
57
75
 
58
76
  // ─── CustodyAction enum + structs (moved from AgentAccount) ────────
59
77
 
@@ -73,7 +91,16 @@ contract CustodyPolicy {
73
91
  ChangeValueCeiling, // 12 — T4
74
92
  SetRecoveryApprovals, // 13 — T4
75
93
  RecoverAccount, // 14 — T6
76
- ChangeApprovalsRequired // 15 — T4 (per-tier custody quorum threshold)
94
+ ChangeApprovalsRequired, // 15 — T4 (per-tier custody quorum threshold)
95
+ RotateCredential, // 16 — T4 (spec 410 §1.2: add + retire + re-approve standing wires, atomically;
96
+ // generation 4: + re-affirm kept modules / delegation manager)
97
+ // ─── Generation 4 (spec 445 §1.5, audit CUST-3 / ACCT-5) — appended; 0..16 keep their numbers ───
98
+ InstallModule, // 17 — T5 (installModule(type, module, initData) — an executor can act as the account)
99
+ UninstallModule, // 18 — T5 (uninstallModule — removing a hook removes a protection)
100
+ LowerSpendCeiling, // 19 — T4 (TreasurySpendPolicy.lowerCeiling — can only tighten)
101
+ SetSpendCeiling // 20 — T5 (TreasurySpendPolicy.setCeiling — may raise)
102
+ // (A custody-quorum `GovernanceCall` was drafted as 21 and withdrawn by owner decision 2026-11-10 — see
103
+ // AUDIT.md 2.27. The next appended action takes 21.)
77
104
  }
78
105
 
79
106
  struct ScheduledChange {
@@ -84,6 +111,9 @@ contract CustodyPolicy {
84
111
  address proposer;
85
112
  bool executed;
86
113
  bool cancelled;
114
+ /// @dev Audit 2026-11-10 CUST-6 — the last second the change may be applied (`eta + APPLY_WINDOW`).
115
+ /// Appended: packs into the slot `proposer / executed / cancelled` already occupy (22 of 32 bytes).
116
+ uint64 expiresAt;
87
117
  }
88
118
 
89
119
  /// @dev Per-account config. One mapping entry per installed-on account.
@@ -109,6 +139,8 @@ contract CustodyPolicy {
109
139
  }
110
140
 
111
141
  mapping(address => Config) internal _configs;
142
+ /// @dev Storage gap (spec 447: behind a stable proxy; layout gated by `check:storage-layouts`).
143
+ uint256[49] private __gap;
112
144
 
113
145
  // ─── Constants ────────────────────────────────────────────────────
114
146
 
@@ -130,20 +162,24 @@ contract CustodyPolicy {
130
162
  "CancelScheduledChangeRequest(address account,uint8 action,bytes32 argsHash,uint256 changeId,uint64 eta)"
131
163
  );
132
164
 
133
- /// @dev Cached at deploy-time for the deploy-time chainId. If
134
- /// `block.chainid` differs at call time (chain fork), we
135
- /// recompute on demand. Mirrors OpenZeppelin's EIP712 base.
136
- uint256 private immutable _CACHED_CHAIN_ID;
137
- bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
138
-
139
- constructor() {
140
- _CACHED_CHAIN_ID = block.chainid;
141
- _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator();
165
+ /// @notice A direct deployment, initialized here (no governance: never upgradeable). Behind a stable proxy
166
+ /// (spec 447), `initialize(governance_)` instead. The quorum signs over this contract's EIP-712 domain,
167
+ /// and every account holds its address as the factory's canonical custody policy, so a fix must keep
168
+ /// the address: scheduled changes and their signatures survive it.
169
+ /// @notice Spec 449: the stateless verifier that recovers each quorum signature slot
170
+ /// (`SignatureSlotRecovery.recoverFromSlot`, unchanged) — moved out of this bytecode for EIP-170 room.
171
+ /// Created by this implementation's constructor, so it is part of the code governance vouched; reached
172
+ /// by STATICCALL from `_verifyQuorum` only; no state, no authority (it returns a signer, this policy
173
+ /// decides whether that signer counts).
174
+ address public immutable signatureVerifier;
175
+
176
+ constructor() initializer {
177
+ signatureVerifier = address(new SignatureVerifier());
142
178
  }
143
179
 
144
180
  // ─── R6.6 / CON-CustodyPolicy-005 — system-pause modifier ──────
145
181
  //
146
- // `whenAccountNotPaused(account)` reverts when
182
+ // The pause gate (`_systemPausedFor(account)`, checked inline) reverts when
147
183
  // `AgenticGovernance.isPaused() == true`, where governance is
148
184
  // resolved per-call via the account's factory:
149
185
  //
@@ -155,7 +191,15 @@ contract CustodyPolicy {
155
191
  // deploys keep working — mirrors the R6.5 pattern in AgentAccount
156
192
  // and `GovernanceManaged._pausedSafe()`.
157
193
  //
158
- // Applied to: `scheduleCustodyChange`, `applyCustodyChange`.
194
+ // Applied to: `scheduleCustodyChange`, `applyCustodyChange` — EXCEPT for the actions in
195
+ // `_isPauseExemptAction` (spec 445 §1.2 / ACCT-2): `RemoveCustodian`, `RemovePasskeyCredential`
196
+ // and `UninstallModule`. Those three only REMOVE authority or attack surface; a quorum must be able
197
+ // to schedule and apply them during the very incident a pause is for. They keep their quorum and
198
+ // their safety delay. The account's `executeFromModule` carries the matching exemption (the canonical
199
+ // policy dispatching `removeCustodian` / `removePasskey` / `uninstallModule` on the account itself);
200
+ // every other action stays frozen at both doors. Before generation 4 the account-side functions
201
+ // were merely un-gated and the only route to them was paused here — recovery was documented live and
202
+ // was not.
159
203
  //
160
204
  // Deliberately NOT applied to (recovery primitives that must
161
205
  // work during an incident):
@@ -165,9 +209,15 @@ contract CustodyPolicy {
165
209
  // `installModule` on AgentAccount (R6.5)
166
210
  // and paused `createAgentAccount`
167
211
  // on AgentAccountFactory
168
- modifier whenAccountNotPaused(address account) {
169
- if (_systemPausedFor(account)) revert SystemPaused();
170
- _;
212
+ /// @dev Spec 445 §1.2 / ACCT-2 — the custody actions that stay schedulable and applicable under a pause.
213
+ /// Removal only: nothing here adds a credential or a trustee, installs or re-affirms anything,
214
+ /// changes a threshold, rotates, recovers, upgrades or raises a ceiling — except that a removal may carry
215
+ /// the T4 / T5 LOWERING it needs to leave every tier reachable (CUST-5; a T5 quorum + the T5 delay):
216
+ /// without it a 3-of-3 account could not expel a compromised custodian during the incident at all.
217
+ function _isPauseExemptAction(CustodyAction action) internal pure returns (bool) {
218
+ return action == CustodyAction.RemoveCustodian
219
+ || action == CustodyAction.RemovePasskeyCredential
220
+ || action == CustodyAction.UninstallModule;
171
221
  }
172
222
 
173
223
  /// @notice R6.6 — thrown when a `whenAccountNotPaused`-guarded
@@ -176,27 +226,32 @@ contract CustodyPolicy {
176
226
  error SystemPaused();
177
227
 
178
228
  function _systemPausedFor(address account) internal view returns (bool) {
179
- if (account == address(0) || account.code.length == 0) return false;
180
- // Hop 1: account → factory
229
+ address gov = _governanceOf(account);
230
+ if (gov == address(0)) return false;
231
+ // Hop 3: governance → isPaused
232
+ (bool okP, bytes memory dataP) = gov.staticcall(
233
+ abi.encodeWithSelector(ICustodyPolicyPauseView.isPaused.selector)
234
+ );
235
+ if (!okP || dataP.length < 32) return false;
236
+ return abi.decode(dataP, (bool));
237
+ }
238
+
239
+ /// @dev Hops 1–2 of the pause read: `account → factory() → governance()`. Zero on any non-conforming hop or a
240
+ /// codeless address.
241
+ function _governanceOf(address account) internal view returns (address gov) {
242
+ if (account == address(0) || account.code.length == 0) return address(0);
181
243
  (bool okF, bytes memory dataF) = account.staticcall(
182
244
  abi.encodeWithSelector(IAgentAccountFactoryAccessor.factory.selector)
183
245
  );
184
- if (!okF || dataF.length < 32) return false;
246
+ if (!okF || dataF.length < 32) return address(0);
185
247
  address fac = abi.decode(dataF, (address));
186
- if (fac == address(0) || fac.code.length == 0) return false;
187
- // Hop 2: factory → governance
248
+ if (fac == address(0) || fac.code.length == 0) return address(0);
188
249
  (bool okG, bytes memory dataG) = fac.staticcall(
189
250
  abi.encodeWithSelector(ICustodyPolicyFactoryView.governance.selector)
190
251
  );
191
- if (!okG || dataG.length < 32) return false;
192
- address gov = abi.decode(dataG, (address));
193
- if (gov == address(0) || gov.code.length == 0) return false;
194
- // Hop 3: governance → isPaused
195
- (bool okP, bytes memory dataP) = gov.staticcall(
196
- abi.encodeWithSelector(ICustodyPolicyPauseView.isPaused.selector)
197
- );
198
- if (!okP || dataP.length < 32) return false;
199
- return abi.decode(dataP, (bool));
252
+ if (!okG || dataG.length < 32) return address(0);
253
+ gov = abi.decode(dataG, (address));
254
+ if (gov.code.length == 0) return address(0);
200
255
  }
201
256
 
202
257
  function _buildDomainSeparator() internal view returns (bytes32) {
@@ -211,8 +266,9 @@ contract CustodyPolicy {
211
266
  );
212
267
  }
213
268
 
269
+ /// @dev Computed per call from `address(this)` — the proxy's address behind a proxy. Never cached in an
270
+ /// immutable: that would carry the implementation's address (spec 447). Recomputes on a chain split.
214
271
  function _domainSeparator() internal view returns (bytes32) {
215
- if (block.chainid == _CACHED_CHAIN_ID) return _CACHED_DOMAIN_SEPARATOR;
216
272
  return _buildDomainSeparator();
217
273
  }
218
274
 
@@ -265,6 +321,20 @@ contract CustodyPolicy {
265
321
  /// primary-owner cancel window.
266
322
  uint64 internal constant RECOVERY_PRIMARY_CANCEL_WINDOW = 24 hours;
267
323
 
324
+ /// @dev Audit 2026-11-10 CUST-6 — A SCHEDULED CHANGE LAPSES. It may be applied from `eta` until
325
+ /// `eta + APPLY_WINDOW` inclusive, then never: a safety delay is notice of a change about to happen,
326
+ /// not a reservation the quorum can hold for years (the PoC applied a recovery's pre-signed approvals
327
+ /// three years later, from an unrelated address). One window for every tier, recovery included, so
328
+ /// `expiresAt` is a pure function of `eta` — and an apply approval, which signs `eta`, signs the expiry
329
+ /// with it (no typehash change). This contract is not upgradeable, so the constant cannot move under
330
+ /// a signature. Recovery keeps its rule: the custodians may cancel in the first 24 h, the trustees
331
+ /// after; past the window the recovery is dead and the trustees must schedule a new one (another
332
+ /// 48 h, another 24 h owner-cancel window).
333
+ uint64 public constant APPLY_WINDOW = 7 days;
334
+
335
+ /// @dev ACCT-11 — the factory's `MAX_INITIAL_TRUSTEES`, applied to a post-deploy install.
336
+ uint256 internal constant MAX_INSTALL_TRUSTEES = 32;
337
+
268
338
  // ─── Events ───────────────────────────────────────────────────────
269
339
 
270
340
  event CustodyPolicyInstalled(address indexed account, uint8 mode, uint8 recoveryApprovals);
@@ -273,13 +343,28 @@ contract CustodyPolicy {
273
343
  event CustodyChangeScheduled(address indexed account, uint256 indexed changeId, CustodyAction indexed action, uint64 eta, address proposer);
274
344
  event CustodyChangeApplied(address indexed account, uint256 indexed changeId);
275
345
  event ScheduledChangeCancelled(address indexed account, uint256 indexed changeId);
276
- event GuardianAdded(address indexed account, address indexed guardian);
277
- event GuardianRemoved(address indexed account, address indexed guardian);
346
+ /// @dev Spec 302 W3 — guardian/trustee events carry an opaque MEMBERSHIP
347
+ /// COMMITMENT, not the raw guardian address: `GuardianAdded(account,
348
+ /// guardian)` published each person's social-recovery graph (who
349
+ /// guards whom) permanently. The commitment
350
+ /// `keccak256(abi.encode(guardian, account))` is unsalted +
351
+ /// on-chain-reproducible (ADR-0040 posture): anyone holding a
352
+ /// CANDIDATE guardian address can confirm membership, but nobody can
353
+ /// enumerate the graph from logs. The ONE read path for a live check
354
+ /// is `isTrustee(account, signer)` (ADR-0012/0013).
355
+ event GuardianAdded(address indexed account, bytes32 indexed guardianCommitment);
356
+ event GuardianRemoved(address indexed account, bytes32 indexed guardianCommitment);
278
357
  event ThresholdChanged(address indexed account, uint8 indexed tier, uint8 oldValue, uint8 newValue);
279
358
  event ModeChanged(address indexed account, uint8 oldMode, uint8 newMode);
280
359
  event T3CeilingChanged(address indexed account, uint256 oldCeiling, uint256 newCeiling);
281
360
  event RecoveryThresholdChanged(address indexed account, uint8 oldValue, uint8 newValue);
282
361
  event OwnersRotated(address indexed account, uint256 newOwnerCount);
362
+ /// @dev Spec 410 §1.2 — a planned rotation applied: one credential in, one out, `reapproved` wires
363
+ /// re-approved under the new custody epoch in the same transaction.
364
+ event CredentialRotated(address indexed account, uint256 reapproved);
365
+ /// @dev Spec 445 §1.3 (ii) — the same rotation also re-affirmed `modules` kept executor modules and,
366
+ /// when `delegationManager` is true, the account's current delegation manager.
367
+ event RotationReaffirmed(address indexed account, uint256 modules, bool delegationManager);
283
368
  /// @notice Audit C-10: per-rotation count of custodians removed.
284
369
  event CustodiansRemovedDuringRotation(address indexed account, uint256 removedCount);
285
370
  /// @notice Audit C-11: CustodyPolicy was uninstalled; the account
@@ -309,12 +394,26 @@ contract CustodyPolicy {
309
394
  error AdminInsufficientQuorum(uint256 supplied, uint8 required);
310
395
  error AdminDuplicateOrUnsortedSigner(address signer);
311
396
  error AdminUnauthorizedSigner(address signer);
397
+ /// @notice ACCT-C2 (spec 300) — the account itself was presented as a quorum
398
+ /// signer (via `isCustodian(address(this))==true` or the `v=0`
399
+ /// self-referential ERC-1271 slot). A self-signature must never count
400
+ /// toward the quorum, else one custodian forges an extra member.
401
+ error AdminSelfSignerNotAllowed(address account);
312
402
  error TrusteeAlreadyExists(address guardian);
313
403
  error TrusteeDoesNotExist(address guardian);
314
404
  error InvalidMode(uint8 mode_);
315
405
  error InvalidThresholdValue(uint8 thr);
406
+ /// @dev EXT-CHANGEMODE-1: a runtime ChangeMode into org mode (3) with an infeasible signer
407
+ /// count (< 2, so separation-of-duties can't split proposers from appliers). Mirrors the
408
+ /// factory's install-time InfeasibleOrgConfig.
409
+ error InfeasibleOrgConfig(uint8 nSigners);
410
+ /// @dev CP-1: a tier that must be configured (T4/T5 at install, T6 at read)
411
+ /// was left unset — refuse rather than fall to the 1-of-n read fallback.
412
+ error UnconfiguredTier(uint8 tier);
316
413
  error RecoveryRequiresGuardians();
317
414
  error EmptyOwnerSet();
415
+ /// @dev Spec 410 §1.2 — `RotateCredential` needs exactly one credential added and exactly one retired.
416
+ error RotationNeedsOneAddAndOneRemove();
318
417
  error CustodyActionNotYetImplemented(uint8 action);
319
418
  error CannotDowngradeWithTrustees();
320
419
  error TimelockRequiredForTier(uint8 tier);
@@ -325,6 +424,35 @@ contract CustodyPolicy {
325
424
  /// @dev Audit C-11: reinstall over a previously-uninstalled config
326
425
  /// is forbidden — stale mappings would compose unpredictably.
327
426
  error ReinstallForbidden(address account);
427
+ /// @dev R917-C-1: `onUninstall` was called while the account still has this module installed — i.e. by
428
+ /// `execute(custodyPolicy, onUninstall)` under a single custodian or a delegation, not by
429
+ /// `uninstallModule`. Accepting it would leave the account governed by a policy that refuses every
430
+ /// change (installed on the account, uninstalled here, reinstall forbidden) — bricked forever.
431
+ error StillInstalledOn(address account);
432
+ /// @dev ACCT-11 (audit 2026-11-10): `onInstall` was called by an address that does not list this module as
433
+ /// an installed EXECUTOR — i.e. by `execute(custodyPolicy, onInstall(cfg))`, not by `installModule`.
434
+ /// Accepting it made the policy report `isInstalledOn == true` and a custody mode for an account it
435
+ /// cannot act on, and made a later genuine install revert `AlreadyInstalledOn`.
436
+ error NotInstalledAsExecutorOn(address account);
437
+ /// @dev ACCT-11 / CUST-8: a safety delay below the product floor on an install that did not come through
438
+ /// the factory (which enforces the same floors itself, EXT-TL-FLOOR-1).
439
+ error SafetyDelayBelowFloor(uint8 tier, uint32 provided, uint32 floorSecs);
440
+ /// @dev Spec 445 §1.5: `UninstallModule` named this custody policy itself.
441
+ error CannotUninstallCustodyPolicy();
442
+ /// @dev Spec 445 §1.5 (CUST-3): a spend-ceiling action named a hook the account does not have installed.
443
+ error HookNotInstalledOn(address account, address hook);
444
+ /// @notice Audit 2026-11-10 CUST-6 — the change's apply window (`eta … expiresAt`) has passed.
445
+ error ProposalExpired(uint256 changeId, uint64 expiresAt);
446
+ /// @notice Audit 2026-11-10 CUST-5 / ACCT-11 — a tier's threshold would exceed what the custodian set can
447
+ /// reach: the custodian count, or `floor(count / 2)` for T4 / T5 in org mode (disjoint proposers and
448
+ /// appliers). Raised by every applied change (except a recovery, which clamps) and by `onInstall`.
449
+ error ThresholdUnreachable(uint8 tier, uint8 required, uint256 bound);
450
+ /// @notice ACCT-11 — a post-deploy install below the factory's per-mode trustee minimum (mode 1: 1, mode 2: 2,
451
+ /// mode 3: 3; a positive recovery quorum) or above its trustee cap.
452
+ error TrusteesOutsideModeBounds(uint8 mode, uint256 trustees, uint8 recoveryApprovals);
453
+ /// @notice CUST-5 — `RemoveCustodian` / `RemovePasskeyCredential` args are neither the one-word form nor the
454
+ /// three-word form that also lowers T4 / T5.
455
+ error MalformedRemovalArgs(uint256 length);
328
456
 
329
457
  // ─── ERC-7579 lifecycle ───────────────────────────────────────────
330
458
 
@@ -351,6 +479,12 @@ contract CustodyPolicy {
351
479
  // ways. Force a new deploy if the operator genuinely needs a
352
480
  // fresh policy for this account.
353
481
  if (c.permanentlyUninstalled) revert ReinstallForbidden(account);
482
+ // ACCT-11: the caller must be an account that is INSTALLING this module — `installModule` sets its
483
+ // installed flag before it calls here. Mirror of the R917-C-1 check in `onUninstall`; fails closed
484
+ // on a caller that cannot answer the view (the staticcall reverts, and so does this).
485
+ if (!ICustodyPolicyAccountModuleView(account).isModuleInstalled(MODULE_TYPE_EXECUTOR, address(this), "")) {
486
+ revert NotInstalledAsExecutorOn(account);
487
+ }
354
488
 
355
489
  (
356
490
  uint8 modeVal,
@@ -370,11 +504,7 @@ contract CustodyPolicy {
370
504
  c.t3HighValueCeiling = t3Ceiling;
371
505
  c.approvedHashRegistry = approvedHashReg;
372
506
 
373
- for (uint8 t = 1; t <= 6; t++) {
374
- if (thresholds[t] > 0) c.approvalsRequiredByTier[t] = thresholds[t];
375
- if (timelocks[t] > 0) c.safetyDelayByTier[t] = timelocks[t];
376
- }
377
-
507
+ // Trustees first so `trusteeCount` is known for the CP-2 recovery check.
378
508
  for (uint256 i; i < trustees.length; i++) {
379
509
  address g = trustees[i];
380
510
  if (g == address(0)) revert ZeroAddress();
@@ -383,13 +513,118 @@ contract CustodyPolicy {
383
513
  c.trusteeCount += 1;
384
514
  }
385
515
 
516
+ // CP-2: a recovery threshold the trustee set can NEVER satisfy bricks the
517
+ // T6 recovery lifeline from birth. Validate at install exactly as
518
+ // `_applySetRecoveryThreshold` does at runtime. `recoveryApprovals == 0`
519
+ // is a legitimate state (trustee recovery simply disabled); a positive
520
+ // threshold MUST be reachable by the configured trustees.
521
+ if (recThr > c.trusteeCount) revert RecoveryRequiresGuardians();
522
+
523
+ // CP-1: floor each unset tier to the spec default-approvals matrix so a
524
+ // direct onInstall that bypasses the factory with a zeroed/partial
525
+ // threshold array can't collapse the admin/critical tiers to the 1-of-n
526
+ // read fallback in `_approvalsValue`. T1–T3 legitimately stay at the
527
+ // 1-of-n floor (read/write/value are single-signer tiers by design);
528
+ // T4/T5 get the council default. T6 (recovery) lives in
529
+ // `recoveryApprovals`, not this map.
530
+ //
531
+ // The custodian count is read best-effort from the installing account
532
+ // (the ERC-7579 flow guarantees `msg.sender` is the deployed account).
533
+ // If it can't be determined (the account isn't yet/at all an
534
+ // `IAgentAccount`), `nCustodians` stays 0 so no flooring happens — and
535
+ // the hard-revert below then REQUIRES the installer to have passed
536
+ // explicit T4/T5 thresholds. Either way the admin/critical tiers can
537
+ // never silently resolve to 1-of-n; the floor is a convenience, the
538
+ // hard-revert is the security invariant.
539
+ uint8 nCustodians;
540
+ if (account.code.length > 0) {
541
+ try IAgentAccount(account).custodianCount() returns (uint256 cnt) {
542
+ nCustodians = cnt > 255 ? 255 : uint8(cnt);
543
+ } catch {}
544
+ }
545
+ for (uint8 t = 1; t <= 6; t++) {
546
+ uint8 thr = thresholds[t];
547
+ if (thr == 0) {
548
+ thr = _defaultApprovals(nCustodians, t);
549
+ // ACCT-11: the factory's mode-3 cap, applied to a DEFAULTED T4 / T5 exactly as the factory applies
550
+ // it. An explicit over-cap value is not rewritten — `_requireThresholdsReachable` refuses it.
551
+ if (modeVal == 3 && (t == 4 || t == 5) && thr > nCustodians / 2) thr = nCustodians / 2;
552
+ }
553
+ if (thr > 0) c.approvalsRequiredByTier[t] = thr;
554
+ if (timelocks[t] > 0) c.safetyDelayByTier[t] = timelocks[t];
555
+ }
556
+
557
+ // CP-1 hard-revert: a non-single account MUST have the admin (T4) +
558
+ // critical (T5) custody quorum configured (explicitly or via the floor
559
+ // above) — never the 1-of-n read fallback. Mode 0 (single signer) has no
560
+ // custody council, so thresholds are moot and this is skipped.
561
+ if (modeVal >= 1) {
562
+ if (c.approvalsRequiredByTier[4] == 0) revert UnconfiguredTier(4);
563
+ if (c.approvalsRequiredByTier[5] == 0) revert UnconfiguredTier(5);
564
+ _requireSafetyDelayFloors(account, c);
565
+ // ACCT-11 (remainder) — the factory's per-mode trustee bounds, so a post-deploy install cannot
566
+ // create a configuration the factory would refuse: ≥ 1 / 2 / 3 trustees for mode 1 / 2 / 3, at most
567
+ // `MAX_INSTALL_TRUSTEES` (the factory's ACCT-10 cap), and a positive recovery quorum (the factory
568
+ // always sets floor(n/2)+1).
569
+ if (trustees.length < modeVal || trustees.length > MAX_INSTALL_TRUSTEES || recThr == 0) {
570
+ revert TrusteesOutsideModeBounds(modeVal, trustees.length, recThr);
571
+ }
572
+ }
573
+ // ACCT-11 / CUST-5 — every tier reachable by the custodian set the account has right now (and in mode 3
574
+ // the separation-of-duties cap, with ≥ 2 custodians). The factory's thresholds satisfy this by
575
+ // construction. Mode 0 with an unreadable custodian count (not an AgentAccount) has nothing to bound.
576
+ if (modeVal >= 1 || nCustodians > 0) _requireThresholdsReachable(c, nCustodians);
577
+
386
578
  emit CustodyPolicyInstalled(account, modeVal, recThr);
387
579
  }
388
580
 
581
+ /// @dev ACCT-11 / CUST-8 (audit 2026-11-10) — THE FACTORY'S DELAY FLOORS, APPLIED AT EVERY INSTALL. The
582
+ /// factory refuses a governed account whose T4 / T5 / T6 delays are below 1 h / 24 h / 48 h
583
+ /// (EXT-TL-FLOOR-1), but a policy installed AFTER deploy (`execute(self, installModule(2, policy,
584
+ /// cfg))` — the spec 422 path every Home person takes) stored whatever the client sent, so "24 h to
585
+ /// upgrade, 48 h to recover, cancellable for 24" was an invariant of factory-born accounts only. A
586
+ /// factory install satisfies these by construction, so they are applied unconditionally:
587
+ /// T5 ≥ 24 h;
588
+ /// T6 ≥ 48 h whenever trustee recovery is enabled (`recoveryApprovals > 0`) — which also keeps the
589
+ /// 24 h owner-cancel window inside the delay;
590
+ /// T4 ≥ 1 h, unless the account's factory declares `relaxedT4Floor` (the local-development
591
+ /// posture, R917-C-5). A factory-less account, or a factory that cannot answer, gets the floor.
592
+ /// The per-mode trustee bounds and the mode-3 separation-of-duties cap are applied in `onInstall` too
593
+ /// (ACCT-11 remainder, generation 4).
594
+ function _requireSafetyDelayFloors(address account, Config storage c) internal view {
595
+ uint32 d5 = c.safetyDelayByTier[5];
596
+ if (d5 < 24 hours) revert SafetyDelayBelowFloor(5, d5, uint32(24 hours));
597
+ uint32 d6 = c.safetyDelayByTier[6];
598
+ if (c.recoveryApprovals > 0 && d6 < 48 hours) revert SafetyDelayBelowFloor(6, d6, uint32(48 hours));
599
+ uint32 d4 = c.safetyDelayByTier[4];
600
+ if (d4 < 1 hours && !_relaxedT4FloorFor(account)) revert SafetyDelayBelowFloor(4, d4, uint32(1 hours));
601
+ }
602
+
603
+ function _relaxedT4FloorFor(address account) internal view returns (bool) {
604
+ (bool okF, bytes memory dataF) = account.staticcall(
605
+ abi.encodeWithSelector(IAgentAccountFactoryAccessor.factory.selector)
606
+ );
607
+ if (!okF || dataF.length < 32) return false;
608
+ address fac = abi.decode(dataF, (address));
609
+ if (fac == address(0) || fac.code.length == 0) return false;
610
+ (bool okR, bytes memory dataR) = fac.staticcall(
611
+ abi.encodeWithSelector(ICustodyPolicyFactoryView.relaxedT4Floor.selector)
612
+ );
613
+ return okR && dataR.length == 32 && abi.decode(dataR, (uint256)) == 1;
614
+ }
615
+
389
616
  function onUninstall(bytes calldata) external {
390
617
  address account = msg.sender;
391
618
  Config storage c = _configs[account];
392
619
  if (!c.installed) revert NotInstalledOn(account);
620
+ // R917-C-1: the account must have ALREADY dropped this module. `AgentAccount.uninstallModule` (onlySelf
621
+ // + `_requireCustodyGoverned`) clears its installed flag before this call; any other caller that is the
622
+ // account — a 1-of-N custodian userOp `execute(custodyPolicy, onUninstall)`, a delegation redeemed
623
+ // through the DM — still lists the module and is refused here. Fail closed on the read as well: a
624
+ // caller that cannot answer the view is not an account that uninstalled us.
625
+ if (ICustodyPolicyAccountModuleView(account).isModuleInstalled(MODULE_TYPE_EXECUTOR, address(this), "")) {
626
+ revert StillInstalledOn(account);
627
+ }
393
628
  c.installed = false;
394
629
  // Audit C-11: lock against ever re-installing on this account.
395
630
  // The mapping state (trustees, thresholds, proposals) is left
@@ -409,7 +644,8 @@ contract CustodyPolicy {
409
644
  CustodyAction action,
410
645
  bytes calldata args,
411
646
  bytes calldata quorumSigs
412
- ) external whenAccountNotPaused(account) returns (uint256 changeId) {
647
+ ) external returns (uint256 changeId) {
648
+ if (!_isPauseExemptAction(action) && _systemPausedFor(account)) revert SystemPaused();
413
649
  Config storage c = _configs[account];
414
650
  if (!c.installed) revert NotInstalledOn(account);
415
651
 
@@ -449,7 +685,8 @@ contract CustodyPolicy {
449
685
  eta: eta,
450
686
  proposer: msg.sender,
451
687
  executed: false,
452
- cancelled: false
688
+ cancelled: false,
689
+ expiresAt: eta + APPLY_WINDOW
453
690
  });
454
691
  }
455
692
  {
@@ -470,16 +707,21 @@ contract CustodyPolicy {
470
707
 
471
708
  function applyCustodyChange(address account, uint256 changeId, bytes calldata quorumSigs)
472
709
  external
473
- whenAccountNotPaused(account)
474
710
  {
475
711
  Config storage c = _configs[account];
712
+ ScheduledChange storage p = c.pending[changeId];
713
+ // Pause gate first (as the modifier did), exempting the removal actions — see `_isPauseExemptAction`.
714
+ // An unknown `changeId` reads action 0 (not exempt), so a paused system still answers `SystemPaused`.
715
+ if (!_isPauseExemptAction(p.action) && _systemPausedFor(account)) revert SystemPaused();
476
716
  if (!c.installed) revert NotInstalledOn(account);
477
717
 
478
- ScheduledChange storage p = c.pending[changeId];
479
718
  if (p.eta == 0) revert ProposalNotFound(changeId);
480
719
  if (p.executed) revert ProposalAlreadyExecuted(changeId);
481
720
  if (p.cancelled) revert ProposalAlreadyCancelled(changeId);
482
721
  if (block.timestamp < p.eta) revert ProposalNotReady(changeId, p.eta);
722
+ // CUST-6: the window closes. Checked before any signature is read: a lapsed change is dead whoever holds
723
+ // its approvals.
724
+ if (block.timestamp > p.expiresAt) revert ProposalExpired(changeId, p.expiresAt);
483
725
 
484
726
  bool isRecovery = (p.action == CustodyAction.RecoverAccount);
485
727
  uint8 tier = _effectiveTierFor(c, p.action, p.args);
@@ -498,6 +740,10 @@ contract CustodyPolicy {
498
740
  p.executed = true;
499
741
  emit CustodyChangeApplied(account, changeId);
500
742
  _applyCustodyChange(account, c, p.action, p.args);
743
+ // CUST-5: no applied change may leave a tier the custodian set cannot reach. A removal that would must
744
+ // carry the lowering itself (the three-word `RemoveCustodian` / `RemovePasskeyCredential` form); a
745
+ // recovery clamps instead (`_clampThresholdsToCustodians`) — it is the lifeline and must not strand.
746
+ _requireThresholdsReachable(c, IAgentAccount(account).custodianCount());
501
747
  }
502
748
 
503
749
  function cancelScheduledChange(address account, uint256 changeId, bytes calldata quorumSigs) external {
@@ -583,6 +829,12 @@ contract CustodyPolicy {
583
829
  return (p.action, p.args, p.proposedAt, p.eta, p.proposer, p.executed, p.cancelled);
584
830
  }
585
831
 
832
+ /// @notice CUST-6 — the last second `changeId` may be applied (`eta + APPLY_WINDOW`); 0 for an unknown id.
833
+ /// A separate view so `getScheduledChange`'s return shape (and every decoder of it) is unchanged.
834
+ function scheduledChangeExpiry(address account, uint256 changeId) external view returns (uint64) {
835
+ return _configs[account].pending[changeId].expiresAt;
836
+ }
837
+
586
838
  /// @notice Pure helper exposing the default-threshold matrix from
587
839
  /// spec § 5.1 — owners over n=1..N produce per-tier defaults.
588
840
  function defaultApprovals(uint8 nCustodians, uint8 tier) external pure returns (uint8) {
@@ -597,8 +849,21 @@ contract CustodyPolicy {
597
849
  action == CustodyAction.ApplySystemUpdate ||
598
850
  action == CustodyAction.RotateDelegationManager ||
599
851
  action == CustodyAction.RotatePaymaster ||
600
- action == CustodyAction.RotateSessionIssuer
852
+ action == CustodyAction.RotateSessionIssuer ||
853
+ // Spec 445 §1.5 (CUST-3 / ACCT-5). T5 (critical: full T5 quorum + the 24 h floor), the tier of
854
+ // `ApplySystemUpdate` and `RotateDelegationManager`, because each is the same kind of change:
855
+ // InstallModule — an executor module can act as the account, like a delegation manager;
856
+ // UninstallModule — removing a hook removes a protection (the treasury ceiling);
857
+ // SetSpendCeiling — may RAISE the ceiling, which is removing part of it.
858
+ // T4 is the tier of custody-SET changes; none of these is allowed to be lighter than that, and
859
+ // raising/removing a ceiling a T4 quorum could lift would bound nothing against that quorum.
860
+ action == CustodyAction.InstallModule ||
861
+ action == CustodyAction.UninstallModule ||
862
+ action == CustodyAction.SetSpendCeiling
601
863
  ) return 5;
864
+ // `LowerSpendCeiling` is T4 — the lightest custody tier there is. It can only tighten
865
+ // (`TreasurySpendPolicy.lowerCeiling` reverts unless the new ceiling is strictly lower), so the worst
866
+ // a T4 quorum can do with it is stop spending, which that quorum can do in other ways already.
602
867
  return 4;
603
868
  }
604
869
 
@@ -616,6 +881,13 @@ contract CustodyPolicy {
616
881
  bytes memory args
617
882
  ) internal view returns (uint8) {
618
883
  uint8 base = _tierFor(action);
884
+ if (action == CustodyAction.RemoveCustodian || action == CustodyAction.RemovePasskeyCredential) {
885
+ // CUST-5: the three-word form lowers T4 / T5 with the removal. A decrease is T5 (audit C-8), exactly
886
+ // as if it had been scheduled as `ChangeApprovalsRequired`.
887
+ (uint8 newT4, uint8 newT5) = _removalLowering(args);
888
+ if (_lowers(c, 4, newT4) || _lowers(c, 5, newT5)) return 5;
889
+ return base;
890
+ }
619
891
  if (action != CustodyAction.ChangeApprovalsRequired) return base;
620
892
  // Decode (uint8 tier, uint8 newCount). Bound the change tier in
621
893
  // [1, 5]; T6 (recovery) routes through SetRecoveryApprovals.
@@ -630,10 +902,120 @@ contract CustodyPolicy {
630
902
  return required;
631
903
  }
632
904
 
905
+ /// @dev CUST-5 — `RemoveCustodian` args are `abi.encode(address)` or `abi.encode(address, uint8 newT4,
906
+ /// uint8 newT5)`; `RemovePasskeyCredential` the same with a `bytes32` credential digest. A zero new value
907
+ /// keeps that tier. Any other length is refused (at schedule, since the tier is computed there).
908
+ function _removalLowering(bytes memory args) internal pure returns (uint8 newT4, uint8 newT5) {
909
+ if (args.length == 32) return (0, 0);
910
+ if (args.length != 96) revert MalformedRemovalArgs(args.length);
911
+ (, newT4, newT5) = abi.decode(args, (bytes32, uint8, uint8));
912
+ }
913
+
914
+ function _lowers(Config storage c, uint8 tier, uint8 newValue) internal view returns (bool) {
915
+ return newValue != 0 && newValue < _approvalsValue(c, tier);
916
+ }
917
+
918
+ /// @dev CUST-5 — apply the lowering a three-word removal carries. Only a DECREASE (or no change) is
919
+ /// accepted: a removal never raises a threshold. Whether the result is reachable by the custodian set
920
+ /// left after the removal is checked once, after the whole change (`_requireThresholdsReachable`).
921
+ function _applyRemovalLowering(address account, Config storage c, bytes memory args) internal {
922
+ (uint8 newT4, uint8 newT5) = _removalLowering(args);
923
+ for (uint8 t = 4; t <= 5; t++) {
924
+ uint8 nv = t == 4 ? newT4 : newT5;
925
+ if (nv == 0) continue;
926
+ uint8 old = _approvalsValue(c, t);
927
+ if (nv > old) revert InvalidThresholdValue(nv);
928
+ if (nv == old) continue;
929
+ c.approvalsRequiredByTier[t] = nv;
930
+ emit ThresholdChanged(account, t, old, nv);
931
+ }
932
+ }
933
+
934
+ /// @dev CUST-5 / ACCT-11 — THE INVARIANT: every tier T1..T5 is reachable by `n` custodians, and in org mode
935
+ /// T4 / T5 by a disjoint proposer + applier pair (`2 × threshold ≤ n`, so `n ≥ 2`). A stored 0 reads as
936
+ /// the 1-of-n fallback and needs only `n ≥ 1`, which the account guarantees (it refuses to remove its
937
+ /// last signer). T6 is `recoveryApprovals`, bounded by the trustee count where it is set.
938
+ function _requireThresholdsReachable(Config storage c, uint256 n) internal view {
939
+ bool org = c.mode == 3;
940
+ if (org && n < 2) revert InfeasibleOrgConfig(uint8(n > 255 ? 255 : n));
941
+ for (uint8 t = 1; t <= 5; t++) {
942
+ uint8 v = c.approvalsRequiredByTier[t];
943
+ uint256 bound = (org && t >= 4) ? n / 2 : n;
944
+ if (v > bound) revert ThresholdUnreachable(t, v, bound);
945
+ }
946
+ }
947
+
948
+ /// @dev CUST-5 — a RECOVERY clamps instead of refusing: it is applied by the trustees after 48 h to give an
949
+ /// owner back an account she lost, and refusing it because the custodian set shrank would strand her.
950
+ /// The trustees already decide the whole custodian set, so lowering a threshold to fit it adds nothing
951
+ /// to what they can do. Each clamp emits `ThresholdChanged`. Org mode with fewer than two custodians
952
+ /// has no clamp that works (separation of duties needs two) and is refused.
953
+ function _clampThresholdsToCustodians(address account, Config storage c) internal {
954
+ uint256 n = IAgentAccount(account).custodianCount();
955
+ bool org = c.mode == 3;
956
+ if (org && n < 2) revert InfeasibleOrgConfig(uint8(n > 255 ? 255 : n));
957
+ for (uint8 t = 1; t <= 5; t++) {
958
+ uint8 v = c.approvalsRequiredByTier[t];
959
+ uint256 bound = (org && t >= 4) ? n / 2 : n;
960
+ if (v > bound) {
961
+ c.approvalsRequiredByTier[t] = uint8(bound);
962
+ emit ThresholdChanged(account, t, v, uint8(bound));
963
+ }
964
+ }
965
+ }
966
+
967
+ /// @dev Audit 2026-11-10 CUST-4 — A RETIRED CREDENTIAL LOSES ITS TRUSTEE SEAT. A trustee may be one of the
968
+ /// account's own credentials (the factory's `SELF_PASSKEY_TRUSTEE` makes the initial passkey's PIA one).
969
+ /// Before generation 4 retiring the credential left the seat, and the retired key could recover the
970
+ /// account alone and expel the credential that replaced it. Every retirement this policy performs —
971
+ /// `RemoveCustodian`, `RemovePasskeyCredential`, `RotateCredential`, `RotateAllCustodians`,
972
+ /// `RecoverAccount` — goes through `_retireCustodian` / `_retirePasskey`, which vacate the seat in the
973
+ /// same applied change. On a custody-governed account those are the ONLY retirement paths (the account
974
+ /// refuses `removeCustodian` / `removePasskey` outside this policy's context), so "retired" and
975
+ /// "trustee" can no longer both be true; an approval the credential signed earlier stops counting
976
+ /// because every apply / cancel verifies its signers against the trustee set as it is at that moment.
977
+ /// If the recovery quorum would then exceed the remaining trustees it is clamped to them (to 0 —
978
+ /// recovery disabled — when none remain), with `RecoveryThresholdChanged`: refusing instead would stop
979
+ /// an owner from retiring a lost device that is also her only trustee.
980
+ function _vacateTrusteeSeat(address account, Config storage c, address credential) internal {
981
+ if (!c.trustees[credential]) return;
982
+ c.trustees[credential] = false;
983
+ c.trusteeCount -= 1;
984
+ emit GuardianRemoved(account, keccak256(abi.encode(credential, account)));
985
+ uint8 oldThr = c.recoveryApprovals;
986
+ if (oldThr > c.trusteeCount) {
987
+ c.recoveryApprovals = uint8(c.trusteeCount);
988
+ emit RecoveryThresholdChanged(account, oldThr, uint8(c.trusteeCount));
989
+ }
990
+ }
991
+
992
+ function _retireCustodian(address account, Config storage c, address o) internal {
993
+ _execute(account, abi.encodeCall(IAgentAccount.removeCustodian, (o)));
994
+ _vacateTrusteeSeat(account, c, o);
995
+ }
996
+
997
+ /// @dev The trustee seat a passkey can hold is its per-account PIA, read from the account BEFORE the key is
998
+ /// deleted. An unregistered digest reads (0, 0) and `removePasskey` reverts.
999
+ function _retirePasskey(address account, Config storage c, bytes32 cid) internal {
1000
+ (uint256 x, uint256 y) = ICustodyPolicyPasskeyView(account).getPasskey(cid);
1001
+ address pia = ICustodyPolicyPasskeyView(account).passkeyIdentity(x, y);
1002
+ _execute(account, abi.encodeWithSignature("removePasskey(bytes32)", cid));
1003
+ _vacateTrusteeSeat(account, c, pia);
1004
+ }
1005
+
633
1006
  function _approvalsValue(Config storage c, uint8 tier) internal view returns (uint8) {
634
1007
  if (tier == 0 || tier > 6) revert InvalidTier(tier);
635
1008
  uint8 v = c.approvalsRequiredByTier[tier];
636
- return v == 0 ? 1 : v;
1009
+ if (v == 0) {
1010
+ // CP-1 defense-in-depth: the T6 (recovery) quorum lives in
1011
+ // `recoveryApprovals`, never in this map — a T6 read here is a
1012
+ // mis-wire, so fail closed instead of returning the 1-of-n fallback.
1013
+ // T1–T5 keep the 1-of-n floor (T4/T5 are install-floored, so the
1014
+ // fallback only ever applies to the low single-signer tiers).
1015
+ if (tier == 6) revert UnconfiguredTier(6);
1016
+ return 1;
1017
+ }
1018
+ return v;
637
1019
  }
638
1020
 
639
1021
  function _safetyDelayValue(Config storage c, uint8 tier) internal view returns (uint32) {
@@ -682,19 +1064,30 @@ contract CustodyPolicy {
682
1064
  QuorumVerifyArgs memory vargs,
683
1065
  bytes calldata signatures
684
1066
  ) internal view returns (address[] memory signers) {
1067
+ // CUST-4: a quorum of zero is no quorum. T1..T5 never read as 0 (`_approvalsValue`), but the recovery quorum
1068
+ // reaches 0 when retirements vacate every trustee seat (`_vacateTrusteeSeat`) — a recovery scheduled before
1069
+ // that must then be unappliable and un-cancellable-by-trustees, never appliable with no signature at all.
1070
+ if (vargs.reqThreshold < 1) revert RecoveryRequiresGuardianQuorum();
685
1071
  if (signatures.length < uint256(vargs.reqThreshold) * 65) {
686
1072
  revert AdminInsufficientQuorum(signatures.length / 65, vargs.reqThreshold);
687
1073
  }
688
- bytes memory sigsMem = signatures;
689
1074
  address approvedHashReg = c.approvedHashRegistry;
1075
+ SignatureVerifier verifier = SignatureVerifier(signatureVerifier);
690
1076
  signers = new address[](vargs.reqThreshold);
691
1077
  address prev;
692
1078
  for (uint256 i; i < vargs.reqThreshold; i++) {
693
- address signer = SignatureSlotRecovery.recoverFromSlot(
694
- vargs.payloadHash, sigsMem, i, approvedHashReg
1079
+ // Its errors (`SignatureSlotRecovery.*`) revert through this call unchanged.
1080
+ address signer = verifier.recoverFromSlot(
1081
+ // Spec 302 W2 — v=2 passkey slots derive the per-ACCOUNT PIA.
1082
+ vargs.payloadHash, signatures, i, approvedHashReg, account
695
1083
  );
696
1084
  if (signer <= prev) revert AdminDuplicateOrUnsortedSigner(signer);
697
1085
  prev = signer;
1086
+ // ACCT-C2 (spec 300): the account is never its own quorum signer. Both
1087
+ // exploit shapes — `isCustodian(address(this))==true` and the `v=0`
1088
+ // self-referential ERC-1271 slot that recovers `signer==account` — land
1089
+ // here as `signer == account`, so one guard closes both.
1090
+ if (signer == account) revert AdminSelfSignerNotAllowed(account);
698
1091
  if (vargs.guardianMode) {
699
1092
  if (!c.trustees[signer]) revert UnauthorizedTrustee(signer);
700
1093
  } else {
@@ -716,8 +1109,12 @@ contract CustodyPolicy {
716
1109
  (address newOwner) = abi.decode(args, (address));
717
1110
  _execute(account, abi.encodeCall(IAgentAccount.addCustodian, (newOwner)));
718
1111
  } else if (action == CustodyAction.RemoveCustodian) {
719
- (address oldOwner) = abi.decode(args, (address));
720
- _execute(account, abi.encodeCall(IAgentAccount.removeCustodian, (oldOwner)));
1112
+ // CUST-5: `abi.encode(address)` or `abi.encode(address, uint8 newT4, uint8 newT5)`.
1113
+ address oldOwner;
1114
+ if (args.length == 32) (oldOwner) = abi.decode(args, (address));
1115
+ else (oldOwner,,) = abi.decode(args, (address, uint8, uint8));
1116
+ _applyRemovalLowering(account, c, args);
1117
+ _retireCustodian(account, c, oldOwner);
721
1118
  } else if (action == CustodyAction.AddPasskeyCredential) {
722
1119
  // H7-C.1 / CON-WEBAUTHN-001: rpIdHash now bundled in the action args
723
1120
  // so credential additions through the custody-policy entrypoint
@@ -729,8 +1126,12 @@ contract CustodyPolicy {
729
1126
  cid, x, y, rpIdHash
730
1127
  ));
731
1128
  } else if (action == CustodyAction.RemovePasskeyCredential) {
732
- (bytes32 cid) = abi.decode(args, (bytes32));
733
- _execute(account, abi.encodeWithSignature("removePasskey(bytes32)", cid));
1129
+ // CUST-5: `abi.encode(bytes32)` or `abi.encode(bytes32, uint8 newT4, uint8 newT5)`.
1130
+ bytes32 cid;
1131
+ if (args.length == 32) (cid) = abi.decode(args, (bytes32));
1132
+ else (cid,,) = abi.decode(args, (bytes32, uint8, uint8));
1133
+ _applyRemovalLowering(account, c, args);
1134
+ _retirePasskey(account, c, cid);
734
1135
  } else if (action == CustodyAction.AddTrustee) {
735
1136
  (address g) = abi.decode(args, (address));
736
1137
  _applyAddGuardian(account, c, g);
@@ -748,7 +1149,7 @@ contract CustodyPolicy {
748
1149
  // current caller (none) was using the legacy form.
749
1150
  (address[] memory addCustodians, address[] memory removeCustodians) =
750
1151
  abi.decode(args, (address[], address[]));
751
- _applyRotateAllOwners(account, addCustodians, removeCustodians);
1152
+ _applyRotateAllOwners(account, c, addCustodians, removeCustodians);
752
1153
  } else if (action == CustodyAction.ChangeValueCeiling) {
753
1154
  (uint256 newCeiling) = abi.decode(args, (uint256));
754
1155
  _applyChangeT3Ceiling(account, c, newCeiling);
@@ -760,10 +1161,40 @@ contract CustodyPolicy {
760
1161
  _applyChangeApprovalsRequired(account, c, tier, newCount);
761
1162
  } else if (action == CustodyAction.RecoverAccount) {
762
1163
  AgentAccountRecoveryArgs memory r = abi.decode(args, (AgentAccountRecoveryArgs));
763
- _applyRecoverAccount(account, r);
1164
+ _applyRecoverAccount(account, c, r);
1165
+ } else if (action == CustodyAction.RotateCredential) {
1166
+ AgentAccountRotateCredentialArgs memory r = abi.decode(args, (AgentAccountRotateCredentialArgs));
1167
+ _applyRotateCredential(account, c, r);
764
1168
  } else if (action == CustodyAction.ApplySystemUpdate) {
765
- (address newImpl) = abi.decode(args, (address));
766
- _execute(account, abi.encodeWithSignature("upgradeToAndCall(address,bytes)", newImpl, ""));
1169
+ // Spec 445 §1.3 (i): the account refuses `newImpl` unless its implementation's UpgradeVoucher
1170
+ // vouches for (newImpl, keccak256(data)) at this moment — a quorum cannot delegatecall arbitrary
1171
+ // code either. Spec 447 §3.4: `args` is `abi.encode(newImpl)` (a plain upgrade) or
1172
+ // `abi.encode(newImpl, data)` (a vouched migration, e.g. the generation-5 factory move).
1173
+ address newImpl;
1174
+ bytes memory data;
1175
+ if (args.length == 32) newImpl = abi.decode(args, (address));
1176
+ else (newImpl, data) = abi.decode(args, (address, bytes));
1177
+ _execute(account, abi.encodeWithSignature("upgradeToAndCall(address,bytes)", newImpl, data));
1178
+ } else if (action == CustodyAction.InstallModule) {
1179
+ (uint256 moduleTypeId, address module, bytes memory initData) = abi.decode(args, (uint256, address, bytes));
1180
+ _execute(account, abi.encodeWithSignature(
1181
+ "installModule(uint256,address,bytes)", moduleTypeId, module, initData
1182
+ ));
1183
+ } else if (action == CustodyAction.UninstallModule) {
1184
+ (uint256 moduleTypeId, address module, bytes memory deInitData) = abi.decode(args, (uint256, address, bytes));
1185
+ // Not this policy: uninstalling the custody policy is permanent (C-11: reinstall forbidden) and
1186
+ // leaves every custodian a 1-of-N owner. It had no route before generation 4 and gets none now
1187
+ // — least of all one that stays open under a pause.
1188
+ if (module == address(this)) revert CannotUninstallCustodyPolicy();
1189
+ _execute(account, abi.encodeWithSignature(
1190
+ "uninstallModule(uint256,address,bytes)", moduleTypeId, module, deInitData
1191
+ ));
1192
+ } else if (action == CustodyAction.LowerSpendCeiling) {
1193
+ (address hook, uint256 newCeiling) = abi.decode(args, (address, uint256));
1194
+ _executeOnHook(account, hook, abi.encodeWithSignature("lowerCeiling(uint256)", newCeiling));
1195
+ } else if (action == CustodyAction.SetSpendCeiling) {
1196
+ (address hook, uint256 newCeiling) = abi.decode(args, (address, uint256));
1197
+ _executeOnHook(account, hook, abi.encodeWithSignature("setCeiling(uint256)", newCeiling));
767
1198
  } else if (action == CustodyAction.RotateDelegationManager) {
768
1199
  (address newDm) = abi.decode(args, (address));
769
1200
  _execute(account, abi.encodeWithSignature("setDelegationManager(address)", newDm));
@@ -799,12 +1230,30 @@ contract CustodyPolicy {
799
1230
  }
800
1231
  }
801
1232
 
1233
+ /// @dev Spec 445 §1.5 (CUST-3) — the account calls one of ITS OWN installed HOOK modules, as the account,
1234
+ /// under the quorum that applied this change. The only non-self target this policy ever dispatches
1235
+ /// to, and only after the account confirms `hook` is installed on it as a hook: without that check a
1236
+ /// quorum at the `LowerSpendCeiling` tier (T4) could make the account call an arbitrary contract
1237
+ /// with a `lowerCeiling(uint256)`-shaped selector. The direction of the change (lower-only vs any)
1238
+ /// is enforced by the hook, at the resource — this module never reads the ceiling to pick a tier.
1239
+ function _executeOnHook(address account, address hook, bytes memory data) internal {
1240
+ if (!ICustodyPolicyAccountModuleView(account).isModuleInstalled(MODULE_TYPE_HOOK, hook, "")) {
1241
+ revert HookNotInstalledOn(account, hook);
1242
+ }
1243
+ (bool ok, bytes memory ret) = account.call(
1244
+ abi.encodeWithSignature("executeFromModule(address,uint256,bytes)", hook, uint256(0), data)
1245
+ );
1246
+ if (!ok) {
1247
+ assembly { revert(add(ret, 32), mload(ret)) }
1248
+ }
1249
+ }
1250
+
802
1251
  function _applyAddGuardian(address account, Config storage c, address g) internal {
803
1252
  if (g == address(0)) revert ZeroAddress();
804
1253
  if (c.trustees[g]) revert TrusteeAlreadyExists(g);
805
1254
  c.trustees[g] = true;
806
1255
  c.trusteeCount += 1;
807
- emit GuardianAdded(account, g);
1256
+ emit GuardianAdded(account, keccak256(abi.encode(g, account)));
808
1257
  }
809
1258
 
810
1259
  function _applyRemoveGuardian(address account, Config storage c, address g) internal {
@@ -814,7 +1263,7 @@ contract CustodyPolicy {
814
1263
  }
815
1264
  c.trustees[g] = false;
816
1265
  c.trusteeCount -= 1;
817
- emit GuardianRemoved(account, g);
1266
+ emit GuardianRemoved(account, keccak256(abi.encode(g, account)));
818
1267
  }
819
1268
 
820
1269
  function _applyChangeMode(address account, Config storage c, uint8 newMode) internal {
@@ -822,6 +1271,11 @@ contract CustodyPolicy {
822
1271
  uint8 oldMode = c.mode;
823
1272
  if (newMode == 0 && c.trusteeCount > 0) revert CannotDowngradeWithTrustees();
824
1273
  c.mode = newMode;
1274
+ // EXT-CHANGEMODE-1 + audit 2026-12-02 C2-7: entering org mode needs >= 2 signers and T4 / T5 within the
1275
+ // floor(N/2) separation-of-duties cap. It is REFUSED when they are not, never capped: capping here lowered
1276
+ // T5 under a T4 quorum (and the lowered value stayed when the mode changed back). The quorum lowers the
1277
+ // thresholds first, as `ChangeApprovalsRequired` — a T5 action that names the numbers it signs.
1278
+ if (newMode == 3) _requireThresholdsReachable(c, IAgentAccount(account).custodianCount());
825
1279
  emit ModeChanged(account, oldMode, newMode);
826
1280
  }
827
1281
 
@@ -837,13 +1291,14 @@ contract CustodyPolicy {
837
1291
  */
838
1292
  function _applyRotateAllOwners(
839
1293
  address account,
1294
+ Config storage c,
840
1295
  address[] memory addCustodians,
841
1296
  address[] memory removeCustodians
842
1297
  ) internal {
843
1298
  if (addCustodians.length == 0 && removeCustodians.length == 0) {
844
1299
  revert EmptyOwnerSet();
845
1300
  }
846
- uint256 added;
1301
+ uint256 added = 0;
847
1302
  for (uint256 i; i < addCustodians.length; i++) {
848
1303
  address o = addCustodians[i];
849
1304
  if (o == address(0)) revert ZeroAddress();
@@ -854,15 +1309,18 @@ contract CustodyPolicy {
854
1309
  }
855
1310
  // Remove AFTER add so we never transiently dip below count=1 in
856
1311
  // the "rotate sole custodian to a new sole custodian" case.
857
- uint256 removed;
1312
+ uint256 removed = 0;
858
1313
  for (uint256 i; i < removeCustodians.length; i++) {
859
1314
  address o = removeCustodians[i];
860
1315
  if (o == address(0)) revert ZeroAddress();
861
1316
  if (IAgentAccount(account).isCustodian(o)) {
862
- _execute(account, abi.encodeCall(IAgentAccount.removeCustodian, (o)));
1317
+ _retireCustodian(account, c, o);
863
1318
  removed++;
864
1319
  }
865
1320
  }
1321
+ // Spec 410 §1.2: a bulk custodian rotation carries no re-approval list; like recovery it voids every
1322
+ // approval so nothing planted for a future epoch survives it. Re-approve through `RotateCredential`.
1323
+ _revokeAllApprovedDigests(account);
866
1324
  emit OwnersRotated(account, added);
867
1325
  // Note: OwnersRotated only carries `added` for ABI compat. A
868
1326
  // future revision should add a `removed` field; that's a
@@ -905,14 +1363,21 @@ contract CustodyPolicy {
905
1363
  if (newCount == 0) revert InvalidThresholdValue(newCount);
906
1364
  uint256 n = IAgentAccount(account).custodianCount();
907
1365
  if (uint256(newCount) > n) revert InvalidThresholdValue(newCount);
1366
+ // acct-mode3-sod-cap-runtime (2026-07-05 audit): the factory caps mode-3 (org) T4/T5 thresholds at
1367
+ // floor(N/2) at install so a DISJOINT propose+apply quorum always exists (2×threshold ≤ N). A later
1368
+ // ChangeApprovalsRequired must not raise them past that cap and silently lock the tier — reject an
1369
+ // explicit over-cap request loud (the org can lower N-constraints or use a lower threshold).
1370
+ if (c.mode == 3 && (tier == 4 || tier == 5) && uint256(newCount) > n / 2) {
1371
+ revert InvalidThresholdValue(newCount);
1372
+ }
908
1373
  uint8 oldValue = c.approvalsRequiredByTier[tier];
909
1374
  if (oldValue == 0) oldValue = 1; // mirror _approvalsValue fallback
910
1375
  c.approvalsRequiredByTier[tier] = newCount;
911
1376
  emit ThresholdChanged(account, tier, oldValue, newCount);
912
1377
  }
913
1378
 
914
- function _applyRecoverAccount(address account, AgentAccountRecoveryArgs memory r) internal {
915
- uint256 addedOwners;
1379
+ function _applyRecoverAccount(address account, Config storage c, AgentAccountRecoveryArgs memory r) internal {
1380
+ uint256 addedOwners = 0;
916
1381
  for (uint256 i; i < r.addOwners.length; i++) {
917
1382
  address o = r.addOwners[i];
918
1383
  if (o == address(0)) revert ZeroAddress();
@@ -922,7 +1387,7 @@ contract CustodyPolicy {
922
1387
  }
923
1388
  }
924
1389
 
925
- uint256 addedPasskeys;
1390
+ uint256 addedPasskeys = 0;
926
1391
  for (uint256 i; i < r.addPasskeys.length; i++) {
927
1392
  AgentAccountRecoveryPasskeyAdd memory pk = r.addPasskeys[i];
928
1393
  // H7-C.1 / CON-WEBAUTHN-001: addPasskey now requires rpIdHash.
@@ -933,25 +1398,78 @@ contract CustodyPolicy {
933
1398
  addedPasskeys++;
934
1399
  }
935
1400
 
936
- uint256 removedOwners;
1401
+ uint256 removedOwners = 0;
937
1402
  for (uint256 i; i < r.removeOwners.length; i++) {
938
1403
  address o = r.removeOwners[i];
939
1404
  if (IAgentAccount(account).isCustodian(o)) {
940
- _execute(account, abi.encodeCall(IAgentAccount.removeCustodian, (o)));
1405
+ _retireCustodian(account, c, o);
941
1406
  removedOwners++;
942
1407
  }
943
1408
  }
944
1409
 
945
- uint256 removedPasskeys;
1410
+ uint256 removedPasskeys = 0;
946
1411
  for (uint256 i; i < r.removePasskeyCredentialIdDigests.length; i++) {
947
- bytes32 cid = r.removePasskeyCredentialIdDigests[i];
948
- _execute(account, abi.encodeWithSignature("removePasskey(bytes32)", cid));
1412
+ _retirePasskey(account, c, r.removePasskeyCredentialIdDigests[i]);
949
1413
  removedPasskeys++;
950
1414
  }
951
1415
 
1416
+ // Spec 410 §1.2 (THESIS-1a): recovery re-approves nothing and voids every approval the account
1417
+ // ever made — including one planted for a future epoch. The person re-issues from a reviewed list.
1418
+ _revokeAllApprovedDigests(account);
1419
+ // CUST-5: fit every threshold to the custodian set the recovery leaves (never refuse the lifeline).
1420
+ _clampThresholdsToCustodians(account, c);
952
1421
  emit AccountRecovered(account, addedOwners, removedOwners, addedPasskeys, removedPasskeys);
953
1422
  }
954
1423
 
1424
+ /// @dev Spec 410 §1.2 — the planned rotation: add → retire → re-approve, one transaction. The account
1425
+ /// derives each key under the post-retirement epoch (`approveDigest`); this module never computes
1426
+ /// a key. Exactly one credential in and one out, so the account is never credential-less and the
1427
+ /// action cannot be bent into a bulk custody change at the rotation tier.
1428
+ function _applyRotateCredential(address account, Config storage c, AgentAccountRotateCredentialArgs memory r) internal {
1429
+ bool addsOwner = r.addOwner != address(0);
1430
+ bool addsPasskey = r.addPasskey.x != 0 || r.addPasskey.y != 0 || r.addPasskey.credentialIdDigest != bytes32(0);
1431
+ bool removesOwner = r.removeOwner != address(0);
1432
+ bool removesPasskey = r.removePasskeyCredentialIdDigest != bytes32(0);
1433
+ if (addsOwner == addsPasskey || removesOwner == removesPasskey) revert RotationNeedsOneAddAndOneRemove();
1434
+
1435
+ if (addsOwner) {
1436
+ _execute(account, abi.encodeCall(IAgentAccount.addCustodian, (r.addOwner)));
1437
+ } else {
1438
+ _execute(account, abi.encodeWithSignature(
1439
+ "addPasskey(bytes32,uint256,uint256,bytes32)",
1440
+ r.addPasskey.credentialIdDigest, r.addPasskey.x, r.addPasskey.y, r.addPasskey.rpIdHash
1441
+ ));
1442
+ }
1443
+ if (removesOwner) {
1444
+ _retireCustodian(account, c, r.removeOwner);
1445
+ } else {
1446
+ _retirePasskey(account, c, r.removePasskeyCredentialIdDigest);
1447
+ }
1448
+ for (uint256 i; i < r.reapprove.length; i++) {
1449
+ _execute(account, abi.encodeWithSignature("approveDigest(bytes32)", r.reapprove[i]));
1450
+ }
1451
+ // Spec 445 §1.3 (ii): the retirement above bumped the custody epoch, which expelled every
1452
+ // non-canonical executor module and a non-canonical delegation manager. A PLANNED rotation carries
1453
+ // what the owner keeps and re-stamps it under the new epoch, in this same applied change. This
1454
+ // module (the canonical custody policy) needs no re-affirmation. `_applyRecoverAccount` and
1455
+ // `_applyRotateAllOwners` have no such step, by construction.
1456
+ for (uint256 i; i < r.reaffirmModules.length; i++) {
1457
+ _execute(account, abi.encodeWithSignature("reaffirmModule(address)", r.reaffirmModules[i]));
1458
+ }
1459
+ if (r.reaffirmDelegationManager) {
1460
+ _execute(account, abi.encodeWithSignature("reaffirmDelegationManager()"));
1461
+ }
1462
+ emit CredentialRotated(account, r.reapprove.length);
1463
+ if (r.reaffirmModules.length != 0 || r.reaffirmDelegationManager) {
1464
+ emit RotationReaffirmed(account, r.reaffirmModules.length, r.reaffirmDelegationManager);
1465
+ }
1466
+ }
1467
+
1468
+ /// @dev Spec 410 §1.2 — `AgentAccount.revokeAllApprovedDigests()` as the account (module context).
1469
+ function _revokeAllApprovedDigests(address account) internal {
1470
+ _execute(account, abi.encodeWithSignature("revokeAllApprovedDigests()"));
1471
+ }
1472
+
955
1473
  /// @dev Spec § 5.1 default-threshold matrix.
956
1474
  function _defaultApprovals(uint8 nCustodians, uint8 tier) internal pure returns (uint8) {
957
1475
  if (nCustodians == 0) return 0;