@crediolabs/policy-synth 0.1.17 → 0.2.0

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 (113) hide show
  1. package/README.md +44 -246
  2. package/dist/adapters/interpreter/adapter.d.ts +6 -7
  3. package/dist/adapters/interpreter/adapter.js +28 -48
  4. package/dist/adapters/oz/adapter.js +12 -13
  5. package/dist/codegen/compile-gate.js +5 -0
  6. package/dist/codegen/template.js +17 -0
  7. package/dist/install/authority-overlap.d.ts +134 -0
  8. package/dist/install/authority-overlap.js +0 -0
  9. package/dist/install/build-add-context-rule.d.ts +8 -0
  10. package/dist/install/build-add-context-rule.js +17 -46
  11. package/dist/install/build-install-policy.d.ts +12 -5
  12. package/dist/install/build-install-policy.js +32 -23
  13. package/dist/install/build-merge-policy.d.ts +70 -0
  14. package/dist/install/build-merge-policy.js +130 -0
  15. package/dist/install/get-interpreter-info.js +2 -2
  16. package/dist/install/index.d.ts +3 -1
  17. package/dist/install/index.js +8 -1
  18. package/dist/install/oz-auth.js +5 -3
  19. package/dist/install/plan-merge-policy.d.ts +49 -0
  20. package/dist/install/plan-merge-policy.js +86 -0
  21. package/dist/install/read-account-rules.d.ts +100 -0
  22. package/dist/install/read-account-rules.js +283 -0
  23. package/dist/predicate/decode.js +1 -1
  24. package/dist/predicate/encode.js +171 -10
  25. package/dist/record/decode.js +5 -6
  26. package/dist/registry/protocols.d.ts +1 -1
  27. package/dist/registry/protocols.js +1 -1
  28. package/dist/review-card/builder.d.ts +6 -0
  29. package/dist/review-card/builder.js +9 -1
  30. package/dist/run/index.d.ts +104 -18
  31. package/dist/run/index.js +359 -75
  32. package/dist/run/schemas.d.ts +479 -18
  33. package/dist/run/schemas.js +132 -24
  34. package/dist/synth/compose-from-recording.d.ts +10 -15
  35. package/dist/synth/compose-from-recording.js +79 -124
  36. package/dist/synth/deny-cases.d.ts +5 -0
  37. package/dist/synth/deny-cases.js +52 -13
  38. package/dist/synth/evaluate.js +69 -119
  39. package/dist/synth/harness.d.ts +13 -1
  40. package/dist/synth/harness.js +22 -1
  41. package/dist/synth/index.d.ts +1 -1
  42. package/dist/synth/synthesize-from-recording.d.ts +31 -21
  43. package/dist/synth/synthesize-from-recording.js +129 -155
  44. package/dist-cjs/adapters/interpreter/adapter.d.ts +6 -7
  45. package/dist-cjs/adapters/interpreter/adapter.js +28 -48
  46. package/dist-cjs/adapters/oz/adapter.js +12 -13
  47. package/dist-cjs/codegen/compile-gate.js +5 -0
  48. package/dist-cjs/codegen/template.js +17 -0
  49. package/dist-cjs/install/authority-overlap.d.ts +134 -0
  50. package/dist-cjs/install/authority-overlap.js +0 -0
  51. package/dist-cjs/install/build-add-context-rule.d.ts +8 -0
  52. package/dist-cjs/install/build-add-context-rule.js +17 -45
  53. package/dist-cjs/install/build-install-policy.d.ts +12 -5
  54. package/dist-cjs/install/build-install-policy.js +32 -23
  55. package/dist-cjs/install/build-merge-policy.d.ts +70 -0
  56. package/dist-cjs/install/build-merge-policy.js +134 -0
  57. package/dist-cjs/install/get-interpreter-info.js +2 -2
  58. package/dist-cjs/install/index.d.ts +3 -1
  59. package/dist-cjs/install/index.js +24 -3
  60. package/dist-cjs/install/oz-auth.js +5 -3
  61. package/dist-cjs/install/plan-merge-policy.d.ts +49 -0
  62. package/dist-cjs/install/plan-merge-policy.js +90 -0
  63. package/dist-cjs/install/read-account-rules.d.ts +100 -0
  64. package/dist-cjs/install/read-account-rules.js +296 -0
  65. package/dist-cjs/predicate/decode.js +1 -1
  66. package/dist-cjs/predicate/encode.js +171 -10
  67. package/dist-cjs/record/decode.js +5 -6
  68. package/dist-cjs/registry/protocols.d.ts +1 -1
  69. package/dist-cjs/registry/protocols.js +1 -1
  70. package/dist-cjs/review-card/builder.d.ts +6 -0
  71. package/dist-cjs/review-card/builder.js +9 -1
  72. package/dist-cjs/run/index.d.ts +104 -18
  73. package/dist-cjs/run/index.js +360 -74
  74. package/dist-cjs/run/schemas.d.ts +479 -18
  75. package/dist-cjs/run/schemas.js +133 -25
  76. package/dist-cjs/synth/compose-from-recording.d.ts +10 -15
  77. package/dist-cjs/synth/compose-from-recording.js +79 -124
  78. package/dist-cjs/synth/deny-cases.d.ts +5 -0
  79. package/dist-cjs/synth/deny-cases.js +52 -13
  80. package/dist-cjs/synth/evaluate.js +69 -119
  81. package/dist-cjs/synth/harness.d.ts +13 -1
  82. package/dist-cjs/synth/harness.js +22 -1
  83. package/dist-cjs/synth/index.d.ts +1 -1
  84. package/dist-cjs/synth/synthesize-from-recording.d.ts +31 -21
  85. package/dist-cjs/synth/synthesize-from-recording.js +129 -153
  86. package/package.json +1 -1
  87. package/src/adapters/interpreter/adapter.ts +28 -48
  88. package/src/adapters/oz/adapter.ts +12 -13
  89. package/src/codegen/compile-gate.ts +5 -0
  90. package/src/codegen/template.ts +17 -0
  91. package/src/install/authority-overlap.ts +0 -0
  92. package/src/install/build-add-context-rule.ts +29 -56
  93. package/src/install/build-install-policy.ts +41 -23
  94. package/src/install/build-merge-policy.ts +219 -0
  95. package/src/install/get-interpreter-info.ts +2 -2
  96. package/src/install/index.ts +36 -2
  97. package/src/install/oz-auth.ts +5 -3
  98. package/src/install/plan-merge-policy.ts +133 -0
  99. package/src/install/read-account-rules.ts +376 -0
  100. package/src/predicate/decode.ts +1 -1
  101. package/src/predicate/encode.ts +176 -10
  102. package/src/record/decode.ts +5 -6
  103. package/src/registry/protocols.ts +1 -1
  104. package/src/review-card/builder.ts +17 -1
  105. package/src/run/index.ts +500 -102
  106. package/src/run/schemas.ts +145 -24
  107. package/src/synth/compose-from-recording.ts +87 -132
  108. package/src/synth/deny-cases.ts +59 -13
  109. package/src/synth/evaluate.ts +70 -118
  110. package/src/synth/harness.ts +29 -1
  111. package/src/synth/index.ts +1 -0
  112. package/src/synth/synthesize-from-recording.ts +209 -192
  113. package/src/contracts/policy-template/OZ_POLICY_TRAIT.md +0 -196
