@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
package/dist/types.d.ts CHANGED
@@ -42,6 +42,23 @@ export declare const SOROBAN_LIMITS: {
42
42
  * used to convert a spend window in seconds to OZ `period_ledgers`. */
43
43
  readonly secondsPerLedger: 5;
44
44
  };
45
+ /** Maximum recursion depth for decoding Recursive `ScVal` shapes (vec-in-vec).
46
+ * A real Stellar tx caps nesting well below this; the bound hard-caps a
47
+ * hand-crafted payload so the recorder fails CLOSED (records the over-depth
48
+ * branch as opaque `depth-exceeded`) rather than RangeErroring the JS stack.
49
+ * Mirrors the `MAX_AUTH_TREE_DEPTH = 16` boundary the auth-tree decoder
50
+ * already enforces; lifted to 30 so legitimate nested args (a path vec
51
+ * inside an order vec inside a market-data vec) decode cleanly while a
52
+ * malformed ~10000-deep payload still trips the cap. */
53
+ export declare const MAX_SCVAL_DEPTH: 30;
54
+ /** Maximum recursion depth for cloning nested `ScVal` shapes (vec-in-vec) into
55
+ * the simulator / verify / harness contexts. Mirrors `MAX_SCVAL_DEPTH` above
56
+ * so a hand-crafted nested-vec payload cannot RangeError the JS stack during
57
+ * context building. Over-depth throws a ToolError (caught by the
58
+ * `synthesizeFromRecording` envelope + the simulator/verify boundaries) so
59
+ * the caller gets a structured `{ok:false, error}` instead of a thrown
60
+ * RangeError. */
61
+ export declare const MAX_SCVAL_CLONE_DEPTH: 30;
45
62
  /** Predicate-document caps - enforced fail-closed at install by BOTH the synth (TS)
46
63
  * AND the interpreter (Rust). Single source: a CI test asserts the two cap sets are
47
64
  * byte-identical (TS reads the same JSON manifest the Rust build emits). If they
@@ -145,7 +162,7 @@ export type PredicateNode = {
145
162
  } | {
146
163
  op: 'in';
147
164
  needle: PredicateLeaf;
148
- haystack: PredicateLeaf[];
165
+ haystack: PredicateLeaf[]; /** set-valued only - the haystack is always sorted by canonical XDR bytes (pure membership). */
149
166
  };
