@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/src/types.ts CHANGED
@@ -33,6 +33,25 @@ export const SOROBAN_LIMITS = {
33
33
  secondsPerLedger: 5,
34
34
  } as const
35
35
 
36
+ /** Maximum recursion depth for decoding Recursive `ScVal` shapes (vec-in-vec).
37
+ * A real Stellar tx caps nesting well below this; the bound hard-caps a
38
+ * hand-crafted payload so the recorder fails CLOSED (records the over-depth
39
+ * branch as opaque `depth-exceeded`) rather than RangeErroring the JS stack.
40
+ * Mirrors the `MAX_AUTH_TREE_DEPTH = 16` boundary the auth-tree decoder
41
+ * already enforces; lifted to 30 so legitimate nested args (a path vec
42
+ * inside an order vec inside a market-data vec) decode cleanly while a
43
+ * malformed ~10000-deep payload still trips the cap. */
44
+ export const MAX_SCVAL_DEPTH = 30 as const
45
+
46
+ /** Maximum recursion depth for cloning nested `ScVal` shapes (vec-in-vec) into
47
+ * the simulator / verify / harness contexts. Mirrors `MAX_SCVAL_DEPTH` above
48
+ * so a hand-crafted nested-vec payload cannot RangeError the JS stack during
49
+ * context building. Over-depth throws a ToolError (caught by the
50
+ * `synthesizeFromRecording` envelope + the simulator/verify boundaries) so
51
+ * the caller gets a structured `{ok:false, error}` instead of a thrown
52
+ * RangeError. */
53
+ export const MAX_SCVAL_CLONE_DEPTH = 30 as const
54
+
36
55
  /** Predicate-document caps - enforced fail-closed at install by BOTH the synth (TS)
37
56
  * AND the interpreter (Rust). Single source: a CI test asserts the two cap sets are
38
57
  * byte-identical (TS reads the same JSON manifest the Rust build emits). If they
@@ -111,7 +130,11 @@ export type PredicateNode =
111
130
  | { op: 'not'; child: PredicateNode }
112
131
  | { op: 'eq'; left: PredicateLeaf; right: PredicateLeaf }
113
132
  | { op: 'lt' | 'lte' | 'gt' | 'gte'; left: PredicateLeaf; right: PredicateLeaf }
114
- | { op: 'in'; needle: PredicateLeaf; haystack: PredicateLeaf[] }
133
+ | {
134
+ op: 'in'
135
+ needle: PredicateLeaf
136
+ haystack: PredicateLeaf[] /** set-valued only - the haystack is always sorted by canonical XDR bytes (pure membership). */
137
+ }
115
138
 
116
139
  export type PredicateLeaf =
117
140
  | { kind: 'call_contract' }
@@ -123,11 +146,24 @@ export type PredicateLeaf =
123
146
  // enforce Context. Scope is per-authorized-context; a v1.1 sub-invocation
124
147
  // tree leaf is gated on the enforce-Context-shape spike result.
125
148
  | { kind: 'amount'; token: string }
126
- | { kind: 'window_spent'; token: string }
149
+ | { kind: 'window_spent'; token: string; windowSeconds: number }
127
150
  | { kind: 'now' }
128
151
  | { kind: 'valid_until' }
129
152
  | { kind: 'invocation_count_in_window'; windowSecs: number }
130
153
  | { kind: 'oracle_price'; asset: string } // Stellar Address (SAC address for SEP-41; XLM uses its network SAC)
