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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/AUDIT.md +60 -26
  2. package/deployments-base-sepolia.json +2 -0
  3. package/deployments-faithchain.json +2 -0
  4. package/deployments-hopechain.json +2 -0
  5. package/dist/abi/AgentAccount.json +175 -0
  6. package/dist/abi/AgentAccountFactory.json +47 -0
  7. package/dist/abi/AgentNameAttributeResolver.json +24 -0
  8. package/dist/abi/AgentNameRegistry.json +369 -0
  9. package/dist/abi/AgentNameUniversalResolver.json +34 -0
  10. package/dist/abi/AgentProfileResolver.json +48 -0
  11. package/dist/abi/AgentRegistryBase.json +158 -0
  12. package/dist/abi/AgentRelationship.json +212 -0
  13. package/dist/abi/AgreementRegistry.json +10 -0
  14. package/dist/abi/AttestationRegistry.json +49 -0
  15. package/dist/abi/AttributeStorage.json +24 -0
  16. package/dist/abi/CustodyPolicy.json +184 -0
  17. package/dist/abi/DelegationManager.json +96 -0
  18. package/dist/abi/DigestBindingEnforcer.json +103 -1
  19. package/dist/abi/EstateProjectionRegistry.json +137 -24
  20. package/dist/abi/GeoFeatureRegistry.json +42 -0
  21. package/dist/abi/IAgentAccountFactoryView.json +13 -0
  22. package/dist/abi/IAgentAccountGovernanceTimelockView.json +15 -0
  23. package/dist/abi/ICustodyPolicyFactoryView.json +13 -0
  24. package/dist/abi/ICustodyPolicyPasskeyView.json +50 -0
  25. package/dist/abi/IRedemptionContext.json +15 -0
  26. package/dist/abi/ITreasurySpendPolicyAccountView.json +44 -0
  27. package/dist/abi/IUpgradeVoucherView.json +26 -0
  28. package/dist/abi/OntologyTermRegistry.json +57 -0
  29. package/dist/abi/PaymentEnforcer.json +10 -0
  30. package/dist/abi/PermissionlessSubregistry.json +165 -0
  31. package/dist/abi/PricedSubregistry.json +57 -0
  32. package/dist/abi/RelationshipTypeRegistry.json +57 -0
  33. package/dist/abi/ShapeRegistry.json +57 -0
  34. package/dist/abi/SkillDefinitionRegistry.json +42 -0
  35. package/dist/abi/TreasurySpendPolicy.json +106 -1
  36. package/dist/abi/UpgradeVoucher.json +176 -0
  37. package/dist/abi/index.d.ts +6 -0
  38. package/dist/abi/index.js +6 -0
  39. package/dist/deployments/base-sepolia.d.ts +2 -0
  40. package/dist/deployments/base-sepolia.js +4 -0
  41. package/dist/deployments/faithchain.d.ts +2 -0
  42. package/dist/deployments/faithchain.js +4 -0
  43. package/dist/deployments/hopechain.d.ts +2 -0
  44. package/dist/deployments/hopechain.js +4 -0
  45. package/package.json +1 -1
  46. package/src/AgentAccount.sol +531 -92
  47. package/src/AgentAccountFactory.sol +28 -2
  48. package/src/IAgentAccount.sol +14 -0
  49. package/src/SmartAgentPaymaster.sol +30 -3
  50. package/src/UpgradeVoucher.sol +74 -0
  51. package/src/agency/DelegationManager.sol +177 -52
  52. package/src/agency/ICaveatEnforcer.sol +10 -0
  53. package/src/agency/IDelegationManager.sol +6 -5
  54. package/src/agreement/AgreementRegistry.sol +61 -17
  55. package/src/attestation/AttestationRegistry.sol +115 -22
  56. package/src/custody/CustodyPolicy.sol +393 -47
  57. package/src/custody/TreasurySpendPolicy.sol +192 -29
  58. package/src/enforcers/AllowedMethodsEnforcer.sol +6 -1
  59. package/src/enforcers/AllowedTargetsEnforcer.sol +6 -1
  60. package/src/enforcers/DigestBindingEnforcer.sol +91 -19
  61. package/src/enforcers/PaymentEnforcer.sol +32 -1
  62. package/src/enforcers/QuorumEnforcer.sol +1 -1
  63. package/src/enforcers/ValueEnforcer.sol +6 -1
  64. package/src/geo/GeoFeatureRegistry.sol +25 -1
  65. package/src/governance/AgenticGovernance.sol +16 -0
  66. package/src/identity/AgentProfileResolver.sol +11 -0
  67. package/src/naming/AgentNameAttributeResolver.sol +17 -2
  68. package/src/naming/AgentNamePredicates.sol +1 -1
  69. package/src/naming/AgentNameRegistry.sol +205 -10
  70. package/src/naming/AgentNameUniversalResolver.sol +26 -0
  71. package/src/naming/PermissionlessSubregistry.sol +69 -23
  72. package/src/naming/PricedSubregistry.sol +28 -0
  73. package/src/ontology/AttributeStorage.sol +93 -80
  74. package/src/ontology/OntologyTermRegistry.sol +28 -0
  75. package/src/ontology/ShapeRegistry.sol +28 -0
  76. package/src/payments/PaymentEscrow.sol +23 -15
  77. package/src/payments/PaymentReceiptRegistry.sol +11 -3
  78. package/src/registry/AgentRegistryBase.sol +39 -0
  79. package/src/registry/EstateProjectionRegistry.sol +94 -40
  80. package/src/relationships/AgentRelationship.sol +112 -7
  81. package/src/relationships/RelationshipTypeRegistry.sol +28 -0
  82. package/src/skills/SkillDefinitionRegistry.sol +25 -1
