@agenticprimitives/contracts 1.0.0-alpha.4 → 1.0.0-alpha.41

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 (108) hide show
  1. package/AUDIT.md +330 -47
  2. package/README.md +56 -10
  3. package/deployments-base-sepolia.json +50 -0
  4. package/deployments-faithchain.json +75 -0
  5. package/deployments-hopechain.json +57 -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/AgentAccount.json +1827 -0
  10. package/dist/abi/AgentAccountFactory.json +545 -0
  11. package/dist/abi/AgentNameRegistry.json +51 -0
  12. package/dist/abi/AgentRegistryBase.json +652 -0
  13. package/dist/abi/AgenticGovernance.json +32 -0
  14. package/dist/abi/AgreementRegistry.json +427 -0
  15. package/dist/abi/ApprovedHashRegistry.json +47 -2
  16. package/dist/abi/AttestationRegistry.json +436 -0
  17. package/dist/abi/CallDataHashEnforcer.json +119 -0
  18. package/dist/abi/CustodyPolicy.json +1179 -0
  19. package/dist/abi/DelegationManager.json +656 -0
  20. package/dist/abi/DigestBindingEnforcer.json +251 -0
  21. package/dist/abi/EstateProjectionRegistry.json +293 -0
  22. package/dist/abi/GeoFeatureRegistry.json +625 -0
  23. package/dist/abi/IAgentAccount.json +262 -0
  24. package/dist/abi/IAgentAccountFactoryAccessor.json +15 -0
  25. package/dist/abi/IAgentAccountFactoryView.json +54 -0
  26. package/dist/abi/IAgentAccountPauseView.json +15 -0
  27. package/dist/abi/IAgenticPrimitivesAgentAccount.json +15 -0
  28. package/dist/abi/IApprovedHashRegistryView.json +26 -0
  29. package/dist/abi/IApprovedHashRegistryWrite.json +35 -0
  30. package/dist/abi/ICustodyPolicyAccountModuleView.json +31 -0
  31. package/dist/abi/ICustodyPolicyFactoryView.json +15 -0
  32. package/dist/abi/ICustodyPolicyPauseView.json +15 -0
  33. package/dist/abi/IDelegationManager.json +171 -0
  34. package/dist/abi/IERC7579HookLike.json +44 -0
  35. package/dist/abi/IERC7579ModuleLike.json +28 -0
  36. package/dist/abi/IPaymentReceiptRegistry.json +50 -0
  37. package/dist/abi/IRegistryMembershipPolicy.json +70 -0
  38. package/dist/abi/MockUSDC.json +621 -0
  39. package/dist/abi/PayloadClassesEnforcer.json +117 -0
  40. package/dist/abi/PaymentEnforcer.json +441 -0
  41. package/dist/abi/PaymentEscrow.json +324 -0
  42. package/dist/abi/PaymentReceiptRegistry.json +182 -0
  43. package/dist/abi/PermissionlessSubregistry.json +5 -0
  44. package/dist/abi/PricedSubregistry.json +869 -0
  45. package/dist/abi/QuorumEnforcer.json +311 -0
  46. package/dist/abi/ReceiptAnchorRegistry.json +153 -0
  47. package/dist/abi/SignatureSlotRecovery.json +88 -0
  48. package/dist/abi/SkillDefinitionRegistry.json +491 -0
  49. package/dist/abi/SmartAgentPaymaster.json +873 -0
  50. package/dist/abi/TreasurySpendPolicy.json +369 -0
  51. package/dist/abi/UniversalSignatureValidator.json +65 -0
  52. package/dist/abi/index.d.ts +38 -0
  53. package/dist/abi/index.js +38 -0
  54. package/dist/deployments/base-sepolia.d.ts +46 -0
  55. package/dist/deployments/base-sepolia.js +54 -0
  56. package/dist/deployments/faithchain.d.ts +55 -0
  57. package/dist/deployments/faithchain.js +79 -0
  58. package/dist/deployments/hopechain.d.ts +53 -0
  59. package/dist/deployments/hopechain.js +61 -0
  60. package/dist/deployments/index.d.ts +13 -0
  61. package/dist/deployments/index.js +28 -0
  62. package/dist/deployments/paymaster-anvil.d.ts +11 -0
  63. package/dist/deployments/paymaster-anvil.js +9 -0
  64. package/dist/deployments/registries-base-sepolia.d.ts +10 -0
  65. package/dist/deployments/registries-base-sepolia.js +8 -0
  66. package/dist/deployments/registries-hopechain.d.ts +10 -0
  67. package/dist/deployments/registries-hopechain.js +8 -0
  68. package/package.json +55 -8
  69. package/src/AgentAccount.sol +569 -38
  70. package/src/AgentAccountFactory.sol +157 -16
  71. package/src/ApprovedHashRegistry.sol +41 -6
  72. package/src/IAgentAccount.sol +23 -0
  73. package/src/SmartAgentPaymaster.sol +156 -12
  74. package/src/UniversalSignatureValidator.sol +3 -0
  75. package/src/agency/DelegationManager.sol +179 -0
  76. package/src/agency/IDelegationManager.sol +38 -0
  77. package/src/agreement/AgreementRegistry.sol +331 -0
  78. package/src/attestation/AttestationRegistry.sol +384 -0
  79. package/src/custody/CustodyPolicy.sol +263 -15
  80. package/src/custody/TreasurySpendPolicy.sol +166 -0
  81. package/src/enforcers/AllowedMethodsEnforcer.sol +6 -0
  82. package/src/enforcers/AllowedTargetsEnforcer.sol +6 -0
  83. package/src/enforcers/CallDataHashEnforcer.sol +61 -0
  84. package/src/enforcers/DigestBindingEnforcer.sol +107 -0
  85. package/src/enforcers/PayloadClassesEnforcer.sol +30 -0
  86. package/src/enforcers/PaymentEnforcer.sol +257 -0
  87. package/src/enforcers/QuorumEnforcer.sol +24 -1
  88. package/src/enforcers/TimestampEnforcer.sol +7 -0
  89. package/src/enforcers/ValueEnforcer.sol +6 -0
  90. package/src/geo/GeoFeatureRegistry.sol +197 -0
  91. package/src/governance/AgenticGovernance.sol +26 -4
  92. package/src/identity/AgentProfilePredicates.sol +23 -0
  93. package/src/libraries/SignatureSlotRecovery.sol +24 -7
  94. package/src/libraries/WebAuthnLib.sol +13 -0
  95. package/src/mocks/MockUSDC.sol +152 -0
  96. package/src/naming/AgentNamePredicates.sol +89 -0
  97. package/src/naming/AgentNameRegistry.sol +65 -18
  98. package/src/naming/AgentNameUniversalResolver.sol +1 -1
  99. package/src/naming/PermissionlessSubregistry.sol +19 -2
  100. package/src/naming/PricedSubregistry.sol +209 -0
  101. package/src/payments/PaymentEscrow.sol +164 -0
  102. package/src/payments/PaymentReceiptRegistry.sol +67 -0
  103. package/src/provenance/ReceiptAnchorRegistry.sol +55 -0
  104. package/src/registry/AgentRegistryBase.sol +313 -0
  105. package/src/registry/EstateProjectionRegistry.sol +109 -0
  106. package/src/registry/IRegistryMembershipPolicy.sol +30 -0
  107. package/src/relationships/AgentRelationship.sol +8 -0
  108. package/src/skills/SkillDefinitionRegistry.sol +187 -0
