@agenticprimitives/contracts 1.0.0-alpha.46 → 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
@@ -14,6 +14,9 @@ interface IAgentAccountFactoryAccessor {
14
14
 
15
15
  interface ICustodyPolicyFactoryView {
16
16
  function governance() external view returns (address);
17
+ /// @dev ACCT-11 — the deployment's T4-floor posture (R917-C-5), read when a policy is installed
18
+ /// post-deploy so `onInstall` applies the same floor the factory would have.
19
+ function relaxedT4Floor() external view returns (bool);
17
20
  }
18
21
 
19
22
  interface ICustodyPolicyPauseView {
@@ -27,6 +30,12 @@ interface ICustodyPolicyAccountModuleView {
27
30
  function isModuleInstalled(uint256 moduleTypeId, address module, bytes calldata additionalContext) external view returns (bool);
28
31
  }
29
32
 
33
+ /// @dev Audit 2026-11-10 CUST-4 — a passkey's trustee seat is its per-account PIA; read before it is removed.
34
+ interface ICustodyPolicyPasskeyView {
35
+ function getPasskey(bytes32 credentialIdDigest) external view returns (uint256 x, uint256 y);
36
+ function passkeyIdentity(uint256 x, uint256 y) external view returns (address);
37
+ }
38
+
30
39
  /**
31
40
  * @title CustodyPolicy
32
41
  * @notice ERC-7579 module that owns the schedule / apply / cancel
@@ -61,6 +70,7 @@ interface ICustodyPolicyAccountModuleView {
61
70
  contract CustodyPolicy {
62
71
  // ─── ERC-7579 marker constants (mirror of the account-side ids) ──
63
72
  uint256 internal constant MODULE_TYPE_EXECUTOR = 2;
73
+ uint256 internal constant MODULE_TYPE_HOOK = 4;
64
74
 
65
75
  // ─── CustodyAction enum + structs (moved from AgentAccount) ────────
66
76
 
@@ -81,7 +91,15 @@ contract CustodyPolicy {
81
91
  SetRecoveryApprovals, // 13 — T4
82
92
  RecoverAccount, // 14 — T6
83
93
  ChangeApprovalsRequired, // 15 — T4 (per-tier custody quorum threshold)
84
- RotateCredential // 16 — T4 (spec 410 §1.2: add + retire + re-approve standing wires, atomically)
94
+ RotateCredential, // 16 — T4 (spec 410 §1.2: add + retire + re-approve standing wires, atomically;
95
+ // generation 4: + re-affirm kept modules / delegation manager)
96
+ // ─── Generation 4 (spec 445 §1.5, audit CUST-3 / ACCT-5) — appended; 0..16 keep their numbers ───
97
+ InstallModule, // 17 — T5 (installModule(type, module, initData) — an executor can act as the account)
98
+ UninstallModule, // 18 — T5 (uninstallModule — removing a hook removes a protection)
99
+ LowerSpendCeiling, // 19 — T4 (TreasurySpendPolicy.lowerCeiling — can only tighten)
100
+ SetSpendCeiling // 20 — T5 (TreasurySpendPolicy.setCeiling — may raise)
101
+ // (A custody-quorum `GovernanceCall` was drafted as 21 and withdrawn by owner decision 2026-11-10 — see
102
+ // AUDIT.md 2.27. The next appended action takes 21.)
85
103
  }
86
104
 
87
105
  struct ScheduledChange {
@@ -92,6 +110,9 @@ contract CustodyPolicy {
92
110
  address proposer;
93
111
  bool executed;
94
112
  bool cancelled;
113
+ /// @dev Audit 2026-11-10 CUST-6 — the last second the change may be applied (`eta + APPLY_WINDOW`).
114
+ /// Appended: packs into the slot `proposer / executed / cancelled` already occupy (22 of 32 bytes).
115
+ uint64 expiresAt;
95
116
  }
96
117
 
97
118
  /// @dev Per-account config. One mapping entry per installed-on account.
@@ -151,7 +172,7 @@ contract CustodyPolicy {
151
172
 
152
173
  // ─── R6.6 / CON-CustodyPolicy-005 — system-pause modifier ──────
153
174
  //
154
- // `whenAccountNotPaused(account)` reverts when
175
+ // The pause gate (`_systemPausedFor(account)`, checked inline) reverts when
155
176
  // `AgenticGovernance.isPaused() == true`, where governance is
156
177
  // resolved per-call via the account's factory:
157
178
  //
@@ -163,7 +184,15 @@ contract CustodyPolicy {
163
184
  // deploys keep working — mirrors the R6.5 pattern in AgentAccount
164
185
  // and `GovernanceManaged._pausedSafe()`.
165
186
  //
166
- // Applied to: `scheduleCustodyChange`, `applyCustodyChange`.
187
+ // Applied to: `scheduleCustodyChange`, `applyCustodyChange` — EXCEPT for the actions in
188
+ // `_isPauseExemptAction` (spec 445 §1.2 / ACCT-2): `RemoveCustodian`, `RemovePasskeyCredential`
189
+ // and `UninstallModule`. Those three only REMOVE authority or attack surface; a quorum must be able
190
+ // to schedule and apply them during the very incident a pause is for. They keep their quorum and
191
+ // their safety delay. The account's `executeFromModule` carries the matching exemption (the canonical
192
+ // policy dispatching `removeCustodian` / `removePasskey` / `uninstallModule` on the account itself);
193
+ // every other action stays frozen at both doors. Before generation 4 the account-side functions
194
+ // were merely un-gated and the only route to them was paused here — recovery was documented live and
195
+ // was not.
167
196
  //
168
197
  // Deliberately NOT applied to (recovery primitives that must
169
198
  // work during an incident):
@@ -173,9 +202,15 @@ contract CustodyPolicy {
173
202
  // `installModule` on AgentAccount (R6.5)
174
203
  // and paused `createAgentAccount`
175
204
  // on AgentAccountFactory
176
- modifier whenAccountNotPaused(address account) {
177
- if (_systemPausedFor(account)) revert SystemPaused();
178
- _;
205
+ /// @dev Spec 445 §1.2 / ACCT-2 — the custody actions that stay schedulable and applicable under a pause.
206
+ /// Removal only: nothing here adds a credential or a trustee, installs or re-affirms anything,
207
+ /// changes a threshold, rotates, recovers, upgrades or raises a ceiling — except that a removal may carry
208
+ /// the T4 / T5 LOWERING it needs to leave every tier reachable (CUST-5; a T5 quorum + the T5 delay):
209
+ /// without it a 3-of-3 account could not expel a compromised custodian during the incident at all.
210
+ function _isPauseExemptAction(CustodyAction action) internal pure returns (bool) {
211
+ return action == CustodyAction.RemoveCustodian
212
+ || action == CustodyAction.RemovePasskeyCredential
213
+ || action == CustodyAction.UninstallModule;
179
214
  }
180
215
 
181
216
  /// @notice R6.6 — thrown when a `whenAccountNotPaused`-guarded
@@ -184,27 +219,32 @@ contract CustodyPolicy {
184
219
  error SystemPaused();
185
220
 
186
221
  function _systemPausedFor(address account) internal view returns (bool) {
187
- if (account == address(0) || account.code.length == 0) return false;
188
- // Hop 1: account → factory
222
+ address gov = _governanceOf(account);
223
+ if (gov == address(0)) return false;
224
+ // Hop 3: governance → isPaused
225
+ (bool okP, bytes memory dataP) = gov.staticcall(
226
+ abi.encodeWithSelector(ICustodyPolicyPauseView.isPaused.selector)
227
+ );
228
+ if (!okP || dataP.length < 32) return false;
229
+ return abi.decode(dataP, (bool));
230
+ }
231
+
232
+ /// @dev Hops 1–2 of the pause read: `account → factory() → governance()`. Zero on any non-conforming hop or a
233
+ /// codeless address.
234
+ function _governanceOf(address account) internal view returns (address gov) {
235
+ if (account == address(0) || account.code.length == 0) return address(0);
189
236
  (bool okF, bytes memory dataF) = account.staticcall(
190
237
  abi.encodeWithSelector(IAgentAccountFactoryAccessor.factory.selector)
191
238
  );
192
- if (!okF || dataF.length < 32) return false;
239
+ if (!okF || dataF.length < 32) return address(0);
193
240
  address fac = abi.decode(dataF, (address));
194
- if (fac == address(0) || fac.code.length == 0) return false;
195
- // Hop 2: factory → governance
241
+ if (fac == address(0) || fac.code.length == 0) return address(0);
196
242
  (bool okG, bytes memory dataG) = fac.staticcall(
197
243
  abi.encodeWithSelector(ICustodyPolicyFactoryView.governance.selector)
198
244
  );
199
- if (!okG || dataG.length < 32) return false;
200
- address gov = abi.decode(dataG, (address));
201
- if (gov == address(0) || gov.code.length == 0) return false;
202
- // Hop 3: governance → isPaused
203
- (bool okP, bytes memory dataP) = gov.staticcall(
204
- abi.encodeWithSelector(ICustodyPolicyPauseView.isPaused.selector)
205
- );
206
- if (!okP || dataP.length < 32) return false;
207
- return abi.decode(dataP, (bool));
245
+ if (!okG || dataG.length < 32) return address(0);
246
+ gov = abi.decode(dataG, (address));
247
+ if (gov.code.length == 0) return address(0);
208
248
  }
209
249
 
210
250
  function _buildDomainSeparator() internal view returns (bytes32) {
@@ -273,6 +313,20 @@ contract CustodyPolicy {
273
313
  /// primary-owner cancel window.
274
314
  uint64 internal constant RECOVERY_PRIMARY_CANCEL_WINDOW = 24 hours;
275
315
 
316
+ /// @dev Audit 2026-11-10 CUST-6 — A SCHEDULED CHANGE LAPSES. It may be applied from `eta` until
317
+ /// `eta + APPLY_WINDOW` inclusive, then never: a safety delay is notice of a change about to happen,
318
+ /// not a reservation the quorum can hold for years (the PoC applied a recovery's pre-signed approvals
319
+ /// three years later, from an unrelated address). One window for every tier, recovery included, so
320
+ /// `expiresAt` is a pure function of `eta` — and an apply approval, which signs `eta`, signs the expiry
321
+ /// with it (no typehash change). This contract is not upgradeable, so the constant cannot move under
322
+ /// a signature. Recovery keeps its rule: the custodians may cancel in the first 24 h, the trustees
323
+ /// after; past the window the recovery is dead and the trustees must schedule a new one (another
324
+ /// 48 h, another 24 h owner-cancel window).
325
+ uint64 public constant APPLY_WINDOW = 7 days;
326
+
327
+ /// @dev ACCT-11 — the factory's `MAX_INITIAL_TRUSTEES`, applied to a post-deploy install.
328
+ uint256 internal constant MAX_INSTALL_TRUSTEES = 32;
329
+
276
330
  // ─── Events ───────────────────────────────────────────────────────
277
331
 
278
332
  event CustodyPolicyInstalled(address indexed account, uint8 mode, uint8 recoveryApprovals);
@@ -300,6 +354,9 @@ contract CustodyPolicy {
300
354
  /// @dev Spec 410 §1.2 — a planned rotation applied: one credential in, one out, `reapproved` wires
301
355
  /// re-approved under the new custody epoch in the same transaction.
302
356
  event CredentialRotated(address indexed account, uint256 reapproved);
357
+ /// @dev Spec 445 §1.3 (ii) — the same rotation also re-affirmed `modules` kept executor modules and,
358
+ /// when `delegationManager` is true, the account's current delegation manager.
359
+ event RotationReaffirmed(address indexed account, uint256 modules, bool delegationManager);
303
360
  /// @notice Audit C-10: per-rotation count of custodians removed.
304
361
  event CustodiansRemovedDuringRotation(address indexed account, uint256 removedCount);
305
362
  /// @notice Audit C-11: CustodyPolicy was uninstalled; the account
@@ -364,6 +421,30 @@ contract CustodyPolicy {
364
421
  /// `uninstallModule`. Accepting it would leave the account governed by a policy that refuses every
365
422
  /// change (installed on the account, uninstalled here, reinstall forbidden) — bricked forever.
366
423
  error StillInstalledOn(address account);
424
+ /// @dev ACCT-11 (audit 2026-11-10): `onInstall` was called by an address that does not list this module as
425
+ /// an installed EXECUTOR — i.e. by `execute(custodyPolicy, onInstall(cfg))`, not by `installModule`.
426
+ /// Accepting it made the policy report `isInstalledOn == true` and a custody mode for an account it
427
+ /// cannot act on, and made a later genuine install revert `AlreadyInstalledOn`.
428
+ error NotInstalledAsExecutorOn(address account);
429
+ /// @dev ACCT-11 / CUST-8: a safety delay below the product floor on an install that did not come through
430
+ /// the factory (which enforces the same floors itself, EXT-TL-FLOOR-1).
431
+ error SafetyDelayBelowFloor(uint8 tier, uint32 provided, uint32 floorSecs);
432
+ /// @dev Spec 445 §1.5: `UninstallModule` named this custody policy itself.
433
+ error CannotUninstallCustodyPolicy();
434
+ /// @dev Spec 445 §1.5 (CUST-3): a spend-ceiling action named a hook the account does not have installed.
435
+ error HookNotInstalledOn(address account, address hook);
436
+ /// @notice Audit 2026-11-10 CUST-6 — the change's apply window (`eta … expiresAt`) has passed.
437
+ error ProposalExpired(uint256 changeId, uint64 expiresAt);
438
+ /// @notice Audit 2026-11-10 CUST-5 / ACCT-11 — a tier's threshold would exceed what the custodian set can
439
+ /// reach: the custodian count, or `floor(count / 2)` for T4 / T5 in org mode (disjoint proposers and
440
+ /// appliers). Raised by every applied change (except a recovery, which clamps) and by `onInstall`.
441
+ error ThresholdUnreachable(uint8 tier, uint8 required, uint256 bound);
442
+ /// @notice ACCT-11 — a post-deploy install below the factory's per-mode trustee minimum (mode 1: 1, mode 2: 2,
443
+ /// mode 3: 3; a positive recovery quorum) or above its trustee cap.
444
+ error TrusteesOutsideModeBounds(uint8 mode, uint256 trustees, uint8 recoveryApprovals);
445
+ /// @notice CUST-5 — `RemoveCustodian` / `RemovePasskeyCredential` args are neither the one-word form nor the
446
+ /// three-word form that also lowers T4 / T5.
447
+ error MalformedRemovalArgs(uint256 length);
367
448
 
368
449
  // ─── ERC-7579 lifecycle ───────────────────────────────────────────
369
450
 
@@ -390,6 +471,12 @@ contract CustodyPolicy {
390
471
  // ways. Force a new deploy if the operator genuinely needs a
391
472
  // fresh policy for this account.
392
473
  if (c.permanentlyUninstalled) revert ReinstallForbidden(account);
474
+ // ACCT-11: the caller must be an account that is INSTALLING this module — `installModule` sets its
475
+ // installed flag before it calls here. Mirror of the R917-C-1 check in `onUninstall`; fails closed
476
+ // on a caller that cannot answer the view (the staticcall reverts, and so does this).
477
+ if (!ICustodyPolicyAccountModuleView(account).isModuleInstalled(MODULE_TYPE_EXECUTOR, address(this), "")) {
478
+ revert NotInstalledAsExecutorOn(account);
479
+ }
393
480
 
394
481
  (
395
482
  uint8 modeVal,
@@ -449,7 +536,12 @@ contract CustodyPolicy {
449
536
  }
450
537
  for (uint8 t = 1; t <= 6; t++) {
451
538
  uint8 thr = thresholds[t];
452
- if (thr == 0) thr = _defaultApprovals(nCustodians, t);
539
+ if (thr == 0) {
540
+ thr = _defaultApprovals(nCustodians, t);
541
+ // ACCT-11: the factory's mode-3 cap, applied to a DEFAULTED T4 / T5 exactly as the factory applies
542
+ // it. An explicit over-cap value is not rewritten — `_requireThresholdsReachable` refuses it.
543
+ if (modeVal == 3 && (t == 4 || t == 5) && thr > nCustodians / 2) thr = nCustodians / 2;
544
+ }
453
545
  if (thr > 0) c.approvalsRequiredByTier[t] = thr;
454
546
  if (timelocks[t] > 0) c.safetyDelayByTier[t] = timelocks[t];
455
547
  }
@@ -461,11 +553,58 @@ contract CustodyPolicy {
461
553
  if (modeVal >= 1) {
462
554
  if (c.approvalsRequiredByTier[4] == 0) revert UnconfiguredTier(4);
463
555
  if (c.approvalsRequiredByTier[5] == 0) revert UnconfiguredTier(5);
556
+ _requireSafetyDelayFloors(account, c);
557
+ // ACCT-11 (remainder) — the factory's per-mode trustee bounds, so a post-deploy install cannot
558
+ // create a configuration the factory would refuse: ≥ 1 / 2 / 3 trustees for mode 1 / 2 / 3, at most
559
+ // `MAX_INSTALL_TRUSTEES` (the factory's ACCT-10 cap), and a positive recovery quorum (the factory
560
+ // always sets floor(n/2)+1).
561
+ if (trustees.length < modeVal || trustees.length > MAX_INSTALL_TRUSTEES || recThr == 0) {
562
+ revert TrusteesOutsideModeBounds(modeVal, trustees.length, recThr);
563
+ }
464
564
  }
565
+ // ACCT-11 / CUST-5 — every tier reachable by the custodian set the account has right now (and in mode 3
566
+ // the separation-of-duties cap, with ≥ 2 custodians). The factory's thresholds satisfy this by
567
+ // construction. Mode 0 with an unreadable custodian count (not an AgentAccount) has nothing to bound.
568
+ if (modeVal >= 1 || nCustodians > 0) _requireThresholdsReachable(c, nCustodians);
465
569
 
466
570
  emit CustodyPolicyInstalled(account, modeVal, recThr);
467
571
  }
468
572
 
573
+ /// @dev ACCT-11 / CUST-8 (audit 2026-11-10) — THE FACTORY'S DELAY FLOORS, APPLIED AT EVERY INSTALL. The
574
+ /// factory refuses a governed account whose T4 / T5 / T6 delays are below 1 h / 24 h / 48 h
575
+ /// (EXT-TL-FLOOR-1), but a policy installed AFTER deploy (`execute(self, installModule(2, policy,
576
+ /// cfg))` — the spec 422 path every Home person takes) stored whatever the client sent, so "24 h to
577
+ /// upgrade, 48 h to recover, cancellable for 24" was an invariant of factory-born accounts only. A
578
+ /// factory install satisfies these by construction, so they are applied unconditionally:
579
+ /// T5 ≥ 24 h;
580
+ /// T6 ≥ 48 h whenever trustee recovery is enabled (`recoveryApprovals > 0`) — which also keeps the
581
+ /// 24 h owner-cancel window inside the delay;
582
+ /// T4 ≥ 1 h, unless the account's factory declares `relaxedT4Floor` (the local-development
583
+ /// posture, R917-C-5). A factory-less account, or a factory that cannot answer, gets the floor.
584
+ /// The per-mode trustee bounds and the mode-3 separation-of-duties cap are applied in `onInstall` too
585
+ /// (ACCT-11 remainder, generation 4).
586
+ function _requireSafetyDelayFloors(address account, Config storage c) internal view {
587
+ uint32 d5 = c.safetyDelayByTier[5];
588
+ if (d5 < 24 hours) revert SafetyDelayBelowFloor(5, d5, uint32(24 hours));
589
+ uint32 d6 = c.safetyDelayByTier[6];
590
+ if (c.recoveryApprovals > 0 && d6 < 48 hours) revert SafetyDelayBelowFloor(6, d6, uint32(48 hours));
591
+ uint32 d4 = c.safetyDelayByTier[4];
592
+ if (d4 < 1 hours && !_relaxedT4FloorFor(account)) revert SafetyDelayBelowFloor(4, d4, uint32(1 hours));
593
+ }
594
+
595
+ function _relaxedT4FloorFor(address account) internal view returns (bool) {
596
+ (bool okF, bytes memory dataF) = account.staticcall(
597
+ abi.encodeWithSelector(IAgentAccountFactoryAccessor.factory.selector)
598
+ );
599
+ if (!okF || dataF.length < 32) return false;
600
+ address fac = abi.decode(dataF, (address));
601
+ if (fac == address(0) || fac.code.length == 0) return false;
602
+ (bool okR, bytes memory dataR) = fac.staticcall(
603
+ abi.encodeWithSelector(ICustodyPolicyFactoryView.relaxedT4Floor.selector)
604
+ );
605
+ return okR && dataR.length == 32 && abi.decode(dataR, (uint256)) == 1;
606
+ }
607
+
469
608
  function onUninstall(bytes calldata) external {
470
609
  address account = msg.sender;
471
610
  Config storage c = _configs[account];
@@ -497,7 +636,8 @@ contract CustodyPolicy {
497
636
  CustodyAction action,
498
637
  bytes calldata args,
499
638
  bytes calldata quorumSigs
500
- ) external whenAccountNotPaused(account) returns (uint256 changeId) {
639
+ ) external returns (uint256 changeId) {
640
+ if (!_isPauseExemptAction(action) && _systemPausedFor(account)) revert SystemPaused();
501
641
  Config storage c = _configs[account];
502
642
  if (!c.installed) revert NotInstalledOn(account);
503
643
 
@@ -537,7 +677,8 @@ contract CustodyPolicy {
537
677
  eta: eta,
538
678
  proposer: msg.sender,
539
679
  executed: false,
540
- cancelled: false
680
+ cancelled: false,
681
+ expiresAt: eta + APPLY_WINDOW
541
682
  });
542
683
  }
543
684
  {
@@ -558,16 +699,21 @@ contract CustodyPolicy {
558
699
 
559
700
  function applyCustodyChange(address account, uint256 changeId, bytes calldata quorumSigs)
560
701
  external
561
- whenAccountNotPaused(account)
562
702
  {
563
703
  Config storage c = _configs[account];
704
+ ScheduledChange storage p = c.pending[changeId];
705
+ // Pause gate first (as the modifier did), exempting the removal actions — see `_isPauseExemptAction`.
706
+ // An unknown `changeId` reads action 0 (not exempt), so a paused system still answers `SystemPaused`.
707
+ if (!_isPauseExemptAction(p.action) && _systemPausedFor(account)) revert SystemPaused();
564
708
  if (!c.installed) revert NotInstalledOn(account);
565
709
 
566
- ScheduledChange storage p = c.pending[changeId];
567
710
  if (p.eta == 0) revert ProposalNotFound(changeId);
568
711
  if (p.executed) revert ProposalAlreadyExecuted(changeId);
569
712
  if (p.cancelled) revert ProposalAlreadyCancelled(changeId);
570
713
  if (block.timestamp < p.eta) revert ProposalNotReady(changeId, p.eta);
714
+ // CUST-6: the window closes. Checked before any signature is read: a lapsed change is dead whoever holds
715
+ // its approvals.
716
+ if (block.timestamp > p.expiresAt) revert ProposalExpired(changeId, p.expiresAt);
571
717
 
572
718
  bool isRecovery = (p.action == CustodyAction.RecoverAccount);
573
719
  uint8 tier = _effectiveTierFor(c, p.action, p.args);
@@ -586,6 +732,10 @@ contract CustodyPolicy {
586
732
  p.executed = true;
587
733
  emit CustodyChangeApplied(account, changeId);
588
734
  _applyCustodyChange(account, c, p.action, p.args);
735
+ // CUST-5: no applied change may leave a tier the custodian set cannot reach. A removal that would must
736
+ // carry the lowering itself (the three-word `RemoveCustodian` / `RemovePasskeyCredential` form); a
737
+ // recovery clamps instead (`_clampThresholdsToCustodians`) — it is the lifeline and must not strand.
738
+ _requireThresholdsReachable(c, IAgentAccount(account).custodianCount());
589
739
  }
590
740
 
591
741
  function cancelScheduledChange(address account, uint256 changeId, bytes calldata quorumSigs) external {
@@ -671,6 +821,12 @@ contract CustodyPolicy {
671
821
  return (p.action, p.args, p.proposedAt, p.eta, p.proposer, p.executed, p.cancelled);
672
822
  }
673
823
 
824
+ /// @notice CUST-6 — the last second `changeId` may be applied (`eta + APPLY_WINDOW`); 0 for an unknown id.
825
+ /// A separate view so `getScheduledChange`'s return shape (and every decoder of it) is unchanged.
826
+ function scheduledChangeExpiry(address account, uint256 changeId) external view returns (uint64) {
827
+ return _configs[account].pending[changeId].expiresAt;
828
+ }
829
+
674
830
  /// @notice Pure helper exposing the default-threshold matrix from
675
831
  /// spec § 5.1 — owners over n=1..N produce per-tier defaults.
676
832
  function defaultApprovals(uint8 nCustodians, uint8 tier) external pure returns (uint8) {
@@ -685,8 +841,21 @@ contract CustodyPolicy {
685
841
  action == CustodyAction.ApplySystemUpdate ||
686
842
  action == CustodyAction.RotateDelegationManager ||
687
843
  action == CustodyAction.RotatePaymaster ||
688
- action == CustodyAction.RotateSessionIssuer
844
+ action == CustodyAction.RotateSessionIssuer ||
845
+ // Spec 445 §1.5 (CUST-3 / ACCT-5). T5 (critical: full T5 quorum + the 24 h floor), the tier of
846
+ // `ApplySystemUpdate` and `RotateDelegationManager`, because each is the same kind of change:
847
+ // InstallModule — an executor module can act as the account, like a delegation manager;
848
+ // UninstallModule — removing a hook removes a protection (the treasury ceiling);
849
+ // SetSpendCeiling — may RAISE the ceiling, which is removing part of it.
850
+ // T4 is the tier of custody-SET changes; none of these is allowed to be lighter than that, and
851
+ // raising/removing a ceiling a T4 quorum could lift would bound nothing against that quorum.
852
+ action == CustodyAction.InstallModule ||
853
+ action == CustodyAction.UninstallModule ||
854
+ action == CustodyAction.SetSpendCeiling
689
855
  ) return 5;
856
+ // `LowerSpendCeiling` is T4 — the lightest custody tier there is. It can only tighten
857
+ // (`TreasurySpendPolicy.lowerCeiling` reverts unless the new ceiling is strictly lower), so the worst
858
+ // a T4 quorum can do with it is stop spending, which that quorum can do in other ways already.
690
859
  return 4;
691
860
  }
692
861
 
@@ -704,6 +873,13 @@ contract CustodyPolicy {
704
873
  bytes memory args
705
874
  ) internal view returns (uint8) {
706
875
  uint8 base = _tierFor(action);
876
+ if (action == CustodyAction.RemoveCustodian || action == CustodyAction.RemovePasskeyCredential) {
877
+ // CUST-5: the three-word form lowers T4 / T5 with the removal. A decrease is T5 (audit C-8), exactly
878
+ // as if it had been scheduled as `ChangeApprovalsRequired`.
879
+ (uint8 newT4, uint8 newT5) = _removalLowering(args);
880
+ if (_lowers(c, 4, newT4) || _lowers(c, 5, newT5)) return 5;
881
+ return base;
882
+ }
707
883
  if (action != CustodyAction.ChangeApprovalsRequired) return base;
708
884
  // Decode (uint8 tier, uint8 newCount). Bound the change tier in
709
885
  // [1, 5]; T6 (recovery) routes through SetRecoveryApprovals.
@@ -718,6 +894,107 @@ contract CustodyPolicy {
718
894
  return required;
719
895
  }
720
896
 
897
+ /// @dev CUST-5 — `RemoveCustodian` args are `abi.encode(address)` or `abi.encode(address, uint8 newT4,
898
+ /// uint8 newT5)`; `RemovePasskeyCredential` the same with a `bytes32` credential digest. A zero new value
899
+ /// keeps that tier. Any other length is refused (at schedule, since the tier is computed there).
900
+ function _removalLowering(bytes memory args) internal pure returns (uint8 newT4, uint8 newT5) {
901
+ if (args.length == 32) return (0, 0);
902
+ if (args.length != 96) revert MalformedRemovalArgs(args.length);
903
+ (, newT4, newT5) = abi.decode(args, (bytes32, uint8, uint8));
904
+ }
905
+
906
+ function _lowers(Config storage c, uint8 tier, uint8 newValue) internal view returns (bool) {
907
+ return newValue != 0 && newValue < _approvalsValue(c, tier);
908
+ }
909
+
910
+ /// @dev CUST-5 — apply the lowering a three-word removal carries. Only a DECREASE (or no change) is
911
+ /// accepted: a removal never raises a threshold. Whether the result is reachable by the custodian set
912
+ /// left after the removal is checked once, after the whole change (`_requireThresholdsReachable`).
913
+ function _applyRemovalLowering(address account, Config storage c, bytes memory args) internal {
914
+ (uint8 newT4, uint8 newT5) = _removalLowering(args);
915
+ for (uint8 t = 4; t <= 5; t++) {
916
+ uint8 nv = t == 4 ? newT4 : newT5;
917
+ if (nv == 0) continue;
918
+ uint8 old = _approvalsValue(c, t);
919
+ if (nv > old) revert InvalidThresholdValue(nv);
920
+ if (nv == old) continue;
921
+ c.approvalsRequiredByTier[t] = nv;
922
+ emit ThresholdChanged(account, t, old, nv);
923
+ }
924
+ }
925
+
926
+ /// @dev CUST-5 / ACCT-11 — THE INVARIANT: every tier T1..T5 is reachable by `n` custodians, and in org mode
927
+ /// T4 / T5 by a disjoint proposer + applier pair (`2 × threshold ≤ n`, so `n ≥ 2`). A stored 0 reads as
928
+ /// the 1-of-n fallback and needs only `n ≥ 1`, which the account guarantees (it refuses to remove its
929
+ /// last signer). T6 is `recoveryApprovals`, bounded by the trustee count where it is set.
930
+ function _requireThresholdsReachable(Config storage c, uint256 n) internal view {
931
+ bool org = c.mode == 3;
932
+ if (org && n < 2) revert InfeasibleOrgConfig(uint8(n > 255 ? 255 : n));
933
+ for (uint8 t = 1; t <= 5; t++) {
934
+ uint8 v = c.approvalsRequiredByTier[t];
935
+ uint256 bound = (org && t >= 4) ? n / 2 : n;
936
+ if (v > bound) revert ThresholdUnreachable(t, v, bound);
937
+ }
938
+ }
939
+
940
+ /// @dev CUST-5 — a RECOVERY clamps instead of refusing: it is applied by the trustees after 48 h to give an
941
+ /// owner back an account she lost, and refusing it because the custodian set shrank would strand her.
942
+ /// The trustees already decide the whole custodian set, so lowering a threshold to fit it adds nothing
943
+ /// to what they can do. Each clamp emits `ThresholdChanged`. Org mode with fewer than two custodians
944
+ /// has no clamp that works (separation of duties needs two) and is refused.
945
+ function _clampThresholdsToCustodians(address account, Config storage c) internal {
946
+ uint256 n = IAgentAccount(account).custodianCount();
947
+ bool org = c.mode == 3;
948
+ if (org && n < 2) revert InfeasibleOrgConfig(uint8(n > 255 ? 255 : n));
949
+ for (uint8 t = 1; t <= 5; t++) {
950
+ uint8 v = c.approvalsRequiredByTier[t];
951
+ uint256 bound = (org && t >= 4) ? n / 2 : n;
952
+ if (v > bound) {
953
+ c.approvalsRequiredByTier[t] = uint8(bound);
954
+ emit ThresholdChanged(account, t, v, uint8(bound));
955
+ }
956
+ }
957
+ }
958
+
959
+ /// @dev Audit 2026-11-10 CUST-4 — A RETIRED CREDENTIAL LOSES ITS TRUSTEE SEAT. A trustee may be one of the
960
+ /// account's own credentials (the factory's `SELF_PASSKEY_TRUSTEE` makes the initial passkey's PIA one).
961
+ /// Before generation 4 retiring the credential left the seat, and the retired key could recover the
962
+ /// account alone and expel the credential that replaced it. Every retirement this policy performs —
963
+ /// `RemoveCustodian`, `RemovePasskeyCredential`, `RotateCredential`, `RotateAllCustodians`,
964
+ /// `RecoverAccount` — goes through `_retireCustodian` / `_retirePasskey`, which vacate the seat in the
965
+ /// same applied change. On a custody-governed account those are the ONLY retirement paths (the account
966
+ /// refuses `removeCustodian` / `removePasskey` outside this policy's context), so "retired" and
967
+ /// "trustee" can no longer both be true; an approval the credential signed earlier stops counting
968
+ /// because every apply / cancel verifies its signers against the trustee set as it is at that moment.
969
+ /// If the recovery quorum would then exceed the remaining trustees it is clamped to them (to 0 —
970
+ /// recovery disabled — when none remain), with `RecoveryThresholdChanged`: refusing instead would stop
971
+ /// an owner from retiring a lost device that is also her only trustee.
972
+ function _vacateTrusteeSeat(address account, Config storage c, address credential) internal {
973
+ if (!c.trustees[credential]) return;
974
+ c.trustees[credential] = false;
975
+ c.trusteeCount -= 1;
976
+ emit GuardianRemoved(account, keccak256(abi.encode(credential, account)));
977
+ uint8 oldThr = c.recoveryApprovals;
978
+ if (oldThr > c.trusteeCount) {
979
+ c.recoveryApprovals = uint8(c.trusteeCount);
980
+ emit RecoveryThresholdChanged(account, oldThr, uint8(c.trusteeCount));
981
+ }
982
+ }
983
+
984
+ function _retireCustodian(address account, Config storage c, address o) internal {
985
+ _execute(account, abi.encodeCall(IAgentAccount.removeCustodian, (o)));
986
+ _vacateTrusteeSeat(account, c, o);
987
+ }
988
+
989
+ /// @dev The trustee seat a passkey can hold is its per-account PIA, read from the account BEFORE the key is
990
+ /// deleted. An unregistered digest reads (0, 0) and `removePasskey` reverts.
991
+ function _retirePasskey(address account, Config storage c, bytes32 cid) internal {
992
+ (uint256 x, uint256 y) = ICustodyPolicyPasskeyView(account).getPasskey(cid);
993
+ address pia = ICustodyPolicyPasskeyView(account).passkeyIdentity(x, y);
994
+ _execute(account, abi.encodeWithSignature("removePasskey(bytes32)", cid));
995
+ _vacateTrusteeSeat(account, c, pia);
996
+ }
997
+
721
998
  function _approvalsValue(Config storage c, uint8 tier) internal view returns (uint8) {
722
999
  if (tier == 0 || tier > 6) revert InvalidTier(tier);
723
1000
  uint8 v = c.approvalsRequiredByTier[tier];
@@ -779,6 +1056,10 @@ contract CustodyPolicy {
779
1056
  QuorumVerifyArgs memory vargs,
780
1057
  bytes calldata signatures
781
1058
  ) internal view returns (address[] memory signers) {
1059
+ // CUST-4: a quorum of zero is no quorum. T1..T5 never read as 0 (`_approvalsValue`), but the recovery quorum
1060
+ // reaches 0 when retirements vacate every trustee seat (`_vacateTrusteeSeat`) — a recovery scheduled before
1061
+ // that must then be unappliable and un-cancellable-by-trustees, never appliable with no signature at all.
1062
+ if (vargs.reqThreshold < 1) revert RecoveryRequiresGuardianQuorum();
782
1063
  if (signatures.length < uint256(vargs.reqThreshold) * 65) {
783
1064
  revert AdminInsufficientQuorum(signatures.length / 65, vargs.reqThreshold);
784
1065
  }
@@ -819,8 +1100,12 @@ contract CustodyPolicy {
819
1100
  (address newOwner) = abi.decode(args, (address));
820
1101
  _execute(account, abi.encodeCall(IAgentAccount.addCustodian, (newOwner)));
821
1102
  } else if (action == CustodyAction.RemoveCustodian) {
822
- (address oldOwner) = abi.decode(args, (address));
823
- _execute(account, abi.encodeCall(IAgentAccount.removeCustodian, (oldOwner)));
1103
+ // CUST-5: `abi.encode(address)` or `abi.encode(address, uint8 newT4, uint8 newT5)`.
1104
+ address oldOwner;
1105
+ if (args.length == 32) (oldOwner) = abi.decode(args, (address));
1106
+ else (oldOwner,,) = abi.decode(args, (address, uint8, uint8));
1107
+ _applyRemovalLowering(account, c, args);
1108
+ _retireCustodian(account, c, oldOwner);
824
1109
  } else if (action == CustodyAction.AddPasskeyCredential) {
825
1110
  // H7-C.1 / CON-WEBAUTHN-001: rpIdHash now bundled in the action args
826
1111
  // so credential additions through the custody-policy entrypoint
@@ -832,8 +1117,12 @@ contract CustodyPolicy {
832
1117
  cid, x, y, rpIdHash
833
1118
  ));
834
1119
  } else if (action == CustodyAction.RemovePasskeyCredential) {
835
- (bytes32 cid) = abi.decode(args, (bytes32));
836
- _execute(account, abi.encodeWithSignature("removePasskey(bytes32)", cid));
1120
+ // CUST-5: `abi.encode(bytes32)` or `abi.encode(bytes32, uint8 newT4, uint8 newT5)`.
1121
+ bytes32 cid;
1122
+ if (args.length == 32) (cid) = abi.decode(args, (bytes32));
1123
+ else (cid,,) = abi.decode(args, (bytes32, uint8, uint8));
1124
+ _applyRemovalLowering(account, c, args);
1125
+ _retirePasskey(account, c, cid);
837
1126
  } else if (action == CustodyAction.AddTrustee) {
838
1127
  (address g) = abi.decode(args, (address));
839
1128
  _applyAddGuardian(account, c, g);
@@ -851,7 +1140,7 @@ contract CustodyPolicy {
851
1140
  // current caller (none) was using the legacy form.
852
1141
  (address[] memory addCustodians, address[] memory removeCustodians) =
853
1142
  abi.decode(args, (address[], address[]));
854
- _applyRotateAllOwners(account, addCustodians, removeCustodians);
1143
+ _applyRotateAllOwners(account, c, addCustodians, removeCustodians);
855
1144
  } else if (action == CustodyAction.ChangeValueCeiling) {
856
1145
  (uint256 newCeiling) = abi.decode(args, (uint256));
857
1146
  _applyChangeT3Ceiling(account, c, newCeiling);
@@ -863,13 +1152,36 @@ contract CustodyPolicy {
863
1152
  _applyChangeApprovalsRequired(account, c, tier, newCount);
864
1153
  } else if (action == CustodyAction.RecoverAccount) {
865
1154
  AgentAccountRecoveryArgs memory r = abi.decode(args, (AgentAccountRecoveryArgs));
866
- _applyRecoverAccount(account, r);
1155
+ _applyRecoverAccount(account, c, r);
867
1156
  } else if (action == CustodyAction.RotateCredential) {
868
1157
  AgentAccountRotateCredentialArgs memory r = abi.decode(args, (AgentAccountRotateCredentialArgs));
869
- _applyRotateCredential(account, r);
1158
+ _applyRotateCredential(account, c, r);
870
1159
  } else if (action == CustodyAction.ApplySystemUpdate) {
1160
+ // Spec 445 §1.3 (i): the account refuses `newImpl` unless its implementation's UpgradeVoucher
1161
+ // vouches for (newImpl, keccak256("")) at this moment — a quorum cannot delegatecall arbitrary
1162
+ // code either. Always a plain upgrade (empty migration data).
871
1163
  (address newImpl) = abi.decode(args, (address));
872
1164
  _execute(account, abi.encodeWithSignature("upgradeToAndCall(address,bytes)", newImpl, ""));
1165
+ } else if (action == CustodyAction.InstallModule) {
1166
+ (uint256 moduleTypeId, address module, bytes memory initData) = abi.decode(args, (uint256, address, bytes));
1167
+ _execute(account, abi.encodeWithSignature(
1168
+ "installModule(uint256,address,bytes)", moduleTypeId, module, initData
1169
+ ));
1170
+ } else if (action == CustodyAction.UninstallModule) {
1171
+ (uint256 moduleTypeId, address module, bytes memory deInitData) = abi.decode(args, (uint256, address, bytes));
1172
+ // Not this policy: uninstalling the custody policy is permanent (C-11: reinstall forbidden) and
1173
+ // leaves every custodian a 1-of-N owner. It had no route before generation 4 and gets none now
1174
+ // — least of all one that stays open under a pause.
1175
+ if (module == address(this)) revert CannotUninstallCustodyPolicy();
1176
+ _execute(account, abi.encodeWithSignature(
1177
+ "uninstallModule(uint256,address,bytes)", moduleTypeId, module, deInitData
1178
+ ));
1179
+ } else if (action == CustodyAction.LowerSpendCeiling) {
1180
+ (address hook, uint256 newCeiling) = abi.decode(args, (address, uint256));
1181
+ _executeOnHook(account, hook, abi.encodeWithSignature("lowerCeiling(uint256)", newCeiling));
1182
+ } else if (action == CustodyAction.SetSpendCeiling) {
1183
+ (address hook, uint256 newCeiling) = abi.decode(args, (address, uint256));
1184
+ _executeOnHook(account, hook, abi.encodeWithSignature("setCeiling(uint256)", newCeiling));
873
1185
  } else if (action == CustodyAction.RotateDelegationManager) {
874
1186
  (address newDm) = abi.decode(args, (address));
875
1187
  _execute(account, abi.encodeWithSignature("setDelegationManager(address)", newDm));
@@ -905,6 +1217,24 @@ contract CustodyPolicy {
905
1217
  }
906
1218
  }
907
1219
 
1220
+ /// @dev Spec 445 §1.5 (CUST-3) — the account calls one of ITS OWN installed HOOK modules, as the account,
1221
+ /// under the quorum that applied this change. The only non-self target this policy ever dispatches
1222
+ /// to, and only after the account confirms `hook` is installed on it as a hook: without that check a
1223
+ /// quorum at the `LowerSpendCeiling` tier (T4) could make the account call an arbitrary contract
1224
+ /// with a `lowerCeiling(uint256)`-shaped selector. The direction of the change (lower-only vs any)
1225
+ /// is enforced by the hook, at the resource — this module never reads the ceiling to pick a tier.
1226
+ function _executeOnHook(address account, address hook, bytes memory data) internal {
1227
+ if (!ICustodyPolicyAccountModuleView(account).isModuleInstalled(MODULE_TYPE_HOOK, hook, "")) {
1228
+ revert HookNotInstalledOn(account, hook);
1229
+ }
1230
+ (bool ok, bytes memory ret) = account.call(
1231
+ abi.encodeWithSignature("executeFromModule(address,uint256,bytes)", hook, uint256(0), data)
1232
+ );
1233
+ if (!ok) {
1234
+ assembly { revert(add(ret, 32), mload(ret)) }
1235
+ }
1236
+ }
1237
+
908
1238
  function _applyAddGuardian(address account, Config storage c, address g) internal {
909
1239
  if (g == address(0)) revert ZeroAddress();
910
1240
  if (c.trustees[g]) revert TrusteeAlreadyExists(g);
@@ -960,13 +1290,14 @@ contract CustodyPolicy {
960
1290
  */
961
1291
  function _applyRotateAllOwners(
962
1292
  address account,
1293
+ Config storage c,
963
1294
  address[] memory addCustodians,
964
1295
  address[] memory removeCustodians
965
1296
  ) internal {
966
1297
  if (addCustodians.length == 0 && removeCustodians.length == 0) {
967
1298
  revert EmptyOwnerSet();
968
1299
  }
969
- uint256 added;
1300
+ uint256 added = 0;
970
1301
  for (uint256 i; i < addCustodians.length; i++) {
971
1302
  address o = addCustodians[i];
972
1303
  if (o == address(0)) revert ZeroAddress();
@@ -977,12 +1308,12 @@ contract CustodyPolicy {
977
1308
  }
978
1309
  // Remove AFTER add so we never transiently dip below count=1 in
979
1310
  // the "rotate sole custodian to a new sole custodian" case.
980
- uint256 removed;
1311
+ uint256 removed = 0;
981
1312
  for (uint256 i; i < removeCustodians.length; i++) {
982
1313
  address o = removeCustodians[i];
983
1314
  if (o == address(0)) revert ZeroAddress();
984
1315
  if (IAgentAccount(account).isCustodian(o)) {
985
- _execute(account, abi.encodeCall(IAgentAccount.removeCustodian, (o)));
1316
+ _retireCustodian(account, c, o);
986
1317
  removed++;
987
1318
  }
988
1319
  }
@@ -1044,8 +1375,8 @@ contract CustodyPolicy {
1044
1375
  emit ThresholdChanged(account, tier, oldValue, newCount);
1045
1376
  }
1046
1377
 
1047
- function _applyRecoverAccount(address account, AgentAccountRecoveryArgs memory r) internal {
1048
- uint256 addedOwners;
1378
+ function _applyRecoverAccount(address account, Config storage c, AgentAccountRecoveryArgs memory r) internal {
1379
+ uint256 addedOwners = 0;
1049
1380
  for (uint256 i; i < r.addOwners.length; i++) {
1050
1381
  address o = r.addOwners[i];
1051
1382
  if (o == address(0)) revert ZeroAddress();
@@ -1055,7 +1386,7 @@ contract CustodyPolicy {
1055
1386
  }
1056
1387
  }
1057
1388
 
1058
- uint256 addedPasskeys;
1389
+ uint256 addedPasskeys = 0;
1059
1390
  for (uint256 i; i < r.addPasskeys.length; i++) {
1060
1391
  AgentAccountRecoveryPasskeyAdd memory pk = r.addPasskeys[i];
1061
1392
  // H7-C.1 / CON-WEBAUTHN-001: addPasskey now requires rpIdHash.
@@ -1066,25 +1397,26 @@ contract CustodyPolicy {
1066
1397
  addedPasskeys++;
1067
1398
  }
1068
1399
 
1069
- uint256 removedOwners;
1400
+ uint256 removedOwners = 0;
1070
1401
  for (uint256 i; i < r.removeOwners.length; i++) {
1071
1402
  address o = r.removeOwners[i];
1072
1403
  if (IAgentAccount(account).isCustodian(o)) {
1073
- _execute(account, abi.encodeCall(IAgentAccount.removeCustodian, (o)));
1404
+ _retireCustodian(account, c, o);
1074
1405
  removedOwners++;
1075
1406
  }
1076
1407
  }
1077
1408
 
1078
- uint256 removedPasskeys;
1409
+ uint256 removedPasskeys = 0;
1079
1410
  for (uint256 i; i < r.removePasskeyCredentialIdDigests.length; i++) {
1080
- bytes32 cid = r.removePasskeyCredentialIdDigests[i];
1081
- _execute(account, abi.encodeWithSignature("removePasskey(bytes32)", cid));
1411
+ _retirePasskey(account, c, r.removePasskeyCredentialIdDigests[i]);
1082
1412
  removedPasskeys++;
1083
1413
  }
1084
1414
 
1085
1415
  // Spec 410 §1.2 (THESIS-1a): recovery re-approves nothing and voids every approval the account
1086
1416
  // ever made — including one planted for a future epoch. The person re-issues from a reviewed list.
1087
1417
  _revokeAllApprovedDigests(account);
1418
+ // CUST-5: fit every threshold to the custodian set the recovery leaves (never refuse the lifeline).
1419
+ _clampThresholdsToCustodians(account, c);
1088
1420
  emit AccountRecovered(account, addedOwners, removedOwners, addedPasskeys, removedPasskeys);
1089
1421
  }
1090
1422
 
@@ -1092,7 +1424,7 @@ contract CustodyPolicy {
1092
1424
  /// derives each key under the post-retirement epoch (`approveDigest`); this module never computes
1093
1425
  /// a key. Exactly one credential in and one out, so the account is never credential-less and the
1094
1426
  /// action cannot be bent into a bulk custody change at the rotation tier.
1095
- function _applyRotateCredential(address account, AgentAccountRotateCredentialArgs memory r) internal {
1427
+ function _applyRotateCredential(address account, Config storage c, AgentAccountRotateCredentialArgs memory r) internal {
1096
1428
  bool addsOwner = r.addOwner != address(0);
1097
1429
  bool addsPasskey = r.addPasskey.x != 0 || r.addPasskey.y != 0 || r.addPasskey.credentialIdDigest != bytes32(0);
1098
1430
  bool removesOwner = r.removeOwner != address(0);
@@ -1108,14 +1440,28 @@ contract CustodyPolicy {
1108
1440
  ));
1109
1441
  }
1110
1442
  if (removesOwner) {
1111
- _execute(account, abi.encodeCall(IAgentAccount.removeCustodian, (r.removeOwner)));
1443
+ _retireCustodian(account, c, r.removeOwner);
1112
1444
  } else {
1113
- _execute(account, abi.encodeWithSignature("removePasskey(bytes32)", r.removePasskeyCredentialIdDigest));
1445
+ _retirePasskey(account, c, r.removePasskeyCredentialIdDigest);
1114
1446
  }
1115
1447
  for (uint256 i; i < r.reapprove.length; i++) {
1116
1448
  _execute(account, abi.encodeWithSignature("approveDigest(bytes32)", r.reapprove[i]));
1117
1449
  }
1450
+ // Spec 445 §1.3 (ii): the retirement above bumped the custody epoch, which expelled every
1451
+ // non-canonical executor module and a non-canonical delegation manager. A PLANNED rotation carries
1452
+ // what the owner keeps and re-stamps it under the new epoch, in this same applied change. This
1453
+ // module (the canonical custody policy) needs no re-affirmation. `_applyRecoverAccount` and
1454
+ // `_applyRotateAllOwners` have no such step, by construction.
1455
+ for (uint256 i; i < r.reaffirmModules.length; i++) {
1456
+ _execute(account, abi.encodeWithSignature("reaffirmModule(address)", r.reaffirmModules[i]));
1457
+ }
1458
+ if (r.reaffirmDelegationManager) {
1459
+ _execute(account, abi.encodeWithSignature("reaffirmDelegationManager()"));
1460
+ }
1118
1461
  emit CredentialRotated(account, r.reapprove.length);
1462
+ if (r.reaffirmModules.length != 0 || r.reaffirmDelegationManager) {
1463
+ emit RotationReaffirmed(account, r.reaffirmModules.length, r.reaffirmDelegationManager);
1464
+ }
1119
1465
  }
1120
1466
 
1121
1467
  /// @dev Spec 410 §1.2 — `AgentAccount.revokeAllApprovedDigests()` as the account (module context).