@crediolabs/policy-synth 0.2.0 → 0.3.1

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 (249) hide show
  1. package/README.md +4 -4
  2. package/dist/adapters/interpreter/adapter.d.ts +19 -25
  3. package/dist/adapters/interpreter/adapter.js +54 -487
  4. package/dist/errors.d.ts +1 -1
  5. package/dist/index.d.ts +1 -4
  6. package/dist/index.js +1 -4
  7. package/dist/install/build-add-context-rule.d.ts +3 -19
  8. package/dist/install/build-add-context-rule.js +3 -98
  9. package/dist/install/build-install-policy.d.ts +4 -53
  10. package/dist/install/build-install-policy.js +44 -123
  11. package/dist/install/index.d.ts +0 -2
  12. package/dist/install/index.js +0 -7
  13. package/dist/predicate/decode.d.ts +1 -1
  14. package/dist/predicate/decode.js +2 -70
  15. package/dist/predicate/encode.js +45 -229
  16. package/dist/predicate/from-json.js +1 -42
  17. package/dist/record/decode.js +3 -8
  18. package/dist/record/freshness.d.ts +17 -11
  19. package/dist/record/freshness.js +28 -18
  20. package/dist/review-card/builder.d.ts +4 -3
  21. package/dist/review-card/builder.js +18 -162
  22. package/dist/review-card/cross-check.js +2 -105
  23. package/dist/review-card/render-leaf.d.ts +4 -0
  24. package/dist/review-card/render-leaf.js +47 -0
  25. package/dist/run/index.d.ts +36 -139
  26. package/dist/run/index.js +125 -437
  27. package/dist/run/schemas.d.ts +168 -1929
  28. package/dist/run/schemas.js +40 -269
  29. package/dist/{synth → simulate}/deny-cases.d.ts +4 -8
  30. package/dist/simulate/deny-cases.js +282 -0
  31. package/dist/simulate/evaluate.d.ts +18 -0
  32. package/dist/simulate/evaluate.js +271 -0
  33. package/dist/simulate/index.d.ts +4 -0
  34. package/dist/simulate/index.js +8 -0
  35. package/dist/synth/compose-from-recording.d.ts +24 -51
  36. package/dist/synth/compose-from-recording.js +120 -282
  37. package/dist/synth/index.d.ts +0 -5
  38. package/dist/synth/index.js +0 -5
  39. package/dist/synth/synthesize-from-recording.d.ts +1 -29
  40. package/dist/synth/synthesize-from-recording.js +41 -356
  41. package/dist/types.d.ts +8 -60
  42. package/dist/types.js +5 -2
  43. package/dist-cjs/adapters/interpreter/adapter.d.ts +19 -25
  44. package/dist-cjs/adapters/interpreter/adapter.js +56 -489
  45. package/dist-cjs/errors.d.ts +1 -1
  46. package/dist-cjs/index.d.ts +1 -4
  47. package/dist-cjs/index.js +1 -4
  48. package/dist-cjs/install/build-add-context-rule.d.ts +3 -19
  49. package/dist-cjs/install/build-add-context-rule.js +1 -97
  50. package/dist-cjs/install/build-install-policy.d.ts +4 -53
  51. package/dist-cjs/install/build-install-policy.js +44 -122
  52. package/dist-cjs/install/index.d.ts +0 -2
  53. package/dist-cjs/install/index.js +2 -23
  54. package/dist-cjs/predicate/decode.d.ts +1 -1
  55. package/dist-cjs/predicate/decode.js +2 -70
  56. package/dist-cjs/predicate/encode.js +45 -229
  57. package/dist-cjs/predicate/from-json.js +1 -42
  58. package/dist-cjs/record/decode.js +3 -8
  59. package/dist-cjs/record/freshness.d.ts +17 -11
  60. package/dist-cjs/record/freshness.js +28 -18
  61. package/dist-cjs/review-card/builder.d.ts +4 -3
  62. package/dist-cjs/review-card/builder.js +23 -167
  63. package/dist-cjs/review-card/cross-check.js +7 -110
  64. package/dist-cjs/review-card/render-leaf.d.ts +4 -0
  65. package/dist-cjs/review-card/render-leaf.js +52 -0
  66. package/dist-cjs/run/index.d.ts +36 -139
  67. package/dist-cjs/run/index.js +125 -444
  68. package/dist-cjs/run/schemas.d.ts +168 -1929
  69. package/dist-cjs/run/schemas.js +41 -270
  70. package/dist-cjs/{synth → simulate}/deny-cases.d.ts +4 -8
  71. package/dist-cjs/simulate/deny-cases.js +286 -0
  72. package/dist-cjs/simulate/evaluate.d.ts +18 -0
  73. package/dist-cjs/simulate/evaluate.js +274 -0
  74. package/dist-cjs/simulate/index.d.ts +4 -0
  75. package/dist-cjs/simulate/index.js +13 -0
  76. package/dist-cjs/synth/compose-from-recording.d.ts +24 -51
  77. package/dist-cjs/synth/compose-from-recording.js +120 -282
  78. package/dist-cjs/synth/index.d.ts +0 -5
  79. package/dist-cjs/synth/index.js +1 -11
  80. package/dist-cjs/synth/synthesize-from-recording.d.ts +1 -29
  81. package/dist-cjs/synth/synthesize-from-recording.js +39 -354
  82. package/dist-cjs/types.d.ts +8 -60
  83. package/dist-cjs/types.js +6 -3
  84. package/package.json +5 -5
  85. package/src/adapters/interpreter/adapter.ts +76 -572
  86. package/src/errors.ts +0 -19
  87. package/src/index.ts +1 -4
  88. package/src/install/build-add-context-rule.ts +5 -139
  89. package/src/install/build-install-policy.ts +93 -214
  90. package/src/install/index.ts +0 -34
  91. package/src/predicate/decode.ts +2 -70
  92. package/src/predicate/encode.ts +49 -261
  93. package/src/predicate/from-json.ts +1 -43
  94. package/src/record/decode.ts +3 -8
  95. package/src/record/freshness.ts +29 -18
  96. package/src/review-card/builder.ts +19 -168
  97. package/src/review-card/cross-check.ts +3 -105
  98. package/src/review-card/render-leaf.ts +48 -0
  99. package/src/run/index.ts +144 -572
  100. package/src/run/schemas.ts +42 -291
  101. package/src/simulate/deny-cases.ts +334 -0
  102. package/src/simulate/evaluate.ts +284 -0
  103. package/src/simulate/index.ts +11 -0
  104. package/src/synth/compose-from-recording.ts +148 -347
  105. package/src/synth/index.ts +0 -13
  106. package/src/synth/synthesize-from-recording.ts +43 -456
  107. package/src/types.ts +13 -49
  108. package/dist/adapters/interpreter/index.d.ts +0 -1
  109. package/dist/adapters/interpreter/index.js +0 -2
  110. package/dist/adapters/oz/adapter.d.ts +0 -20
  111. package/dist/adapters/oz/adapter.js +0 -295
  112. package/dist/adapters/oz/index.d.ts +0 -1
  113. package/dist/adapters/oz/index.js +0 -2
  114. package/dist/codegen/compile-gate.d.ts +0 -33
  115. package/dist/codegen/compile-gate.js +0 -124
  116. package/dist/codegen/index.d.ts +0 -2
  117. package/dist/codegen/index.js +0 -8
  118. package/dist/codegen/template.d.ts +0 -18
  119. package/dist/codegen/template.js +0 -148
  120. package/dist/install/authority-overlap.d.ts +0 -134
  121. package/dist/install/authority-overlap.js +0 -0
  122. package/dist/install/build-install-predicate.d.ts +0 -96
  123. package/dist/install/build-install-predicate.js +0 -444
  124. package/dist/install/build-merge-policy.d.ts +0 -70
  125. package/dist/install/build-merge-policy.js +0 -130
  126. package/dist/install/plan-merge-policy.d.ts +0 -49
  127. package/dist/install/plan-merge-policy.js +0 -86
  128. package/dist/install/read-account-rules.d.ts +0 -100
  129. package/dist/install/read-account-rules.js +0 -283
  130. package/dist/ir/index.d.ts +0 -1
  131. package/dist/ir/index.js +0 -2
  132. package/dist/ir/types.d.ts +0 -140
  133. package/dist/ir/types.js +0 -11
  134. package/dist/mandate/index.d.ts +0 -2
  135. package/dist/mandate/index.js +0 -2
  136. package/dist/mandate/to-ir.d.ts +0 -3
  137. package/dist/mandate/to-ir.js +0 -60
  138. package/dist/mandate/types.d.ts +0 -20
  139. package/dist/mandate/types.js +0 -8
  140. package/dist/seams/index.d.ts +0 -1
  141. package/dist/seams/index.js +0 -2
  142. package/dist/seams/types.d.ts +0 -66
  143. package/dist/seams/types.js +0 -11
  144. package/dist/synth/deny-cases.js +0 -562
  145. package/dist/synth/evaluate.d.ts +0 -39
  146. package/dist/synth/evaluate.js +0 -551
  147. package/dist/synth/harness.d.ts +0 -28
  148. package/dist/synth/harness.js +0 -47
  149. package/dist/synth/minimize.d.ts +0 -4
  150. package/dist/synth/minimize.js +0 -38
  151. package/dist/synth/permit-context.d.ts +0 -15
  152. package/dist/synth/permit-context.js +0 -116
  153. package/dist/synth/predicate-literals.d.ts +0 -5
  154. package/dist/synth/predicate-literals.js +0 -25
  155. package/dist/synth/synthesize-from-mandate.d.ts +0 -20
  156. package/dist/synth/synthesize-from-mandate.js +0 -59
  157. package/dist/verify/envelope.d.ts +0 -15
  158. package/dist/verify/envelope.js +0 -22
  159. package/dist/verify/index.d.ts +0 -3
  160. package/dist/verify/index.js +0 -3
  161. package/dist/verify/simulate.d.ts +0 -31
  162. package/dist/verify/simulate.js +0 -258
  163. package/dist/verify/verify.d.ts +0 -21
  164. package/dist/verify/verify.js +0 -189
  165. package/dist-cjs/adapters/interpreter/index.d.ts +0 -1
  166. package/dist-cjs/adapters/interpreter/index.js +0 -8
  167. package/dist-cjs/adapters/oz/adapter.d.ts +0 -20
  168. package/dist-cjs/adapters/oz/adapter.js +0 -300
  169. package/dist-cjs/adapters/oz/index.d.ts +0 -1
  170. package/dist-cjs/adapters/oz/index.js +0 -8
  171. package/dist-cjs/codegen/compile-gate.d.ts +0 -33
  172. package/dist-cjs/codegen/compile-gate.js +0 -128
  173. package/dist-cjs/codegen/index.d.ts +0 -2
  174. package/dist-cjs/codegen/index.js +0 -14
  175. package/dist-cjs/codegen/template.d.ts +0 -18
  176. package/dist-cjs/codegen/template.js +0 -151
  177. package/dist-cjs/install/authority-overlap.d.ts +0 -134
  178. package/dist-cjs/install/authority-overlap.js +0 -0
  179. package/dist-cjs/install/build-install-predicate.d.ts +0 -96
  180. package/dist-cjs/install/build-install-predicate.js +0 -479
  181. package/dist-cjs/install/build-merge-policy.d.ts +0 -70
  182. package/dist-cjs/install/build-merge-policy.js +0 -134
  183. package/dist-cjs/install/plan-merge-policy.d.ts +0 -49
  184. package/dist-cjs/install/plan-merge-policy.js +0 -90
  185. package/dist-cjs/install/read-account-rules.d.ts +0 -100
  186. package/dist-cjs/install/read-account-rules.js +0 -296
  187. package/dist-cjs/ir/index.d.ts +0 -1
  188. package/dist-cjs/ir/index.js +0 -3
  189. package/dist-cjs/ir/types.d.ts +0 -140
  190. package/dist-cjs/ir/types.js +0 -12
  191. package/dist-cjs/mandate/index.d.ts +0 -2
  192. package/dist-cjs/mandate/index.js +0 -6
  193. package/dist-cjs/mandate/to-ir.d.ts +0 -3
  194. package/dist-cjs/mandate/to-ir.js +0 -63
  195. package/dist-cjs/mandate/types.d.ts +0 -20
  196. package/dist-cjs/mandate/types.js +0 -9
  197. package/dist-cjs/seams/index.d.ts +0 -1
  198. package/dist-cjs/seams/index.js +0 -3
  199. package/dist-cjs/seams/types.d.ts +0 -66
  200. package/dist-cjs/seams/types.js +0 -12
  201. package/dist-cjs/synth/deny-cases.js +0 -568
  202. package/dist-cjs/synth/evaluate.d.ts +0 -39
  203. package/dist-cjs/synth/evaluate.js +0 -554
  204. package/dist-cjs/synth/harness.d.ts +0 -28
  205. package/dist-cjs/synth/harness.js +0 -50
  206. package/dist-cjs/synth/minimize.d.ts +0 -4
  207. package/dist-cjs/synth/minimize.js +0 -41
  208. package/dist-cjs/synth/permit-context.d.ts +0 -15
  209. package/dist-cjs/synth/permit-context.js +0 -119
  210. package/dist-cjs/synth/predicate-literals.d.ts +0 -5
  211. package/dist-cjs/synth/predicate-literals.js +0 -28
  212. package/dist-cjs/synth/synthesize-from-mandate.d.ts +0 -20
  213. package/dist-cjs/synth/synthesize-from-mandate.js +0 -62
  214. package/dist-cjs/verify/envelope.d.ts +0 -15
  215. package/dist-cjs/verify/envelope.js +0 -23
  216. package/dist-cjs/verify/index.d.ts +0 -3
  217. package/dist-cjs/verify/index.js +0 -8
  218. package/dist-cjs/verify/simulate.d.ts +0 -31
  219. package/dist-cjs/verify/simulate.js +0 -261
  220. package/dist-cjs/verify/verify.d.ts +0 -21
  221. package/dist-cjs/verify/verify.js +0 -192
  222. package/src/adapters/interpreter/index.ts +0 -8
  223. package/src/adapters/oz/adapter.ts +0 -376
  224. package/src/adapters/oz/index.ts +0 -9
  225. package/src/codegen/compile-gate.ts +0 -167
  226. package/src/codegen/index.ts +0 -17
  227. package/src/codegen/template.ts +0 -165
  228. package/src/install/authority-overlap.ts +0 -0
  229. package/src/install/build-merge-policy.ts +0 -219
  230. package/src/install/plan-merge-policy.ts +0 -133
  231. package/src/install/read-account-rules.ts +0 -376
  232. package/src/ir/index.ts +0 -13
  233. package/src/ir/types.ts +0 -132
  234. package/src/mandate/index.ts +0 -4
  235. package/src/mandate/to-ir.ts +0 -71
  236. package/src/mandate/types.ts +0 -21
  237. package/src/seams/index.ts +0 -11
  238. package/src/seams/types.ts +0 -81
  239. package/src/synth/deny-cases.ts +0 -663
  240. package/src/synth/evaluate.ts +0 -613
  241. package/src/synth/harness.ts +0 -68
  242. package/src/synth/minimize.ts +0 -48
  243. package/src/synth/permit-context.ts +0 -136
  244. package/src/synth/predicate-literals.ts +0 -27
  245. package/src/synth/synthesize-from-mandate.ts +0 -82
  246. package/src/verify/envelope.ts +0 -28
  247. package/src/verify/index.ts +0 -5
  248. package/src/verify/simulate.ts +0 -311
  249. package/src/verify/verify.ts +0 -243