@@ -1,9 +1,32 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  pragma solidity ^0.8.28;
3
3
 
4
- import {IAgentAccount, AgentAccountRecoveryArgs, AgentAccountRecoveryPasskeyAdd} from "../IAgentAccount.sol";
4
+ import {IAgentAccount, AgentAccountRecoveryArgs, AgentAccountRecoveryPasskeyAdd, AgentAccountRotateCredentialArgs} from "../IAgentAccount.sol";
5
5
  import {SignatureSlotRecovery} from "../libraries/SignatureSlotRecovery.sol";
6
6
 
7
+ /// @dev R6.6 — minimal interface for the `account → factory → governance.isPaused()`
8
+ /// staticcall chain. Mirrors the same patterns introduced by R6.5
9
+ /// in `AgentAccount` (see `IAgentAccountFactoryView` /
10
+ /// `IAgentAccountPauseView` in `AgentAccount.sol`).
11
+ interface IAgentAccountFactoryAccessor {
12
+ function factory() external view returns (address);
13
+ }
14
+
15
+ interface ICustodyPolicyFactoryView {
16
+ function governance() external view returns (address);
17
+ }
18
+
19
+ interface ICustodyPolicyPauseView {
20
+ function isPaused() external view returns (bool);
21
+ }
22
+
23
+ /// @dev R917-C-1 — the account's ERC-7579 module view. `onUninstall` refuses while the account still lists
24
+ /// this module as installed, so the only path to it is `AgentAccount.uninstallModule` (onlySelf +
25
+ /// custody-quorum), which clears the flag BEFORE calling out.
26
+ interface ICustodyPolicyAccountModuleView {
27
+ function isModuleInstalled(uint256 moduleTypeId, address module, bytes calldata additionalContext) external view returns (bool);
28
+ }
29
+
7
30
  /**
8
31
  * @title CustodyPolicy
9
32
  * @notice ERC-7579 module that owns the schedule / apply / cancel
@@ -57,7 +80,8 @@ contract CustodyPolicy {
57
80
  ChangeValueCeiling, // 12 — T4
58
81
  SetRecoveryApprovals, // 13 — T4
59
82
  RecoverAccount, // 14 — T6
60
- ChangeApprovalsRequired // 15 — T4 (per-tier custody quorum threshold)
83
+ ChangeApprovalsRequired, // 15 — T4 (per-tier custody quorum threshold)
84
+ RotateCredential // 16 — T4 (spec 410 §1.2: add + retire + re-approve standing wires, atomically)
61
85
  }
62
86
 
63
87
  struct ScheduledChange {
@@ -125,6 +149,64 @@ contract CustodyPolicy {
125
149
  _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator();
126
150
  }
127
151
 
152
+ // ─── R6.6 / CON-CustodyPolicy-005 — system-pause modifier ──────
153
+ //
154
+ // `whenAccountNotPaused(account)` reverts when
155
+ // `AgenticGovernance.isPaused() == true`, where governance is
156
+ // resolved per-call via the account's factory:
157
+ //
158
+ // account.factory() → factory.governance() → governance.isPaused()
159
+ //
160
+ // 3 staticcalls. Custody schedule/apply are rare; the gas cost
161
+ // is acceptable. Non-conforming hops (EOA factory, EOA governance,
162
+ // missing fn) treat the system as "not paused" so legacy / test
163
+ // deploys keep working — mirrors the R6.5 pattern in AgentAccount
164
+ // and `GovernanceManaged._pausedSafe()`.
165
+ //
166
+ // Applied to: `scheduleCustodyChange`, `applyCustodyChange`.
167
+ //
168
+ // Deliberately NOT applied to (recovery primitives that must
169
+ // work during an incident):
170
+ // - `cancelScheduledChange` — defensive de-escalation
171
+ // - `onUninstall` — removing attack surface
172
+ // - `onInstall` — gated upstream by paused
173
+ // `installModule` on AgentAccount (R6.5)
174
+ // and paused `createAgentAccount`
175
+ // on AgentAccountFactory
176
+ modifier whenAccountNotPaused(address account) {
177
+ if (_systemPausedFor(account)) revert SystemPaused();
178
+ _;
179
+ }
180
+
181
+ /// @notice R6.6 — thrown when a `whenAccountNotPaused`-guarded
182
+ /// entrypoint is called while the governance pause flag
183
+ /// is set.
184
+ error SystemPaused();
185
+
186
+ function _systemPausedFor(address account) internal view returns (bool) {
187
+ if (account == address(0) || account.code.length == 0) return false;
188
+ // Hop 1: account → factory
189
+ (bool okF, bytes memory dataF) = account.staticcall(
190
+ abi.encodeWithSelector(IAgentAccountFactoryAccessor.factory.selector)
191
+ );
192
+ if (!okF || dataF.length < 32) return false;
193
+ address fac = abi.decode(dataF, (address));
194
+ if (fac == address(0) || fac.code.length == 0) return false;
195
+ // Hop 2: factory → governance
196
+ (bool okG, bytes memory dataG) = fac.staticcall(
197
+ abi.encodeWithSelector(ICustodyPolicyFactoryView.governance.selector)
198
+ );
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));
208
+ }
209
+
128
210
  function _buildDomainSeparator() internal view returns (bytes32) {
129
211
  return keccak256(
130
212
  abi.encode(
@@ -199,13 +281,25 @@ contract CustodyPolicy {
199
281
  event CustodyChangeScheduled(address indexed account, uint256 indexed changeId, CustodyAction indexed action, uint64 eta, address proposer);
200
282
  event CustodyChangeApplied(address indexed account, uint256 indexed changeId);
201
283
  event ScheduledChangeCancelled(address indexed account, uint256 indexed changeId);
202
- event GuardianAdded(address indexed account, address indexed guardian);
203
- event GuardianRemoved(address indexed account, address indexed guardian);
284
+ /// @dev Spec 302 W3 — guardian/trustee events carry an opaque MEMBERSHIP
285
+ /// COMMITMENT, not the raw guardian address: `GuardianAdded(account,
286
+ /// guardian)` published each person's social-recovery graph (who
287
+ /// guards whom) permanently. The commitment
288
+ /// `keccak256(abi.encode(guardian, account))` is unsalted +
289
+ /// on-chain-reproducible (ADR-0040 posture): anyone holding a
290
+ /// CANDIDATE guardian address can confirm membership, but nobody can
291
+ /// enumerate the graph from logs. The ONE read path for a live check
292
+ /// is `isTrustee(account, signer)` (ADR-0012/0013).
293
+ event GuardianAdded(address indexed account, bytes32 indexed guardianCommitment);
294
+ event GuardianRemoved(address indexed account, bytes32 indexed guardianCommitment);
204
295
  event ThresholdChanged(address indexed account, uint8 indexed tier, uint8 oldValue, uint8 newValue);
205
296
  event ModeChanged(address indexed account, uint8 oldMode, uint8 newMode);
206
297
  event T3CeilingChanged(address indexed account, uint256 oldCeiling, uint256 newCeiling);
207
298
  event RecoveryThresholdChanged(address indexed account, uint8 oldValue, uint8 newValue);
208
299
  event OwnersRotated(address indexed account, uint256 newOwnerCount);
300
+ /// @dev Spec 410 §1.2 — a planned rotation applied: one credential in, one out, `reapproved` wires
301
+ /// re-approved under the new custody epoch in the same transaction.
302
+ event CredentialRotated(address indexed account, uint256 reapproved);
209
303
  /// @notice Audit C-10: per-rotation count of custodians removed.
210
304
  event CustodiansRemovedDuringRotation(address indexed account, uint256 removedCount);
211
305
  /// @notice Audit C-11: CustodyPolicy was uninstalled; the account
@@ -235,12 +329,26 @@ contract CustodyPolicy {
235
329
  error AdminInsufficientQuorum(uint256 supplied, uint8 required);
236
330
  error AdminDuplicateOrUnsortedSigner(address signer);
237
331
  error AdminUnauthorizedSigner(address signer);
332
+ /// @notice ACCT-C2 (spec 300) — the account itself was presented as a quorum
333
+ /// signer (via `isCustodian(address(this))==true` or the `v=0`
334
+ /// self-referential ERC-1271 slot). A self-signature must never count
335
+ /// toward the quorum, else one custodian forges an extra member.
336
+ error AdminSelfSignerNotAllowed(address account);
238
337
  error TrusteeAlreadyExists(address guardian);
239
338
  error TrusteeDoesNotExist(address guardian);
240
339
  error InvalidMode(uint8 mode_);
241
340
  error InvalidThresholdValue(uint8 thr);
341
+ /// @dev EXT-CHANGEMODE-1: a runtime ChangeMode into org mode (3) with an infeasible signer
342
+ /// count (< 2, so separation-of-duties can't split proposers from appliers). Mirrors the
343
+ /// factory's install-time InfeasibleOrgConfig.
344
+ error InfeasibleOrgConfig(uint8 nSigners);
345
+ /// @dev CP-1: a tier that must be configured (T4/T5 at install, T6 at read)
346
+ /// was left unset — refuse rather than fall to the 1-of-n read fallback.
347
+ error UnconfiguredTier(uint8 tier);
242
348
  error RecoveryRequiresGuardians();
243
349
  error EmptyOwnerSet();
350
+ /// @dev Spec 410 §1.2 — `RotateCredential` needs exactly one credential added and exactly one retired.
351
+ error RotationNeedsOneAddAndOneRemove();
244
352
  error CustodyActionNotYetImplemented(uint8 action);
245
353
  error CannotDowngradeWithTrustees();
246
354
  error TimelockRequiredForTier(uint8 tier);
@@ -251,6 +359,11 @@ contract CustodyPolicy {
251
359
  /// @dev Audit C-11: reinstall over a previously-uninstalled config
252
360
  /// is forbidden — stale mappings would compose unpredictably.
253
361
  error ReinstallForbidden(address account);
362
+ /// @dev R917-C-1: `onUninstall` was called while the account still has this module installed — i.e. by
363
+ /// `execute(custodyPolicy, onUninstall)` under a single custodian or a delegation, not by
364
+ /// `uninstallModule`. Accepting it would leave the account governed by a policy that refuses every
365
+ /// change (installed on the account, uninstalled here, reinstall forbidden) — bricked forever.
366
+ error StillInstalledOn(address account);
254
367
 
255
368
  // ─── ERC-7579 lifecycle ───────────────────────────────────────────
256
369
 
@@ -296,11 +409,7 @@ contract CustodyPolicy {
296
409
  c.t3HighValueCeiling = t3Ceiling;
297
410
  c.approvedHashRegistry = approvedHashReg;
298
411
 
299
- for (uint8 t = 1; t <= 6; t++) {
300
- if (thresholds[t] > 0) c.approvalsRequiredByTier[t] = thresholds[t];
301
- if (timelocks[t] > 0) c.safetyDelayByTier[t] = timelocks[t];
302
- }
303
-
412
+ // Trustees first so `trusteeCount` is known for the CP-2 recovery check.
304
413
  for (uint256 i; i < trustees.length; i++) {
305
414
  address g = trustees[i];
306
415
  if (g == address(0)) revert ZeroAddress();
@@ -309,6 +418,51 @@ contract CustodyPolicy {
309
418
  c.trusteeCount += 1;
310
419
  }
311
420
 
421
+ // CP-2: a recovery threshold the trustee set can NEVER satisfy bricks the
422
+ // T6 recovery lifeline from birth. Validate at install exactly as
423
+ // `_applySetRecoveryThreshold` does at runtime. `recoveryApprovals == 0`
424
+ // is a legitimate state (trustee recovery simply disabled); a positive
425
+ // threshold MUST be reachable by the configured trustees.
426
+ if (recThr > c.trusteeCount) revert RecoveryRequiresGuardians();
427
+
428
+ // CP-1: floor each unset tier to the spec default-approvals matrix so a
429
+ // direct onInstall that bypasses the factory with a zeroed/partial
430
+ // threshold array can't collapse the admin/critical tiers to the 1-of-n
431
+ // read fallback in `_approvalsValue`. T1–T3 legitimately stay at the
432
+ // 1-of-n floor (read/write/value are single-signer tiers by design);
433
+ // T4/T5 get the council default. T6 (recovery) lives in
434
+ // `recoveryApprovals`, not this map.
435
+ //
436
+ // The custodian count is read best-effort from the installing account
437
+ // (the ERC-7579 flow guarantees `msg.sender` is the deployed account).
438
+ // If it can't be determined (the account isn't yet/at all an
439
+ // `IAgentAccount`), `nCustodians` stays 0 so no flooring happens — and
440
+ // the hard-revert below then REQUIRES the installer to have passed
441
+ // explicit T4/T5 thresholds. Either way the admin/critical tiers can
442
+ // never silently resolve to 1-of-n; the floor is a convenience, the
443
+ // hard-revert is the security invariant.
444
+ uint8 nCustodians;
445
+ if (account.code.length > 0) {
446
+ try IAgentAccount(account).custodianCount() returns (uint256 cnt) {
447
+ nCustodians = cnt > 255 ? 255 : uint8(cnt);
448
+ } catch {}
449
+ }
450
+ for (uint8 t = 1; t <= 6; t++) {
451
+ uint8 thr = thresholds[t];
452
+ if (thr == 0) thr = _defaultApprovals(nCustodians, t);
453
+ if (thr > 0) c.approvalsRequiredByTier[t] = thr;
454
+ if (timelocks[t] > 0) c.safetyDelayByTier[t] = timelocks[t];
455
+ }
456
+
457
+ // CP-1 hard-revert: a non-single account MUST have the admin (T4) +
458
+ // critical (T5) custody quorum configured (explicitly or via the floor
459
+ // above) — never the 1-of-n read fallback. Mode 0 (single signer) has no
460
+ // custody council, so thresholds are moot and this is skipped.
461
+ if (modeVal >= 1) {
462
+ if (c.approvalsRequiredByTier[4] == 0) revert UnconfiguredTier(4);
463
+ if (c.approvalsRequiredByTier[5] == 0) revert UnconfiguredTier(5);
464
+ }
465
+
312
466
  emit CustodyPolicyInstalled(account, modeVal, recThr);
313
467
  }
314
468
 
@@ -316,6 +470,14 @@ contract CustodyPolicy {
316
470
  address account = msg.sender;
317
471
  Config storage c = _configs[account];
318
472
  if (!c.installed) revert NotInstalledOn(account);
473
+ // R917-C-1: the account must have ALREADY dropped this module. `AgentAccount.uninstallModule` (onlySelf
474
+ // + `_requireCustodyGoverned`) clears its installed flag before this call; any other caller that is the
475
+ // account — a 1-of-N custodian userOp `execute(custodyPolicy, onUninstall)`, a delegation redeemed
476
+ // through the DM — still lists the module and is refused here. Fail closed on the read as well: a
477
+ // caller that cannot answer the view is not an account that uninstalled us.
478
+ if (ICustodyPolicyAccountModuleView(account).isModuleInstalled(MODULE_TYPE_EXECUTOR, address(this), "")) {
479
+ revert StillInstalledOn(account);
480
+ }
319
481
  c.installed = false;
320
482
  // Audit C-11: lock against ever re-installing on this account.
321
483
  // The mapping state (trustees, thresholds, proposals) is left
@@ -335,7 +497,7 @@ contract CustodyPolicy {
335
497
  CustodyAction action,
336
498
  bytes calldata args,
337
499
  bytes calldata quorumSigs
338
- ) external returns (uint256 changeId) {
500
+ ) external whenAccountNotPaused(account) returns (uint256 changeId) {
339
501
  Config storage c = _configs[account];
340
502
  if (!c.installed) revert NotInstalledOn(account);
341
503
 
@@ -394,7 +556,10 @@ contract CustodyPolicy {
394
556
  emit CustodyChangeScheduled(account, changeId, action, eta, msg.sender);
395
557
  }
396
558
 
397
- function applyCustodyChange(address account, uint256 changeId, bytes calldata quorumSigs) external {
559
+ function applyCustodyChange(address account, uint256 changeId, bytes calldata quorumSigs)
560
+ external
561
+ whenAccountNotPaused(account)
562
+ {
398
563
  Config storage c = _configs[account];
399
564
  if (!c.installed) revert NotInstalledOn(account);
400
565
 
@@ -556,7 +721,16 @@ contract CustodyPolicy {
556
721
  function _approvalsValue(Config storage c, uint8 tier) internal view returns (uint8) {
557
722
  if (tier == 0 || tier > 6) revert InvalidTier(tier);
558
723
  uint8 v = c.approvalsRequiredByTier[tier];
559
- return v == 0 ? 1 : v;
724
+ if (v == 0) {
725
+ // CP-1 defense-in-depth: the T6 (recovery) quorum lives in
726
+ // `recoveryApprovals`, never in this map — a T6 read here is a
727
+ // mis-wire, so fail closed instead of returning the 1-of-n fallback.
728
+ // T1–T5 keep the 1-of-n floor (T4/T5 are install-floored, so the
729
+ // fallback only ever applies to the low single-signer tiers).
730
+ if (tier == 6) revert UnconfiguredTier(6);
731
+ return 1;
732
+ }
733
+ return v;
560
734
  }
561
735
 
562
736
  function _safetyDelayValue(Config storage c, uint8 tier) internal view returns (uint32) {
@@ -614,10 +788,16 @@ contract CustodyPolicy {
614
788
  address prev;
615
789
  for (uint256 i; i < vargs.reqThreshold; i++) {
616
790
  address signer = SignatureSlotRecovery.recoverFromSlot(
617
- vargs.payloadHash, sigsMem, i, approvedHashReg
791
+ // Spec 302 W2 — v=2 passkey slots derive the per-ACCOUNT PIA.
792
+ vargs.payloadHash, sigsMem, i, approvedHashReg, account
618
793
  );
619
794
  if (signer <= prev) revert AdminDuplicateOrUnsortedSigner(signer);
620
795
  prev = signer;
796
+ // ACCT-C2 (spec 300): the account is never its own quorum signer. Both
797
+ // exploit shapes — `isCustodian(address(this))==true` and the `v=0`
798
+ // self-referential ERC-1271 slot that recovers `signer==account` — land
799
+ // here as `signer == account`, so one guard closes both.
800
+ if (signer == account) revert AdminSelfSignerNotAllowed(account);
621
801
  if (vargs.guardianMode) {
622
802
  if (!c.trustees[signer]) revert UnauthorizedTrustee(signer);
623
803
  } else {
@@ -684,6 +864,9 @@ contract CustodyPolicy {
684
864
  } else if (action == CustodyAction.RecoverAccount) {
685
865
  AgentAccountRecoveryArgs memory r = abi.decode(args, (AgentAccountRecoveryArgs));
686
866
  _applyRecoverAccount(account, r);
867
+ } else if (action == CustodyAction.RotateCredential) {
868
+ AgentAccountRotateCredentialArgs memory r = abi.decode(args, (AgentAccountRotateCredentialArgs));
869
+ _applyRotateCredential(account, r);
687
870
  } else if (action == CustodyAction.ApplySystemUpdate) {
688
871
  (address newImpl) = abi.decode(args, (address));
689
872
  _execute(account, abi.encodeWithSignature("upgradeToAndCall(address,bytes)", newImpl, ""));
@@ -727,7 +910,7 @@ contract CustodyPolicy {
727
910
  if (c.trustees[g]) revert TrusteeAlreadyExists(g);
728
911
  c.trustees[g] = true;
729
912
  c.trusteeCount += 1;
730
- emit GuardianAdded(account, g);
913
+ emit GuardianAdded(account, keccak256(abi.encode(g, account)));
731
914
  }
732
915
 
733
916
  function _applyRemoveGuardian(address account, Config storage c, address g) internal {
@@ -737,13 +920,30 @@ contract CustodyPolicy {
737
920
  }
738
921
  c.trustees[g] = false;
739
922
  c.trusteeCount -= 1;
740
- emit GuardianRemoved(account, g);
923
+ emit GuardianRemoved(account, keccak256(abi.encode(g, account)));
741
924
  }
742
925
 
743
926
  function _applyChangeMode(address account, Config storage c, uint8 newMode) internal {
744
927
  if (newMode > 3) revert InvalidMode(newMode);
745
928
  uint8 oldMode = c.mode;
746
929
  if (newMode == 0 && c.trusteeCount > 0) revert CannotDowngradeWithTrustees();
930
+ // EXT-CHANGEMODE-1 (2026-07-05 audit): a runtime ChangeMode must re-run the factory's install-time
931
+ // mode-3 feasibility so the account can't enter an un-executable / liveness-hostile org mode.
932
+ // Org SoD needs ≥2 signers (distinct proposers + appliers) and T4/T5 thresholds within the
933
+ // floor(N/2) cap (else 2×threshold > N → no disjoint quorum → the tier silently locks). Require the
934
+ // signer floor; cap the SoD-constrained thresholds (mirrors the factory, avoids a locked mode).
935
+ if (newMode == 3) {
936
+ uint256 n = IAgentAccount(account).custodianCount();
937
+ if (n < 2) revert InfeasibleOrgConfig(uint8(n));
938
+ uint8 sodCap = uint8(n / 2); // ≥ 1 since n ≥ 2
939
+ for (uint8 tier = 4; tier <= 5; tier++) {
940
+ uint8 v = c.approvalsRequiredByTier[tier];
941
+ if (v > sodCap) {
942
+ c.approvalsRequiredByTier[tier] = sodCap;
943
+ emit ThresholdChanged(account, tier, v, sodCap);
944
+ }
945
+ }
946
+ }
747
947
  c.mode = newMode;
748
948
  emit ModeChanged(account, oldMode, newMode);
749
949
  }
@@ -786,6 +986,9 @@ contract CustodyPolicy {
786
986
  removed++;
787
987
  }
788
988
  }
989
+ // Spec 410 §1.2: a bulk custodian rotation carries no re-approval list; like recovery it voids every
990
+ // approval so nothing planted for a future epoch survives it. Re-approve through `RotateCredential`.
991
+ _revokeAllApprovedDigests(account);
789
992
  emit OwnersRotated(account, added);
790
993
  // Note: OwnersRotated only carries `added` for ABI compat. A
791
994
  // future revision should add a `removed` field; that's a
@@ -828,6 +1031,13 @@ contract CustodyPolicy {
828
1031
  if (newCount == 0) revert InvalidThresholdValue(newCount);
829
1032
  uint256 n = IAgentAccount(account).custodianCount();
830
1033
  if (uint256(newCount) > n) revert InvalidThresholdValue(newCount);
1034
+ // acct-mode3-sod-cap-runtime (2026-07-05 audit): the factory caps mode-3 (org) T4/T5 thresholds at
1035
+ // floor(N/2) at install so a DISJOINT propose+apply quorum always exists (2×threshold ≤ N). A later
1036
+ // ChangeApprovalsRequired must not raise them past that cap and silently lock the tier — reject an
1037
+ // explicit over-cap request loud (the org can lower N-constraints or use a lower threshold).
1038
+ if (c.mode == 3 && (tier == 4 || tier == 5) && uint256(newCount) > n / 2) {
1039
+ revert InvalidThresholdValue(newCount);
1040
+ }
831
1041
  uint8 oldValue = c.approvalsRequiredByTier[tier];
832
1042
  if (oldValue == 0) oldValue = 1; // mirror _approvalsValue fallback
833
1043
  c.approvalsRequiredByTier[tier] = newCount;
@@ -872,9 +1082,47 @@ contract CustodyPolicy {
872
1082
  removedPasskeys++;
873
1083
  }
874
1084
 
1085
+ // Spec 410 §1.2 (THESIS-1a): recovery re-approves nothing and voids every approval the account
1086
+ // ever made — including one planted for a future epoch. The person re-issues from a reviewed list.
1087
+ _revokeAllApprovedDigests(account);
875
1088
  emit AccountRecovered(account, addedOwners, removedOwners, addedPasskeys, removedPasskeys);
876
1089
  }
877
1090
 
1091
+ /// @dev Spec 410 §1.2 — the planned rotation: add → retire → re-approve, one transaction. The account
1092
+ /// derives each key under the post-retirement epoch (`approveDigest`); this module never computes
1093
+ /// a key. Exactly one credential in and one out, so the account is never credential-less and the
1094
+ /// action cannot be bent into a bulk custody change at the rotation tier.
1095
+ function _applyRotateCredential(address account, AgentAccountRotateCredentialArgs memory r) internal {
1096
+ bool addsOwner = r.addOwner != address(0);
1097
+ bool addsPasskey = r.addPasskey.x != 0 || r.addPasskey.y != 0 || r.addPasskey.credentialIdDigest != bytes32(0);
1098
+ bool removesOwner = r.removeOwner != address(0);
1099
+ bool removesPasskey = r.removePasskeyCredentialIdDigest != bytes32(0);
1100
+ if (addsOwner == addsPasskey || removesOwner == removesPasskey) revert RotationNeedsOneAddAndOneRemove();
1101
+
1102
+ if (addsOwner) {
1103
+ _execute(account, abi.encodeCall(IAgentAccount.addCustodian, (r.addOwner)));
1104
+ } else {
1105
+ _execute(account, abi.encodeWithSignature(
1106
+ "addPasskey(bytes32,uint256,uint256,bytes32)",
1107
+ r.addPasskey.credentialIdDigest, r.addPasskey.x, r.addPasskey.y, r.addPasskey.rpIdHash
1108
+ ));
1109
+ }
1110
+ if (removesOwner) {
1111
+ _execute(account, abi.encodeCall(IAgentAccount.removeCustodian, (r.removeOwner)));
1112
+ } else {
1113
+ _execute(account, abi.encodeWithSignature("removePasskey(bytes32)", r.removePasskeyCredentialIdDigest));
1114
+ }
1115
+ for (uint256 i; i < r.reapprove.length; i++) {
1116
+ _execute(account, abi.encodeWithSignature("approveDigest(bytes32)", r.reapprove[i]));
1117
+ }
1118
+ emit CredentialRotated(account, r.reapprove.length);
1119
+ }
1120
+
1121
+ /// @dev Spec 410 §1.2 — `AgentAccount.revokeAllApprovedDigests()` as the account (module context).
1122
+ function _revokeAllApprovedDigests(address account) internal {
1123
+ _execute(account, abi.encodeWithSignature("revokeAllApprovedDigests()"));
1124
+ }
1125
+
878
1126
  /// @dev Spec § 5.1 default-threshold matrix.
879
1127
  function _defaultApprovals(uint8 nCustodians, uint8 tier) internal pure returns (uint8) {
880
1128
  if (nCustodians == 0) return 0;
@@ -0,0 +1,166 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ /**
5
+ * @title TreasurySpendPolicy — an aggregate ceiling AT THE RESOURCE (spec 410 §7, THESIS-6)
6
+ * @notice Every caveat enforcer bounds ONE delegation: `ValueEnforcer` a call's value, `PaymentEnforcer` a
7
+ * mandate's budget under (delegator, delegationHash). None of them can see the treasury's other
8
+ * delegates, so two delegates each under their own ceiling can jointly exceed the principal's
9
+ * budget. This module is the ceiling that belongs to the TREASURY: an ERC-7579 HOOK the account
10
+ * installs, consulted on every `execute` / `executeBatch` — a custodian's own userOp and a delegated
11
+ * redemption alike, because the account runs its hooks on both — that adds the value each call moves
12
+ * to the current window and refuses the one that would pass the ceiling.
13
+ *
14
+ * WHAT IT COUNTS. Native value (`value` on the call) when `asset == address(0)`; otherwise ERC-20
15
+ * `transfer(to, amount)` and `transferFrom(from, to, amount)` calldata aimed at `asset`. Anything else
16
+ * moves no value of this asset and is not counted. A batch is one call: its inner calls are summed.
17
+ *
18
+ * WINDOWS are fixed-length epochs from `windowStart` — never sliding — so the check is O(1) and the
19
+ * refusal is reproducible off chain from the receipt and the block time.
20
+ *
21
+ * WHO SETS IT. The budget is the install data: `installModule(4, this, abi.encode(asset, ceiling,
22
+ * windowSeconds))`, which on a custody-governed treasury is a governance selector under its quorum;
23
+ * changing it is an uninstall + reinstall under the same gate. There is no setter a single key could
24
+ * reach. Per-delegation ceilings are untouched: the tighter of the two refuses.
25
+ *
26
+ * WHAT IT IS NOT: a policy of who may spend (that is the mandate), a rate limit on calls, or anything
27
+ * a planner consults — the harness may READ `budget()` to say "this would exceed the treasury's
28
+ * shared budget" before a signature (honesty); the hook is the authority.
29
+ */
30
+ contract TreasurySpendPolicy {
31
+ struct Budget {
32
+ address asset; // address(0) = native value
33
+ uint256 ceiling; // per window, in the asset's base units
34
+ uint64 windowSeconds; // fixed epochs from windowStart
35
+ uint64 windowStart;
36
+ uint64 windowIndex; // the epoch `spent` belongs to
37
+ uint256 spent;
38
+ bool installed;
39
+ }
40
+
41
+ /// account => budget
42
+ mapping(address => Budget) private _budgets;
43
+
44
+ event BudgetInstalled(address indexed account, address indexed asset, uint256 ceiling, uint64 windowSeconds, uint64 windowStart);
45
+ event BudgetUninstalled(address indexed account);
46
+ event Spent(address indexed account, uint64 indexed windowIndex, uint256 amount, uint256 spentInWindow);
47
+
48
+ error BudgetExceeded(uint256 ceiling, uint256 spentInWindow, uint256 amount);
49
+ error NotInstalledOn(address account);
50
+ error AlreadyInstalledOn(address account);
51
+ error BadBudget();
52
+
53
+ bytes4 private constant TRANSFER = bytes4(keccak256("transfer(address,uint256)"));
54
+ bytes4 private constant TRANSFER_FROM = bytes4(keccak256("transferFrom(address,address,uint256)"));
55
+
56
+ // ─── ERC-7579 module surface ───────────────────────────────────────
57
+
58
+ function isModuleType(uint256 moduleTypeId) external pure returns (bool) { return moduleTypeId == 4; }
59
+ function moduleId() external pure returns (string memory) { return "agenticprimitives-treasury-spend-policy-1"; }
60
+
61
+ /// @notice Called by the account from `installModule` (governance-gated there): the budget is the install data.
62
+ function onInstall(bytes calldata initData) external {
63
+ Budget storage b = _budgets[msg.sender];
64
+ if (b.installed) revert AlreadyInstalledOn(msg.sender);
65
+ (address asset, uint256 ceiling, uint64 windowSeconds) = abi.decode(initData, (address, uint256, uint64));
66
+ if (windowSeconds == 0) revert BadBudget();
67
+ b.asset = asset;
68
+ b.ceiling = ceiling;
69
+ b.windowSeconds = windowSeconds;
70
+ b.windowStart = uint64(block.timestamp);
71
+ b.windowIndex = 0;
72
+ b.spent = 0;
73
+ b.installed = true;
74
+ emit BudgetInstalled(msg.sender, asset, ceiling, windowSeconds, b.windowStart);
75
+ }
76
+
77
+ function onUninstall(bytes calldata) external {
78
+ if (!_budgets[msg.sender].installed) revert NotInstalledOn(msg.sender);
79
+ delete _budgets[msg.sender];
80
+ emit BudgetUninstalled(msg.sender);
81
+ }
82
+
83
+ // ─── The hook ──────────────────────────────────────────────────────
84
+
85
+ /// @notice `preCheck` from the account: `msgData` is `abi.encode(target, value, data)` for `execute` and
86
+ /// `abi.encode(Call[])` for `executeBatch`. Sums the value this call moves in the budget's asset and
87
+ /// refuses when the window's total would pass the ceiling.
88
+ function preCheck(address, uint256, bytes calldata msgData) external returns (bytes memory) {
89
+ Budget storage b = _budgets[msg.sender];
90
+ if (!b.installed) return hex"";
91
+ uint256 amount = _valueMoved(b.asset, msgData);
92
+ if (amount == 0) return hex"";
93
+ uint64 idx = uint64((block.timestamp - b.windowStart) / b.windowSeconds);
94
+ if (idx != b.windowIndex) { b.windowIndex = idx; b.spent = 0; }
95
+ uint256 next = b.spent + amount;
96
+ if (next > b.ceiling) revert BudgetExceeded(b.ceiling, b.spent, amount);
97
+ b.spent = next;
98
+ emit Spent(msg.sender, idx, amount, next);
99
+ return hex"";
100
+ }
101
+
102
+ function postCheck(bytes calldata) external {}
103
+
104
+ // ─── Reads (the harness's honesty, never its authority) ────────────
105
+
106
+ function budget(address account) external view returns (address asset, uint256 ceiling, uint64 windowSeconds, uint64 windowStart, uint64 windowIndex, uint256 spent, bool installed) {
107
+ Budget storage b = _budgets[account];
108
+ return (b.asset, b.ceiling, b.windowSeconds, b.windowStart, b.windowIndex, b.spent, b.installed);
109
+ }
110
+
111
+ /// @notice What the account has spent in the CURRENT window (0 once the window rolled), and the ceiling.
112
+ function remaining(address account) external view returns (uint256 left, uint256 ceiling) {
113
+ Budget storage b = _budgets[account];
114
+ if (!b.installed) return (type(uint256).max, 0);
115
+ uint64 idx = uint64((block.timestamp - b.windowStart) / b.windowSeconds);
116
+ uint256 spent = idx == b.windowIndex ? b.spent : 0;
117
+ return (b.ceiling > spent ? b.ceiling - spent : 0, b.ceiling);
118
+ }
119
+
120
+ // ─── Internals ─────────────────────────────────────────────────────
121
+
122
+ /// @dev Both encodings the account uses, told apart by the first word: `abi.encode(Call[])` opens with the
123
+ /// array's offset (exactly 0x20), `abi.encode(target, value, data)` with the target address — and no
124
+ /// contract lives at address 0x20. The decode runs through an external self-call so a malformed payload
125
+ /// is caught rather than reverting the account's call (abi.decode cannot be tried in place).
126
+ function _valueMoved(address asset, bytes calldata msgData) internal view returns (uint256 total) {
127
+ if (msgData.length < 32) return 0;
128
+ uint256 first = uint256(bytes32(msgData[0:32]));
129
+ if (first == 0x20) {
130
+ try this.decodeBatch(msgData) returns (Call[] memory calls) {
131
+ for (uint256 i = 0; i < calls.length; i++) total += _amountOf(asset, calls[i].target, calls[i].value, calls[i].data);
132
+ return total;
133
+ } catch { return 0; }
134
+ }
135
+ try this.decodeSingle(msgData) returns (address target, uint256 value, bytes memory data) {
136
+ return _amountOf(asset, target, value, data);
137
+ } catch { return 0; }
138
+ }
139
+
140
+ struct Call { address target; uint256 value; bytes data; }
141
+
142
+ function decodeSingle(bytes calldata msgData) external pure returns (address, uint256, bytes memory) {
143
+ return abi.decode(msgData, (address, uint256, bytes));
144
+ }
145
+ function decodeBatch(bytes calldata msgData) external pure returns (Call[] memory) {
146
+ return abi.decode(msgData, (Call[]));
147
+ }
148
+
149
+ function _amountOf(address asset, address target, uint256 value, bytes memory data) internal pure returns (uint256) {
150
+ if (asset == address(0)) return value;
151
+ if (target != asset || data.length < 4) return 0;
152
+ bytes4 sel;
153
+ assembly { sel := mload(add(data, 32)) }
154
+ if (sel == TRANSFER && data.length >= 68) {
155
+ uint256 amount;
156
+ assembly { amount := mload(add(data, 68)) }
157
+ return amount;
158
+ }
159
+ if (sel == TRANSFER_FROM && data.length >= 100) {
160
+ uint256 amount;
161
+ assembly { amount := mload(add(data, 100)) }
162
+ return amount;
163
+ }
164
+ return 0;
165
+ }
166
+ }
@@ -8,6 +8,12 @@ import "../agency/ICaveatEnforcer.sol";
8
8
  * @notice Restricts delegated calls to specific function selectors.
