@crediolabs/policy-synth 0.1.2 → 0.1.4

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