150
167
  export type PredicateLeaf = {
151
168
  kind: 'call_contract';
@@ -160,6 +177,7 @@ export type PredicateLeaf = {
160
177
  } | {
161
178
  kind: 'window_spent';
162
179
  token: string;
180
+ windowSeconds: number;
163
181
  } | {
164
182
  kind: 'now';
165
183
  } | {
@@ -170,6 +188,27 @@ export type PredicateLeaf = {
170
188
  } | {
171
189
  kind: 'oracle_price';
172
190
  asset: string;
191
+ } | {
192
+ kind: 'literal_address';
193
+ value: string;
194
+ } | {
195
+ kind: 'literal_i128';
196
+ value: string;
197
+ } | {
198
+ kind: 'literal_symbol';
199
+ value: string;
200
+ } | {
201
+ kind: 'literal_u32';
202
+ value: number;
203
+ } | {
204
+ kind: 'literal_u64';
205
+ value: string;
206
+ } | {
207
+ kind: 'literal_bytes';
208
+ value: string;
209
+ } | {
210
+ kind: 'literal_vec';
211
+ elements: PredicateLeaf[];
173
212
  };
174
213
  export interface OZPrimitiveConfig {
175
214
  primitive: 'spending_limit' | 'simple_threshold' | 'weighted_threshold';
package/dist/types.js CHANGED
@@ -17,6 +17,23 @@ export const SOROBAN_LIMITS = {
17
17
  * used to convert a spend window in seconds to OZ `period_ledgers`. */
18
18
  secondsPerLedger: 5,
19
19
  };
20
+ /** Maximum recursion depth for decoding Recursive `ScVal` shapes (vec-in-vec).
21
+ * A real Stellar tx caps nesting well below this; the bound hard-caps a
22
+ * hand-crafted payload so the recorder fails CLOSED (records the over-depth
23
+ * branch as opaque `depth-exceeded`) rather than RangeErroring the JS stack.
24
+ * Mirrors the `MAX_AUTH_TREE_DEPTH = 16` boundary the auth-tree decoder
25
+ * already enforces; lifted to 30 so legitimate nested args (a path vec
26
+ * inside an order vec inside a market-data vec) decode cleanly while a
27
+ * malformed ~10000-deep payload still trips the cap. */
28
+ export const MAX_SCVAL_DEPTH = 30;
29
+ /** Maximum recursion depth for cloning nested `ScVal` shapes (vec-in-vec) into
30
+ * the simulator / verify / harness contexts. Mirrors `MAX_SCVAL_DEPTH` above
31
+ * so a hand-crafted nested-vec payload cannot RangeError the JS stack during
32
+ * context building. Over-depth throws a ToolError (caught by the
33
+ * `synthesizeFromRecording` envelope + the simulator/verify boundaries) so
34
+ * the caller gets a structured `{ok:false, error}` instead of a thrown
35
+ * RangeError. */
36
+ export const MAX_SCVAL_CLONE_DEPTH = 30;
20
37
  /** Predicate-document caps - enforced fail-closed at install by BOTH the synth (TS)
21
38
  * AND the interpreter (Rust). Single source: a CI test asserts the two cap sets are
22
39
  * byte-identical (TS reads the same JSON manifest the Rust build emits). If they
@@ -0,0 +1,15 @@
1
+ export type SimulationResult = {
2
+ permit: {
3
+ tx: 'permit';
4
+ } | {
5
+ tx: 'deny';
6
+ reason: string;
7
+ };
8
+ evaluatedCases: Array<{
9
+ dimension: string;
10
+ outcome: 'permit' | 'deny';
11
+ reason: string;
12
+ }>;
13
+ backend: 'interpreter-v1' | 'ts-model';
14
+ simulatorVersion: string;
15
+ };
@@ -0,0 +1,22 @@
1
+ // src/verify/envelope.ts - the post-simulation result envelope used by
2
+ // review-card rendering and verification.
3
+ //
4
+ // `SimulationResult` is the structured verdict a `simulate_policy` run
5
+ // produces; the review-card builder reads it as one of its inputs (so the
6
+ // rendered card can quote the backend that evaluated the policy) and the
7
+ // verification pipeline reads `permit` + `evaluatedCases` to confirm every
8
+ // generated deny case really did deny.
9
+ //
10
+ // This envelope is intentionally separate from the CustodyAdapter
11
+ // `SimulationResult` in `src/seams/types.ts` (which is the dry-run stub
12
+ // returned by `adapter.simulate(ir, permitTx)`); the seam result is the
13
+ // adapter contract, this envelope is the post-simulation record consumed by
14
+ // downstream rendering + verification.
15
+ //
16
+ // Fields:
17
+ // - `permit` is the single verdict for the candidate recorded tx.
18
+ // - `evaluatedCases` is the deny-case battery outcome (every dimension
19
+ // must report `deny` when the policy is minimal).
20
+ // - `backend` is the actual evaluator that produced the verdict.
21
+ // - `simulatorVersion` lets the reviewer / audit log distinguish runs.
22
+ export {};
@@ -0,0 +1,3 @@
1
+ export type { SimulationResult } from './envelope.ts';
2
+ export { type SimulateOptions, simulatePolicy } from './simulate.ts';
3
+ export { type VerifyOptions, verifyPolicy } from './verify.ts';
@@ -0,0 +1,3 @@
1
+ // src/verify/index.ts - re-export the simulation / verification surface.
2
+ export { simulatePolicy } from "./simulate.js";
3
+ export { verifyPolicy } from "./verify.js";
@@ -0,0 +1,31 @@
1
+ import type { ToolResponse } from '../errors.ts';
2
+ import type { PredicateNode, RecordedTransaction } from '../types.ts';
3
+ import type { SimulationResult } from './envelope.ts';
4
+ /** Options for `simulatePolicy`. `validUntilLedger` is propagated onto the
5
+ * permit EvalContext so the simulator exercises the expiry gate; absent ->
6
+ * no expiry check (mirrors the orchestrator's "no `validUntilLedger`
7
+ * supplied" path). `oraclePricesByAsset` is the test fixture the simulator
8
+ * uses to satisfy `oracle_price` leaves so the permit call evaluates under
9
+ * the bound; absent -> derive satisfying prices from the predicate itself
10
+ * (the orchestrator's oracle-satisfying-price logic). */
11
+ export interface SimulateOptions {
12
+ validUntilLedger?: number;
13
+ /** Pre-populated oracle-price entries keyed by asset address. The fixture
14
+ * must satisfy every `oracle_price` leaf in the predicate; absent or
15
+ * unsatisfying entries cause `SIMULATION_ERROR`. */
16
+ oraclePricesByAsset?: Record<string, {
17
+ price: string;
18
+ timestampSeconds: number;
19
+ } | {
20
+ error: 'stale' | 'missing' | 'deviation' | 'paused' | 'decimals' | 'fingerprint';
21
+ }>;
22
+ }
23
+ /** Replay a recorded transaction against a proposed predicate and emit the
24
+ * `SimulationResult` envelope. The simulator returns the SAME permit
25
+ * verdict `runHarness` expects: the intended recorded call must permit; every
26
+ * generated deny dimension must deny. A runtime evaluation failure
27
+ * (malformed input, missing oracle fixture, etc.) returns a `SIMULATION_ERROR`
28
+ * `ToolError` - NOT a deny verdict, NOT `VERIFICATION_FAILED`. The boundary
29
+ * is pinned: minimality is a verify-time concern, runtime evaluation is a
30
+ * simulate-time concern. */
31
+ export declare function simulatePolicy(predicate: PredicateNode | null, permitTx: RecordedTransaction, opts?: SimulateOptions): ToolResponse<SimulationResult>;
@@ -0,0 +1,258 @@
1
+ // src/verify/simulate.ts - the post-simulation verdict for `simulate_policy`.
2
+ //
3
+ // `simulatePolicy` replays a recorded transaction against a proposed
4
+ // `PredicateNode` and emits the `SimulationResult` envelope the review-card
5
+ // builder + the verification pipeline consume.
6
+ //
7
+ // Boundary (pinned, must not drift):
8
+ // - `SIMULATION_ERROR` = RUNTIME evaluation failed. Surfaced by
9
+ // `simulatePolicy`. Reasons: malformed `permitTx` input (no top-level
10
+ // invocation to build an EvalContext from), a referenced oracle asset
11
+ // without a satisfying price fixture, or a non-runtime propagation (a
12
+ // throw that is not an oracle error or a controlled deny). A
13
+ // runtime evaluation failure is NOT a policy-minimality problem; the
14
+ // policy may still be minimal. Re-running with a complete fixture MAY
15
+ // succeed.
16
+ // - `VERIFICATION_FAILED` = STATIC minimality check failed. Surfaced
17
+ // by `verifyPolicy`. The minimiser identified a load-bearing-free
18
+ // constraint; the policy is structurally over-broad regardless of how
19
+ // any concrete call evaluates. Re-running with a different fixture
20
+ // will NOT fix it; the policy must be trimmed.
21
+ //
22
+ // Determinism: same `(predicate, permitTx, opts)` -> byte-identical
23
+ // envelope, no clock, no randomness.
24
+ //
25
+ // The permit EvalContext is built locally (mirror of the helper used in
26
+ // `synthesize-from-recording.ts`) so this module does not couple to the
27
+ // orchestrator's private build helpers. The shape is pinned by the test
28
+ // suite to stay in lockstep.
29
+ import { generateCases } from "../synth/deny-cases.js";
30
+ import { evaluate } from "../synth/evaluate.js";
31
+ import { MAX_SCVAL_CLONE_DEPTH } from "../types.js";
32
+ const SIMULATOR_VERSION = 'ts-model-1.0.0';
33
+ /** Replay a recorded transaction against a proposed predicate and emit the
34
+ * `SimulationResult` envelope. The simulator returns the SAME permit
35
+ * verdict `runHarness` expects: the intended recorded call must permit; every
36
+ * generated deny dimension must deny. A runtime evaluation failure
37
+ * (malformed input, missing oracle fixture, etc.) returns a `SIMULATION_ERROR`
38
+ * `ToolError` - NOT a deny verdict, NOT `VERIFICATION_FAILED`. The boundary
39
+ * is pinned: minimality is a verify-time concern, runtime evaluation is a
40
+ * simulate-time concern. */
41
+ export function simulatePolicy(predicate, permitTx, opts = {}) {
42
+ // The permit EvalContext requires a top-level invocation. A recorded tx
43
+ // with no invocations is structurally malformed input - we surface a
44
+ // runtime `SIMULATION_ERROR` rather than fabricating a permit verdict.
45
+ const topLevel = permitTx.invocations[0];
46
+ if (!topLevel) {
47
+ return {
48
+ ok: false,
49
+ error: simulationError('recorded transaction has no top-level invocation to simulate'),
50
+ };
51
+ }
52
+ let permitCtx;
53
+ try {
54
+ permitCtx = buildPermitContext(predicate, permitTx, topLevel, opts);
55
+ }
56
+ catch (e) {
57
+ return {
58
+ ok: false,
59
+ error: simulationError(`could not build permit evaluation context: ${e.message}`),
60
+ };
61
+ }
62
+ // `predicate === null` means the policy is OZ-only (no interpreter
63
+ // predicate). We still emit the envelope so the review card + verifier
64
+ // can consume it: the permit verdict evaluates an always-permit empty
65
+ // tree, and the deny battery is empty (nothing to verify at the
66
+ // interpreter layer).
67
+ const evaluatePredicate = predicate ?? { op: 'and', children: [] };
68
+ const evaluatedCases = [];
69
+ let permitVerdict;
70
+ try {
71
+ permitVerdict = evaluate(evaluatePredicate, permitCtx);
72
+ }
73
+ catch (e) {
74
+ return {
75
+ ok: false,
76
+ error: simulationError(`permit evaluation threw at runtime: ${e.message}`, e),
77
+ };
78
+ }
79
+ evaluatedCases.push({
80
+ dimension: 'permit',
81
+ outcome: permitVerdict.permit ? 'permit' : 'deny',
82
+ reason: permitVerdict.permit ? 'matches recorded call' : permitVerdict.reason,
83
+ });
84
+ // The deny battery is generated against the SAME permit context. A
85
+ // runtime evaluation failure on ANY deny case is a `SIMULATION_ERROR` -
86
+ // not a deny verdict (an evaluate-throws is not a deny) and not a
87
+ // minimality problem.
88
+ const cases = generateCases(evaluatePredicate, permitCtx);
89
+ for (const deny of cases.denies) {
90
+ let result;
91
+ try {
92
+ result = evaluate(evaluatePredicate, deny.ctx);
93
+ }
94
+ catch (e) {
95
+ return {
96
+ ok: false,
97
+ error: simulationError(`deny case "${deny.dimension}" threw at runtime: ${e.message}`, e),
98
+ };
99
+ }
100
+ evaluatedCases.push({
101
+ dimension: deny.dimension,
102
+ outcome: result.permit ? 'permit' : 'deny',
103
+ reason: result.permit ? 'no matching deny' : result.reason,
104
+ });
105
+ }
106
+ const envelope = {
107
+ permit: permitVerdict.permit ? { tx: 'permit' } : { tx: 'deny', reason: permitVerdict.reason },
108
+ evaluatedCases,
109
+ backend: 'ts-model',
110
+ simulatorVersion: SIMULATOR_VERSION,
111
+ };
112
+ return { ok: true, data: envelope };
113
+ }
114
+ /** Build the permit `EvalContext` the simulator drives. Mirrors the
115
+ * helper in `synthesize-from-recording.ts` so the simulator sees the same
116
+ * shape the orchestrator's self-verify pipeline sees; we mirror here
117
+ * rather than import to keep `src/verify/` decoupled from the
118
+ * orchestrator's private helpers. The shape is pinned by tests so the
119
+ * two implementations stay in lockstep. */
120
+ function buildPermitContext(predicate, tx, topLevel, opts) {
121
+ const amountByToken = {};
122
+ const totals = new Map();
123
+ for (const m of tx.tokenMovements) {
124
+ const current = totals.get(m.token) ?? 0n;
125
+ totals.set(m.token, current + BigInt(m.amount));
126
+ }
127
+ for (const [token, total] of totals) {
128
+ amountByToken[token] = total.toString();
129
+ }
130
+ // Oracle prices: when the caller supplies a fixture, use it; otherwise
131
+ // derive a satisfying entry per `oracle_price` leaf in the predicate so
132
+ // the permit call permits. Negatives are clamped at 0 (Stellar oracle
133
+ // prices are non-negative).
134
+ const oraclePriceByAsset = {};
135
+ if (opts.oraclePricesByAsset) {
136
+ for (const [asset, entry] of Object.entries(opts.oraclePricesByAsset)) {
137
+ oraclePriceByAsset[asset] = entry;
138
+ }
139
+ }
140
+ if (predicate !== null) {
141
+ visitOracleLeaves(predicate, (asset, op, bound) => {
142
+ // A caller-supplied fixture entry always wins; we only fill gaps.
143
+ if (oraclePriceByAsset[asset] !== undefined)
144
+ return;
145
+ let price;
146
+ switch (op) {
147
+ case 'lt':
148
+ case 'gt':
149
+ price = op === 'lt' ? bound - 1n : bound + 1n;
150
+ break;
151
+ case 'lte':
152
+ case 'gte':
153
+ case 'eq':
154
+ price = bound;
155
+ break;
156
+ }
157
+ if (price < 0n)
158
+ price = 0n;
159
+ oraclePriceByAsset[asset] = {
160
+ price: price.toString(),
161
+ timestampSeconds: tx.fetchedAt,
162
+ };
163
+ });
164
+ }
165
+ const ctx = {
166
+ contract: topLevel.contract,
167
+ fn: topLevel.fn,
168
+ args: topLevel.args.map(cloneScVal),
169
+ atLedger: tx.ledgerSequence,
170
+ nowSeconds: tx.fetchedAt,
171
+ amountByToken,
172
+ windowSpentByToken: {},
173
+ invocationCountByWindow: {},
174
+ oraclePriceByAsset,
175
+ };
176
+ if (opts.validUntilLedger !== undefined) {
177
+ ctx.validUntilLedger = opts.validUntilLedger;
178
+ }
179
+ return ctx;
180
+ }
181
+ function cloneScVal(value, depth = 0) {
182
+ // Recursion is bounded by MAX_SCVAL_CLONE_DEPTH so a hand-crafted nested-vec
183
+ // payload cannot RangeError the JS stack during context building. Over-depth
184
+ // throws a ToolError-shaped error that the simulator's existing try/catch
185
+ // converts to a structured `{ok:false, error}` (not a thrown RangeError).
186
+ if (value.type === 'vec') {
187
+ if (depth >= MAX_SCVAL_CLONE_DEPTH) {
188
+ throw cloneDepthError(value);
189
+ }
190
+ return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) };
191
+ }
192
+ return { ...value };
193
+ }
194
+ function cloneDepthError(value) {
195
+ const err = new Error(`ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${MAX_SCVAL_CLONE_DEPTH})`);
196
+ err.code = 'SIMULATION_ERROR';
197
+ err.severity = 'error';
198
+ err.retryable = false;
199
+ err.depthContext = value.type;
200
+ throw err;
201
+ }
202
+ function visitOracleLeaves(node, visit) {
203
+ switch (node.op) {
204
+ case 'and':
205
+ case 'or':
206
+ for (const child of node.children)
207
+ visitOracleLeaves(child, visit);
208
+ return;
209
+ case 'not':
210
+ visitOracleLeaves(node.child, visit);
211
+ return;
212
+ case 'eq':
213
+ case 'lt':
214
+ case 'lte':
215
+ case 'gt':
216
+ case 'gte': {
217
+ const leftLeaf = node.left;
218
+ const rightLeaf = node.right;
219
+ let oracleAsset;
220
+ let literal;
221
+ if (leftLeaf.kind === 'oracle_price') {
222
+ oracleAsset = leftLeaf.asset;
223
+ literal = oracleLiteralFromLeaf(rightLeaf);
224
+ }
225
+ else if (rightLeaf.kind === 'oracle_price') {
226
+ oracleAsset = rightLeaf.asset;
227
+ literal = oracleLiteralFromLeaf(leftLeaf);
228
+ }
229
+ if (oracleAsset === undefined || literal === undefined)
230
+ return;
231
+ visit(oracleAsset, node.op, literal);
232
+ return;
233
+ }
234
+ case 'in':
235
+ return;
236
+ }
237
+ }
238
+ function oracleLiteralFromLeaf(leaf) {
239
+ if (leaf.kind !== 'literal_i128')
240
+ return undefined;
241
+ try {
242
+ return BigInt(leaf.value);
243
+ }
244
+ catch {
245
+ return undefined;
246
+ }
247
+ }
248
+ function simulationError(message, cause) {
249
+ const error = {
250
+ code: 'SIMULATION_ERROR',
251
+ message,
252
+ severity: 'error',
253
+ retryable: false,
254
+ };
255
+ if (cause !== undefined)
256
+ error.details = { cause: String(cause) };
257
+ return error;
258
+ }
@@ -0,0 +1,21 @@
1
+ import type { ToolResponse } from '../errors.ts';
2
+ import type { PredicateNode, RecordedTransaction } from '../types.ts';
3
+ /** Options for `verifyPolicy`. Mirrors the orchestrator's permit-context
4
+ * knobs (expiry; oracle fixture) so verify sees the same shape
5
+ * `simulatePolicy` sees. */
6
+ export interface VerifyOptions {
7
+ validUntilLedger?: number;
8
+ oraclePricesByAsset?: Record<string, {
9
+ price: string;
10
+ timestampSeconds: number;
11
+ } | {
12
+ error: 'stale' | 'missing' | 'deviation' | 'paused' | 'decimals' | 'fingerprint';
13
+ }>;
14
+ }
15
+ /** Run the static minimality check on a proposed predicate + recorded tx.
16
+ * Returns `{ ok: true }` when the predicate is minimal (every top-level
17
+ * conjunct carries load) and `VERIFICATION_FAILED` when a conjunct could
18
+ * be dropped without losing a deny-case. The dropped conjuncts are
19
+ * reported in `details.droppedConstraints` so the caller can render a
20
+ * review-card warning. */
21
+ export declare function verifyPolicy(predicate: PredicateNode, permitTx: RecordedTransaction, opts?: VerifyOptions): ToolResponse<true>;
@@ -0,0 +1,189 @@
1
+ // src/verify/verify.ts - the static minimality check for `verify_policy`.
2
+ //
3
+ // `verifyPolicy` proves the policy is MINIMAL: no top-level conjunct is
4
+ // load-bearing-free. It is the static sibling of `simulatePolicy` and emits
5
+ // `VERIFICATION_FAILED` (not `SIMULATION_ERROR`) on failure. The boundary is
6
+ // pinned:
7
+ //
8
+ // - `VERIFICATION_FAILED` = STATIC minimality check failed. The policy is
9
+ // structurally over-broad: a constraint could be dropped without losing
10
+ // a deny-case. Surfaced by `verifyPolicy`. Runtime evaluation is not
11
+ // part of this check; the policy may evaluate to a permit/deny just
12
+ // fine, the failure is shape-only.
13
+ //
14
+ // - `SIMULATION_ERROR` = RUNTIME evaluation failed (see simulate.ts).
15
+ // This module never emits SIMULATION_ERROR. A minimality failure is
16
+ // never a simulation error and vice-versa.
17
+ //
18
+ // Algorithm:
19
+ // 1. Build the permit EvalContext from `permitTx` (mirror of the
20
+ // orchestrator's helper so verify is self-contained).
21
+ // 2. Run `minimize(predicate, permitCtx)` to strip load-bearing-free
22
+ // top-level conjuncts (only `and` predicates are minimisable; other
23
+ // shapes are returned unchanged by `minimize`).
24
+ // 3. If the minimised tree has fewer top-level conjuncts than the input,
25
+ // return `VERIFICATION_FAILED` listing the dropped conjuncts by their
26
+ // structural fingerprint.
27
+ // 4. Otherwise `{ ok: true }`.
28
+ //
29
+ // Determinism: same `(predicate, permitTx)` -> byte-identical verdict.
30
+ import { minimize } from "../synth/minimize.js";
31
+ import { MAX_SCVAL_CLONE_DEPTH } from "../types.js";
32
+ /** Run the static minimality check on a proposed predicate + recorded tx.
33
+ * Returns `{ ok: true }` when the predicate is minimal (every top-level
34
+ * conjunct carries load) and `VERIFICATION_FAILED` when a conjunct could
35
+ * be dropped without losing a deny-case. The dropped conjuncts are
36
+ * reported in `details.droppedConstraints` so the caller can render a
37
+ * review-card warning. */
38
+ export function verifyPolicy(predicate, permitTx, opts = {}) {
39
+ const topLevel = permitTx.invocations[0];
40
+ if (!topLevel) {
41
+ return {
42
+ ok: false,
43
+ error: verificationFailed('recorded transaction has no top-level invocation to verify against', { droppedConstraints: [] }),
44
+ };
45
+ }
46
+ let permitCtx;
47
+ try {
48
+ permitCtx = buildPermitContextForVerify(permitTx, topLevel, opts);
49
+ }
50
+ catch (e) {
51
+ return {
52
+ ok: false,
53
+ error: verificationFailed(`could not build permit evaluation context: ${e.message}`, { droppedConstraints: [] }),
54
+ };
55
+ }
56
+ // `minimize` only reduces `and` predicates; other shapes are returned
57
+ // unchanged. A non-`and` predicate therefore trivially passes the static
58
+ // minimality check (its top-level structure carries no removable
59
+ // conjuncts). The runtime harness in `simulatePolicy` covers the
60
+ // OR / NOT / comparison shapes.
61
+ const minimised = minimize(predicate, permitCtx);
62
+ // Drop count: only meaningful for `and`. For other shapes we already
63
+ // returned the input unchanged; report ok.
64
+ if (predicate.op !== 'and' || minimised.op !== 'and') {
65
+ if (!structuralEqual(predicate, minimised)) {
66
+ return {
67
+ ok: false,
68
+ error: verificationFailed('minimizer returned a structurally different tree for a non-and predicate', { droppedConstraints: [fingerprint(minimised)] }),
69
+ };
70
+ }
71
+ return { ok: true, data: true };
72
+ }
73
+ const inputChildren = predicate.children;
74
+ const minimisedChildren = minimised.children;
75
+ if (minimisedChildren.length >= inputChildren.length) {
76
+ return { ok: true, data: true };
77
+ }
78
+ // Over-broad: identify the dropped conjuncts by structural fingerprint
79
+ // (so the review card can quote exactly which constraint was redundant).
80
+ // We use a multiset comparison because two structurally identical
81
+ // conjuncts (e.g. a duplicate `call_fn == transfer`) collapse to the
82
+ // same fingerprint - the dropped item is the one whose fingerprint
83
+ // count drops between input and minimised.
84
+ const inputCounts = fingerprintCounts(inputChildren);
85
+ const minimisedCounts = fingerprintCounts(minimisedChildren);
86
+ const dropped = [];
87
+ for (const [fp, count] of inputCounts) {
88
+ const kept = minimisedCounts.get(fp) ?? 0;
89
+ for (let i = 0; i < count - kept; i++)
90
+ dropped.push(fp);
91
+ }
92
+ return {
93
+ ok: false,
94
+ error: verificationFailed(`policy is structurally over-broad: ${dropped.length} redundant conjunct(s) can be dropped without losing a deny case`, { droppedConstraints: dropped }),
95
+ };
96
+ }
97
+ function buildPermitContextForVerify(tx, topLevel, opts) {
98
+ const amountByToken = {};
99
+ const totals = new Map();
100
+ for (const m of tx.tokenMovements) {
101
+ const current = totals.get(m.token) ?? 0n;
102
+ totals.set(m.token, current + BigInt(m.amount));
103
+ }
104
+ for (const [token, total] of totals) {
105
+ amountByToken[token] = total.toString();
106
+ }
107
+ const oraclePriceByAsset = {};
108
+ if (opts.oraclePricesByAsset) {
109
+ for (const [asset, entry] of Object.entries(opts.oraclePricesByAsset)) {
110
+ oraclePriceByAsset[asset] = entry;
111
+ }
112
+ }
113
+ const ctx = {
114
+ contract: topLevel.contract,
115
+ fn: topLevel.fn,
116
+ args: topLevel.args.map(cloneScVal),
117
+ atLedger: tx.ledgerSequence,
118
+ nowSeconds: tx.fetchedAt,
119
+ amountByToken,
120
+ windowSpentByToken: {},
121
+ invocationCountByWindow: {},
122
+ oraclePriceByAsset,
123
+ };
124
+ if (opts.validUntilLedger !== undefined) {
125
+ ctx.validUntilLedger = opts.validUntilLedger;
126
+ }
127
+ return ctx;
128
+ }
129
+ function cloneScVal(value, depth = 0) {
130
+ // Recursion is bounded by MAX_SCVAL_CLONE_DEPTH so a hand-crafted nested-vec
131
+ // payload cannot RangeError the JS stack during context building. Over-depth
132
+ // throws a ToolError-shaped error that the verifier's existing try/catch
133
+ // converts to a structured `{ok:false, error}` (not a thrown RangeError).
134
+ if (value.type === 'vec') {
135
+ if (depth >= MAX_SCVAL_CLONE_DEPTH) {
136
+ throw cloneDepthError(value);
137
+ }
138
+ return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) };
139
+ }
140
+ return { ...value };
141
+ }
142
+ function cloneDepthError(value) {
143
+ const err = new Error(`ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${MAX_SCVAL_CLONE_DEPTH})`);
144
+ err.code = 'VERIFICATION_FAILED';
145
+ err.severity = 'error';
146
+ err.retryable = false;
147
+ err.depthContext = value.type;
148
+ throw err;
149
+ }
150
+ function fingerprint(node) {
151
+ return JSON.stringify(node, replacer);
152
+ }
153
+ /** Multiset fingerprint counts for a list of conjuncts. Two structurally
154
+ * identical conjuncts (e.g. a duplicate `call_fn == transfer`) each
155
+ * contribute their own count. The minimiser may drop one of them; we
156
+ * surface exactly the surplus via the count difference. */
157
+ function fingerprintCounts(children) {
158
+ const counts = new Map();
159
+ for (const child of children) {
160
+ const fp = fingerprint(child);
161
+ counts.set(fp, (counts.get(fp) ?? 0) + 1);
162
+ }
163
+ return counts;
164
+ }
165
+ /** Deterministic JSON key order for fingerprinting. Object keys are sorted
166
+ * recursively so the same shape produces the same string. */
167
+ function replacer(_key, value) {
168
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
169
+ const obj = value;
170
+ const sorted = {};
171
+ for (const k of Object.keys(obj).sort()) {
172
+ sorted[k] = obj[k];
173
+ }
174
+ return sorted;
175
+ }
176
+ return value;
177
+ }
178
+ function structuralEqual(a, b) {
179
+ return fingerprint(a) === fingerprint(b);
180
+ }
181
+ function verificationFailed(message, details) {
182
+ return {
183
+ code: 'VERIFICATION_FAILED',
184
+ message,
185
+ severity: 'error',
186
+ retryable: false,
187
+ details,
188
+ };
189
+ }