9
9
  * @dev terms = abi.encode(bytes4[] allowedSelectors)
10
10
  * Follows ERC-7710 / MetaMask DeleGator beforeHook/afterHook pattern.
11
+ *
12
+ * R6.7 — Stateless validator; no `whenNotPaused` modifier needed
13
+ * (hooks are `pure`, contract has zero storage). The DM-side pause
14
+ * check in `DelegationManager.redeemDelegation` gates all
15
+ * reachable enforcer dispatch. See `docs/audits/r6-contracts-recon-2026-05-31.md`
16
+ * § 4.4 + `test/EnforcerPauseInvariantR67.t.sol`.
11
17
  */
12
18
  contract AllowedMethodsEnforcer is ICaveatEnforcer {
13
19
  error MethodNotAllowed();
@@ -8,6 +8,12 @@ import "../agency/ICaveatEnforcer.sol";
8
8
  * @notice Restricts delegated calls to a specific set of target contracts.
9
9
  * @dev terms = abi.encode(address[] allowedTargets)
10
10
  * Follows ERC-7710 / MetaMask DeleGator beforeHook/afterHook pattern.
11
+ *
12
+ * R6.7 — Stateless validator; no `whenNotPaused` modifier needed
13
+ * (hooks are `pure`, contract has zero storage). The DM-side pause
14
+ * check in `DelegationManager.redeemDelegation` gates all
15
+ * reachable enforcer dispatch. See `docs/audits/r6-contracts-recon-2026-05-31.md`
16
+ * § 4.4 + `test/EnforcerPauseInvariantR67.t.sol`.
11
17
  */
12
18
  contract AllowedTargetsEnforcer is ICaveatEnforcer {
13
19
  error TargetNotAllowed();