package/src/types.ts CHANGED
@@ -64,13 +64,11 @@ export const MAX_SCVAL_CLONE_DEPTH = 30 as const
64
64
  * - MAX_DEPTH = 5: 3 walkthroughs need depth 2; budget = 2x growth + 1 for `not` chain.
65
65
  * - MAX_LEAVES = 200: allowlists (recipients, paths) typically < 100; budget = 2x + 1 nested allowlist.
66
66
  * - MAX_PREDICATE_BYTES = 32 KB: well under the per-ledger-entry 64 KB persistent-storage limit.
67
- * - MAX_ORACLE_READS = 6: two-round confirmation per asset consumes 2 reads; cap accommodates a predicate that references up to 3 unique oracle assets (3 * 2 = 6 reads). Stays a fail-closed install-time cap.
68
67
  * - MAX_IN_OPERAND_COUNT = 32: allowlist < 32 is a UX-natural bound. */
69
68
  export const PREDICATE_CAPS = {
70
69
  MAX_DEPTH: 5,
71
70
  MAX_LEAVES: 200,
72
71
  MAX_PREDICATE_BYTES: 32 * 1024,
73
- MAX_ORACLE_READS: 6,
74
72
  MAX_IN_OPERAND_COUNT: 32,
75
73
  } as const