@@ -2,26 +2,9 @@
2
2
  // src/adapters/interpreter/adapter.ts - the interpreter-policy CustodyAdapter.
3
3
  //
4
4
  // Compiles a PolicyIR to a single interpreter `PolicyDocument` + `PolicyRef`
5
- // carrying the canonical predicate encoding defined in
6
- // `packages/policy-interpreter/INTERPRETER_INSTALL_PARAMS.md`. The adapter is
7
- // the second backend (the OZ built-in adapter is the first); together they
8
- // cover the canonical language subset. The compose step (P3) routes IR
9
- // constructs between them.
10
- //
11
- // What it lowers (every IR construct the predicate DSL expresses):
12
- // - IRLogic and/or -> PredicateNode and/or
13
- // - IRLogic not -> PredicateNode not
14
- // - IRCompare -> selector(left) vs literal(right), op carried over
15
- // - IR `in` -> needle=selector, haystack=literals (PURESET
16
- // membership; the haystack is always sorted by the
17
- // encoder)
18
- // - IR `eq_seq` -> eq(selectorLeaf, literal_vec([...])) - exact ordered
19
- // sequence equality; element order is preserved
20
- // verbatim (the encoder does NOT sort the vec)
21
- // - IRSelector -> matching PredicateLeaf (see lowerSelector)
22
- // - scope.contract -> sibling `call_contract == <contract>` (always
23
- // emitted when set)
24
- // - scope.method -> sibling `call_fn == <method>`
5
+ // carrying the canonical predicate encoding from `predicate/encode.ts`. Second
6
+ // backend (the OZ built-in adapter is the first); the compose step (P3) routes
7
+ // IR constructs between them.
25
8
  //
26
9
  // Three fail-closed enforcement gates (per spec):
27
10
  // - oracle_price leaves MUST sit directly under the top-level `and`; nesting
@@ -43,7 +26,7 @@ const encode_ts_1 = require("../../predicate/encode.js");
43
26
  /** [VERIFY] NOT a real deployed address. The interpreter is a per-network
44
27
  * deploy artifact we do not have yet; install is a later phase. */
45
28
  exports.PLACEHOLDER_INTERPRETER_ADDRESS = 'VERIFY-interpreter-address';
46
- /** Wasm-level oracle defaults (mirrors INTERPRETER_INSTALL_PARAMS.md OracleParams).
29
+ /** Wasm-level oracle defaults (mirrors the interpreter's `OracleParams`).
47
30
  * Per-policy overrides may TIGHTEN only - they may never exceed these. */
