@crediolabs/policy-synth 0.1.3 → 0.1.5

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 (194) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +193 -5
  3. package/dist/adapters/interpreter/adapter.d.ts +38 -0
  4. package/dist/adapters/interpreter/adapter.js +522 -0
  5. package/dist/adapters/interpreter/index.d.ts +1 -0
  6. package/dist/adapters/interpreter/index.js +2 -0
  7. package/dist/adapters/oz/adapter.js +2 -0
  8. package/dist/codegen/compile-gate.d.ts +33 -0
  9. package/dist/codegen/compile-gate.js +119 -0
  10. package/dist/codegen/index.d.ts +2 -0
  11. package/dist/codegen/index.js +8 -0
  12. package/dist/codegen/template.d.ts +18 -0
  13. package/dist/codegen/template.js +131 -0
  14. package/dist/errors.d.ts +1 -1
  15. package/dist/index.d.ts +2 -0
  16. package/dist/index.js +2 -0
  17. package/dist/ir/types.d.ts +13 -2
  18. package/dist/predicate/encode.d.ts +10 -0
  19. package/dist/predicate/encode.js +249 -0
  20. package/dist/predicate/index.d.ts +1 -0
  21. package/dist/predicate/index.js +2 -0
  22. package/dist/record/decode.d.ts +6 -3
  23. package/dist/record/decode.js +13 -3
  24. package/dist/review-card/builder.d.ts +14 -0
  25. package/dist/review-card/builder.js +261 -0
  26. package/dist/review-card/conflict.d.ts +40 -0
  27. package/dist/review-card/conflict.js +111 -0
  28. package/dist/review-card/cross-check.d.ts +11 -0
  29. package/dist/review-card/cross-check.js +148 -0
  30. package/dist/review-card/index.d.ts +3 -0
  31. package/dist/review-card/index.js +4 -0
  32. package/dist/run/index.d.ts +31 -0
  33. package/dist/run/index.js +164 -0
  34. package/dist/run/schemas.d.ts +2003 -0
  35. package/dist/run/schemas.js +215 -0
  36. package/dist/synth/compose-from-recording.d.ts +35 -7
  37. package/dist/synth/compose-from-recording.js +225 -34
  38. package/dist/synth/deny-cases.d.ts +12 -0
  39. package/dist/synth/deny-cases.js +377 -0
  40. package/dist/synth/evaluate.d.ts +39 -0
  41. package/dist/synth/evaluate.js +425 -0
  42. package/dist/synth/harness.d.ts +16 -0
  43. package/dist/synth/harness.js +26 -0
  44. package/dist/synth/index.d.ts +4 -0
  45. package/dist/synth/index.js +4 -0
  46. package/dist/synth/minimize.d.ts +4 -0
  47. package/dist/synth/minimize.js +38 -0
  48. package/dist/synth/predicate-literals.d.ts +5 -0
  49. package/dist/synth/predicate-literals.js +25 -0
  50. package/dist/synth/synthesize-from-recording.d.ts +37 -5
  51. package/dist/synth/synthesize-from-recording.js +550 -18
  52. package/dist/types.d.ts +40 -1
  53. package/dist/types.js +17 -0
  54. package/dist/verify/envelope.d.ts +15 -0
  55. package/dist/verify/envelope.js +22 -0
  56. package/dist/verify/index.d.ts +3 -0
  57. package/dist/verify/index.js +3 -0
  58. package/dist/verify/simulate.d.ts +31 -0
  59. package/dist/verify/simulate.js +258 -0
  60. package/dist/verify/verify.d.ts +21 -0
  61. package/dist/verify/verify.js +189 -0
  62. package/dist-cjs/adapters/interpreter/adapter.d.ts +38 -0
  63. package/dist-cjs/adapters/interpreter/adapter.js +527 -0
  64. package/dist-cjs/adapters/interpreter/index.d.ts +1 -0
  65. package/dist-cjs/adapters/interpreter/index.js +8 -0
  66. package/dist-cjs/adapters/oz/adapter.d.ts +20 -0
  67. package/dist-cjs/adapters/oz/adapter.js +289 -0
  68. package/dist-cjs/adapters/oz/index.d.ts +1 -0
  69. package/dist-cjs/adapters/oz/index.js +8 -0
  70. package/dist-cjs/codegen/compile-gate.d.ts +33 -0
  71. package/dist-cjs/codegen/compile-gate.js +123 -0
  72. package/dist-cjs/codegen/index.d.ts +2 -0
  73. package/dist-cjs/codegen/index.js +14 -0
  74. package/dist-cjs/codegen/template.d.ts +18 -0
  75. package/dist-cjs/codegen/template.js +134 -0
  76. package/dist-cjs/errors.d.ts +37 -0
  77. package/dist-cjs/errors.js +3 -0
  78. package/dist-cjs/index.d.ts +11 -0
  79. package/dist-cjs/index.js +27 -0
  80. package/dist-cjs/ir/index.d.ts +1 -0
  81. package/dist-cjs/ir/index.js +3 -0
  82. package/dist-cjs/ir/types.d.ts +108 -0
  83. package/dist-cjs/ir/types.js +12 -0
  84. package/dist-cjs/mandate/index.d.ts +2 -0
  85. package/dist-cjs/mandate/index.js +6 -0
  86. package/dist-cjs/mandate/to-ir.d.ts +3 -0
  87. package/dist-cjs/mandate/to-ir.js +63 -0
  88. package/dist-cjs/mandate/types.d.ts +20 -0
  89. package/dist-cjs/mandate/types.js +9 -0
  90. package/dist-cjs/package.json +3 -0
  91. package/dist-cjs/predicate/encode.d.ts +10 -0
  92. package/dist-cjs/predicate/encode.js +252 -0
  93. package/dist-cjs/predicate/index.d.ts +1 -0
  94. package/dist-cjs/predicate/index.js +6 -0
  95. package/dist-cjs/record/decode.d.ts +79 -0
  96. package/dist-cjs/record/decode.js +398 -0
  97. package/dist-cjs/record/freshness.d.ts +17 -0
  98. package/dist-cjs/record/freshness.js +55 -0
  99. package/dist-cjs/record/index.d.ts +21 -0
  100. package/dist-cjs/record/index.js +166 -0
  101. package/dist-cjs/record/movements.d.ts +20 -0
  102. package/dist-cjs/record/movements.js +192 -0
  103. package/dist-cjs/record/rpc.d.ts +22 -0
  104. package/dist-cjs/record/rpc.js +74 -0
  105. package/dist-cjs/record/validate.d.ts +22 -0
  106. package/dist-cjs/record/validate.js +63 -0
  107. package/dist-cjs/registry/identify.d.ts +11 -0
  108. package/dist-cjs/registry/identify.js +87 -0
  109. package/dist-cjs/registry/index.d.ts +3 -0
  110. package/dist-cjs/registry/index.js +15 -0
  111. package/dist-cjs/registry/known-addresses.d.ts +16 -0
  112. package/dist-cjs/registry/known-addresses.js +53 -0
  113. package/dist-cjs/registry/protocols.d.ts +38 -0
  114. package/dist-cjs/registry/protocols.js +153 -0
  115. package/dist-cjs/review-card/builder.d.ts +14 -0
  116. package/dist-cjs/review-card/builder.js +264 -0
  117. package/dist-cjs/review-card/conflict.d.ts +40 -0
  118. package/dist-cjs/review-card/conflict.js +114 -0
  119. package/dist-cjs/review-card/cross-check.d.ts +11 -0
  120. package/dist-cjs/review-card/cross-check.js +151 -0
  121. package/dist-cjs/review-card/index.d.ts +3 -0
  122. package/dist-cjs/review-card/index.js +10 -0
  123. package/dist-cjs/run/index.d.ts +31 -0
  124. package/dist-cjs/run/index.js +178 -0
  125. package/dist-cjs/run/schemas.d.ts +2003 -0
  126. package/dist-cjs/run/schemas.js +218 -0
  127. package/dist-cjs/seams/index.d.ts +1 -0
  128. package/dist-cjs/seams/index.js +3 -0
  129. package/dist-cjs/seams/types.d.ts +66 -0
  130. package/dist-cjs/seams/types.js +12 -0
  131. package/dist-cjs/synth/compose-from-recording.d.ts +64 -0
  132. package/dist-cjs/synth/compose-from-recording.js +356 -0
  133. package/dist-cjs/synth/deny-cases.d.ts +12 -0
  134. package/dist-cjs/synth/deny-cases.js +380 -0
  135. package/dist-cjs/synth/evaluate.d.ts +39 -0
  136. package/dist-cjs/synth/evaluate.js +428 -0
  137. package/dist-cjs/synth/harness.d.ts +16 -0
  138. package/dist-cjs/synth/harness.js +29 -0
  139. package/dist-cjs/synth/index.d.ts +9 -0
  140. package/dist-cjs/synth/index.js +23 -0
  141. package/dist-cjs/synth/lower.d.ts +23 -0
  142. package/dist-cjs/synth/lower.js +119 -0
  143. package/dist-cjs/synth/minimize.d.ts +4 -0
  144. package/dist-cjs/synth/minimize.js +41 -0
  145. package/dist-cjs/synth/predicate-literals.d.ts +5 -0
  146. package/dist-cjs/synth/predicate-literals.js +28 -0
  147. package/dist-cjs/synth/scope.d.ts +26 -0
  148. package/dist-cjs/synth/scope.js +81 -0
  149. package/dist-cjs/synth/synthesize-from-mandate.d.ts +5 -0
  150. package/dist-cjs/synth/synthesize-from-mandate.js +37 -0
  151. package/dist-cjs/synth/synthesize-from-recording.d.ts +49 -0
  152. package/dist-cjs/synth/synthesize-from-recording.js +711 -0
  153. package/dist-cjs/types.d.ts +288 -0
  154. package/dist-cjs/types.js +55 -0
  155. package/dist-cjs/verify/envelope.d.ts +15 -0
  156. package/dist-cjs/verify/envelope.js +23 -0
  157. package/dist-cjs/verify/index.d.ts +3 -0
  158. package/dist-cjs/verify/index.js +8 -0
  159. package/dist-cjs/verify/simulate.d.ts +31 -0
  160. package/dist-cjs/verify/simulate.js +261 -0
  161. package/dist-cjs/verify/verify.d.ts +21 -0
  162. package/dist-cjs/verify/verify.js +192 -0
  163. package/package.json +43 -3
  164. package/src/adapters/interpreter/adapter.ts +642 -0
  165. package/src/adapters/interpreter/index.ts +8 -0
  166. package/src/adapters/oz/adapter.ts +2 -0
  167. package/src/codegen/compile-gate.ts +162 -0
  168. package/src/codegen/index.ts +17 -0
  169. package/src/codegen/template.ts +148 -0
  170. package/src/errors.ts +2 -0
  171. package/src/index.ts +2 -0
  172. package/src/ir/types.ts +9 -2
  173. package/src/predicate/encode.ts +307 -0
  174. package/src/predicate/index.ts +3 -0
  175. package/src/record/decode.ts +21 -10
  176. package/src/review-card/builder.ts +303 -0
  177. package/src/review-card/conflict.ts +143 -0
  178. package/src/review-card/cross-check.ts +158 -0
  179. package/src/review-card/index.ts +12 -0
  180. package/src/run/index.ts +213 -0
  181. package/src/run/schemas.ts +242 -0
  182. package/src/synth/compose-from-recording.ts +277 -43
  183. package/src/synth/deny-cases.ts +466 -0
  184. package/src/synth/evaluate.ts +493 -0
  185. package/src/synth/harness.ts +40 -0
  186. package/src/synth/index.ts +12 -0
  187. package/src/synth/minimize.ts +44 -0
  188. package/src/synth/predicate-literals.ts +27 -0
  189. package/src/synth/synthesize-from-recording.ts +655 -19
  190. package/src/types.ts +38 -2
  191. package/src/verify/envelope.ts +28 -0
  192. package/src/verify/index.ts +5 -0
  193. package/src/verify/simulate.ts +311 -0
  194. package/src/verify/verify.ts +243 -0