76
74
 
@@ -97,15 +95,23 @@ export type SignerDraft =
97
95
  | { kind: 'external'; verifier: string; keyBytes: string }
98
96
 
99
97
  /** Reference to one policy attached to a context rule. */
100
- export type PolicyRef =
101
- | { kind: 'oz_builtin'; primitive: OZPrimitiveConfig; instanceAddress: string }
102
- | { kind: 'interpreter'; interpreterAddress: string; predicateBlobBase64: string }
98
+ export type PolicyRef = {
99
+ kind: 'interpreter'
100
+ interpreterAddress: string
101
+ predicateBlobBase64: string
102
+ }
103
+
104
+ /** Grammar version baked into the interpreter wasm, mirroring `SELF_VERSION` in
105
+ * `contracts/policy-interpreter/src/version.rs`. Every value this package puts on
106
+ * the wire derives from here; `grammar-version-parity.test.ts` pins it to the
107
+ * contract so a skew cannot pass a green test run. */
108
+ export const GRAMMAR_VERSION = 3 as const
103
109
 
104
110
  /** A serialised predicate document stored against a (smart_account, rule_id) pair. */
105
111
  export interface PolicyDocument {
106
112
  /** Grammar version baked into the interpreter wasm. Fail-closed strict match at install
107
113
  * AND at evaluate (defence in depth). NOT the per-edit revision. */
108
- grammarVersion: 1
114
+ grammarVersion: typeof GRAMMAR_VERSION
109
115
  /** Per-rule install nonce. Must equal the interpreter's stored nonce + 1 at install.
110
116
  * First install accepts nonce = 1 with stored nonce = 0. Re-install is structurally
111
117
  * possible by incrementing the nonce; uninstall removes the nonce with state so a
@@ -117,24 +123,13 @@ export interface PolicyDocument {
117
123
  /** Hash of the post-canonicalisation bytes of encodedPredicate. Stored alongside the
118
124
  * doc and re-verified at evaluate. */
119
125
  predicateHash: string
120
- /** Per-policy overrides of oracle thresholds; absent = use defaults.
121
- * Overrides may TIGHTEN only (never widen) - the interpreter rejects any per-policy
122
- * value looser than the wasm-level defaults at install. */
123
- oracleParams?: {
124
- /** Seconds; must be <= MAX_ORACLE_STALENESS_SECONDS (600). */
125
- maxStalenessSeconds?: number
126
- /** Basis points; must be <= MAX_ORACLE_DEVIATION_BPS (200). */
127
- maxDeviationBps?: number
128
- }
129
126
  }