154
+ // Literal leaves: bare ScVal on the wire (no selector-tuple wrapper). Right-hand side of
155
+ // comparisons, elements of `in` haystacks, and operands to future arithmetic nodes.
156
+ | { kind: 'literal_address'; value: string }
157
+ | { kind: 'literal_i128'; value: string }
158
+ | { kind: 'literal_symbol'; value: string }
159
+ | { kind: 'literal_u32'; value: number }
160
+ | { kind: 'literal_u64'; value: string }
161
+ | { kind: 'literal_bytes'; value: string } // hex string; wrapped as ScVal::Bytes at encode time
162
+ // Exact ordered vector of literals (e.g. a swap hop path). Encodes to a bare
163
+ // ScVal::Vec with the caller's order preserved verbatim - the order IS the
164
+ // semantic. An exact ordered sequence equality is expressed by `eq(selector,
165
+ // literal_vec([...]))`. `in` is reserved for pure set membership (sorted).
166
+ | { kind: 'literal_vec'; elements: PredicateLeaf[] }
131
167
 
132
168
  export interface OZPrimitiveConfig {
133
169
  primitive: 'spending_limit' | 'simple_threshold' | 'weighted_threshold'
@@ -0,0 +1,28 @@
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
+
23
+ export type SimulationResult = {
24
+ permit: { tx: 'permit' } | { tx: 'deny'; reason: string }
25
+ evaluatedCases: Array<{ dimension: string; outcome: 'permit' | 'deny'; reason: string }>
26
+ backend: 'interpreter-v1' | 'ts-model'
27
+ simulatorVersion: string
28
+ }
@@ -0,0 +1,5 @@
1
+ // src/verify/index.ts - re-export the simulation / verification surface.
2
+
3
+ export type { SimulationResult } from './envelope.ts'
4
+ export { type SimulateOptions, simulatePolicy } from './simulate.ts'
5
+ export { type VerifyOptions, verifyPolicy } from './verify.ts'
@@ -0,0 +1,311 @@
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
+
30
+ import type { ToolError, ToolResponse } from '../errors.ts'
31
+ import { generateCases } from '../synth/deny-cases.ts'
32
+ import { type EvalContext, evaluate } from '../synth/evaluate.ts'
33
+ import type {
34
+ ContractInvocation,
35
+ PredicateLeaf,
36
+ PredicateNode,
37
+ RecordedTransaction,
38
+ ScVal,
39
+ } from '../types.ts'
40
+ import { MAX_SCVAL_CLONE_DEPTH } from '../types.ts'
41
+ import type { SimulationResult } from './envelope.ts'
42
+
43
+ const SIMULATOR_VERSION = 'ts-model-1.0.0'
44
+
45
+ /** Options for `simulatePolicy`. `validUntilLedger` is propagated onto the
46
+ * permit EvalContext so the simulator exercises the expiry gate; absent ->
47
+ * no expiry check (mirrors the orchestrator's "no `validUntilLedger`
48
+ * supplied" path). `oraclePricesByAsset` is the test fixture the simulator
49
+ * uses to satisfy `oracle_price` leaves so the permit call evaluates under
50
+ * the bound; absent -> derive satisfying prices from the predicate itself
51
+ * (the orchestrator's oracle-satisfying-price logic). */
52
+ export interface SimulateOptions {
53
+ validUntilLedger?: number
54
+ /** Pre-populated oracle-price entries keyed by asset address. The fixture
55
+ * must satisfy every `oracle_price` leaf in the predicate; absent or
56
+ * unsatisfying entries cause `SIMULATION_ERROR`. */
57
+ oraclePricesByAsset?: Record<
58
+ string,
59
+ | { price: string; timestampSeconds: number }
60
+ | {
61
+ error: 'stale' | 'missing' | 'deviation' | 'paused' | 'decimals' | 'fingerprint'
62
+ }
63
+ >
64
+ }
65
+
66
+ /** Replay a recorded transaction against a proposed predicate and emit the
67
+ * `SimulationResult` envelope. The simulator returns the SAME permit
68
+ * verdict `runHarness` expects: the intended recorded call must permit; every
69
+ * generated deny dimension must deny. A runtime evaluation failure
70
+ * (malformed input, missing oracle fixture, etc.) returns a `SIMULATION_ERROR`
71
+ * `ToolError` - NOT a deny verdict, NOT `VERIFICATION_FAILED`. The boundary
72
+ * is pinned: minimality is a verify-time concern, runtime evaluation is a
73
+ * simulate-time concern. */
74
+ export function simulatePolicy(
75
+ predicate: PredicateNode | null,
76
+ permitTx: RecordedTransaction,
77
+ opts: SimulateOptions = {}
78
+ ): ToolResponse<SimulationResult> {
79
+ // The permit EvalContext requires a top-level invocation. A recorded tx
80
+ // with no invocations is structurally malformed input - we surface a
81
+ // runtime `SIMULATION_ERROR` rather than fabricating a permit verdict.
82
+ const topLevel = permitTx.invocations[0]
83
+ if (!topLevel) {
84
+ return {
85
+ ok: false,
86
+ error: simulationError('recorded transaction has no top-level invocation to simulate'),
87
+ }
88
+ }
89
+
90
+ let permitCtx: EvalContext
91
+ try {
92
+ permitCtx = buildPermitContext(predicate, permitTx, topLevel, opts)
93
+ } catch (e) {
94
+ return {
95
+ ok: false,
96
+ error: simulationError(`could not build permit evaluation context: ${(e as Error).message}`),
97
+ }
98
+ }
99
+
100
+ // `predicate === null` means the policy is OZ-only (no interpreter
101
+ // predicate). We still emit the envelope so the review card + verifier
102
+ // can consume it: the permit verdict evaluates an always-permit empty
103
+ // tree, and the deny battery is empty (nothing to verify at the
104
+ // interpreter layer).
105
+ const evaluatePredicate: PredicateNode = predicate ?? { op: 'and', children: [] }
106
+
107
+ const evaluatedCases: SimulationResult['evaluatedCases'] = []
108
+
109
+ let permitVerdict: { permit: true } | { permit: false; reason: string }
110
+ try {
111
+ permitVerdict = evaluate(evaluatePredicate, permitCtx)
112
+ } catch (e) {
113
+ return {
114
+ ok: false,
115
+ error: simulationError(`permit evaluation threw at runtime: ${(e as Error).message}`, e),
116
+ }
117
+ }
118
+ evaluatedCases.push({
119
+ dimension: 'permit',
120
+ outcome: permitVerdict.permit ? 'permit' : 'deny',
121
+ reason: permitVerdict.permit ? 'matches recorded call' : permitVerdict.reason,
122
+ })
123
+
124
+ // The deny battery is generated against the SAME permit context. A
125
+ // runtime evaluation failure on ANY deny case is a `SIMULATION_ERROR` -
126
+ // not a deny verdict (an evaluate-throws is not a deny) and not a
127
+ // minimality problem.
128
+ const cases = generateCases(evaluatePredicate, permitCtx)
129
+ for (const deny of cases.denies) {
130
+ let result: { permit: true } | { permit: false; reason: string }
131
+ try {
132
+ result = evaluate(evaluatePredicate, deny.ctx)
133
+ } catch (e) {
134
+ return {
135
+ ok: false,
136
+ error: simulationError(
137
+ `deny case "${deny.dimension}" threw at runtime: ${(e as Error).message}`,
138
+ e
139
+ ),
140
+ }
141
+ }
142
+ evaluatedCases.push({
143
+ dimension: deny.dimension,
144
+ outcome: result.permit ? 'permit' : 'deny',
145
+ reason: result.permit ? 'no matching deny' : result.reason,
146
+ })
147
+ }
148
+
149
+ const envelope: SimulationResult = {
150
+ permit: permitVerdict.permit ? { tx: 'permit' } : { tx: 'deny', reason: permitVerdict.reason },
151
+ evaluatedCases,
152
+ backend: 'ts-model',
153
+ simulatorVersion: SIMULATOR_VERSION,
154
+ }
155
+ return { ok: true, data: envelope }
156
+ }
157
+
158
+ /** Build the permit `EvalContext` the simulator drives. Mirrors the
159
+ * helper in `synthesize-from-recording.ts` so the simulator sees the same
160
+ * shape the orchestrator's self-verify pipeline sees; we mirror here
161
+ * rather than import to keep `src/verify/` decoupled from the
162
+ * orchestrator's private helpers. The shape is pinned by tests so the
163
+ * two implementations stay in lockstep. */
164
+ function buildPermitContext(
165
+ predicate: PredicateNode | null,
166
+ tx: RecordedTransaction,
167
+ topLevel: ContractInvocation,
168
+ opts: SimulateOptions
169
+ ): EvalContext {
170
+ const amountByToken: Record<string, string> = {}
171
+ const totals = new Map<string, bigint>()
172
+ for (const m of tx.tokenMovements) {
173
+ const current = totals.get(m.token) ?? 0n
174
+ totals.set(m.token, current + BigInt(m.amount))
175
+ }
176
+ for (const [token, total] of totals) {
177
+ amountByToken[token] = total.toString()
178
+ }
179
+
180
+ // Oracle prices: when the caller supplies a fixture, use it; otherwise
181
+ // derive a satisfying entry per `oracle_price` leaf in the predicate so
182
+ // the permit call permits. Negatives are clamped at 0 (Stellar oracle
183
+ // prices are non-negative).
184
+ const oraclePriceByAsset: EvalContext['oraclePriceByAsset'] = {}
185
+ if (opts.oraclePricesByAsset) {
186
+ for (const [asset, entry] of Object.entries(opts.oraclePricesByAsset)) {
187
+ oraclePriceByAsset[asset] = entry
188
+ }
189
+ }
190
+ if (predicate !== null) {
191
+ visitOracleLeaves(predicate, (asset, op, bound) => {
192
+ // A caller-supplied fixture entry always wins; we only fill gaps.
193
+ if (oraclePriceByAsset[asset] !== undefined) return
194
+ let price: bigint
195
+ switch (op) {
196
+ case 'lt':
197
+ case 'gt':
198
+ price = op === 'lt' ? bound - 1n : bound + 1n
199
+ break
200
+ case 'lte':
201
+ case 'gte':
202
+ case 'eq':
203
+ price = bound
204
+ break
205
+ }
206
+ if (price < 0n) price = 0n
207
+ oraclePriceByAsset[asset] = {
208
+ price: price.toString(),
209
+ timestampSeconds: tx.fetchedAt,
210
+ }
211
+ })
212
+ }
213
+
214
+ const ctx: EvalContext = {
215
+ contract: topLevel.contract,
216
+ fn: topLevel.fn,
217
+ args: topLevel.args.map(cloneScVal),
218
+ atLedger: tx.ledgerSequence,
219
+ nowSeconds: tx.fetchedAt,
220
+ amountByToken,
221
+ windowSpentByToken: {},
222
+ invocationCountByWindow: {},
223
+ oraclePriceByAsset,
224
+ }
225
+ if (opts.validUntilLedger !== undefined) {
226
+ ctx.validUntilLedger = opts.validUntilLedger
227
+ }
228
+ return ctx
229
+ }
230
+
231
+ function cloneScVal(value: ScVal, depth = 0): ScVal {
232
+ // Recursion is bounded by MAX_SCVAL_CLONE_DEPTH so a hand-crafted nested-vec
233
+ // payload cannot RangeError the JS stack during context building. Over-depth
234
+ // throws a ToolError-shaped error that the simulator's existing try/catch
235
+ // converts to a structured `{ok:false, error}` (not a thrown RangeError).
236
+ if (value.type === 'vec') {
237
+ if (depth >= MAX_SCVAL_CLONE_DEPTH) {
238
+ throw cloneDepthError(value)
239
+ }
240
+ return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) }
241
+ }
242
+ return { ...value }
243
+ }
244
+
245
+ function cloneDepthError(value: ScVal): never {
246
+ const err = new Error(
247
+ `ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${MAX_SCVAL_CLONE_DEPTH})`
248
+ ) as Error & { code: string; severity: string; retryable: boolean; depthContext: unknown }
249
+ err.code = 'SIMULATION_ERROR'
250
+ err.severity = 'error'
251
+ err.retryable = false
252
+ err.depthContext = value.type
253
+ throw err
254
+ }
255
+
256
+ function visitOracleLeaves(
257
+ node: PredicateNode,
258
+ visit: (asset: string, op: 'eq' | 'lt' | 'lte' | 'gt' | 'gte', bound: bigint) => void
259
+ ): void {
260
+ switch (node.op) {
261
+ case 'and':
262
+ case 'or':
263
+ for (const child of node.children) visitOracleLeaves(child, visit)
264
+ return
265
+ case 'not':
266
+ visitOracleLeaves(node.child, visit)
267
+ return
268
+ case 'eq':
269
+ case 'lt':
270
+ case 'lte':
271
+ case 'gt':
272
+ case 'gte': {
273
+ const leftLeaf = node.left
274
+ const rightLeaf = node.right
275
+ let oracleAsset: string | undefined
276
+ let literal: bigint | undefined
277
+ if (leftLeaf.kind === 'oracle_price') {
278
+ oracleAsset = leftLeaf.asset
279
+ literal = oracleLiteralFromLeaf(rightLeaf)
280
+ } else if (rightLeaf.kind === 'oracle_price') {
281
+ oracleAsset = rightLeaf.asset
282
+ literal = oracleLiteralFromLeaf(leftLeaf)
283
+ }
284
+ if (oracleAsset === undefined || literal === undefined) return
285
+ visit(oracleAsset, node.op, literal)
286
+ return
287
+ }
288
+ case 'in':
289
+ return
290
+ }
291
+ }
292
+
293
+ function oracleLiteralFromLeaf(leaf: PredicateLeaf): bigint | undefined {
294
+ if (leaf.kind !== 'literal_i128') return undefined
295
+ try {
296
+ return BigInt(leaf.value)
297
+ } catch {
298
+ return undefined
299
+ }
300
+ }
301
+
302
+ function simulationError(message: string, cause?: unknown): ToolError {
303
+ const error: ToolError = {
304
+ code: 'SIMULATION_ERROR',
305
+ message,
306
+ severity: 'error',
307
+ retryable: false,
308
+ }
309
+ if (cause !== undefined) error.details = { cause: String(cause) }
310
+ return error
311
+ }
@@ -0,0 +1,243 @@
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
+
31
+ import type { ToolError, ToolResponse } from '../errors.ts'
32
+ import type { EvalContext } from '../synth/evaluate.ts'
33
+ import { minimize } from '../synth/minimize.ts'
34
+ import type { ContractInvocation, PredicateNode, RecordedTransaction, ScVal } from '../types.ts'
35
+ import { MAX_SCVAL_CLONE_DEPTH } from '../types.ts'
36
+
37
+ /** Options for `verifyPolicy`. Mirrors the orchestrator's permit-context
38
+ * knobs (expiry; oracle fixture) so verify sees the same shape
39
+ * `simulatePolicy` sees. */
40
+ export interface VerifyOptions {
41
+ validUntilLedger?: number
42
+ oraclePricesByAsset?: Record<
43
+ string,
44
+ | { price: string; timestampSeconds: number }
45
+ | {
46
+ error: 'stale' | 'missing' | 'deviation' | 'paused' | 'decimals' | 'fingerprint'
47
+ }
48
+ >
49
+ }
50
+
51
+ /** Run the static minimality check on a proposed predicate + recorded tx.
52
+ * Returns `{ ok: true }` when the predicate is minimal (every top-level
53
+ * conjunct carries load) and `VERIFICATION_FAILED` when a conjunct could
54
+ * be dropped without losing a deny-case. The dropped conjuncts are
55
+ * reported in `details.droppedConstraints` so the caller can render a
56
+ * review-card warning. */
57
+ export function verifyPolicy(
58
+ predicate: PredicateNode,
59
+ permitTx: RecordedTransaction,
60
+ opts: VerifyOptions = {}
61
+ ): ToolResponse<true> {
62
+ const topLevel = permitTx.invocations[0]
63
+ if (!topLevel) {
64
+ return {
65
+ ok: false,
66
+ error: verificationFailed(
67
+ 'recorded transaction has no top-level invocation to verify against',
68
+ { droppedConstraints: [] }
69
+ ),
70
+ }
71
+ }
72
+
73
+ let permitCtx: EvalContext
74
+ try {
75
+ permitCtx = buildPermitContextForVerify(permitTx, topLevel, opts)
76
+ } catch (e) {
77
+ return {
78
+ ok: false,
79
+ error: verificationFailed(
80
+ `could not build permit evaluation context: ${(e as Error).message}`,
81
+ { droppedConstraints: [] }
82
+ ),
83
+ }
84
+ }
85
+
86
+ // `minimize` only reduces `and` predicates; other shapes are returned
87
+ // unchanged. A non-`and` predicate therefore trivially passes the static
88
+ // minimality check (its top-level structure carries no removable
89
+ // conjuncts). The runtime harness in `simulatePolicy` covers the
90
+ // OR / NOT / comparison shapes.
91
+ const minimised = minimize(predicate, permitCtx)
92
+
93
+ // Drop count: only meaningful for `and`. For other shapes we already
94
+ // returned the input unchanged; report ok.
95
+ if (predicate.op !== 'and' || minimised.op !== 'and') {
96
+ if (!structuralEqual(predicate, minimised)) {
97
+ return {
98
+ ok: false,
99
+ error: verificationFailed(
100
+ 'minimizer returned a structurally different tree for a non-and predicate',
101
+ { droppedConstraints: [fingerprint(minimised)] }
102
+ ),
103
+ }
104
+ }
105
+ return { ok: true, data: true }
106
+ }
107
+
108
+ const inputChildren = predicate.children
109
+ const minimisedChildren = minimised.children
110
+ if (minimisedChildren.length >= inputChildren.length) {
111
+ return { ok: true, data: true }
112
+ }
113
+
114
+ // Over-broad: identify the dropped conjuncts by structural fingerprint
115
+ // (so the review card can quote exactly which constraint was redundant).
116
+ // We use a multiset comparison because two structurally identical
117
+ // conjuncts (e.g. a duplicate `call_fn == transfer`) collapse to the
118
+ // same fingerprint - the dropped item is the one whose fingerprint
119
+ // count drops between input and minimised.
120
+ const inputCounts = fingerprintCounts(inputChildren)
121
+ const minimisedCounts = fingerprintCounts(minimisedChildren)
122
+ const dropped: string[] = []
123
+ for (const [fp, count] of inputCounts) {
124
+ const kept = minimisedCounts.get(fp) ?? 0
125
+ for (let i = 0; i < count - kept; i++) dropped.push(fp)
126
+ }
127
+ return {
128
+ ok: false,
129
+ error: verificationFailed(
130
+ `policy is structurally over-broad: ${dropped.length} redundant conjunct(s) can be dropped without losing a deny case`,
131
+ { droppedConstraints: dropped }
132
+ ),
133
+ }
134
+ }
135
+
136
+ function buildPermitContextForVerify(
137
+ tx: RecordedTransaction,
138
+ topLevel: ContractInvocation,
139
+ opts: VerifyOptions
140
+ ): EvalContext {
141
+ const amountByToken: Record<string, string> = {}
142
+ const totals = new Map<string, bigint>()
143
+ for (const m of tx.tokenMovements) {
144
+ const current = totals.get(m.token) ?? 0n
145
+ totals.set(m.token, current + BigInt(m.amount))
146
+ }
147
+ for (const [token, total] of totals) {
148
+ amountByToken[token] = total.toString()
149
+ }
150
+
151
+ const oraclePriceByAsset: EvalContext['oraclePriceByAsset'] = {}
152
+ if (opts.oraclePricesByAsset) {
153
+ for (const [asset, entry] of Object.entries(opts.oraclePricesByAsset)) {
154
+ oraclePriceByAsset[asset] = entry
155
+ }
156
+ }
157
+
158
+ const ctx: EvalContext = {
159
+ contract: topLevel.contract,
160
+ fn: topLevel.fn,
161
+ args: topLevel.args.map(cloneScVal),
162
+ atLedger: tx.ledgerSequence,
163
+ nowSeconds: tx.fetchedAt,
164
+ amountByToken,
165
+ windowSpentByToken: {},
166
+ invocationCountByWindow: {},
167
+ oraclePriceByAsset,
168
+ }
169
+ if (opts.validUntilLedger !== undefined) {
170
+ ctx.validUntilLedger = opts.validUntilLedger
171
+ }
172
+ return ctx
173
+ }
174
+
175
+ function cloneScVal(value: ScVal, depth = 0): ScVal {
176
+ // Recursion is bounded by MAX_SCVAL_CLONE_DEPTH so a hand-crafted nested-vec
177
+ // payload cannot RangeError the JS stack during context building. Over-depth
178
+ // throws a ToolError-shaped error that the verifier's existing try/catch
179
+ // converts to a structured `{ok:false, error}` (not a thrown RangeError).
180
+ if (value.type === 'vec') {
181
+ if (depth >= MAX_SCVAL_CLONE_DEPTH) {
182
+ throw cloneDepthError(value)
183
+ }
184
+ return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) }
185
+ }
186
+ return { ...value }
187
+ }
188
+
189
+ function cloneDepthError(value: ScVal): never {
190
+ const err = new Error(
191
+ `ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${MAX_SCVAL_CLONE_DEPTH})`
192
+ ) as Error & { code: string; severity: string; retryable: boolean; depthContext: unknown }
193
+ err.code = 'VERIFICATION_FAILED'
194
+ err.severity = 'error'
195
+ err.retryable = false
196
+ err.depthContext = value.type
197
+ throw err
198
+ }
199
+
200
+ function fingerprint(node: PredicateNode): string {
201
+ return JSON.stringify(node, replacer)
202
+ }
203
+
204
+ /** Multiset fingerprint counts for a list of conjuncts. Two structurally
205
+ * identical conjuncts (e.g. a duplicate `call_fn == transfer`) each
206
+ * contribute their own count. The minimiser may drop one of them; we
207
+ * surface exactly the surplus via the count difference. */
208
+ function fingerprintCounts(children: PredicateNode[]): Map<string, number> {
209
+ const counts = new Map<string, number>()
210
+ for (const child of children) {
211
+ const fp = fingerprint(child)
212
+ counts.set(fp, (counts.get(fp) ?? 0) + 1)
213
+ }
214
+ return counts
215
+ }
216
+
217
+ /** Deterministic JSON key order for fingerprinting. Object keys are sorted
218
+ * recursively so the same shape produces the same string. */
219
+ function replacer(_key: string, value: unknown): unknown {
220
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
221
+ const obj = value as Record<string, unknown>
222
+ const sorted: Record<string, unknown> = {}
223
+ for (const k of Object.keys(obj).sort()) {
224
+ sorted[k] = obj[k]
225
+ }
226
+ return sorted
227
+ }
228
+ return value
229
+ }
230
+
231
+ function structuralEqual(a: PredicateNode, b: PredicateNode): boolean {
232
+ return fingerprint(a) === fingerprint(b)
233
+ }
234
+
235
+ function verificationFailed(message: string, details: unknown): ToolError {
236
+ return {
237
+ code: 'VERIFICATION_FAILED',
238
+ message,
239
+ severity: 'error',
240
+ retryable: false,
241
+ details,
242
+ }
243
+ }