@@ -55,6 +55,13 @@ contract AgentAccountFactory is GovernanceManaged {
55
55
  /// sentinel consults it; it is NOT a mutable factory-view.
56
56
  address public immutable approvedHashRegistry;
57
57
 
58
+ /// @notice Spec 445 §1.3 (i) — the `UpgradeVoucher` baked (immutable) into the AgentAccount implementation
59
+ /// this factory deploys; surfaced here for deploy-time auditing only. Accounts read it from their
60
+ /// IMPLEMENTATION, never from this factory (an account upgraded in place still names the factory
61
+ /// that created it). `address(0)` builds an implementation that can never be upgraded away from
62
+ /// — every upgrade fails closed; `Deploy.s.sol` always passes a governance-managed voucher.
63
+ address public immutable upgradeVoucher;
64
+
58
65
  /// @notice R917-C-5 (spec 408 §1.3) — whether the T4 (admin) safety-delay floor is LIFTED to zero for
59
66
  /// accounts this factory deploys. A DEPLOYMENT decision, stated by the deployer in the
60
67
  /// constructor and recorded in the deployments JSON, never a `block.chainid` list in bytecode:
@@ -109,6 +116,16 @@ contract AgentAccountFactory is GovernanceManaged {
109
116
  /// threshold at `_buildValidatorInitData:252`.
110
117
  uint256 public constant MAX_INITIAL_CUSTODIANS = 32;
111
118
 
119
+ /// @notice ACCT-10 (audit 2026-11-10) — upper bound on the initial trustee list, beside
120
+ /// `MAX_INITIAL_CUSTODIANS` and for the same reason: `_buildValidatorInitData` derives the
121
+ /// recovery threshold as `uint8(trustees / 2 + 1)`. Uncapped, 510 trustees truncated it to 0
122
+ /// ("recovery disabled", the state audit C-9 forbids reaching at runtime) and 512 to 1-of-512.
123
+ /// With the cap the threshold is at most 17 and the cast cannot truncate.
124
+ uint256 public constant MAX_INITIAL_TRUSTEES = 32;
125
+
126
+ /// @notice ACCT-10 — `params.trustees.length` exceeds `MAX_INITIAL_TRUSTEES`.
127
+ error TooManyInitialTrustees(uint256 actual, uint256 max);
128
+
112
129
  /// @notice Spec 302 W2 — trustee-slot sentinel meaning "the initial
113
130
  /// passkey's Passkey-Identity-Address on the account being
114
131
  /// deployed". The PIA is now account-scoped, so it CANNOT be
@@ -136,11 +153,13 @@ contract AgentAccountFactory is GovernanceManaged {
136
153
  address sessionIssuer_,
137
154
  address governance_,
138
155
  address approvedHashRegistry_,
139
- bool relaxedT4Floor_
156
+ bool relaxedT4Floor_,
157
+ address upgradeVoucher_
140
158
  ) GovernanceManaged(governance_) {
141
159
  if (custodyPolicy_ == address(0)) revert ZeroAddress();
142
- accountImplementation = new AgentAccount(entryPoint_, approvedHashRegistry_);
160
+ accountImplementation = new AgentAccount(entryPoint_, approvedHashRegistry_, upgradeVoucher_);
143
161
  approvedHashRegistry = approvedHashRegistry_;
162
+ upgradeVoucher = upgradeVoucher_;
144
163
  relaxedT4Floor = relaxedT4Floor_;
145
164
  delegationManager = delegationManager_;
146
165
  custodyPolicy = custodyPolicy_;
@@ -310,6 +329,11 @@ contract AgentAccountFactory is GovernanceManaged {
310
329
  revert TooManyInitialCustodians(params.custodians.length, MAX_INITIAL_CUSTODIANS);
311
330
  }
312
331
 
332
+ // ACCT-10: cap the trustee list on every mode (it is committed to the salt on every mode).
333
+ if (params.trustees.length > MAX_INITIAL_TRUSTEES) {
334
+ revert TooManyInitialTrustees(params.trustees.length, MAX_INITIAL_TRUSTEES);
335
+ }
336
+
313
337
  // Spec 302 W2 — the self-passkey trustee sentinel is meaningless
314
338
  // without an initial passkey to resolve it to (fail-closed at
315
339
  // predict time too, so counterfactual and deploy agree).
@@ -389,6 +413,8 @@ contract AgentAccountFactory is GovernanceManaged {
389
413
  if (timelocks[5] < 24 hours) revert TimelockBelowFloor(5, timelocks[5], uint32(24 hours));
390
414
  if (timelocks[6] < 48 hours) revert TimelockBelowFloor(6, timelocks[6], uint32(48 hours));
391
415
 
416
+ // ACCT-10: `trustees.length <= MAX_INITIAL_TRUSTEES` (32) is enforced in `_validateInitParams`, so
417
+ // this is at most 17 and the cast cannot truncate.
392
418
  uint8 recThr = uint8(params.trustees.length / 2 + 1);
393
419
 
394
420
  // Spec 302 W2 — resolve the self-passkey trustee sentinel to the
@@ -104,6 +104,18 @@ struct AgentAccountRecoveryArgs {
104
104
  * This is the ONLY custody action that carries a re-approval list. `AgentAccountRecoveryArgs`
105
105
  * has no such field by construction: a recovery is the moment a planted grant would otherwise
106
106
  * ride through, so recovery re-approves nothing and ends with `revokeAllApprovedDigests`.
107
+ *
108
+ * GENERATION 4 (spec 445 §1.3 (ii)) — two fields APPENDED, so the ABI encoding of this struct changed
109
+ * (a generation-3 payload does not decode; the EIP-712 typehashes did not change — the args ride as
110
+ * `argsHash`). A retirement now also expels every non-canonical executor module and a non-canonical
111
+ * delegation manager, so the rotation carries what the owner KEEPS:
112
+ * `reaffirmModules` — installed executor modules to re-stamp under the new epoch
113
+ * (`AgentAccount.reaffirmModule` each), after the retirement;
114
+ * `reaffirmDelegationManager` — re-stamp the current delegation manager
115
+ * (`AgentAccount.reaffirmDelegationManager`). Needed only when it
116
+ * is not the factory's canonical one.
117
+ * The whole ceremony stays one applied change: add → retire → approveDigest×N → reaffirm×M.
118
+ * `AgentAccountRecoveryArgs` has neither field, by construction: a recovery re-affirms nothing.
107
119
  */
108
120
  struct AgentAccountRotateCredentialArgs {
109
121
  address addOwner;
@@ -111,6 +123,8 @@ struct AgentAccountRotateCredentialArgs {
111
123
  address removeOwner;
112
124
  bytes32 removePasskeyCredentialIdDigest;
113
125
  bytes32[] reapprove;
126
+ address[] reaffirmModules;
127
+ bool reaffirmDelegationManager;
114
128
  }
115
129
 
116
130
  /**
@@ -122,6 +122,15 @@ contract SmartAgentPaymaster is BasePaymaster {
122
122
  /// independent source (ADR-0013: cache-of-canonical, no fallback).
123
123
  bool private _pausedMirror;
124
124
 
125
+ /// @notice Audit DLG-13 — governance's own EXPLICIT pause push (`setPauseMirror`), kept apart
126
+ /// from the mirrored flag so the permissionless `syncPauseFromGovernance()` cannot
127
+ /// undo it. Before generation 4 anyone could call sync while governance's global flag
128
+ /// was clear and overwrite a pushed `true` with `false`, re-opening sponsorship that
129
+ /// governance had deliberately halted for this paymaster alone. The validation-time
130
+ /// read is still the single own-storage `_pausedMirror` (ERC-7562); this flag only
131
+ /// feeds what sync writes into it. Packs into the same slot as `_pausedMirror`.
132
+ bool private _pausePushed;
133
+
125
134
  /// @notice PM-2 — a scheduled, governance-authorized EntryPoint-deposit
126
135
  /// withdrawal. The inherited owner `withdrawTo` is an INSTANT drain
127
136
  /// gated only by the Ownable owner; this path couples a withdrawal to
@@ -172,6 +181,8 @@ contract SmartAgentPaymaster is BasePaymaster {
172
181
  /// @dev Offset in `paymasterAndData` where the post-prefix payload
173
182
  /// begins: 20 (paymaster addr) + 16 (verifGas) + 16 (postOpGas).
174
183
  uint256 private constant PM_DATA_OFFSET = 52;
184
+ /// @dev Offset of the two packed uint128 paymaster gas limits (after the paymaster address).
185
+ uint256 private constant PM_GAS_LIMITS_OFFSET = 20;
175
186
 
176
187
  /// @param devMode_ true → accept-all (dev/anvil); false → require
177
188
  /// verifying-signer or allowlist. R5.7 removed
@@ -240,8 +251,10 @@ contract SmartAgentPaymaster is BasePaymaster {
240
251
  /// (not paymaster validation), so the ERC-7562 scope rules don't
241
252
  /// apply to its cross-contract read. The mirror only ever holds the
242
253
  /// canonical governance value — no independent pause source.
254
+ /// DLG-13: a pause governance pushed with `setPauseMirror(true)` survives a
255
+ /// sync — the mirror is `pushed OR governance.isPaused()`; only governance clears its push.
243
256
  function syncPauseFromGovernance() external {
244
- bool p = _governanceIsPaused();
257
+ bool p = _pausePushed || _governanceIsPaused();
245
258
  _pausedMirror = p;
246
259
  emit PauseMirrorSynced(p, msg.sender);
247
260
  }
@@ -251,6 +264,7 @@ contract SmartAgentPaymaster is BasePaymaster {
251
264
  /// third party to sync. `onlyGovernance` ⇒ inherits the 24h
252
265
  /// timelock (or guardian-driven governance flow).
253
266
  function setPauseMirror(bool paused_) external onlyGovernance {
267
+ _pausePushed = paused_;
254
268
  _pausedMirror = paused_;
255
269
  emit PauseMirrorSynced(paused_, msg.sender);
256
270
  }
@@ -333,10 +347,19 @@ contract SmartAgentPaymaster is BasePaymaster {
333
347
  /// Off-chain callers compute the same hash + sign via
334
348
  /// EIP-191 ("\x19Ethereum Signed Message:\n32" prefix);
335
349
  /// on-chain validation recovers via that wrapper.
336
- /// @dev Deliberately omits paymasterAndData (the signature lives
337
- /// there) and the userOp.signature (the account signs
350
+ /// @dev Omits the paymaster-data TAIL (validity window is passed in; the
351
+ /// signature lives there) and the userOp.signature (the account signs
338
352
  /// independently). Includes chainId + paymaster address for
339
353
  /// replay protection across chains + deployments.
354
+ ///
355
+ /// Spec 445 / audit DLG-4: the hash BINDS the paymaster gas limits —
356
+ /// `paymasterAndData[20:52]` = `paymasterVerificationGasLimit (uint128) ‖
357
+ /// paymasterPostOpGasLimit (uint128)`, as the reference VerifyingPaymaster
358
+ /// does. Before generation 4 they were unsigned, so a sponsored sender could
359
+ /// raise both after the sponsor signed, inflating the prefund reserved
360
+ /// against the deposit (and the post-op unused-gas penalty the day this
361
+ /// paymaster returns a context). A `paymasterAndData` shorter than the
362
+ /// 52-byte static prefix reverts `PaymasterDataMalformed`.
340
363
  function getHash(
341
364
  PackedUserOperation calldata userOp,
342
365
  uint48 validUntil,
@@ -349,6 +372,9 @@ contract SmartAgentPaymaster is BasePaymaster {
349
372
  // current EntryPoint would have been verifiable against a NEW
350
373
  // EntryPoint deployed at a different address, allowing cross-deployment
351
374
  // replay until validUntil elapses.
375
+ if (userOp.paymasterAndData.length < PM_DATA_OFFSET) revert PaymasterDataMalformed();
376
+ // DLG-4: verificationGasLimit ‖ postOpGasLimit, exactly as they sit in the userOp.
377
+ bytes32 paymasterGasLimits = bytes32(userOp.paymasterAndData[PM_GAS_LIMITS_OFFSET:PM_DATA_OFFSET]);
352
378
  return keccak256(
353
379
  abi.encode(
354
380
  userOp.sender,
@@ -356,6 +382,7 @@ contract SmartAgentPaymaster is BasePaymaster {
356
382
  keccak256(userOp.initCode),
357
383
  keccak256(userOp.callData),
358
384
  userOp.accountGasLimits,
385
+ paymasterGasLimits, // DLG-4 binding
359
386
  userOp.preVerificationGas,
360
387
  userOp.gasFees,
361
388
  block.chainid,
@@ -0,0 +1,74 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.28;
3
+
4
+ import "./governance/GovernanceManaged.sol";
5
+
6
+ /**
7
+ * @title UpgradeVoucher — which implementations, with which migration data, an AgentAccount may upgrade to
8
+ * @notice Spec 445 §1.3 (i), audit 2026-11-10 H-2 / ACCT-1. `upgradeToAndCall(newImplementation, data)` delegatecalls
9
+ * `data` on `newImplementation` in the account's own storage. On a self-governed (mode-0) account one
10
+ * credential could therefore run arbitrary code as the account — plant an approved hash for a future
11
+ * custody epoch, write a custodian with no event — and none of it can be detected or undone afterwards.
12
+ * The only way to prevent that is to constrain what may be upgraded to. An `AgentAccount`
13
+ * implementation carries the address of ONE voucher as an immutable and refuses every upgrade — a
14
+ * person's own, a custody quorum's `ApplySystemUpdate`, a matured queued upgrade — unless
15
+ * `isVouched(newImplementation, keccak256(data))` is true here at the moment the upgrade executes.
16
+ *
17
+ * WHO VOUCHES. Governance only (`onlyGovernance` — the `AgenticGovernance` contract, which forwards
18
+ * nothing but calls its timelock executed). No guardian fast path, no signer path, no setter for the
19
+ * governance pointer, no upgradeability: to change who vouches, a new voucher is deployed and a new
20
+ * account implementation is built around it — and reaching that implementation is itself an upgrade
21
+ * this voucher must vouch for.
22
+ *
23
+ * WHAT IS VOUCHED. The pair `(implementation, dataHash)`. `dataHash` is `keccak256(data)` of the exact
24
+ * migration calldata; a plain upgrade (no migration call) is `keccak256("")` =
25
+ * `0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470`. Vouching an implementation for
26
+ * a plain upgrade does not vouch it for any migration call, and the reverse.
27
+ *
28
+ * WHAT GOVERNANCE MUST NOT VOUCH. An implementation that does not itself carry a voucher (any
29
+ * generation ≤ 3 `AgentAccount`, or foreign code): an account that upgrades to it leaves this rule
30
+ * behind for good — its next upgrade is checked by nobody. And migration data is CODE RUN AS EVERY
31
+ * ACCOUNT THAT USES IT: vouch only for a call whose every effect on account storage was reviewed.
32
+ *
33
+ * WHAT IT IS NOT. An authorization to upgrade any particular account — every account-side gate
34
+ * (`onlySelf`, the per-account timelock, the custody quorum) still applies. A voucher answers "is this
35
+ * code one the estate's governance reviewed?", never "may this caller upgrade?".
36
+ *
37
+ * WHY IT TRAVELS WITH THE IMPLEMENTATION AND NOT THE FACTORY. An account's factory pointer is set once
38
+ * at initialization and has no setter; an account upgraded in place still names its original factory.
39
+ * A vouching view on a new factory would never be consulted by an existing account.
40
+ */
41
+ contract UpgradeVoucher is GovernanceManaged {
42
+ /// @notice `keccak256("")` — the `dataHash` of a plain upgrade (no migration call).
43
+ bytes32 public constant PLAIN_UPGRADE = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
44
+
45
+ /// implementation => keccak256(migration data) => vouched
46
+ mapping(address => mapping(bytes32 => bool)) private _vouched;
47
+
48
+ event UpgradeVouched(address indexed implementation, bytes32 indexed dataHash);
49
+ event UpgradeUnvouched(address indexed implementation, bytes32 indexed dataHash);
50
+
51
+ /// @dev Vouching for an address with no code would vouch for whatever is later deployed there.
52
+ error ImplementationHasNoCode(address implementation);
53
+
54
+ constructor(address governance_) GovernanceManaged(governance_) {}
55
+
56
+ /// @notice Vouch for upgrading to `implementation` with migration data hashing to `dataHash`.
57
+ function vouch(address implementation, bytes32 dataHash) external onlyGovernance {
58
+ if (implementation.code.length == 0) revert ImplementationHasNoCode(implementation);
59
+ _vouched[implementation][dataHash] = true;
60
+ emit UpgradeVouched(implementation, dataHash);
61
+ }
62
+
63
+ /// @notice Withdraw a vouch. An upgrade that has not executed yet (including a queued one) is refused
64
+ /// from this transaction on; an account already running `implementation` is not affected.
65
+ function unvouch(address implementation, bytes32 dataHash) external onlyGovernance {
66
+ _vouched[implementation][dataHash] = false;
67
+ emit UpgradeUnvouched(implementation, dataHash);
68
+ }
69
+
70
+ /// @notice The one read an account makes before it upgrades.
71
+ function isVouched(address implementation, bytes32 dataHash) external view returns (bool) {
72
+ return _vouched[implementation][dataHash];
73
+ }
74
+ }
@@ -47,12 +47,40 @@ contract DelegationManager is IDelegationManager, ReentrancyGuard {
47
47
  // `AgenticGovernance.isPaused()` (a guardian can pause without delay;
48
48
  // unpause needs the timelock).
49
49
  //
50
- // `governance` is `address(0)` for legacy deploys; in that case the
51
- // pause check is skipped (no governance, no pause source). Production
52
- // deploys pass a real AgenticGovernance address.
50
+ // `governance` is `address(0)` ONLY as an explicit opt-out (legacy / test
51
+ // deploys): there is then no pause source and the gate is skipped.
52
+ //
53
+ // Spec 445 / audit DLG-7 — THE READ NO LONGER FAILS OPEN. Before generation 4 a
54
+ // governance read that reverted, returned fewer than 32 bytes, or was aimed at a
55
+ // codeless address was treated as "not paused", so a typo'd / griefed / broken
56
+ // governance silently disabled the kill-switch for the life of this immutable
57
+ // contract. The rule now:
58
+ // 1. construction: `governance_` is `address(0)` (the explicit opt-out) or an
59
+ // address that HAS CODE at deploy time — a codeless non-zero address reverts
60
+ // `GovernanceHasNoCode`. A kill-switch that can never fire is refused at
61
+ // birth rather than discovered during an incident;
62
+ // 2. redemption: a configured governance with code MUST answer `isPaused()`
63
+ // with exactly one ABI word that is 0 or 1. A revert, a short / long return,
64
+ // or a non-boolean word reverts `GovernanceReadFailed` (FAIL CLOSED): a
65
+ // pause source that cannot be read is not evidence of "not paused";
66
+ // 3. a configured governance that has NO code at redemption time is skipped.
67
+ // Rule 1 makes that state unreachable in practice (EIP-6780 removed code
68
+ // deletion outside the creating transaction), and treating an impossible
69
+ // state as "paused forever" would only add a way to brick the singleton.
70
+ // The trade is deliberate: fail-closed on a faulted read means a governance
71
+ // contract that breaks freezes redemptions until a new DelegationManager is
72
+ // deployed (this contract is a re-deploy-on-bug singleton, SC4 § 4.3.4) — the
73
+ // same posture `SmartAgentPaymaster._governanceIsPaused` already takes (L1).
53
74
  address public immutable governance;
54
75
 
55
76
  error SystemPaused();
77
+ /// @dev DLG-7: constructor refused a non-zero governance address with no code.
78
+ error GovernanceHasNoCode(address governance);
79
+ /// @dev DLG-7: the configured governance did not answer `isPaused()` with one boolean word.
80
+ error GovernanceReadFailed();
81
+ /// @dev Spec 445 / audit DLG-2: a redemption whose `target` is the account that executes it
82
+ /// (the root delegator). See {redeemDelegation}.
83
+ error SelfTargetedRedemption();
56
84
 
57
85
  /// @dev Root authority constant — delegations with this authority are root-level
58
86
  bytes32 public constant ROOT_AUTHORITY = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
@@ -60,8 +88,18 @@ contract DelegationManager is IDelegationManager, ReentrancyGuard {
60
88
  /// @dev Open delegation sentinel — any address can redeem
61
89
  address public constant OPEN_DELEGATION = address(0xa11);
62
90
 
63
- /// @dev EIP-712 domain separator
64
- bytes32 public immutable DOMAIN_SEPARATOR;
91
+ /// @dev EIP-712 domain separator as computed at deploy, and the chain id it was computed for.
92
+ /// Audit DLG-10: {DOMAIN_SEPARATOR} recomputes when `block.chainid` differs, so a
93
+ /// delegation signed on one side of a chain split does not verify on the other.
94
+ bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
95
+ uint256 private immutable _CACHED_CHAIN_ID;
96
+
97
+ /// @dev The root delegator of the redemption in flight (zero outside one). Transient
98
+ /// (EIP-1153): set and cleared inside the non-reentrant {redeemDelegation}. Lets a
99
+ /// stateful enforcer on a RE-DELEGATED link learn whose account actually executes —
100
+ /// the hook's `delegator` argument is the delegator of the link carrying the caveat,
101
+ /// which for a derived mandate is an intermediary, not the payer (audit DLG-8c).
102
+ address private transient _redemptionRoot;
65
103
 
66
104
  /// @dev Delegation type hash for EIP-712.
67
105
  ///
@@ -128,8 +166,20 @@ contract DelegationManager is IDelegationManager, ReentrancyGuard {
128
166
  /// (legacy / test deploys). Production deploys pass an
129
167
  /// `AgenticGovernance` address.
130
168
  constructor(address governance_) {
169
+ // DLG-7 rule 1: zero is the explicit opt-out; anything else must already be a contract.
170
+ if (governance_ != address(0) && governance_.code.length == 0) revert GovernanceHasNoCode(governance_);
131
171
  governance = governance_;
132
- DOMAIN_SEPARATOR = keccak256(
172
+ _CACHED_CHAIN_ID = block.chainid;
173
+ _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator();
174
+ }
175
+
176
+ /// @notice EIP-712 domain separator for the CURRENT chain id (audit DLG-10).
177
+ function DOMAIN_SEPARATOR() public view returns (bytes32) {
178
+ return block.chainid == _CACHED_CHAIN_ID ? _CACHED_DOMAIN_SEPARATOR : _buildDomainSeparator();
179
+ }
180
+
181
+ function _buildDomainSeparator() private view returns (bytes32) {
182
+ return keccak256(
133
183
  abi.encode(
134
184
  keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
135
185
  keccak256("AgentDelegationManager"),
@@ -140,29 +190,61 @@ contract DelegationManager is IDelegationManager, ReentrancyGuard {
140
190
  );
141
191
  }
142
192
 
193
+ /// @notice The account that executes the redemption in flight — the ROOT delegator, whose
194
+ /// funds / authority move. Zero outside a redemption (including under the view
195
+ /// verifiers, which execute nothing). Enforcers read it for attribution only; it is
196
+ /// never an authorization input.
197
+ function redemptionRootDelegator() external view returns (address) {
198
+ return _redemptionRoot;
199
+ }
200
+
201
+ /// @dev DLG-7 — the pause gate. See the rule at `governance`.
202
+ function _requireNotPaused() internal view {
203
+ address gov = governance;
204
+ if (gov == address(0) || gov.code.length == 0) return;
205
+ (bool ok, bytes memory ret) = gov.staticcall(abi.encodeWithSelector(IGovernanceView.isPaused.selector));
206
+ if (!ok || ret.length != 32) revert GovernanceReadFailed();
207
+ uint256 word = abi.decode(ret, (uint256));
208
+ if (word > 1) revert GovernanceReadFailed();
209
+ if (word == 1) revert SystemPaused();
210
+ }
211
+
143
212
  /// @inheritdoc IDelegationManager
144
213
  /// @dev Phase A.5 (SC5 § 6.2) — `nonReentrant` blocks nested
145
214
  /// redemption (a caveat enforcer or target call cannot
146
215
  /// reenter this function).
216
+ ///
217
+ /// Spec 445 / audit DLG-2 — A REDEMPTION NEVER TARGETS THE ACCOUNT THAT EXECUTES IT.
218
+ /// Every enforcer judges the one `(target, value, data)` handed to this function. If
219
+ /// `target` is the root delegator's own account, `data` is an instruction to that account
220
+ /// (`executeBatch(Call[])`, `execute(...)`, any future multi-call entry point) whose INNER
221
+ /// calls carry their own targets, values and calldata that no enforcer saw — a
222
+ /// `ValueEnforcer(0.01 ether)` delegation moved 10 ETH that way. The rule is therefore
223
+ /// structural rather than a selector list: `target == rootDelegator` reverts
224
+ /// `SelfTargetedRedemption`, so every call a delegation causes is exactly the call the
225
+ /// caveats were evaluated against. It holds for any account implementation (a selector
226
+ /// list would go stale the day an account gains another batching entry point) and costs
227
+ /// nothing legitimate: every self-only mutator on `AgentAccount` is already a governance
228
+ /// selector that a delegation stack may not reach (`_rejectDelegatedGovernance`), and no
229
+ /// flow in this repository or the product repos redeems against the delegator itself.
230
+ /// Atomic multi-call under delegation, if it is ever needed, is a batch-aware redemption
231
+ /// that presents every inner call to every hook — not a self-call. The view twin
232
+ /// {verifyAuthorizationForCall} returns `(false, "self-target")` for the same input.
147
233
  function redeemDelegation(
148
234
  Delegation[] calldata delegations,
149
235
  address target,
150
236
  uint256 value,
151
237
  bytes calldata data
152
238
  ) external nonReentrant {
153
- // H7-C.10 / EXT3-010: system-wide pause gate. Skipped when
154
- // `governance` is `address(0)`, an EOA, or a non-conforming
155
- // contract (legacy / test deploys). Production deploys pass an
156
- // `AgenticGovernance` address; a guardian can pause without delay;
157
- // unpause requires the 24h timelock.
158
- if (governance != address(0) && governance.code.length > 0) {
159
- (bool ok, bytes memory data) = governance.staticcall(
160
- abi.encodeWithSelector(IGovernanceView.isPaused.selector)
161
- );
162
- if (ok && data.length >= 32 && abi.decode(data, (bool))) revert SystemPaused();
163
- }
239
+ // H7-C.10 / EXT3-010: system-wide pause gate (DLG-7: a faulted read fails closed).
240
+ _requireNotPaused();
164
241
  if (delegations.length == 0) revert EmptyChain();
165
242
 
243
+ // DLG-2: the executing account is never the target (see NatSpec).
244
+ address rootDelegator = delegations[delegations.length - 1].delegator;
245
+ if (target == rootDelegator) revert SelfTargetedRedemption();
246
+ _redemptionRoot = rootDelegator;
247
+
166
248
  // Phase 1: Validate chain + run beforeHooks (leaf to root)
167
249
  for (uint256 i = 0; i < delegations.length; i++) {
168
250
  _validateDelegation(delegations, i);
@@ -170,13 +252,13 @@ contract DelegationManager is IDelegationManager, ReentrancyGuard {
170
252
  }
171
253
 
172
254
  // Phase 2: Execute through the root delegator's smart account
173
- address rootDelegator = delegations[delegations.length - 1].delegator;
174
255
  _executeFromDelegator(rootDelegator, target, value, data);
175
256
 
176
257
  // Phase 3: After-hooks (root to leaf, per DeleGator convention)
177
258
  for (uint256 i = delegations.length; i > 0; i--) {
178
259
  _runAfterHooks(delegations[i - 1], target, value, data);
179
260
  }
261
+ _redemptionRoot = address(0);
180
262
  }
181
263
 
182
264
  /// @inheritdoc IDelegationManager
@@ -196,35 +278,67 @@ contract DelegationManager is IDelegationManager, ReentrancyGuard {
196
278
  revert LegacyRevocationDisabled();
197
279
  }
198
280
 
199
- /// @notice Phase A.5 — authenticated revocation path that works for
200
- /// Variant A (off-chain caveated delegation, never
201
- /// registered) by deriving the hash from the delegation
202
- /// struct + signature provided by the caller.
281
+ /// @notice Authenticated revocation of one delegation, by its delegator or its delegate.
282
+ ///
283
+ /// @dev Works for Variant A (off-chain, never registered) delegations: the hash is derived
284
+ /// from the struct the caller presents.
285
+ ///
286
+ /// Spec 445 / audit DLG-9 — THE DELEGATOR REVOKES WITHOUT A SIGNATURE CHECK. Before
287
+ /// generation 4 both parties had to present a signature that verifies NOW. A delegation
288
+ /// signed by a custodian who has since been removed, or approved under an earlier custody
289
+ /// epoch, fails that check today — so it could not be marked revoked, and it came back to
290
+ /// life with no revocation on record the moment the custodian was re-added or the digest
291
+ /// re-approved. `msg.sender == delegation.delegator` is the whole authorization for the
292
+ /// delegator path: the only hash it can mark is one whose struct names the caller itself
293
+ /// as delegator, i.e. a grant only the caller could ever have made. Marking a struct it
294
+ /// never signed harms nobody (it forecloses a grant the caller alone could issue).
295
+ ///
296
+ /// The DELEGATE path keeps the signature requirement: without it a delegate could revoke
297
+ /// the hash of a struct the delegator has not signed yet, pre-empting a future grant.
203
298
  ///
204
- /// @dev Authorization gate: `msg.sender` MUST be either
205
- /// `delegation.delegator` OR `delegation.delegate` (the latter
206
- /// blocks a random EOA from revoking a delegation it doesn't
207
- /// hold, which would otherwise be a permissionless DoS vector
208
- /// against the legacy `revokeDelegation(bytes32)` path).
299
+ /// Deliberately not `nonReentrant`: a delegator account revokes its own grants through a
300
+ /// redeemed mandate (`redeemDelegation(…, target = this, revokeDelegationByOwner(g))`),
301
+ /// which calls back in while the redemption guard is held.
209
302
  ///
210
- /// @param delegation The delegation to revoke. The signature inside
211
- /// it is verified to confirm the struct is
212
- /// legitimate before we mark the hash revoked —
213
- /// otherwise a malicious delegate could revoke a
214
- /// *forged* delegation hash by submitting a struct
215
- /// they invented.
303
+ /// @param delegation The delegation to revoke.
216
304
  function revokeDelegationByOwner(Delegation calldata delegation) external {
217
- if (msg.sender != delegation.delegator && msg.sender != delegation.delegate) {
305
+ bytes32 dHash = hashDelegation(delegation);
306
+ if (msg.sender == delegation.delegator) {
307
+ // DLG-9: the delegator's own struct — no signature needed.
308
+ } else if (msg.sender == delegation.delegate) {
309
+ // A delegate may renounce only a delegation that really exists.
310
+ _validateSignature(delegation.delegator, dHash, delegation.signature);
311
+ } else {
218
312
  revert NotDelegatorOrDelegate();
219
313
  }
314
+ _revoke(dHash);
315
+ }
220
316
 
221
- bytes32 dHash = hashDelegation(delegation);
222
-
223
- // Verify the delegation struct is signed by its declared
224
- // delegator. We don't want a delegate to be able to revoke
225
- // a hash that was never a real delegation.
226
- _validateSignature(delegation.delegator, dHash, delegation.signature);
317
+ /// @notice Revocation of a DOWNSTREAM link by an upstream delegator (audit DLG-9, second half).
318
+ /// `chain` is leaf-first exactly as it would be redeemed, truncated wherever the caller
319
+ /// likes: `chain[0]` is the link to revoke and `chain[chain.length - 1].delegator` must
320
+ /// be `msg.sender`.
321
+ ///
322
+ /// @dev A delegator can always cut its own link (and with it every chain through it) via
323
+ /// {revokeDelegationByOwner}. This is the finer tool: prune ONE re-delegation made
324
+ /// under your grant while the grant itself, and its other descendants, stay live.
325
+ /// Authorization is structural — every link must name the next by hash
326
+ /// (`chain[k].authority == hashDelegation(chain[k + 1])`), which proves `chain[0]`
327
+ /// claims its authority from the caller's delegation. No signature is checked, for the
328
+ /// same reason as the delegator path above (a dormant link must be revocable); the
329
+ /// only hashes reachable are of structs that could never be redeemed except THROUGH
330
+ /// the caller's own grant, so the caller forecloses nothing that was not its to give.
331
+ function revokeDelegationAsUpstream(Delegation[] calldata chain) external {
332
+ uint256 n = chain.length;
333
+ if (n < 2) revert EmptyChain();
334
+ if (msg.sender != chain[n - 1].delegator) revert NotDelegatorOrDelegate();
335
+ for (uint256 k = 0; k + 1 < n; k++) {
336
+ if (chain[k].authority != hashDelegation(chain[k + 1])) revert InvalidAuthority();
337
+ }
338
+ _revoke(hashDelegation(chain[0]));
339
+ }
227
340
 
341
+ function _revoke(bytes32 dHash) private {
228
342
  _revoked[dHash] = true;
229
343
  emit DelegationRevoked(dHash);
230
344
  emit DelegationRevokedBy(dHash, msg.sender);
@@ -248,7 +362,7 @@ contract DelegationManager is IDelegationManager, ReentrancyGuard {
248
362
  d.salt
249
363
  )
250
364
  );
251
- return keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
365
+ return keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), structHash));
252
366
  }
253
367
 
254
368
  /// @notice View-only verification of a delegation chain. Returns whether
@@ -319,6 +433,8 @@ contract DelegationManager is IDelegationManager, ReentrancyGuard {
319
433
  bytes calldata data
320
434
  ) external view returns (bool ok, string memory reason) {
321
435
  if (delegations.length == 0) return (false, "empty-chain");
436
+ // DLG-2: identical to redemption — the executing account is never the target.
437
+ if (target == delegations[delegations.length - 1].delegator) return (false, "self-target");
322
438
 
323
439
  for (uint256 i = 0; i < delegations.length; i++) {
324
440
  (bool valid, string memory r) = _validateDelegationView(delegations, i, sender);
@@ -378,11 +494,14 @@ contract DelegationManager is IDelegationManager, ReentrancyGuard {
378
494
  }
379
495
  }
380
496
 
381
- // Authority chain
382
- if (d.authority != ROOT_AUTHORITY) {
383
- if (i + 1 >= delegations.length) return (false, "invalid-authority");
384
- bytes32 parentHash = hashDelegation(delegations[i + 1]);
385
- if (d.authority != parentHash) return (false, "invalid-authority-chain");
497
+ // Authority chain — exactly one root, and it is the LAST link (spec 445 §1.1, audit H-1).
498
+ // Every non-terminal link must name its parent by hash; a ROOT_AUTHORITY link in a
499
+ // non-terminal position is refused (it never re-delegated the parent's authority).
500
+ if (i + 1 < delegations.length) {
501
+ if (d.authority == ROOT_AUTHORITY) return (false, "root-authority-not-terminal");
502
+ if (d.authority != hashDelegation(delegations[i + 1])) return (false, "invalid-authority-chain");
503
+ } else {
504
+ if (d.authority != ROOT_AUTHORITY) return (false, "invalid-authority");
386
505
  }
387
506
 
388
507
  // Signature
@@ -411,8 +530,11 @@ contract DelegationManager is IDelegationManager, ReentrancyGuard {
411
530
  }
412
531
  // EOA — tryRecover the eth-signed message hash
413
532
  bytes32 ethHash = digest.toEthSignedMessageHash();
533
+ // The error value is checked explicitly; the third return is OpenZeppelin's error ARGUMENT
534
+ // (the offending length / s value), which carries nothing to act on once `err` is known.
535
+ // slither-disable-next-line unused-return
414
536
  (address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(ethHash, signature);
415
- if (err != ECDSA.RecoverError.NoError) return false;
537
+ if (err != ECDSA.RecoverError.NoError || recovered == address(0)) return false;
416
538
  return recovered == signer;
417
539
  }
418
540
 
@@ -435,11 +557,14 @@ contract DelegationManager is IDelegationManager, ReentrancyGuard {
435
557
  if (d.delegate != OPEN_DELEGATION && d.delegate != delegations[i - 1].delegator) revert InvalidDelegate();
436
558
  }
437
559
 
438
- // Validate authority chain
439
- if (d.authority != ROOT_AUTHORITY) {
440
- if (i + 1 >= delegations.length) revert InvalidAuthority();
441
- bytes32 parentHash = hashDelegation(delegations[i + 1]);
442
- if (d.authority != parentHash) revert InvalidAuthority();
560
+ // Validate authority chain — exactly one root, and it is the LAST link (spec 445 §1.1,
561
+ // audit H-1). Every non-terminal link must name its parent by hash, so a ROOT_AUTHORITY
562
+ // link spliced in front of someone else's root grant is refused: the middle delegator
563
+ // never re-delegated. The terminal link must be the root.
564
+ if (i + 1 < delegations.length) {
565
+ if (d.authority != hashDelegation(delegations[i + 1])) revert InvalidAuthority();
566
+ } else {
567
+ if (d.authority != ROOT_AUTHORITY) revert InvalidAuthority();
443
568
  }
444
569
 
445
570
  // Validate signature
@@ -11,6 +11,16 @@ pragma solidity ^0.8.28;
11
11
  *
12
12
  * @dev terms: Immutable parameters set when the delegation is created (e.g., time window, allowed methods).
13
13
  * args: Mutable parameters provided by the redeemer at redemption time (e.g., proof data).
14
+ *
15
+ * Two rules for enforcer authors (spec 445, audit DLG-2 / DLG-3 / DLG-8):
16
+ * - `args` are NOT signed. Anything that bounds the redeemer — a use count, a nonce set, a payer —
17
+ * must come from `terms` or from chain state, never from `args`: the party a caveat constrains
18
+ * is the party that writes them.
19
+ * - `delegator` is the delegator of the LINK that carries the caveat. In a re-delegated chain the
20
+ * call executes from the ROOT delegator's account, which a stateful enforcer can read from
21
+ * `DelegationManager.redemptionRootDelegator()` during a redemption. The hooks see exactly the
22
+ * one `(target, value, callData)` being executed; the manager guarantees that is the whole
23
+ * call by refusing a target equal to the executing account.
14
24
  */
15
25
  interface ICaveatEnforcer {
16
26
  /**
@@ -43,7 +43,8 @@ interface IDelegationManager {
43
43
  event DelegationRevoked(bytes32 indexed delegationHash);
44
44
 
45
45
  /// @notice Redeem a delegation chain to execute an action on behalf of the delegator.
46
- /// The delegator's smart account executes the call via executeFromExecutor.
46
+ /// The ROOT delegator's smart account executes the call via `execute`.
47
+ /// `target` may not be that account itself (spec 445 / audit DLG-2).
47
48
  function redeemDelegation(
48
49
  Delegation[] calldata delegations,
49
50
  address target,
@@ -58,10 +59,10 @@ interface IDelegationManager {
58
59
  /// works for Variant A delegations.
59
60
  function revokeDelegation(bytes32 delegationHash) external;
60
61
 
61
- /// @notice Phase A.5 — authenticated revocation. Caller must be
62
- /// either `delegation.delegator` or `delegation.delegate`.
63
- /// The delegation struct is signature-checked first to
64
- /// prevent a malicious delegate from revoking a forged hash.
62
+ /// @notice Authenticated revocation. Caller must be either `delegation.delegator` or
63
+ /// `delegation.delegate`. The DELEGATOR revokes its own struct with no signature check
64
+ /// (spec 445 / audit DLG-9: a dormant delegation must be revocable); the DELEGATE must
65
+ /// present a struct whose signature verifies, so it cannot revoke a forged hash.
65
66
  function revokeDelegationByOwner(Delegation calldata delegation) external;
66
67
 
67
68
  /// @notice Check if a delegation has been revoked.