130
127
 
131
128
  /** The versioned predicate AST (interpreter side). Tagged union. */
132
129
  export type PredicateNode =
133
130
  | { op: 'and'; children: PredicateNode[] }
134
- | { op: 'or'; children: PredicateNode[] }
135
- | { op: 'not'; child: PredicateNode }
136
131
  | { op: 'eq'; left: PredicateLeaf; right: PredicateLeaf }
137
- | { op: 'lt' | 'lte' | 'gt' | 'gte'; left: PredicateLeaf; right: PredicateLeaf }
132
+ | { op: 'lte'; left: PredicateLeaf; right: PredicateLeaf }
138
133
  | {
139
134
  op: 'in'
140
135
  needle: PredicateLeaf
@@ -155,48 +150,18 @@ export type PredicateLeaf =
155
150
  // recorded ScVal type. A non-vec arg, missing element, missing field, or
156
151
  // type mismatch all DENY (fail-closed).
157
152
  | { kind: 'call_arg_field'; index: number; element: number; field: string }
158
- // `call_arg_scaled(index, num, den)` evaluates to `args[index] * num / den`
159
- // (truncating toward zero). The slippage-floor leaf: a swap policy
160
- // expresses `call_arg[out] >= call_arg_scaled(in, num, den)` as "the
161
- // minimum output must be at least this ratio of the input". `num`/`den`
162
- // are decimal strings on i128 (mirrors `literal_i128`); the contract
163
- // refuses `den == 0` and `num <= 0` / `den <= 0` at install.
164
- | { kind: 'call_arg_scaled'; index: number; num: string; den: string }
165
- // `call_sub_invocation[i]` is NOT in v1 grammar. OZ `Policy::enforce`
166
- // receives one `Context`, not a sub-invocation tree; sub-invocations live under
167
- // `InvokerContractAuthEntry::Contract(SubContractInvocation)`, not in the
168
- // enforce Context. Scope is per-authorized-context; a v1.1 sub-invocation
169
- // tree leaf is gated on the enforce-Context-shape spike result.
170
- | { kind: 'amount'; token: string }
171
- | { kind: 'window_spent'; token: string; windowSeconds: number }
172
- | { kind: 'now' }
173
- | { kind: 'valid_until' }
174
- | { kind: 'invocation_count_in_window'; windowSecs: number }
175
- | { kind: 'oracle_price'; asset: string } // Stellar Address (SAC address for SEP-41; XLM uses its network SAC)
176
- // The right-hand side of an oracle comparison. It carries its own decimal
177
- // basis because the contract cannot recover it: prices normalise to 9 dp, so
178
- // a raw 14-dp threshold is ~10^5 too large and `price <= threshold` becomes
179
- // trivially true. `value` is a decimal string on i128, like `literal_i128`.
180
- | { kind: 'oracle_threshold'; value: string; decimals: number }
181
153
  // Literal leaves: bare ScVal on the wire (no selector-tuple wrapper). Right-hand side of
182
154
  // comparisons, elements of `in` haystacks, and operands to future arithmetic nodes.
183
155
  | { kind: 'literal_address'; value: string }
184
156
  | { kind: 'literal_i128'; value: string }
185
157
  | { kind: 'literal_symbol'; value: string }
186
158
  | { kind: 'literal_u32'; value: number }
187
- | { kind: 'literal_u64'; value: string }
188
- | { kind: 'literal_bytes'; value: string } // hex string; wrapped as ScVal::Bytes at encode time
189
159
  // Exact ordered vector of literals (e.g. a swap hop path). Encodes to a bare
190
160
  // ScVal::Vec with the caller's order preserved verbatim - the order IS the
191
161
  // semantic. An exact ordered sequence equality is expressed by `eq(selector,
192
162
  // literal_vec([...]))`. `in` is reserved for pure set membership (sorted).
193
163
  | { kind: 'literal_vec'; elements: PredicateLeaf[] }
194
164
 
195
- export interface OZPrimitiveConfig {
196
- primitive: 'spending_limit' | 'simple_threshold' | 'weighted_threshold'
197
- params: Record<string, unknown>
198
- }
199
-
200
165
  export interface ContractInvocation {
201
166
  contract: string
202
167
  fn: string
@@ -263,7 +228,6 @@ export type AmbiguityCode =
263
228
  | 'AMOUNT_BOUND_MISSING'
264
229
  | 'RECIPIENT_ALLOWLIST_EMPTY'
265
230
  | 'FREQUENCY_BOUND_MISSING'
266
- | 'ORACLE_ASSET_UNKNOWN'
267
231
  | 'MULTIPLE_UNRELATED_TARGETS'
268
232
 
269
233
  /** Structured recording freshness. `overall` is the gate threshold (default 1.0); the
@@ -1 +0,0 @@
1
- export { createInterpreterAdapter, type InterpreterAdapterConfig, ORACLE_DEFAULTS, PLACEHOLDER_INTERPRETER_ADDRESS, } from './adapter.ts';
@@ -1,2 +0,0 @@
1
- // src/adapters/interpreter/index.ts - re-export the interpreter-policy CustodyAdapter.
2
- export { createInterpreterAdapter, ORACLE_DEFAULTS, PLACEHOLDER_INTERPRETER_ADDRESS, } from "./adapter.js";
@@ -1,20 +0,0 @@
1
- import type { CustodyAdapter } from '../../seams/types.ts';
2
- import type { Network } from '../../types.ts';
3
- /** OZ built-in policy contract instance addresses, per primitive. */
4
- export interface OzPrimitiveInstances {
5
- spending_limit: string;
6
- simple_threshold: string;
7
- weighted_threshold: string;
8
- }
9
- /** Per-network config for the OZ adapter. */
10
- export interface OzAdapterConfig {
11
- network: Network;
12
- instances: OzPrimitiveInstances;
13
- }
14
- /** [VERIFY] NOT real deployed addresses. The OZ built-in policy instances are
15
- * per-network deploy artifacts we do not have yet; install is a later phase.
16
- * Injected so the adapter never invents a Stellar contract address. */
17
- export declare const PLACEHOLDER_OZ_INSTANCES: OzPrimitiveInstances;
18
- /** Week-1 OZ adapter config with placeholder instance addresses. */
19
- export declare function placeholderOzConfig(network: Network): OzAdapterConfig;
20
- export declare function createOzAdapter(config: OzAdapterConfig): CustodyAdapter;
@@ -1,295 +0,0 @@
1
- // src/adapters/oz/adapter.ts - the OZ Accounts CustodyAdapter.
2
- //
3
- // Compiles a PolicyIR to an OZ `ProposedPolicy` using OZ built-in policy
4
- // primitives. Only the constructs OZ can express natively are lowered:
5
- // scope.contract -> ContextRuleType.call_contract (else default)
6
- // expiry.validUntilLedger -> ContextRuleDraft.validUntilLedger
7
- // window_spent(t,w) <= L -> `spending_limit` primitive
8
- // approval.threshold -> `simple_threshold` / `weighted_threshold`
9
- // Anything needing a capability this backend lacks (oracle price, invocation
10
- // count, per-arg comparison/allowlist, guard, nested boolean predicate) is NOT
11
- // emitted: it is named in `uncovered` and `covered` is set false. Nothing is
12
- // silently dropped.
13
- //
14
- // OZ built-in policy instance addresses are per-network deploy artifacts we do
15
- // not have yet (install is a later phase). They are injected via config; week-1
16
- // ships a clearly-labelled [VERIFY] placeholder so nothing invents an address.
17
- import { OZ_LIMITS, SOROBAN_LIMITS } from "../../types.js";
18
- /** [VERIFY] NOT real deployed addresses. The OZ built-in policy instances are
19
- * per-network deploy artifacts we do not have yet; install is a later phase.
20
- * Injected so the adapter never invents a Stellar contract address. */
21
- export const PLACEHOLDER_OZ_INSTANCES = {
22
- spending_limit: 'VERIFY-oz-spending-limit-instance-address',
23
- simple_threshold: 'VERIFY-oz-simple-threshold-instance-address',
24
- weighted_threshold: 'VERIFY-oz-weighted-threshold-instance-address',
25
- };
26
- /** Week-1 OZ adapter config with placeholder instance addresses. */
27
- export function placeholderOzConfig(network) {
28
- return { network, instances: PLACEHOLDER_OZ_INSTANCES };
29
- }
30
- /** Parse confidence for a deterministic (non-decoded) input: full (1.0). A
31
- * mandate needs no decoding, so the gate is not applicable. */
32
- const FULL_PARSE_CONFIDENCE = {
33
- overall: 1,
34
- knownContracts: [],
35
- unknownContracts: [],
36
- opaqueScVals: [],
37
- thresholdUsed: 1,
38
- };
39
- const CAPABILITIES = {
40
- supportsSpendWindow: true,
41
- supportsThreshold: true,
42
- supportsTimeExpiry: true,
43
- supportsOraclePrice: false,
44
- supportsInvocationCount: false,
45
- supportsGeneralPredicate: false,
46
- };
47
- export function createOzAdapter(config) {
48
- return {
49
- name: 'oz-accounts',
50
- mode: 'enforce',
51
- capabilities: () => ({ ...CAPABILITIES }),
52
- compile: (ir) => compile(ir, config),
53
- simulate: () => simulateStub(),
54
- export: (ir) => canonicalStringify(ir),
55
- };
56
- }
57
- function compile(ir, config) {
58
- const uncovered = [];
59
- const firstRule = ir.rules[0];
60
- if (!firstRule) {
61
- return { covered: false, uncovered: ['empty PolicyIR (no rules to compile)'] };
62
- }
63
- if (ir.rules.length > 1) {
64
- uncovered.push(`multi-rule PolicyIR: ${ir.rules.length - 1} rule(s) beyond the first are not compiled (a ProposedPolicy carries a single context rule in this slice)`);
65
- }
66
- const lowered = lowerRule(firstRule, config);
67
- uncovered.push(...lowered.uncovered);
68
- const result = { covered: uncovered.length === 0, uncovered };
69
- if (!lowered.capExceeded) {
70
- const proposed = {
71
- contextRule: lowered.contextRule,
72
- policyDocuments: [],
73
- policyRefs: lowered.policyRefs,
74
- parseConfidence: { ...FULL_PARSE_CONFIDENCE },
75
- warnings: [],
76
- ambiguities: [],
77
- };
78
- result.proposed = proposed;
79
- }
80
- return result;
81
- }
82
- function lowerRule(rule, config) {
83
- const uncovered = [];
84
- const policyRefs = [];
85
- // scope -> context rule type. OZ scopes by contract (CallContract); a
86
- // method-level restriction is flagged as not covered because CallContract
87
- // alone permits other methods on the same contract (e.g. an unbounded approve
88
- // alongside a capped transfer).
89
- const contextRuleType = rule.scope.contract !== undefined
90
- ? { kind: 'call_contract', contract: rule.scope.contract }
91
- : { kind: 'default' };
92
- if (rule.scope.method !== undefined && rule.scope.contract !== undefined) {
93
- uncovered.push(`per-method scoping to \`${rule.scope.method}\` (OZ CallContract scopes by contract only; requires the interpreter predicate)`);
94
- }
95
- if (rule.scope.chainId !== undefined) {
96
- uncovered.push(`chainId \`${rule.scope.chainId}\` not bindable by the Stellar OZ adapter (network is per-context, not per-rule)`);
97
- }
98
- if (rule.roles.length > 0) {
99
- uncovered.push(`roles [${rule.roles.join(', ')}] dropped (role-to-signer mapping is a later phase; OZ signers carry addresses, not role names)`);
100
- }
101
- // expiry -> validUntilLedger. Unix-timestamp expiry cannot be expressed by an
102
- // OZ context rule (it expires by ledger sequence), so flag it.
103
- let validUntilLedger = null;
104
- if (rule.expiry) {
105
- if (rule.expiry.validUntilLedger !== undefined) {
106
- validUntilLedger = rule.expiry.validUntilLedger;
107
- }
108
- else if (rule.expiry.validUntilUnixSeconds !== undefined) {
109
- uncovered.push('time expiry given as a unix timestamp (OZ context rules expire by ledger sequence; supply expiry.validUntilLedger)');
110
- }
111
- }
112
- // guard -> not covered (applicability predicates are not an OZ built-in).
113
- if (rule.guard) {
114
- uncovered.push(`guard: ${describeCondition(rule.guard)}`);
115
- }
116
- // constraints -> spending_limit where they match; else not covered. The OZ
117
- // spending_limit takes `{ spending_limit: i128, period_ledgers: u32 }` and
118
- // has NO token param: it only accepts a CallContract context rule
119
- // (OnlyCallContractAllowed) and limits transfers of that context's contract,
120
- // so the spent token must equal the scope contract, and the window is a
121
- // ledger count (~5s/ledger), not seconds.
122
- for (const c of rule.constraints) {
123
- const spend = matchSpendingLimit(c);
124
- if (!spend) {
125
- uncovered.push(describeCondition(c));
126
- continue;
127
- }
128
- if (contextRuleType.kind !== 'call_contract' || spend.token !== contextRuleType.contract) {
129
- uncovered.push(`spending_limit on token ${spend.token} needs a CallContract context scoped to that token (OZ pins the limit to the context contract, not a token param)`);
130
- continue;
131
- }
132
- policyRefs.push({
133
- kind: 'oz_builtin',
134
- primitive: {
135
- primitive: 'spending_limit',
136
- params: {
137
- spending_limit: spend.limit,
138
- period_ledgers: secondsToLedgers(spend.windowSeconds),
139
- },
140
- },
141
- instanceAddress: config.instances.spending_limit,
142
- });
143
- }
144
- // approval.threshold -> simple/weighted threshold primitive. A threshold < 1
145
- // is not a real M-of-N gate (0 approvals authorises everything), so refuse to
146
- // emit a no-op primitive and flag it as not covered.
147
- if (rule.approval) {
148
- if (!Number.isInteger(rule.approval.threshold) || rule.approval.threshold < 1) {
149
- uncovered.push(`approval threshold ${rule.approval.threshold} is not a positive integer (a 0 or negative threshold is not an M-of-N gate)`);
150
- }
151
- else {
152
- const weights = rule.approval.weights;
153
- if (weights && Object.keys(weights).length > 0) {
154
- policyRefs.push({
155
- kind: 'oz_builtin',
156
- primitive: {
157
- primitive: 'weighted_threshold',
158
- params: { threshold: rule.approval.threshold, weights },
159
- },
160
- instanceAddress: config.instances.weighted_threshold,
161
- });
162
- }
163
- else {
164
- policyRefs.push({
165
- kind: 'oz_builtin',
166
- primitive: {
167
- primitive: 'simple_threshold',
168
- params: { threshold: rule.approval.threshold },
169
- },
170
- instanceAddress: config.instances.simple_threshold,
171
- });
172
- }
173
- }
174
- }
175
- const capExceeded = policyRefs.length > OZ_LIMITS.maxPoliciesPerRule;
176
- if (capExceeded) {
177
- uncovered.push(`policy count ${policyRefs.length} exceeds OZ maxPoliciesPerRule (${OZ_LIMITS.maxPoliciesPerRule})`);
178
- }
179
- const contextRule = {
180
- contextRuleType,
181
- name: contextRuleType.kind === 'call_contract'
182
- ? `call_contract:${contextRuleType.contract}`
183
- : 'default',
184
- validUntilLedger,
185
- signers: [],
186
- policies: policyRefs,
187
- };
188
- return { contextRule, policyRefs, uncovered, capExceeded };
189
- }
190
- /** Convert a spend window in seconds to OZ `period_ledgers` (u32, >= 1).
191
- * Stellar targets a ~5s ledger close time. */
192
- function secondsToLedgers(windowSeconds) {
193
- return Math.max(1, Math.round(windowSeconds / SOROBAN_LIMITS.secondsPerLedger));
194
- }
195
- /** Match the `window_spent(token, window) <= limit` compare that lowers to the
196
- * OZ `spending_limit` primitive. Only `lte` matches (the spend-cap semantic). */
197
- function matchSpendingLimit(c) {
198
- if (c.op !== 'compare')
199
- return null;
200
- const { selector, operator, value } = c.compare;
201
- if (selector.kind !== 'window_spent' || operator !== 'lte')
202
- return null;
203
- return { token: selector.token, limit: value, windowSeconds: selector.windowSeconds };
204
- }
205
- /** Human-readable descriptor for a construct the OZ built-in-primitive backend
206
- * cannot express, used to populate `uncovered`. */
207
- function describeCondition(cond) {
208
- switch (cond.op) {
209
- case 'slippage_floor':
210
- // OZ primitives bound a value against a constant; this bounds one call
211
- // argument against another, which none of them can express.
212
- return `slippage floor on arg[${cond.outArgIndex}] (OZ built-ins cannot bound one argument against another)`;
213
- case 'in':
214
- return `value allowlist on ${describeSelector(cond.selector)} (arg allowlist)`;
215
- case 'eq_seq':
216
- return `exact ordered sequence on ${describeSelector(cond.selector)} (OZ built-ins cannot express an exact vector)`;
217
- case 'not':
218
- return 'negated condition (predicate DSL)';
219
- case 'and':
220
- case 'or':
221
- return `nested ${cond.op} condition (predicate DSL)`;
222
- case 'compare': {
223
- const s = cond.compare.selector;
224
- switch (s.kind) {
225
- case 'oracle_price':
226
- return `oracle price condition on ${s.asset} (oracle price not supported in week-1)`;
227
- case 'invocation_count':
228
- return `invocation-count window (${s.windowSeconds}s) condition (not supported in week-1)`;
229
- case 'window_spent':
230
- return `spend-window comparison with operator '${cond.compare.operator}' (only 'lte' lowers to spending_limit)`;
231
- case 'amount':
232
- return `per-call amount comparison on ${s.token} (predicate DSL)`;
233
- case 'arg':
234
- return `argument comparison on arg ${s.argIndex} (predicate DSL)`;
235
- case 'arg_len':
236
- return `vec length comparison on arg ${s.argIndex} (predicate DSL)`;
237
- case 'arg_field':
238
- return `map field comparison on arg ${s.argIndex}.${s.field} (predicate DSL)`;
239
- case 'calldata':
240
- return 'EVM calldata comparison (predicate DSL)';
241
- case 'value':
242
- return 'tx.value comparison (predicate DSL)';
243
- case 'now':
244
- case 'valid_until':
245
- return 'time comparison (predicate DSL)';
246
- }
247
- }
248
- }
249
- }
250
- function describeSelector(s) {
251
- switch (s.kind) {
252
- case 'arg':
253
- return `arg ${s.argIndex}`;
254
- case 'arg_len':
255
- return `arg_len(${s.argIndex})`;
256
- case 'arg_field':
257
- return `arg_field(${s.argIndex}, ${s.element}, ${s.field})`;
258
- case 'amount':
259
- return `amount(${s.token})`;
260
- case 'window_spent':
261
- return `window_spent(${s.token})`;
262
- case 'oracle_price':
263
- return `oracle_price(${s.asset})`;
264
- case 'invocation_count':
265
- return `invocation_count(${s.windowSeconds}s)`;
266
- case 'calldata':
267
- return `calldata[${s.offset}:${s.offset + s.length}]`;
268
- default:
269
- return s.kind;
270
- }
271
- }
272
- function simulateStub() {
273
- return {
274
- backend: 'ts-model',
275
- permitted: null,
276
- evaluations: [],
277
- notes: ['stub: real permit/deny semantics wiring is a later phase'],
278
- };
279
- }
280
- /** Canonical JSON with recursively sorted object keys (stable across runs). */
281
- function canonicalStringify(value) {
282
- return JSON.stringify(sortKeys(value));
283
- }
284
- function sortKeys(value) {
285
- if (Array.isArray(value))
286
- return value.map(sortKeys);
287
- if (value && typeof value === 'object') {
288
- const out = {};
289
- for (const key of Object.keys(value).sort()) {
290
- out[key] = sortKeys(value[key]);
291
- }
292
- return out;
293
- }
294
- return value;
295
- }
@@ -1 +0,0 @@
1
- export { createOzAdapter, type OzAdapterConfig, type OzPrimitiveInstances, PLACEHOLDER_OZ_INSTANCES, placeholderOzConfig, } from './adapter.ts';
@@ -1,2 +0,0 @@
1
- // src/adapters/oz/index.ts - re-export the OZ Accounts CustodyAdapter.
2
- export { createOzAdapter, PLACEHOLDER_OZ_INSTANCES, placeholderOzConfig, } from "./adapter.js";
@@ -1,33 +0,0 @@
1
- export type CompileGateResult = {
2
- code: 'COMPILE_OK';
3
- } | {
4
- code: 'COMPILE_GATE_FAILED';
5
- stderr: string;
6
- } | {
7
- code: 'SKIPPED';
8
- reason: string;
9
- };
10
- export interface CompileGateOpts {
11
- /** Caller-controlled abort signal; aborting before toolchain probe resolves
12
- * the gate to `SKIPPED` rather than starting a cargo invocation. */
13
- signal?: AbortSignal;
14
- /** Override the `cargo` binary (mostly for tests). */
15
- cargoBin?: string;
16
- /** Override the target directory (mostly for tests). */
17
- tempDir?: string;
18
- }
19
- /** Probe the host for the Rust toolchain the gate requires. We require BOTH
20
- * `cargo` AND `stellar` (the Soroban CLI) because a real gate run invokes
21
- * `stellar contract build`; absent either, the gate returns `SKIPPED`. */
22
- export declare function hasRustToolchain(): Promise<boolean>;
23
- /** Compile-check a Rust source string against the pinned Soroban SDK.
24
- *
25
- * - Toolchain absent -> `{ code: 'SKIPPED', reason }` (NOT a failure).
26
- * - Toolchain present, source compiles -> `{ code: 'COMPILE_OK' }`.
27
- * - Toolchain present, source broken -> `{ code: 'COMPILE_GATE_FAILED', stderr }`.
28
- *
29
- * The gate writes the source to a temporary crate and runs `cargo check`
30
- * against it; the crate is cleaned up whether or not compilation succeeds.
31
- * The caller is expected to surface `COMPILE_GATE_FAILED.stderr` to the
32
- * user (the LLM agent) so the user can iterate. */
33
- export declare function compileCheck(rustSource: string, opts?: CompileGateOpts): Promise<CompileGateResult>;
@@ -1,124 +0,0 @@
1
- // src/codegen/compile-gate.ts - toolchain-gated `cargo check` for the
2
- // codegen escape hatch.
3
- //
4
- // The escape hatch ships as the `policy-builder escape-hatch` CLI subcommand
5
- // (a later phase). This gate is its safety net, NOT the happy path. Property:
6
- // generated Rust compiles against the pinned OZ crate; broken source returns
7
- // `COMPILE_GATE_FAILED` with `stderr`; an absent toolchain returns `SKIPPED`
8
- // (does NOT fail - we cannot make build tools a hard runtime requirement for
9
- // a TypeScript package).
10
- import { spawn } from 'node:child_process';
11
- import { mkdtemp, rm, writeFile } from 'node:fs/promises';
12
- import { tmpdir } from 'node:os';
13
- import { join } from 'node:path';
14
- /** Probe the host for the Rust toolchain the gate requires. We require BOTH
15
- * `cargo` AND `stellar` (the Soroban CLI) because a real gate run invokes
16
- * `stellar contract build`; absent either, the gate returns `SKIPPED`. */
17
- export async function hasRustToolchain() {
18
- const probe = await probeToolchain();
19
- return probe.present;
20
- }
21
- async function probeToolchain() {
22
- const cargo = await which('cargo');
23
- if (!cargo)
24
- return { present: false, reason: 'cargo not found on PATH' };
25
- const stellar = await which('stellar');
26
- if (!stellar)
27
- return { present: false, reason: 'stellar not found on PATH' };
28
- return { present: true, reason: `${cargo} + ${stellar}` };
29
- }
30
- async function which(bin) {
31
- try {
32
- const out = await runProcess('sh', ['-c', `command -v ${bin}`], { capture: true });
33
- const path = out.stdout.trim();
34
- return path.length > 0 ? path : null;
35
- }
36
- catch {
37
- return null;
38
- }
39
- }
40
- function runProcess(cmd, args, opts) {
41
- return new Promise((resolve, reject) => {
42
- if (opts.signal?.aborted) {
43
- reject(new Error('aborted'));
44
- return;
45
- }
46
- const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
47
- let stdout = '';
48
- let stderr = '';
49
- child.stdout.on('data', (b) => {
50
- stdout += b.toString('utf8');
51
- });
52
- child.stderr.on('data', (b) => {
53
- stderr += b.toString('utf8');
54
- });
55
- const onAbort = () => {
56
- child.kill('SIGTERM');
57
- reject(new Error('aborted'));
58
- };
59
- opts.signal?.addEventListener('abort', onAbort, { once: true });
60
- child.on('error', (e) => {
61
- opts.signal?.removeEventListener('abort', onAbort);
62
- reject(e);
63
- });
64
- child.on('close', (code) => {
65
- opts.signal?.removeEventListener('abort', onAbort);
66
- resolve({ stdout, stderr, code: code ?? -1 });
67
- });
68
- });
69
- }
70
- const CARGO_MANIFEST = `[package]
71
- name = "escape-hatch-gate"
72
- version = "0.0.0"
73
- edition = "2021"
74
- publish = false
75
-
76
- [lib]
77
- crate-type = ["cdylib"]
78
- # The gate writes the source beside the manifest rather than under src/, so
79
- # the path is stated. Without it cargo looks for src/lib.rs and fails to
80
- # parse the manifest before it ever compiles anything, which reads as a
81
- # broken generator rather than a broken scaffold.
82
- path = "lib.rs"
83
-
84
- [dependencies]
85
- soroban-sdk = "22"
86
-
87
- [workspace]
88
- `;
89
- /** Compile-check a Rust source string against the pinned Soroban SDK.
90
- *
91
- * - Toolchain absent -> `{ code: 'SKIPPED', reason }` (NOT a failure).
92
- * - Toolchain present, source compiles -> `{ code: 'COMPILE_OK' }`.
93
- * - Toolchain present, source broken -> `{ code: 'COMPILE_GATE_FAILED', stderr }`.
94
- *
95
- * The gate writes the source to a temporary crate and runs `cargo check`
96
- * against it; the crate is cleaned up whether or not compilation succeeds.
97
- * The caller is expected to surface `COMPILE_GATE_FAILED.stderr` to the
98
- * user (the LLM agent) so the user can iterate. */
99
- export async function compileCheck(rustSource, opts = {}) {
100
- if (opts.signal?.aborted) {
101
- return { code: 'SKIPPED', reason: 'aborted before probe' };
102
- }
103
- const probe = await probeToolchain();
104
- if (!probe.present) {
105
- return { code: 'SKIPPED', reason: probe.reason };
106
- }
107
- let dir = null;
108
- try {
109
- dir = await mkdtemp(join(opts.tempDir ?? tmpdir(), 'codegen-gate-'));
110
- await writeFile(join(dir, 'Cargo.toml'), CARGO_MANIFEST);
111
- await writeFile(join(dir, 'lib.rs'), rustSource);
112
- const runOpts = opts.signal ? { signal: opts.signal } : {};
113
- const result = await runProcess(opts.cargoBin ?? 'cargo', ['check', '--quiet', '--offline', '--manifest-path', join(dir, 'Cargo.toml')], runOpts).catch((e) => ({ stdout: '', stderr: e.message, code: -1 }));
114
- if (result.code === 0) {
115
- return { code: 'COMPILE_OK' };
116
- }
117
- return { code: 'COMPILE_GATE_FAILED', stderr: result.stderr || result.stdout };
118
- }
119
- finally {
120
- if (dir) {
121
- await rm(dir, { recursive: true, force: true }).catch(() => { });
122
- }
123
- }
124
- }
@@ -1,2 +0,0 @@
1
- export { type CompileGateOpts, type CompileGateResult, compileCheck, hasRustToolchain, } from './compile-gate.ts';
2
- export { type EscapeHatchSpec, generateRust, } from './template.ts';
@@ -1,8 +0,0 @@
1
- // src/codegen/index.ts - re-export the codegen escape-hatch surface.
2
- //
3
- // The escape hatch is OUT of the audited happy path: the synthesiser never
4
- // calls `generateRust` itself; the CLI subcommand (a later phase) is the only
5
- // entry point. Keeping the surface in one file makes that boundary visible
6
- // in import statements.
7
- export { compileCheck, hasRustToolchain, } from "./compile-gate.js";
8
- export { generateRust, } from "./template.js";
@@ -1,18 +0,0 @@
1
- /** A small typed description of one uncovered constraint the v1 DSL refused
2
- * to express. The synthesiser surfaces these from `CompileResult.uncovered`
3
- * and the codegen escape hatch wraps them into a hand-auditable skeleton. */
4
- export interface EscapeHatchSpec {
5
- /** Address of the policy contract the skeleton is generated for. */
6
- contract: string;
7
- /** The trait method the predicate lives inside (default: 'enforce'). */
8
- fnName?: string;
9
- /** Human-readable description of each construct the DSL could not cover. */
10
- uncovered: string[];
11
- }
12
- /** Generate a deterministic OZ `Policy` skeleton for an uncovered constraint.
13
- *
14
- * The skeleton is NOT a finished policy; the user fills in the predicate
15
- * logic in the marked TODO(user) holes and audits the result themselves.
16
- *
17
- * Same `(spec, name)` always produces byte-identical output. */
18
- export declare function generateRust(spec: EscapeHatchSpec, name: string): string;