@@ -0,0 +1,642 @@
1
+ // src/adapters/interpreter/adapter.ts - the interpreter-policy CustodyAdapter.
2
+ //
3
+ // Compiles a PolicyIR to a single interpreter `PolicyDocument` + `PolicyRef`
4
+ // carrying the canonical predicate encoding defined in
5
+ // `packages/policy-interpreter/INTERPRETER_INSTALL_PARAMS.md`. The adapter is
6
+ // the second backend (the OZ built-in adapter is the first); together they
7
+ // cover the canonical language subset. The compose step (P3) routes IR
8
+ // constructs between them.
9
+ //
10
+ // What it lowers (every IR construct the predicate DSL expresses):
11
+ // - IRLogic and/or -> PredicateNode and/or
12
+ // - IRLogic not -> PredicateNode not
13
+ // - IRCompare -> selector(left) vs literal(right), op carried over
14
+ // - IR `in` -> needle=selector, haystack=literals (PURESET
15
+ // membership; the haystack is always sorted by the
16
+ // encoder)
17
+ // - IR `eq_seq` -> eq(selectorLeaf, literal_vec([...])) - exact ordered
18
+ // sequence equality; element order is preserved
19
+ // verbatim (the encoder does NOT sort the vec)
20
+ // - IRSelector -> matching PredicateLeaf (see lowerSelector)
21
+ // - scope.contract -> sibling `call_contract == <contract>` (always
22
+ // emitted when set)
23
+ // - scope.method -> sibling `call_fn == <method>`
24
+ //
25
+ // Three fail-closed enforcement gates (per spec):
26
+ // - oracle_price leaves MUST sit directly under the top-level `and`; nesting
27
+ // under `not` / `or` / inside `in` throws ORACLE_LEAF_INVALID_POSITION.
28
+ // - oracleParams overrides may only TIGHTEN vs wasm defaults
29
+ // (maxStalenessSeconds <= 600, maxDeviationBps <= 200); a widening value
30
+ // throws ORACLE_PARAMS_OUT_OF_RANGE at compile time.
31
+ // - an `in` allowlist (or a `compare eq` vs an address, or any value in an
32
+ // `eq_seq`) that targets the smart account's own address throws
33
+ // SCOPE_SELF_CALL.
34
+ //
35
+ // Anything the adapter genuinely cannot express (EVM calldata / value, unix
36
+ // expiry, etc.) is named in `uncovered` rather than silently dropped.
37
+
38
+ import type { ToolError } from '../../errors.ts'
39
+ import type {
40
+ IRCompare,
41
+ IRCondition,
42
+ IRPolicyRule,
43
+ IRScalarType,
44
+ IRSelector,
45
+ PolicyIR,
46
+ } from '../../ir/types.ts'
47
+ import { encodePredicate } from '../../predicate/encode.ts'
48
+ import type {
49
+ CompileResult,
50
+ CustodyAdapter,
51
+ CustodyCapabilities,
52
+ SimulationResult,
53
+ } from '../../seams/types.ts'
54
+ import type {
55
+ ContextRuleDraft,
56
+ Network,
57
+ ParseConfidence,
58
+ PolicyDocument,
59
+ PolicyRef,
60
+ PredicateLeaf,
61
+ PredicateNode,
62
+ ProposedPolicy,
63
+ } from '../../types.ts'
64
+
65
+ /** [VERIFY] NOT a real deployed address. The interpreter is a per-network
66
+ * deploy artifact we do not have yet; install is a later phase. */
67
+ export const PLACEHOLDER_INTERPRETER_ADDRESS = 'VERIFY-interpreter-address'
68
+
69
+ /** Wasm-level oracle defaults (mirrors INTERPRETER_INSTALL_PARAMS.md OracleParams).
70
+ * Per-policy overrides may TIGHTEN only - they may never exceed these. */
71
+ export const ORACLE_DEFAULTS = {
72
+ maxStalenessSeconds: 600,
73
+ maxDeviationBps: 200,
74
+ } as const
75
+
76
+ export interface InterpreterAdapterConfig {
77
+ network: Network
78
+ /** Per-rule install nonce (first install = 1; replay-protected). */
79
+ installNonce: number
80
+ /** The smart account this interpreter policy will be installed against. Used
81
+ * by the self-call gate: any `in`-allowlist containing this address is
82
+ * rejected as `SCOPE_SELF_CALL`. */
83
+ smartAccountAddress: string
84
+ /** Optional per-policy oracle overrides. Must TIGHTEN vs ORACLE_DEFAULTS
85
+ * (i.e. <= each default). A widening value throws ORACLE_PARAMS_OUT_OF_RANGE
86
+ * at compile time. */
87
+ oracleParams?: { maxStalenessSeconds?: number; maxDeviationBps?: number }
88
+ }
89
+
90
+ const CAPABILITIES: CustodyCapabilities = {
91
+ supportsSpendWindow: true,
92
+ supportsThreshold: false, // thresholds are the OZ adapter's job
93
+ supportsTimeExpiry: true, // via valid_until ledger expiry
94
+ supportsOraclePrice: true,
95
+ supportsInvocationCount: true,
96
+ supportsGeneralPredicate: true,
97
+ }
98
+
99
+ /** Parse confidence for a deterministic (non-decoded) input: full, with an
100
+ * empty unknown/opaque breakdown. A mandate needs no decoding, so the gate is
101
+ * not applicable and confidence is 1. */
102
+ const FULL_PARSE_CONFIDENCE: ParseConfidence = {
103
+ overall: 1,
104
+ knownContracts: [],
105
+ unknownContracts: [],
106
+ opaqueScVals: [],
107
+ thresholdUsed: 1,
108
+ }
109
+
110
+ export function createInterpreterAdapter(config: InterpreterAdapterConfig): CustodyAdapter {
111
+ return {
112
+ name: 'interpreter',
113
+ mode: 'enforce',
114
+ capabilities: () => ({ ...CAPABILITIES }),
115
+ compile: (ir) => compile(ir, config),
116
+ simulate: () => simulateStub(),
117
+ export: (ir) => canonicalStringify(ir),
118
+ }
119
+ }
120
+
121
+ /** Lower a single IR rule to the canonical pre-encoding `PredicateNode`. The
122
+ * orchestrator uses this to wire the self-verify + minimise pipeline: after
123
+ * `compile(ir)` succeeds (`covered === true`, `proposed` set), the
124
+ * orchestrator re-derives the PredicateNode via this helper to drive
125
+ * `minimize` and `runHarness` on the SAME shape the encoder saw. Pure and
126
+ * deterministic: same `rule + config` -> byte-identical PredicateNode. The
127
+ * `uncovered` list the adapter surfaces during compile is NOT re-derived
128
+ * here; callers that need it should use the result of `compile(ir)`. */
129
+ export function lowerRuleToPredicate(
130
+ rule: IRPolicyRule,
131
+ config: InterpreterAdapterConfig
132
+ ): PredicateNode {
133
+ return lowerRule(rule, config).predicate
134
+ }
135
+
136
+ function compile(ir: PolicyIR, config: InterpreterAdapterConfig): CompileResult {
137
+ // Tighten-only oracle-params gate (config-time). Widening -> throw at compile
138
+ // time before any lowering happens, so a misuse fails closed loudly.
139
+ assertOracleParamsTighten(config.oracleParams)
140
+
141
+ const firstRule = ir.rules[0]
142
+ if (!firstRule) {
143
+ return { covered: false, uncovered: ['empty PolicyIR (no rules to compile)'] }
144
+ }
145
+ if (ir.rules.length > 1) {
146
+ return {
147
+ covered: false,
148
+ uncovered: [
149
+ `multi-rule PolicyIR: ${ir.rules.length - 1} rule(s) beyond the first are not compiled (the interpreter adapter handles one rule per document in this slice)`,
150
+ ],
151
+ }
152
+ }
153
+
154
+ const lowered = lowerRule(firstRule, config)
155
+ if (lowered.uncovered.length > 0) {
156
+ return { covered: false, uncovered: lowered.uncovered }
157
+ }
158
+
159
+ const { encodedPredicate, predicateHash } = encodePredicate(lowered.predicate)
160
+ const policyDocument: PolicyDocument = {
161
+ grammarVersion: 1,
162
+ installNonce: config.installNonce,
163
+ encodedPredicate,
164
+ predicateHash,
165
+ ...(config.oracleParams ? { oracleParams: config.oracleParams } : {}),
166
+ }
167
+ const policyRef: PolicyRef = {
168
+ kind: 'interpreter',
169
+ interpreterAddress: PLACEHOLDER_INTERPRETER_ADDRESS,
170
+ predicateBlobBase64: encodedPredicate,
171
+ }
172
+ const proposed: ProposedPolicy = {
173
+ contextRule: lowered.contextRule,
174
+ policyDocuments: [policyDocument],
175
+ policyRefs: [policyRef],
176
+ parseConfidence: { ...FULL_PARSE_CONFIDENCE },
177
+ warnings: [],
178
+ ambiguities: [],
179
+ }
180
+ return { covered: true, uncovered: [], proposed }
181
+ }
182
+
183
+ interface LoweredRule {
184
+ predicate: PredicateNode
185
+ contextRule: ContextRuleDraft
186
+ uncovered: string[]
187
+ }
188
+
189
+ function lowerRule(rule: IRPolicyRule, config: InterpreterAdapterConfig): LoweredRule {
190
+ const uncovered: string[] = []
191
+
192
+ // scope -> context rule + sibling predicates. contract/method each become
193
+ // their own `eq` leaf and are merged into the top-level and alongside the
194
+ // constraints. This keeps the top-level shape `and` (mandatory per the oracle
195
+ // position rule and the canonical hash stability for `and`).
196
+ const scopeContract: string | undefined = rule.scope.contract
197
+ const scopeMethod: string | undefined = rule.scope.method
198
+ if (rule.scope.chainId !== undefined) {
199
+ uncovered.push(
200
+ `chainId \`${rule.scope.chainId}\` not bindable by the interpreter adapter (network is per-context, not per-rule)`
201
+ )
202
+ }
203
+
204
+ if (rule.roles.length > 0) {
205
+ uncovered.push(
206
+ `roles [${rule.roles.join(', ')}] dropped (role-to-signer mapping is a later phase; interpreter policies reference addresses, not role names)`
207
+ )
208
+ }
209
+
210
+ if (rule.guard) {
211
+ uncovered.push(
212
+ `guard: ${describeCondition(rule.guard)} (interpreter adapter currently treats guards as uncovered)`
213
+ )
214
+ }
215
+
216
+ // expiry -> context rule validUntilLedger only. Unix-timestamp expiry is
217
+ // honoured by the interpreter (the `valid_until` selector), but we surface
218
+ // it here as Path-B because the IR contract already says "OZ context rules
219
+ // expire by ledger sequence" and we keep one expiry model for both adapters.
220
+ let validUntilLedger: number | null = null
221
+ if (rule.expiry) {
222
+ if (rule.expiry.validUntilLedger !== undefined) {
223
+ validUntilLedger = rule.expiry.validUntilLedger
224
+ } else if (rule.expiry.validUntilUnixSeconds !== undefined) {
225
+ uncovered.push(
226
+ 'time expiry given as a unix timestamp (interpreter adapter currently lowers expiry only via the OZ context-rule validUntilLedger; supply expiry.validUntilLedger)'
227
+ )
228
+ }
229
+ }
230
+
231
+ // approval is the OZ adapter's job (it lowers to simple_threshold /
232
+ // weighted_threshold primitives). Surface it here so a caller that drops it
233
+ // through to the interpreter adapter sees an explicit uncovered entry
234
+ // instead of a silently-dropped M-of-N gate.
235
+ if (rule.approval) {
236
+ uncovered.push(
237
+ `approval threshold ${rule.approval.threshold} not emitted by the interpreter adapter (thresholds lower to OZ built-in primitives in the OZ adapter)`
238
+ )
239
+ }
240
+
241
+ // Pre-scan constraints: anything the interpreter adapter cannot express is
242
+ // named in `uncovered` and skipped from the predicate lowering. We surface
243
+ // these BEFORE lowering so the predicate is built from only the
244
+ // expressible subset.
245
+ const expressibleConstraints: IRCondition[] = []
246
+ for (const c of rule.constraints) {
247
+ const unsupp = unsupportedConstruct(c)
248
+ if (unsupp !== null) {
249
+ uncovered.push(unsupp)
250
+ } else {
251
+ expressibleConstraints.push(c)
252
+ }
253
+ }
254
+
255
+ // Build the top-level `and` of scope + expressible constraints. The
256
+ // top-level MUST be `and` so oracle leaves sit directly under it - the
257
+ // position rule is enforced inside `lowerCondition`.
258
+ const topChildren: PredicateNode[] = []
259
+ if (scopeContract !== undefined) {
260
+ topChildren.push({
261
+ op: 'eq',
262
+ left: { kind: 'call_contract' },
263
+ right: { kind: 'literal_address', value: scopeContract },
264
+ })
265
+ }
266
+ if (scopeMethod !== undefined) {
267
+ topChildren.push({
268
+ op: 'eq',
269
+ left: { kind: 'call_fn' },
270
+ right: { kind: 'literal_symbol', value: scopeMethod },
271
+ })
272
+ }
273
+ for (const c of expressibleConstraints) {
274
+ topChildren.push(lowerCondition(c, config))
275
+ }
276
+
277
+ const predicate: PredicateNode =
278
+ topChildren.length === 1 && topChildren[0] !== undefined
279
+ ? topChildren[0]
280
+ : { op: 'and', children: topChildren }
281
+
282
+ const contextRule: ContextRuleDraft = {
283
+ contextRuleType: { kind: 'default' },
284
+ name: 'interpreter',
285
+ validUntilLedger,
286
+ signers: [],
287
+ policies: [],
288
+ }
289
+
290
+ return { predicate, contextRule, uncovered }
291
+ }
292
+
293
+ /** Detect IR constructs the interpreter adapter cannot express; return a
294
+ * human-readable descriptor (or null if the construct IS expressible). Used
295
+ * by `lowerRule` to populate `uncovered` before lowering. */
296
+ function unsupportedConstruct(cond: IRCondition): string | null {
297
+ switch (cond.op) {
298
+ case 'in':
299
+ return cond.selector.kind === 'calldata' || cond.selector.kind === 'value'
300
+ ? `EVM \`${cond.selector.kind}\` selector on allowlist (predicate DSL)`
301
+ : null
302
+ case 'eq_seq':
303
+ return cond.selector.kind === 'calldata' || cond.selector.kind === 'value'
304
+ ? `EVM \`${cond.selector.kind}\` selector on ordered-sequence equality (predicate DSL)`
305
+ : null
306
+ case 'compare': {
307
+ const s = cond.compare.selector
308
+ if (s.kind === 'calldata') return 'EVM calldata comparison (predicate DSL)'
309
+ if (s.kind === 'value') return 'tx.value comparison (predicate DSL)'
310
+ return null
311
+ }
312
+ case 'and':
313
+ case 'or':
314
+ case 'not':
315
+ return null
316
+ }
317
+ }
318
+
319
+ /** Lower one IR condition to a PredicateNode. Enforces the oracle position
320
+ * rule (oracle_price leaves must sit directly under the top-level `and`) and
321
+ * the self-call rule (`in` allowlist / `compare eq` vs the smart account
322
+ * address -> SCOPE_SELF_CALL). */
323
+ function lowerCondition(cond: IRCondition, config: InterpreterAdapterConfig): PredicateNode {
324
+ switch (cond.op) {
325
+ case 'and':
326
+ return { op: 'and', children: cond.children.map((c) => lowerCondition(c, config)) }
327
+ case 'or':
328
+ // `or` at this depth: oracle_price anywhere inside is invalid (would
329
+ // not be a direct child of the top-level `and`).
330
+ assertNoOracleDescendants(cond)
331
+ return { op: 'or', children: cond.children.map((c) => lowerCondition(c, config)) }
332
+ case 'not':
333
+ // `not` at this depth: oracle_price anywhere inside is invalid.
334
+ assertNoOracleDescendants(cond)
335
+ return { op: 'not', child: lowerCondition(cond.child, config) }
336
+ case 'in': {
337
+ assertNoOracleDescendants(cond)
338
+ for (const v of cond.values) {
339
+ assertNotSelfCallAddress(v, config)
340
+ }
341
+ // `in` is PURE set membership; the encoder sorts the haystack. An exact
342
+ // ordered sequence (e.g. swap hop path) is expressed as `eq_seq` and
343
+ // lowers to `eq(selector, literal_vec)` instead - never to `in` with an
344
+ // `ordered` flag.
345
+ return {
346
+ op: 'in',
347
+ needle: lowerSelector(cond.selector),
348
+ haystack: cond.values.map((v) => literalFromScalar(v, selectorScalarType(cond.selector))),
349
+ }
350
+ }
351
+ case 'eq_seq': {
352
+ assertNoOracleDescendants(cond)
353
+ for (const v of cond.values) {
354
+ assertNotSelfCallAddress(v, config)
355
+ }
356
+ // Exact ordered sequence equality: the right-hand side is a literal_vec
357
+ // whose element order is preserved verbatim by the encoder. `eq` does
358
+ // deep equality at evaluate time - this is the ONLY way to express an
359
+ // exact ordered sequence in the predicate grammar (the path of a swap).
360
+ return {
361
+ op: 'eq',
362
+ left: lowerSelector(cond.selector),
363
+ right: {
364
+ kind: 'literal_vec',
365
+ elements: cond.values.map((v) => literalFromScalar(v, selectorScalarType(cond.selector))),
366
+ },
367
+ }
368
+ }
369
+ case 'compare': {
370
+ // Self-call on an address eq.
371
+ if (
372
+ cond.compare.operator === 'eq' &&
373
+ cond.compare.selector.kind === 'arg' &&
374
+ cond.compare.selector.scalarType === 'address'
375
+ ) {
376
+ assertNotSelfCallAddress(cond.compare.value, config)
377
+ }
378
+ return {
379
+ op: cond.compare.operator,
380
+ left: lowerSelector(cond.compare.selector),
381
+ right: literalFromIRCompare(cond.compare),
382
+ }
383
+ }
384
+ }
385
+ }
386
+
387
+ /** Lower an IR selector to the matching PredicateLeaf. */
388
+ function lowerSelector(s: IRSelector): PredicateLeaf {
389
+ switch (s.kind) {
390
+ case 'arg':
391
+ return { kind: 'call_arg', index: s.argIndex }
392
+ case 'amount':
393
+ return { kind: 'amount', token: s.token }
394
+ case 'window_spent':
395
+ return { kind: 'window_spent', token: s.token, windowSeconds: s.windowSeconds }
396
+ case 'invocation_count':
397
+ return { kind: 'invocation_count_in_window', windowSecs: s.windowSeconds }
398
+ case 'now':
399
+ return { kind: 'now' }
400
+ case 'valid_until':
401
+ return { kind: 'valid_until' }
402
+ case 'oracle_price':
403
+ return { kind: 'oracle_price', asset: s.asset }
404
+ case 'calldata':
405
+ case 'value':
406
+ // Unreachable: the caller flagged these as Path-B before reaching here.
407
+ throw toolError(
408
+ 'SYNTHESIS_ERROR',
409
+ `selector kind \`${s.kind}\` is not lowerable to a predicate leaf`
410
+ )
411
+ }
412
+ }
413
+
414
+ /** Build a literal leaf from the right-hand side of an IRCompare, mapping the
415
+ * selector kind to the matching `literal_*` kind. The IR compare value is a
416
+ * raw string (i128-safe); the selector kind fixes the canonical wire type:
417
+ * - arg -> IR scalarType (set by the recorder/parser)
418
+ * - amount -> i128 (canonical Stellar token amount encoding)
419
+ * - window_spent -> i128 (canonical amount encoding)
420
+ * - oracle_price -> i128 (canonical price encoding)
421
+ * - invocation_count -> u32 (counts are small non-negative integers)
422
+ * - now / valid_until -> u64 (unix timestamps in seconds) */
423
+ function literalFromIRCompare(c: IRCompare): PredicateLeaf {
424
+ const scalarType: IRScalarType =
425
+ c.selector.kind === 'arg' ? c.selector.scalarType : literalScalarForSelector(c.selector.kind)
426
+ return literalFromScalar(c.value, scalarType)
427
+ }
428
+
429
+ function literalScalarForSelector(kind: IRSelector['kind']): IRScalarType {
430
+ switch (kind) {
431
+ case 'amount':
432
+ case 'window_spent':
433
+ case 'oracle_price':
434
+ return 'i128'
435
+ case 'invocation_count':
436
+ return 'u32'
437
+ case 'now':
438
+ case 'valid_until':
439
+ return 'u64'
440
+ case 'arg':
441
+ case 'calldata':
442
+ case 'value':
443
+ // arg -> caller handles scalarType; calldata/value -> unreachable (Path-B).
444
+ return 'i128'
445
+ }
446
+ }
447
+
448
+ /** Build a literal leaf from a raw string value + an IRScalarType hint. */
449
+ function literalFromScalar(value: string, scalarType: IRScalarType): PredicateLeaf {
450
+ switch (scalarType) {
451
+ case 'address':
452
+ return { kind: 'literal_address', value }
453
+ case 'i128':
454
+ case 'u128':
455
+ return { kind: 'literal_i128', value }
456
+ case 'u32':
457
+ return { kind: 'literal_u32', value: Number.parseInt(value, 10) }
458
+ case 'u64':
459
+ case 'i64':
460
+ return { kind: 'literal_u64', value }
461
+ case 'symbol':
462
+ return { kind: 'literal_symbol', value }
463
+ case 'bytes':
464
+ return { kind: 'literal_bytes', value }
465
+ case 'bool':
466
+ throw toolError(
467
+ 'MALFORMED_PREDICATE',
468
+ `boolean literal not supported in v1 predicate grammar`
469
+ )
470
+ }
471
+ }
472
+
473
+ /** Scalar type of an IRSelector for the purpose of building literal leaves
474
+ * (the right-hand side of `eq` / elements of an `in` haystack / elements of
475
+ * a `literal_vec`). Mirrors `literalScalarForSelector` for OZ extensions and
476
+ * uses the selector's own `scalarType` for `arg` selectors. */
477
+ function selectorScalarType(selector: IRSelector): IRScalarType {
478
+ if (selector.kind === 'arg') return selector.scalarType
479
+ return literalScalarForSelector(selector.kind)
480
+ }
481
+
482
+ /** Walk a condition tree and throw if any oracle_price leaf is found anywhere
483
+ * inside. Used by `lowerCondition` for `not`, `or`, and `in` - the three
484
+ * positions where oracle leaves would not be direct children of the
485
+ * top-level `and`. */
486
+ function assertNoOracleDescendants(node: IRCondition): void {
487
+ if (containsOracle(node)) {
488
+ throw toolError(
489
+ 'ORACLE_LEAF_INVALID_POSITION',
490
+ 'oracle_price leaves must sit directly under the top-level `and`'
491
+ )
492
+ }
493
+ }
494
+
495
+ function containsOracle(node: IRCondition): boolean {
496
+ switch (node.op) {
497
+ case 'compare':
498
+ return node.compare.selector.kind === 'oracle_price'
499
+ case 'in':
500
+ return node.selector.kind === 'oracle_price'
501
+ case 'eq_seq':
502
+ return node.selector.kind === 'oracle_price'
503
+ case 'not':
504
+ return containsOracle(node.child)
505
+ case 'and':
506
+ case 'or':
507
+ return node.children.some(containsOracle)
508
+ }
509
+ }
510
+
511
+ /** Reject a value that targets the smart account's own address (a self-call
512
+ * is a structural privilege-escalation hole the interpreter forbids). */
513
+ function assertNotSelfCallAddress(value: string, config: InterpreterAdapterConfig): void {
514
+ if (value === config.smartAccountAddress) {
515
+ throw toolError(
516
+ 'SCOPE_SELF_CALL',
517
+ `value \`${value}\` is the smart account's own address (self-call in an allowlist / compare is rejected)`
518
+ )
519
+ }
520
+ }
521
+
522
+ /** Tighten-only oracle-params gate. Any widening value (above the wasm-level
523
+ * defaults) throws ORACLE_PARAMS_OUT_OF_RANGE at compile time. */
524
+ function assertOracleParamsTighten(params: InterpreterAdapterConfig['oracleParams']): void {
525
+ if (!params) return
526
+ if (
527
+ params.maxStalenessSeconds !== undefined &&
528
+ params.maxStalenessSeconds > ORACLE_DEFAULTS.maxStalenessSeconds
529
+ ) {
530
+ throw toolError(
531
+ 'ORACLE_PARAMS_OUT_OF_RANGE',
532
+ `maxStalenessSeconds ${params.maxStalenessSeconds} exceeds default ${ORACLE_DEFAULTS.maxStalenessSeconds}`
533
+ )
534
+ }
535
+ if (
536
+ params.maxDeviationBps !== undefined &&
537
+ params.maxDeviationBps > ORACLE_DEFAULTS.maxDeviationBps
538
+ ) {
539
+ throw toolError(
540
+ 'ORACLE_PARAMS_OUT_OF_RANGE',
541
+ `maxDeviationBps ${params.maxDeviationBps} exceeds default ${ORACLE_DEFAULTS.maxDeviationBps}`
542
+ )
543
+ }
544
+ }
545
+
546
+ /** Human-readable descriptor for a construct the interpreter adapter cannot
547
+ * express. Mirrors the OZ adapter's `describeCondition` for parity. */
548
+ function describeCondition(cond: IRCondition): string {
549
+ switch (cond.op) {
550
+ case 'in':
551
+ return `value allowlist on ${describeSelector(cond.selector)} (predicate DSL)`
552
+ case 'eq_seq':
553
+ return `exact ordered sequence on ${describeSelector(cond.selector)} (predicate DSL)`
554
+ case 'not':
555
+ return 'negated condition (predicate DSL)'
556
+ case 'and':
557
+ case 'or':
558
+ return `nested ${cond.op} condition (predicate DSL)`
559
+ case 'compare': {
560
+ const s = cond.compare.selector
561
+ switch (s.kind) {
562
+ case 'oracle_price':
563
+ return `oracle price condition on ${s.asset}`
564
+ case 'invocation_count':
565
+ return `invocation-count window (${s.windowSeconds}s) condition`
566
+ case 'window_spent':
567
+ return `spend-window comparison with operator '${cond.compare.operator}'`
568
+ case 'amount':
569
+ return `per-call amount comparison on ${s.token}`
570
+ case 'arg':
571
+ return `argument comparison on arg ${s.argIndex}`
572
+ case 'calldata':
573
+ return 'EVM calldata comparison'
574
+ case 'value':
575
+ return 'tx.value comparison'
576
+ case 'now':
577
+ case 'valid_until':
578
+ return 'time comparison'
579
+ }
580
+ }
581
+ }
582
+ }
583
+
584
+ function describeSelector(s: IRSelector): string {
585
+ switch (s.kind) {
586
+ case 'arg':
587
+ return `arg ${s.argIndex}`
588
+ case 'amount':
589
+ return `amount(${s.token})`
590
+ case 'window_spent':
591
+ return `window_spent(${s.token})`
592
+ case 'oracle_price':
593
+ return `oracle_price(${s.asset})`
594
+ case 'invocation_count':
595
+ return `invocation_count(${s.windowSeconds}s)`
596
+ case 'calldata':
597
+ return `calldata[${s.offset}:${s.offset + s.length}]`
598
+ default:
599
+ return s.kind
600
+ }
601
+ }
602
+
603
+ function simulateStub(): SimulationResult {
604
+ return {
605
+ backend: 'ts-model',
606
+ permitted: null,
607
+ evaluations: [],
608
+ notes: ['stub: real permit/deny semantics wiring is a later phase'],
609
+ }
610
+ }
611
+
612
+ /** Canonical JSON with recursively sorted object keys (stable across runs). */
613
+ function canonicalStringify(value: unknown): string {
614
+ return JSON.stringify(sortKeys(value))
615
+ }
616
+
617
+ function sortKeys(value: unknown): unknown {
618
+ if (Array.isArray(value)) return value.map(sortKeys)
619
+ if (value && typeof value === 'object') {
620
+ const out: Record<string, unknown> = {}
621
+ for (const key of Object.keys(value as Record<string, unknown>).sort()) {
622
+ out[key] = sortKeys((value as Record<string, unknown>)[key])
623
+ }
624
+ return out
625
+ }
626
+ return value
627
+ }
628
+
629
+ /** Build a synthetic Error carrying the ToolError code/severity/retryable
630
+ * fields the existing ToolError shape uses (the encoder pattern). Callers
631
+ * inspect `e.code` in catch blocks. */
632
+ function toolError(code: ToolError['code'], message: string): Error {
633
+ const err = new Error(message) as Error & {
634
+ code: ToolError['code']
635
+ severity: ToolError['severity']
636
+ retryable: boolean
637
+ }
638
+ err.code = code
639
+ err.severity = 'error'
640
+ err.retryable = false
641
+ return err
642
+ }
@@ -0,0 +1,8 @@
1
+ // src/adapters/interpreter/index.ts - re-export the interpreter-policy CustodyAdapter.
2
+
3
+ export {
4
+ createInterpreterAdapter,
5
+ type InterpreterAdapterConfig,
6
+ ORACLE_DEFAULTS,
7
+ PLACEHOLDER_INTERPRETER_ADDRESS,
8
+ } from './adapter.ts'
@@ -287,6 +287,8 @@ function describeCondition(cond: IRCondition): string {
287
287
  switch (cond.op) {
288
288
  case 'in':
289
289
  return `value allowlist on ${describeSelector(cond.selector)} (arg allowlist)`
290
+ case 'eq_seq':
291
+ return `exact ordered sequence on ${describeSelector(cond.selector)} (OZ built-ins cannot express an exact vector)`
290
292
  case 'not':
291
293
  return 'negated condition (predicate DSL)'
292
294
  case 'and':