48
31
  exports.ORACLE_DEFAULTS = {
49
32
  maxStalenessSeconds: 600,
@@ -52,17 +35,15 @@ exports.ORACLE_DEFAULTS = {
52
35
  const CAPABILITIES = {
53
36
  supportsSpendWindow: true,
54
37
  supportsThreshold: false, // thresholds are the OZ adapter's job
55
- // False for the predicate-leaf path: the interpreter refuses a `valid_until`
56
- // leaf at install. Expiry is still available, but as the context rule's
57
- // validUntilLedger, which the smart account enforces - not as a predicate.
38
+ // Expiry is via the context rule's validUntilLedger, not a predicate - the
39
+ // interpreter refuses a `valid_until` leaf at install.
58
40
  supportsTimeExpiry: false,
59
41
  supportsOraclePrice: true,
60
42
  supportsInvocationCount: true,
61
43
  supportsGeneralPredicate: true,
62
44
  };
63
- /** Parse confidence for a deterministic (non-decoded) input: full, with an
64
- * empty unknown/opaque breakdown. A mandate needs no decoding, so the gate is
65
- * not applicable and confidence is 1. */
45
+ /** Parse confidence for a deterministic (non-decoded) input: full (1.0). A
46
+ * mandate needs no decoding, so the gate is not applicable. */
66
47
  const FULL_PARSE_CONFIDENCE = {
67
48
  overall: 1,
68
49
  knownContracts: [],
@@ -82,12 +63,11 @@ function createInterpreterAdapter(config) {
82
63
  }
83
64
  /** Lower a single IR rule to the canonical pre-encoding `PredicateNode`. The
84
65
  * orchestrator uses this to wire the self-verify + minimise pipeline: after
85
- * `compile(ir)` succeeds (`covered === true`, `proposed` set), the
86
- * orchestrator re-derives the PredicateNode via this helper to drive
87
- * `minimize` and `runHarness` on the SAME shape the encoder saw. Pure and
88
- * deterministic: same `rule + config` -> byte-identical PredicateNode. The
89
- * `uncovered` list the adapter surfaces during compile is NOT re-derived
90
- * here; callers that need it should use the result of `compile(ir)`. */
66
+ * `compile(ir)` succeeds it re-derives the PredicateNode via this helper to
67
+ * drive `minimize` and `runHarness` on the SAME shape the encoder saw. Pure
68
+ * and deterministic: same `rule + config` -> byte-identical PredicateNode.
69
+ * The `uncovered` list is NOT re-derived - callers needing it must use
70
+ * `compile(ir)`. */
91
71
  function lowerRuleToPredicate(rule, config) {
92
72
  return lowerRule(rule, config).predicate;
93
73
  }
@@ -137,9 +117,9 @@ function compile(ir, config) {
137
117
  function lowerRule(rule, config) {
138
118
  const uncovered = [];
139
119
  // scope -> context rule + sibling predicates. contract/method each become
140
- // their own `eq` leaf and are merged into the top-level and alongside the
141
- // constraints. This keeps the top-level shape `and` (mandatory per the oracle
142
- // position rule and the canonical hash stability for `and`).
120
+ // their own `eq` leaf and are merged into the top-level `and` alongside the
121
+ // constraints. The top-level MUST be `and` so oracle leaves sit directly
122
+ // under it (mandatory per the oracle position rule + canonical hash stability).
143
123
  const scopeContract = rule.scope.contract;
144
124
  const scopeMethod = rule.scope.method;
145
125
  if (rule.scope.chainId !== undefined) {
@@ -247,18 +227,18 @@ function unsupportedConstruct(cond) {
247
227
  return 'EVM calldata comparison (predicate DSL)';
248
228
  if (s.kind === 'value')
249
229
  return 'tx.value comparison (predicate DSL)';
250
- // The on-chain interpreter sees ONE authorized call - there is no
251
- // `Context.sub_invocations` in v1 - so it cannot observe the
252
- // transaction's token movements. `amount` has no value to read, and
253
- // `window_spent` accumulates BY that amount, so its counter would never
254
- // move. Deriving either from the call payload would quietly swap "value
230
+ // The on-chain interpreter sees ONE authorized call - no
231
+ // `Context.sub_invocations` in v1 - so it cannot observe token
232
+ // movements. `amount` has no value to read, and `window_spent`
233
+ // accumulates BY that amount, so its counter would never move.
234
+ // Deriving either from the call payload would quietly swap "value
255
235
  // actually moved" for "value the caller declared" - a weaker guarantee
256
236
  // than the review card would be claiming.
257
237
  //
258
- // Rolling spend caps belong to the OZ `spending_limit` primitive, which
259
- // is already audited and which the OZ adapter emits. A per-call cap is
260
- // expressible here as `arg_field`; bounding it with `invocation_count`
261
- // gives an enforceable ceiling per window.
238
+ // Rolling spend caps belong to the OZ `spending_limit` primitive (already
239
+ // audited, emitted by the OZ adapter). A per-call cap is expressible here
240
+ // as `arg_field`; bounding it with `invocation_count` gives an enforceable
241
+ // ceiling per window.
262
242
  return unsourceableSelector(s);
263
243
  }
264
244
  // Recurse: a nested `and`/`or`/`not` must not smuggle a selector past the
@@ -372,9 +352,9 @@ function lowerSelector(s) {
372
352
  case 'arg_field':
373
353
  return { kind: 'call_arg_field', index: s.argIndex, element: s.element, field: s.field };
374
354
  // `amount` / `window_spent` are filtered out by `unsupportedConstruct`
375
- // before lowering - the interpreter cannot source either on chain. Reaching
376
- // here means the pre-scan was bypassed, so fail loudly rather than emit a
377
- // leaf the contract will refuse.
355
+ // before lowering - the interpreter cannot source either on chain.
356
+ // Reaching here means the pre-scan was bypassed; fail loudly rather than
357
+ // emit a leaf the contract will refuse.
378
358
  case 'amount':
379
359
  case 'window_spent':
380
360
  throw new Error(`interpreter adapter cannot lower \`${s.kind}\`: it should have been reported as uncovered`);
@@ -10,7 +10,7 @@
10
10
  // Anything needing a capability this backend lacks (oracle price, invocation
11
11
  // count, per-arg comparison/allowlist, guard, nested boolean predicate) is NOT
12
12
  // emitted: it is named in `uncovered` and `covered` is set false. Nothing is
13
- // silently dropped - the uncovered constructs are named instead.
13
+ // silently dropped.
14
14
  //
15
15
  // OZ built-in policy instance addresses are per-network deploy artifacts we do
16
16
  // not have yet (install is a later phase). They are injected via config; week-1
@@ -32,9 +32,8 @@ exports.PLACEHOLDER_OZ_INSTANCES = {
32
32
  function placeholderOzConfig(network) {
33
33
  return { network, instances: exports.PLACEHOLDER_OZ_INSTANCES };
34
34
  }
35
- /** Parse confidence for a deterministic (non-decoded) input: full, with an
36
- * empty unknown/opaque breakdown. A mandate needs no decoding, so the gate is
37
- * not applicable and confidence is 1. */
35
+ /** Parse confidence for a deterministic (non-decoded) input: full (1.0). A
36
+ * mandate needs no decoding, so the gate is not applicable. */
38
37
  const FULL_PARSE_CONFIDENCE = {
39
38
  overall: 1,
40
39
  knownContracts: [],
@@ -88,10 +87,10 @@ function compile(ir, config) {
88
87
  function lowerRule(rule, config) {
89
88
  const uncovered = [];
90
89
  const policyRefs = [];
91
- // scope -> context rule type. OZ scopes by contract (CallContract); a finer
92
- // method-level restriction is a predicate concern and must be flagged as not
93
- // covered because CallContract alone permits other methods on the same contract
94
- // (e.g. an unbounded approve alongside a capped transfer).
90
+ // scope -> context rule type. OZ scopes by contract (CallContract); a
91
+ // method-level restriction is flagged as not covered because CallContract
92
+ // alone permits other methods on the same contract (e.g. an unbounded approve
93
+ // alongside a capped transfer).
95
94
  const contextRuleType = rule.scope.contract !== undefined
96
95
  ? { kind: 'call_contract', contract: rule.scope.contract }
97
96
  : { kind: 'default' };
@@ -120,8 +119,8 @@ function lowerRule(rule, config) {
120
119
  uncovered.push(`guard: ${describeCondition(rule.guard)}`);
121
120
  }
122
121
  // constraints -> spending_limit where they match; else not covered. The OZ
123
- // spending_limit policy takes `{ spending_limit: i128, period_ledgers: u32 }`
124
- // and has NO token param: it only accepts a CallContract context rule
122
+ // spending_limit takes `{ spending_limit: i128, period_ledgers: u32 }` and
123
+ // has NO token param: it only accepts a CallContract context rule
125
124
  // (OnlyCallContractAllowed) and limits transfers of that context's contract,
126
125
  // so the spent token must equal the scope contract, and the window is a
127
126
  // ledger count (~5s/ledger), not seconds.
@@ -149,7 +148,7 @@ function lowerRule(rule, config) {
149
148
  }
150
149
  // approval.threshold -> simple/weighted threshold primitive. A threshold < 1
151
150
  // is not a real M-of-N gate (0 approvals authorises everything), so refuse to
152
- // emit a no-op primitive and flag it as not covered instead.
151
+ // emit a no-op primitive and flag it as not covered.
153
152
  if (rule.approval) {
154
153
  if (!Number.isInteger(rule.approval.threshold) || rule.approval.threshold < 1) {
155
154
  uncovered.push(`approval threshold ${rule.approval.threshold} is not a positive integer (a 0 or negative threshold is not an M-of-N gate)`);
@@ -213,8 +212,8 @@ function matchSpendingLimit(c) {
213
212
  function describeCondition(cond) {
214
213
  switch (cond.op) {
215
214
  case 'slippage_floor':
216
- // The OZ primitives bound a value against a constant; this bounds one
217
- // call argument against another, which none of them can express.
215
+ // OZ primitives bound a value against a constant; this bounds one call
216
+ // argument against another, which none of them can express.
218
217
  return `slippage floor on arg[${cond.outArgIndex}] (OZ built-ins cannot bound one argument against another)`;
219
218
  case 'in':
220
219
  return `value allowlist on ${describeSelector(cond.selector)} (arg allowlist)`;
@@ -79,6 +79,11 @@ publish = false
79
79
 
80
80
  [lib]
81
81
  crate-type = ["cdylib"]
82
+ # The gate writes the source beside the manifest rather than under src/, so
83
+ # the path is stated. Without it cargo looks for src/lib.rs and fails to
84
+ # parse the manifest before it ever compiles anything, which reads as a
85
+ # broken generator rather than a broken scaffold.
86
+ path = "lib.rs"
82
87
 
83
88
  [dependencies]
84
89
  soroban-sdk = "22"
@@ -2,6 +2,23 @@
2
2
  // src/codegen/template.ts - deterministic Rust source generator for the OZ
3
3
  // `Policy` escape-hatch skeleton.
4
4
  //
5
+ // SUPERSEDED. The architecture this belongs to no longer exists. A deployed
6
+ // policy involves exactly two contracts, the OZ smart account and one
7
+ // immutable interpreter, and the synthesiser emits policy DATA rather than
8
+ // code. Nothing on the synthesis path reaches this module, and no install can
9
+ // produce a contract from it. When a constraint falls outside the grammar the
10
+ // answer is to version the synthesiser and the interpreter together, not to
11
+ // put unaudited Rust on chain per policy.
12
+ //
13
+ // Deleting it is a decision nobody has taken yet, not a dependency question.
14
+ // `compile-gate.ts` takes a Rust string and knows nothing about this module,
15
+ // and its tests compile a hardcoded fixture, so the gate keeps working either
16
+ // way. What deleting this would remove is the only in-repo producer of policy
17
+ // Rust for the gate to check. Do not read its presence as the product
18
+ // generating contracts, and do not wire it into the synthesis path.
19
+ //
20
+ // What follows describes the abandoned design.
21
+ //
5
22
  // This is the LAST-RESORT tool for constraints the v1 DSL cannot express. It
6
23
  // lives OUT of the audited happy-path surface; the synthesiser never emits it
7
24
  // automatically. It mirrors Zodiac Roles' `Custom` operator: a hand-written
@@ -0,0 +1,134 @@
1
+ import type { PredicateNode, SignerDraft } from '../types.ts';
2
+ /** Wildcard component of a `Selector`: the predicate does not pin this half. */
3
+ export declare const ANY = "*";
4
+ /** A (contract, function) pair a predicate may permit. `ANY` in either half
5
+ * means unconstrained, so `{contract: ANY, fn: ANY}` is "any call at all". */
6
+ export interface Selector {
7
+ contract: string;
8
+ fn: string;
9
+ }
10
+ export type ContextType = {
11
+ kind: 'default';
12
+ } | {
13
+ kind: 'call_contract';
14
+ address: string;
15
+ } | {
16
+ kind: 'create_contract';
17
+ wasmHash: string;
18
+ };
19
+ /** How much we can say about a neighbouring rule.
20
+ * - `interpreter`: policed by our interpreter and the predicate was readable,
21
+ * so its authority is known exactly and it can be merged.
22
+ * - `foreign`: policed by some other contract. The address is visible, the
23
+ * semantics are not, so it must be reviewed by hand.
24
+ * - `unpoliced`: no policy at all. Whatever the rule's context type allows,
25
+ * its signers may do without constraint. */
26
+ export type RuleClass = 'interpreter' | 'foreign' | 'unpoliced';
27
+ export interface ObservedRule {
28
+ id: number;
29
+ contextType: ContextType;
30
+ signers: SignerDraft[];
31
+ /** Policy contract addresses attached to the rule, in OZ's order. */
32
+ policyAddresses: string[];
33
+ /** OZ's global registry ids for those policies, index-aligned with
34
+ * `policyAddresses`. `remove_policy` takes the id, not the address, so
35
+ * detaching a policy is impossible without them. */
36
+ policyIds?: number[];
37
+ /** Per-policy oracle bounds from the stored document, when it was
38
+ * readable. A merge must re-install these or it silently widens them. */
39
+ oracleBounds?: {
40
+ maxStalenessSeconds?: number;
41
+ maxDeviationBps?: number;
42
+ maxCrossFeedDeviationBps?: number;
43
+ };
44
+ /** Decoded predicate. Present only when the rule is policed by our
45
+ * interpreter AND the stored document was readable. */
46
+ predicate?: PredicateNode;
47
+ }
48
+ export interface IntendedInstall {
49
+ /** Rule the predicate is being installed onto. A re-install onto the same
50
+ * id is a replacement, not an overlap, so this id is skipped. */
51
+ ruleId: number;
52
+ contextType: ContextType;
53
+ signers: SignerDraft[];
54
+ predicate: PredicateNode;
55
+ }
56
+ export type OverlapSeverity =
57
+ /** A neighbouring rule imposes no constraint at all on the shared calls. */
58
+ 'bypass'
59
+ /** A neighbouring policy exists but we cannot read what it permits. */
60
+ | 'unknown'
61
+ /** Both rules are ours. The new rule will not restrict the shared calls,
62
+ * because the signer can name whichever rule is more permissive. */
63
+ | 'not-restricting';
64
+ export interface AuthorityOverlap {
65
+ ruleId: number;
66
+ ruleClass: RuleClass;
67
+ severity: OverlapSeverity;
68
+ /** Signers present in both rules. Overlap is only reachable by a signer who
69
+ * can name both rules, so a rule sharing no signer is not a collision. */
70
+ sharedSigners: SignerDraft[];
71
+ /** The selectors both rules can serve. Non-empty by construction. */
72
+ sharedSelectors: Selector[];
73
+ /** True when the neighbour is ours and can therefore be replaced by the
74
+ * conjunction of the two predicates. */
75
+ mergeable: boolean;
76
+ advice: string;
77
+ }
78
+ /** Canonical key for signer equality. Mirrors OZ's `Signer` enum: a delegated
79
+ * signer is its address, an external signer is the verifier plus the key
80
+ * bytes, since one verifier may hold many keys. */
81
+ export declare function signerKey(s: SignerDraft): string;
82
+ /** Intersection of two selector SETS: every compatible pairing survives. */
83
+ export declare function intersectSelectors(a: Selector[], b: Selector[]): Selector[];
84
+ /**
85
+ * The set of `(contract, fn)` selectors a predicate may permit.
86
+ *
87
+ * This is a deliberate OVER-approximation: every call the predicate actually
88
+ * permits is covered by some returned selector, and unrecognised structure
89
+ * widens to the wildcard rather than narrowing. That direction is what makes
90
+ * the emptiness test below sound. A call carries exactly one `(contract, fn)`,
91
+ * so if two predicates' over-approximations do not intersect, no single call
92
+ * can be routed to either of them and the rules provably cannot collide.
93
+ *
94
+ * `not` is treated as unconstrained. Complementing a selector set would need
95
+ * the universe of addresses and function names, which is not available and
96
+ * would not be sound to guess.
97
+ */
98
+ export declare function permittedSelectors(node: PredicateNode): Selector[];
99
+ /** Selectors a context type admits, before the predicate narrows them. */
100
+ export declare function selectorsForContextType(ct: ContextType): Selector[];
101
+ /** What a rule can actually authorise: its context type narrowed by its
102
+ * predicate. An unpoliced or unreadable rule contributes no narrowing. */
103
+ export declare function effectiveSelectors(rule: ObservedRule): Selector[];
104
+ /**
105
+ * Every existing rule that a signer of the intended install could name instead.
106
+ *
107
+ * A rule collides when it shares at least one signer AND at least one selector,
108
+ * because both conditions are needed for the signer to have a choice. The rule
109
+ * being installed onto is skipped: re-installing over it replaces its
110
+ * predicate rather than adding a second source of authority.
111
+ */
112
+ export declare function findAuthorityOverlaps(args: {
113
+ intended: IntendedInstall;
114
+ existing: ObservedRule[];
115
+ }): AuthorityOverlap[];
116
+ export interface MergeResult {
117
+ ok: boolean;
118
+ predicate?: PredicateNode;
119
+ /** Set when `ok` is false. */
120
+ reason?: string;
121
+ }
122
+ /**
123
+ * Conjunction of an existing predicate with a new one, for the tightening case.
124
+ *
125
+ * `and` children are flattened so repeated merges do not nest, which keeps the
126
+ * encoded form closer to the byte cap.
127
+ *
128
+ * The guard matters more than the merge. `and` is only correct when the caller
129
+ * means to tighten. Applied to two predicates that pin DIFFERENT selectors it
130
+ * produces a predicate permitting nothing, which silently disables the policy
131
+ * instead of restricting it. That case is refused, because the caller wanted
132
+ * two capabilities and two rules already express that correctly.
133
+ */
134
+ export declare function mergeIntoAnd(existing: PredicateNode, incoming: PredicateNode): MergeResult;
@@ -46,3 +46,11 @@ export type AddContextRuleArgs = readonly [
46
46
  /** Build the `add_context_rule` invocation args. Throws a `ToolError`-shaped
47
47
  * error on limit breaches or malformed input. */
48
48
  export declare function buildAddContextRuleArgs(draft: ContextRuleDraft, args: BuildAddContextRuleArgs): AddContextRuleArgs;
49
+ /** The `PolicyInstallParams` ScVal an interpreter policy receives.
50
+ *
51
+ * Exported so the merge remedy can re-install a policy through `add_policy`
52
+ * using the SAME encoder as a fresh install. Re-implementing it would risk
53
+ * exactly the drift this file warns about: the field order is ABI-significant
54
+ * and a differing encoding yields a rule that denies every call. */
55
+ export type PolicyInstallParamArgs = Pick<BuildAddContextRuleArgs, 'encodedPredicate' | 'predicateHash' | 'installNonce' | 'oracleParams' | 'grammarVersion'>;
56
+ export declare function encodePolicyInstallParams(args: PolicyInstallParamArgs): xdr.ScVal;
@@ -50,6 +50,7 @@
50
50
  Object.defineProperty(exports, "__esModule", { value: true });
51
51
  exports.ADD_CONTEXT_RULE_SYMBOL = exports.DEFAULT_GRAMMAR_VERSION = void 0;
52
52
  exports.buildAddContextRuleArgs = buildAddContextRuleArgs;
53
+ exports.encodePolicyInstallParams = encodePolicyInstallParams;
53
54
  const node_crypto_1 = require("node:crypto");
54
55
  const stellar_sdk_1 = require("@stellar/stellar-sdk");
55
56
  const types_ts_1 = require("../types.js");
@@ -144,13 +145,12 @@ function encodePoliciesMap(args) {
144
145
  const entries = [];
145
146
  for (const ref of args.policies) {
146
147
  if (ref.kind === 'interpreter') {
147
- const val = encodePolicyInstallParams(args);
148
148
  entries.push(new stellar_sdk_1.xdr.ScMapEntry({
149
149
  key: stellar_sdk_1.Address.fromString(ref.interpreterAddress).toScVal(),
150
- val,
150
+ val: encodePolicyInstallParams(args),
151
151
  }));
152
152
  }
153
- if (ref.kind === 'oz_builtin') {
153
+ else if (ref.kind === 'oz_builtin') {
154
154
  entries.push(new stellar_sdk_1.xdr.ScMapEntry({
155
155
  key: stellar_sdk_1.Address.fromString(ref.instanceAddress).toScVal(),
156
156
  val: encodeOzPrimitiveParams(ref.primitive),
@@ -225,48 +225,20 @@ function encodePolicyInstallParams(args) {
225
225
  if (computedHash !== args.predicateHash) {
226
226
  throw limitError('INSTALL_BUILD_FAILED', `predicateHash ${args.predicateHash.slice(0, 16)}... does not match sha256(encodedPredicate) ${computedHash.slice(0, 16)}...`);
227
227
  }
228
- const entries = [];
229
- for (const k of POLICY_INSTALL_PARAM_FIELDS) {
230
- const key = stellar_sdk_1.xdr.ScVal.scvSymbol(k);
231
- switch (k) {
232
- case 'grammar_version':
233
- entries.push(new stellar_sdk_1.xdr.ScMapEntry({
234
- key,
235
- val: stellar_sdk_1.xdr.ScVal.scvU32(args.grammarVersion ?? exports.DEFAULT_GRAMMAR_VERSION),
236
- }));
237
- break;
238
- case 'install_nonce':
239
- entries.push(new stellar_sdk_1.xdr.ScMapEntry({ key, val: stellar_sdk_1.xdr.ScVal.scvU32(args.installNonce) }));
240
- break;
241
- case 'predicate':
242
- entries.push(new stellar_sdk_1.xdr.ScMapEntry({ key, val: stellar_sdk_1.xdr.ScVal.scvBytes(predicate) }));
243
- break;
244
- case 'predicate_hash':
245
- entries.push(new stellar_sdk_1.xdr.ScMapEntry({
246
- key,
247
- val: stellar_sdk_1.xdr.ScVal.scvBytes(Buffer.from(args.predicateHash, 'hex')),
248
- }));
249
- break;
250
- case 'oracle_max_staleness_seconds':
251
- entries.push(new stellar_sdk_1.xdr.ScMapEntry({
252
- key,
253
- val: encodeOptionU32(args.oracleParams?.maxStalenessSeconds),
254
- }));
255
- break;
256
- case 'oracle_max_deviation_bps':
257
- entries.push(new stellar_sdk_1.xdr.ScMapEntry({
258
- key,
259
- val: encodeOptionU32(args.oracleParams?.maxDeviationBps),
260
- }));
261
- break;
262
- case 'oracle_max_xfeed_dev_bps':
263
- entries.push(new stellar_sdk_1.xdr.ScMapEntry({
264
- key,
265
- val: encodeOptionU32(args.oracleParams?.maxCrossFeedDeviationBps),
266
- }));
267
- break;
268
- }
269
- }
228
+ // Per-field value encoders. Each entry returns the ScVal to drop into the
229
+ // map; the key symbol comes from the surrounding loop. Adding a field is
230
+ // one row here plus the symbol in POLICY_INSTALL_PARAM_FIELDS.
231
+ const oracleParams = args.oracleParams;
232
+ const valueFor = {
233
+ grammar_version: () => stellar_sdk_1.xdr.ScVal.scvU32(args.grammarVersion ?? exports.DEFAULT_GRAMMAR_VERSION),
234
+ install_nonce: () => stellar_sdk_1.xdr.ScVal.scvU32(args.installNonce),
235
+ predicate: () => stellar_sdk_1.xdr.ScVal.scvBytes(predicate),
236
+ predicate_hash: () => stellar_sdk_1.xdr.ScVal.scvBytes(Buffer.from(args.predicateHash, 'hex')),
237
+ oracle_max_staleness_seconds: () => encodeOptionU32(oracleParams?.maxStalenessSeconds),
238
+ oracle_max_deviation_bps: () => encodeOptionU32(oracleParams?.maxDeviationBps),
239
+ oracle_max_xfeed_dev_bps: () => encodeOptionU32(oracleParams?.maxCrossFeedDeviationBps),
240
+ };
241
+ const entries = POLICY_INSTALL_PARAM_FIELDS.map((k) => new stellar_sdk_1.xdr.ScMapEntry({ key: stellar_sdk_1.xdr.ScVal.scvSymbol(k), val: valueFor[k]() }));
270
242
  // The host orders map entries by the SYMBOL STRING, not by XDR bytes. A
271
243
  // length prefix in the XDR encoding would otherwise put `amount` before
272
244
  // `address` and produce a struct the contract reads differently. Emit the
@@ -18,11 +18,10 @@ export interface InstallRpcClient {
18
18
  * `getContractVersion` lookup uses `simulateTransaction` against
19
19
  * `contract.call('grammar_version')` and decodes the returned u32.
20
20
  *
21
- * The passphrase is a REQUIRED argument rather than something read off the
22
- * server: `rpc.Server` does not carry one, so reaching for
23
- * `server.networkPassphrase` yielded a non-string and every version probe
24
- * died with "Invalid passphrase provided to Transaction". The caller knows
25
- * which network it dialled; make it say so. */
21
+ * The passphrase is a REQUIRED argument (not read off the server): `rpc.Server`
22
+ * does not carry one, so reaching for `server.networkPassphrase` returned a
23
+ * non-string and every version probe died with "Invalid passphrase provided to
24
+ * Transaction". The caller knows which network it dialled; make it say so. */
26
25
  export declare function rpcClientFromServer(server: rpc.Server, networkPassphrase: string): InstallRpcClient;
27
26
  /** Inputs for the install-policy build. */
28
27
  export interface BuildInstallPolicyArgs {
@@ -115,6 +114,14 @@ export interface InstallCallDescribes {
115
114
  kind: 'external';
116
115
  verifier: string;
117
116
  }>;
117
+ /** Cross-layer L1: a human-readable note about the OZ any-of-N signer
118
+ * semantic that fires for rules with multiple signers. Present only
119
+ * when `signers.length >= 2` (a single-signer rule is trivially any-of-1,
120
+ * and the note would just add noise). The note is purely additive to
121
+ * the review card text - it does NOT alter the wire bytes or the
122
+ * signer-set constraint, only the description a human reads before
123
+ * signing the install. */
124
+ signerNote: string | null;
118
125
  /** One entry per policy attached to the rule, decoded from the policies
119
126
  * map (args[4]). The address is the map key; the kind + extras below
120
127
  * describe the value. The interpreter policy also reports the
@@ -1,25 +1,22 @@
1
1
  "use strict";
2
- // src/install/build-install-policy.ts - builds the unsigned Soroban
3
- // transaction XDR for `account.add_context_rule(...)` and
4
- // `account.remove_context_rule(...)`.
2
+ // src/install/build-install-policy.ts - builds the unsigned Soroban transaction
3
+ // XDR for `account.add_context_rule(...)` and `account.remove_context_rule(...)`.
5
4
  //
6
- // The MCP server is stateless and holds no key material (server.ts:10-12),
7
- // so this module NEVER signs. The caller (the wallet / CLI / SDK consumer)
8
- // wraps the returned XDR in a transaction envelope and signs that envelope
9
- // with their wallet; the wallet signature IS the user-confirmation step.
5
+ // The MCP server is stateless and holds no key material, so this module NEVER
6
+ // signs. The caller (wallet / CLI / SDK consumer) wraps the returned XDR in a
7
+ // transaction envelope and signs that envelope with their wallet; the wallet
8
+ // signature IS the user-confirmation step.
10
9
  //
11
- // We deliberately depart from the spec in plans/phase-04 which calls for a
10
+ // We deliberately depart from the original design, which called for a
12
11
  // two-call `install_policy`/`confirm_install` pair backed by a host-signed
13
- // short-TTL `action_id`. That contract requires (a) a stateful store and
14
- // (b) key material the server does not have, so we ship the simpler ONE-CALL
15
- // shape. The wallet signature covers the change.
12
+ // short-TTL `action_id`. That contract requires stateful store + key material
13
+ // the server does not have, so we ship the simpler ONE-CALL shape. The wallet
14
+ // signature covers the change.
16
15
  //
17
16
  // `buildInstallPolicyXdr` installs the policy in ONE call. `add_context_rule`
18
17
  // takes `policies` as a `Map<policy_address, install_param>` and the account
19
18
  // forwards each install_param to that policy, so the interpreter stores the
20
- // predicate document as part of this same transaction. Earlier revisions
21
- // documented a second `interpreter.install` call; that was wrong, and issuing
22
- // it fails - the account re-enters the interpreter while it is mid-install.
19
+ // predicate document as part of this same transaction.
23
20
  Object.defineProperty(exports, "__esModule", { value: true });
24
21
  exports.DEFAULT_GRAMMAR_VERSION = exports.Contract = void 0;
25
22
  exports.rpcClientFromServer = rpcClientFromServer;
@@ -35,11 +32,10 @@ const oz_auth_ts_1 = require("./oz-auth.js");
35
32
  * `getContractVersion` lookup uses `simulateTransaction` against
36
33
  * `contract.call('grammar_version')` and decodes the returned u32.
37
34
  *
38
- * The passphrase is a REQUIRED argument rather than something read off the
39
- * server: `rpc.Server` does not carry one, so reaching for
40
- * `server.networkPassphrase` yielded a non-string and every version probe
41
- * died with "Invalid passphrase provided to Transaction". The caller knows
42
- * which network it dialled; make it say so. */
35
+ * The passphrase is a REQUIRED argument (not read off the server): `rpc.Server`
36
+ * does not carry one, so reaching for `server.networkPassphrase` returned a
37
+ * non-string and every version probe died with "Invalid passphrase provided to
38
+ * Transaction". The caller knows which network it dialled; make it say so. */
43
39
  function rpcClientFromServer(server, networkPassphrase) {
44
40
  return {
45
41
  getAccount: (address) => server.getAccount(address),
@@ -345,7 +341,7 @@ function decodeInstallCallDescribes(tx, expectedInstallNonce) {
345
341
  const tag = tuple[0]?.sym().toString();
346
342
  const inner = tuple[1];
347
343
  if (tag === 'Delegated') {
348
- if (!inner || inner.switch().name !== 'scvAddress') {
344
+ if (inner?.switch().name !== 'scvAddress') {
349
345
  throw new Error('install_policy: a Delegated signer is missing its Address');
350
346
  }
351
347
  signers.push({
@@ -355,7 +351,7 @@ function decodeInstallCallDescribes(tx, expectedInstallNonce) {
355
351
  continue;
356
352
  }
357
353
  if (tag === 'External') {
358
- if (!inner || inner.switch().name !== 'scvAddress') {
354
+ if (inner?.switch().name !== 'scvAddress') {
359
355
  throw new Error('install_policy: an External signer is missing its verifier Address');
360
356
  }
361
357
  signers.push({
@@ -397,12 +393,12 @@ function decodeInstallCallDescribes(tx, expectedInstallNonce) {
397
393
  // OZ primitives carry spending_limit/period_ledgers/threshold/signers.
398
394
  if (fields.has('predicate') || fields.has('grammar_version') || fields.has('install_nonce')) {
399
395
  const installNonceScv = fields.get('install_nonce');
400
- if (!installNonceScv || installNonceScv.switch().name !== 'scvU32') {
396
+ if (installNonceScv?.switch().name !== 'scvU32') {
401
397
  throw new Error(`install_policy: interpreter policy ${address} is missing a u32 install_nonce`);
402
398
  }
403
399
  const installNonce = installNonceScv.u32();
404
400
  const predicateScv = fields.get('predicate');
405
- if (!predicateScv || predicateScv.switch().name !== 'scvBytes') {
401
+ if (predicateScv?.switch().name !== 'scvBytes') {
406
402
  throw new Error(`install_policy: interpreter policy ${address} is missing its bytes predicate`);
407
403
  }
408
404
  const predicateBytes = Buffer.from(predicateScv.bytes());
@@ -443,12 +439,25 @@ function decodeInstallCallDescribes(tx, expectedInstallNonce) {
443
439
  // `observedInstallNonce` is the nonce baked into whichever interpreter
444
440
  // policy is present; when none, fall back to the caller-supplied value.
445
441
  const installNonce = observedInstallNonce ?? expectedInstallNonce;
442
+ // Cross-layer L1: OZ Accounts context rules follow any-of-N semantics for
443
+ // the signers they accept - any ONE attached signer may authorise a
444
+ // permitted op under the rule. A user with multiple signers attached
445
+ // therefore has a strict superset of authority of a single-signer rule,
446
+ // not a stricter one; the install succeeds as written, but a human
447
+ // reviewing the install card may expect the opposite (and choose the
448
+ // wrong threshold because of it). Surface the any-of-N note on the
449
+ // description so the human reads the same wire-level semantic the
450
+ // contract enforces.
451
+ const signerNote = signers.length >= 2
452
+ ? 'any ONE signer may authorise a permitted op under this rule (OZ any-of-N semantic)'
453
+ : null;
446
454
  return {
447
455
  targetContract,
448
456
  fnName: 'add_context_rule',
449
457
  ruleName,
450
458
  validUntilLedger,
451
459
  signers,
460
+ signerNote,
452
461
  policies,
453
462
  installNonce,
454
463
  };