@crediolabs/policy-synth 0.2.0 → 0.3.0

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 (184) hide show
  1. package/README.md +4 -4
  2. package/dist/adapters/interpreter/adapter.d.ts +19 -25
  3. package/dist/adapters/interpreter/adapter.js +54 -487
  4. package/dist/adapters/interpreter/index.d.ts +1 -1
  5. package/dist/adapters/interpreter/index.js +1 -1
  6. package/dist/adapters/oz/adapter.js +1 -15
  7. package/dist/errors.d.ts +1 -1
  8. package/dist/index.d.ts +1 -4
  9. package/dist/index.js +1 -4
  10. package/dist/install/build-add-context-rule.d.ts +3 -19
  11. package/dist/install/build-add-context-rule.js +3 -98
  12. package/dist/install/build-install-policy.d.ts +4 -53
  13. package/dist/install/build-install-policy.js +44 -123
  14. package/dist/install/index.d.ts +0 -2
  15. package/dist/install/index.js +0 -7
  16. package/dist/ir/index.d.ts +1 -1
  17. package/dist/ir/types.d.ts +7 -76
  18. package/dist/ir/types.js +0 -2
  19. package/dist/predicate/decode.d.ts +1 -1
  20. package/dist/predicate/decode.js +2 -70
  21. package/dist/predicate/encode.js +45 -229
  22. package/dist/predicate/from-json.js +1 -42
  23. package/dist/record/decode.js +3 -8
  24. package/dist/review-card/builder.d.ts +4 -3
  25. package/dist/review-card/builder.js +18 -162
  26. package/dist/review-card/cross-check.js +2 -105
  27. package/dist/review-card/render-leaf.d.ts +4 -0
  28. package/dist/review-card/render-leaf.js +47 -0
  29. package/dist/run/index.d.ts +36 -139
  30. package/dist/run/index.js +125 -437
  31. package/dist/run/schemas.d.ts +168 -1929
  32. package/dist/run/schemas.js +40 -269
  33. package/dist/seams/types.d.ts +0 -2
  34. package/dist/simulate/deny-cases.d.ts +26 -0
  35. package/dist/simulate/deny-cases.js +282 -0
  36. package/dist/simulate/evaluate.d.ts +18 -0
  37. package/dist/simulate/evaluate.js +271 -0
  38. package/dist/simulate/index.d.ts +4 -0
  39. package/dist/simulate/index.js +8 -0
  40. package/dist/synth/compose-from-recording.d.ts +24 -51
  41. package/dist/synth/compose-from-recording.js +120 -282
  42. package/dist/synth/deny-cases.d.ts +5 -7
  43. package/dist/synth/deny-cases.js +23 -373
  44. package/dist/synth/evaluate.d.ts +0 -21
  45. package/dist/synth/evaluate.js +56 -336
  46. package/dist/synth/index.d.ts +0 -5
  47. package/dist/synth/index.js +0 -5
  48. package/dist/synth/permit-context.d.ts +2 -9
  49. package/dist/synth/permit-context.js +1 -82
  50. package/dist/synth/synthesize-from-recording.d.ts +1 -29
  51. package/dist/synth/synthesize-from-recording.js +41 -356
  52. package/dist/types.d.ts +8 -60
  53. package/dist/types.js +5 -2
  54. package/dist/verify/simulate.d.ts +1 -14
  55. package/dist/verify/simulate.js +2 -88
  56. package/dist/verify/verify.d.ts +1 -7
  57. package/dist/verify/verify.js +0 -8
  58. package/dist-cjs/adapters/interpreter/adapter.d.ts +19 -25
  59. package/dist-cjs/adapters/interpreter/adapter.js +56 -489
  60. package/dist-cjs/adapters/interpreter/index.d.ts +1 -1
  61. package/dist-cjs/adapters/interpreter/index.js +1 -2
  62. package/dist-cjs/adapters/oz/adapter.js +1 -15
  63. package/dist-cjs/errors.d.ts +1 -1
  64. package/dist-cjs/index.d.ts +1 -4
  65. package/dist-cjs/index.js +1 -4
  66. package/dist-cjs/install/build-add-context-rule.d.ts +3 -19
  67. package/dist-cjs/install/build-add-context-rule.js +1 -97
  68. package/dist-cjs/install/build-install-policy.d.ts +4 -53
  69. package/dist-cjs/install/build-install-policy.js +44 -122
  70. package/dist-cjs/install/index.d.ts +0 -2
  71. package/dist-cjs/install/index.js +2 -23
  72. package/dist-cjs/ir/index.d.ts +1 -1
  73. package/dist-cjs/ir/types.d.ts +7 -76
  74. package/dist-cjs/ir/types.js +0 -2
  75. package/dist-cjs/predicate/decode.d.ts +1 -1
  76. package/dist-cjs/predicate/decode.js +2 -70
  77. package/dist-cjs/predicate/encode.js +45 -229
  78. package/dist-cjs/predicate/from-json.js +1 -42
  79. package/dist-cjs/record/decode.js +3 -8
  80. package/dist-cjs/review-card/builder.d.ts +4 -3
  81. package/dist-cjs/review-card/builder.js +23 -167
  82. package/dist-cjs/review-card/cross-check.js +7 -110
  83. package/dist-cjs/review-card/render-leaf.d.ts +4 -0
  84. package/dist-cjs/review-card/render-leaf.js +52 -0
  85. package/dist-cjs/run/index.d.ts +36 -139
  86. package/dist-cjs/run/index.js +125 -444
  87. package/dist-cjs/run/schemas.d.ts +168 -1929
  88. package/dist-cjs/run/schemas.js +41 -270
  89. package/dist-cjs/seams/types.d.ts +0 -2
  90. package/dist-cjs/simulate/deny-cases.d.ts +26 -0
  91. package/dist-cjs/simulate/deny-cases.js +286 -0
  92. package/dist-cjs/simulate/evaluate.d.ts +18 -0
  93. package/dist-cjs/simulate/evaluate.js +274 -0
  94. package/dist-cjs/simulate/index.d.ts +4 -0
  95. package/dist-cjs/simulate/index.js +13 -0
  96. package/dist-cjs/synth/compose-from-recording.d.ts +24 -51
  97. package/dist-cjs/synth/compose-from-recording.js +120 -282
  98. package/dist-cjs/synth/deny-cases.d.ts +5 -7
  99. package/dist-cjs/synth/deny-cases.js +23 -374
  100. package/dist-cjs/synth/evaluate.d.ts +0 -21
  101. package/dist-cjs/synth/evaluate.js +57 -337
  102. package/dist-cjs/synth/index.d.ts +0 -5
  103. package/dist-cjs/synth/index.js +1 -11
  104. package/dist-cjs/synth/permit-context.d.ts +2 -9
  105. package/dist-cjs/synth/permit-context.js +1 -82
  106. package/dist-cjs/synth/synthesize-from-recording.d.ts +1 -29
  107. package/dist-cjs/synth/synthesize-from-recording.js +39 -354
  108. package/dist-cjs/types.d.ts +8 -60
  109. package/dist-cjs/types.js +6 -3
  110. package/dist-cjs/verify/simulate.d.ts +1 -14
  111. package/dist-cjs/verify/simulate.js +2 -88
  112. package/dist-cjs/verify/verify.d.ts +1 -7
  113. package/dist-cjs/verify/verify.js +0 -8
  114. package/package.json +4 -4
  115. package/src/adapters/interpreter/adapter.ts +76 -572
  116. package/src/errors.ts +0 -19
  117. package/src/index.ts +1 -4
  118. package/src/install/build-add-context-rule.ts +5 -139
  119. package/src/install/build-install-policy.ts +93 -214
  120. package/src/install/index.ts +0 -34
  121. package/src/predicate/decode.ts +2 -70
  122. package/src/predicate/encode.ts +49 -261
  123. package/src/predicate/from-json.ts +1 -43
  124. package/src/record/decode.ts +3 -8
  125. package/src/review-card/builder.ts +19 -168
  126. package/src/review-card/cross-check.ts +3 -105
  127. package/src/review-card/render-leaf.ts +48 -0
  128. package/src/run/index.ts +144 -572
  129. package/src/run/schemas.ts +42 -291
  130. package/src/simulate/deny-cases.ts +334 -0
  131. package/src/simulate/evaluate.ts +284 -0
  132. package/src/simulate/index.ts +11 -0
  133. package/src/synth/compose-from-recording.ts +148 -347
  134. package/src/synth/index.ts +0 -13
  135. package/src/synth/synthesize-from-recording.ts +43 -456
  136. package/src/types.ts +13 -49
  137. package/dist/install/authority-overlap.d.ts +0 -134
  138. package/dist/install/authority-overlap.js +0 -0
  139. package/dist/install/build-install-predicate.d.ts +0 -96
  140. package/dist/install/build-install-predicate.js +0 -444
  141. package/dist/install/build-merge-policy.d.ts +0 -70
  142. package/dist/install/build-merge-policy.js +0 -130
  143. package/dist/install/plan-merge-policy.d.ts +0 -49
  144. package/dist/install/plan-merge-policy.js +0 -86
  145. package/dist/install/read-account-rules.d.ts +0 -100
  146. package/dist/install/read-account-rules.js +0 -283
  147. package/dist-cjs/install/authority-overlap.d.ts +0 -134
  148. package/dist-cjs/install/authority-overlap.js +0 -0
  149. package/dist-cjs/install/build-install-predicate.d.ts +0 -96
  150. package/dist-cjs/install/build-install-predicate.js +0 -479
  151. package/dist-cjs/install/build-merge-policy.d.ts +0 -70
  152. package/dist-cjs/install/build-merge-policy.js +0 -134
  153. package/dist-cjs/install/plan-merge-policy.d.ts +0 -49
  154. package/dist-cjs/install/plan-merge-policy.js +0 -90
  155. package/dist-cjs/install/read-account-rules.d.ts +0 -100
  156. package/dist-cjs/install/read-account-rules.js +0 -296
  157. package/src/adapters/interpreter/index.ts +0 -8
  158. package/src/adapters/oz/adapter.ts +0 -376
  159. package/src/adapters/oz/index.ts +0 -9
  160. package/src/codegen/compile-gate.ts +0 -167
  161. package/src/codegen/index.ts +0 -17
  162. package/src/codegen/template.ts +0 -165
  163. package/src/install/authority-overlap.ts +0 -0
  164. package/src/install/build-merge-policy.ts +0 -219
  165. package/src/install/plan-merge-policy.ts +0 -133
  166. package/src/install/read-account-rules.ts +0 -376
  167. package/src/ir/index.ts +0 -13
  168. package/src/ir/types.ts +0 -132
  169. package/src/mandate/index.ts +0 -4
  170. package/src/mandate/to-ir.ts +0 -71
  171. package/src/mandate/types.ts +0 -21
  172. package/src/seams/index.ts +0 -11
  173. package/src/seams/types.ts +0 -81
  174. package/src/synth/deny-cases.ts +0 -663
  175. package/src/synth/evaluate.ts +0 -613
  176. package/src/synth/harness.ts +0 -68
  177. package/src/synth/minimize.ts +0 -48
  178. package/src/synth/permit-context.ts +0 -136
  179. package/src/synth/predicate-literals.ts +0 -27
  180. package/src/synth/synthesize-from-mandate.ts +0 -82
  181. package/src/verify/envelope.ts +0 -28
  182. package/src/verify/index.ts +0 -5
  183. package/src/verify/simulate.ts +0 -311
  184. package/src/verify/verify.ts +0 -243
@@ -1,48 +0,0 @@
1
- import type { PredicateNode } from '../types.ts'
2
- import { type DenyCase, generateCases } from './deny-cases.ts'
3
- import type { EvalContext } from './evaluate.ts'
4
- import { runHarness } from './harness.ts'
5
-
6
- /** Remove top-level conjuncts only when the current and regenerated batteries still deny. */
7
- export function minimize(
8
- predicate: PredicateNode,
9
- permitCtx: EvalContext,
10
- dimensions?: string[]
11
- ): PredicateNode {
12
- if (predicate.op !== 'and') return predicate
13
-
14
- let children = [...predicate.children]
15
- let index = 0
16
-
17
- while (index < children.length) {
18
- const current: PredicateNode = { op: 'and', children }
19
- const currentCases = generateCases(current, permitCtx, dimensions)
20
- const candidateChildren = children.filter((_, childIndex) => childIndex !== index)
21
- const candidate: PredicateNode = { op: 'and', children: candidateChildren }
22
- const candidateCases = generateCases(candidate, permitCtx, dimensions)
23
- const verificationCases = {
24
- permit: candidateCases.permit,
25
- denies: mergeDenyCases(currentCases.denies, candidateCases.denies),
26
- }
27
-
28
- if (runHarness(candidate, verificationCases).ok) {
29
- children = candidateChildren
30
- continue
31
- }
32
- index += 1
33
- }
34
-
35
- return { op: 'and', children }
36
- }
37
-
38
- function mergeDenyCases(current: DenyCase[], candidate: DenyCase[]): DenyCase[] {
39
- const merged: DenyCase[] = []
40
- const seen = new Set<string>()
41
- for (const deny of [...current, ...candidate]) {
42
- const key = `${deny.dimension}:${JSON.stringify(deny.ctx)}`
43
- if (seen.has(key)) continue
44
- seen.add(key)
45
- merged.push(deny)
46
- }
47
- return merged
48
- }
@@ -1,136 +0,0 @@
1
- // src/synth/permit-context.ts - build the EvalContext that represents the
2
- // recorded call being replayed.
3
- //
4
- // Extracted from the over-permissiveness harness so the same construction
5
- // feeds both the in-process battery and the on-chain replay
6
- // (scripts/verify-mutations-testnet.ts). Two callers building this
7
- // separately would be two chances to disagree about what "the recorded
8
- // call" means, which is the one thing both must share.
9
-
10
- import type { PredicateLeaf, PredicateNode, RecordedTransaction } from '../types.ts'
11
- import { cloneScVal } from './deny-cases.ts'
12
- import type { EvalContext } from './evaluate.ts'
13
-
14
- export interface PermitContextResponses {
15
- windowSeconds: number
16
- invocationLimit?: number
17
- limitAmount?: string
18
- validUntilLedger: number
19
- oraclePriceBound?: Array<{ asset: string; operator: string; value: string; decimals: number }>
20
- }
21
-
22
- export function buildPermitContext(
23
- tx: RecordedTransaction,
24
- responses: PermitContextResponses,
25
- predicate: PredicateNode
26
- ): EvalContext {
27
- const amountByToken: Record<string, string> = {}
28
- const totals = new Map<string, bigint>()
29
- for (const m of tx.tokenMovements) {
30
- const current = totals.get(m.token) ?? 0n
31
- totals.set(m.token, current + BigInt(m.amount))
32
- }
33
- for (const [token, total] of totals) {
34
- amountByToken[token] = total.toString()
35
- }
36
-
37
- const topLevel = tx.invocations[0]
38
- const scopeContract = topLevel?.contract ?? ''
39
-
40
- const oraclePriceByAsset: EvalContext['oraclePriceByAsset'] = {}
41
- visitOracleLeaves(predicate, (asset, op, bound) => {
42
- let price: bigint
43
- switch (op) {
44
- case 'lt':
45
- price = bound - 1n
46
- break
47
- case 'gt':
48
- price = bound + 1n
49
- break
50
- default:
51
- price = bound
52
- }
53
- if (price < 0n) price = 0n
54
- oraclePriceByAsset[asset] = { price: price.toString(), timestampSeconds: tx.fetchedAt }
55
- })
56
-
57
- const ctx: EvalContext = {
58
- contract: scopeContract,
59
- fn: topLevel?.fn ?? '',
60
- args: (topLevel?.args ?? []).map(cloneScVal),
61
- atLedger: tx.ledgerSequence,
62
- nowSeconds: tx.fetchedAt,
63
- amountByToken,
64
- windowSpentByToken: {},
65
- invocationCountByWindow: {},
66
- oraclePriceByAsset,
67
- }
68
- if (responses.validUntilLedger !== undefined) {
69
- ctx.validUntilLedger = responses.validUntilLedger
70
- }
71
- return ctx
72
- }
73
-
74
- function visitOracleLeaves(
75
- node: PredicateNode,
76
- visit: (asset: string, op: string, bound: bigint) => void
77
- ): void {
78
- switch (node.op) {
79
- case 'and':
80
- case 'or':
81
- for (const child of node.children) visitOracleLeaves(child, visit)
82
- return
83
- case 'not':
84
- visitOracleLeaves(node.child, visit)
85
- return
86
- case 'eq':
87
- case 'lt':
88
- case 'lte':
89
- case 'gt':
90
- case 'gte': {
91
- const leftIsOracle = node.left.kind === 'oracle_price'
92
- const rightIsOracle = node.right.kind === 'oracle_price'
93
- let asset: string | undefined
94
- let literal: bigint | undefined
95
- if (leftIsOracle) {
96
- asset = node.left.kind === 'oracle_price' ? node.left.asset : undefined
97
- literal = oracleThresholdNormalised(node.right)
98
- } else if (rightIsOracle) {
99
- asset = node.right.kind === 'oracle_price' ? node.right.asset : undefined
100
- literal = oracleThresholdNormalised(node.left)
101
- }
102
- if (asset !== undefined && literal !== undefined) {
103
- visit(asset, node.op, literal)
104
- }
105
- return
106
- }
107
- case 'in':
108
- return
109
- }
110
- }
111
-
112
- /** Oracle prices normalise to 9 decimals; mirrors NORMALISED_DECIMALS in
113
- * oracle.rs. */
114
- const NORMALISED_DECIMALS = 9n
115
-
116
- /** A threshold restated on the normalised basis, so a derived permit price is
117
- * comparable to it. Thresholds carry their own basis, so the conversion has
118
- * to happen here - reading the digits raw would build a context off by a
119
- * factor of 10^(decimals-9). Returns undefined for any other leaf. */
120
- function oracleThresholdNormalised(leaf: PredicateLeaf): bigint | undefined {
121
- if (leaf.kind !== 'oracle_threshold') return undefined
122
- let value: bigint
123
- try {
124
- value = BigInt(leaf.value)
125
- } catch {
126
- return undefined
127
- }
128
- const decimals = BigInt(leaf.decimals)
129
- if (decimals <= NORMALISED_DECIMALS) {
130
- return value * 10n ** (NORMALISED_DECIMALS - decimals)
131
- }
132
- // Floor: a finer-grained threshold has no exact 9-dp representation. The
133
- // caller only needs a price that lands on the right side of the bound, and
134
- // it offsets by one from here.
135
- return value / 10n ** (decimals - NORMALISED_DECIMALS)
136
- }
@@ -1,27 +0,0 @@
1
- // src/synth/predicate-literals.ts - read scalar values out of predicate literal leaves.
2
- //
3
- // Small shared helpers for interpreting a `PredicateLeaf` literal. Kept out of
4
- // `evaluate.ts` so the evaluator stays focused on the deny-order semantics; the
5
- // deny-case generator uses the same reader so both sides agree on what a numeric
6
- // literal means.
7
-
8
- import type { PredicateLeaf } from '../types.ts'
9
-
10
- /** BigInt value of a numeric-integer literal leaf (`literal_i128` / `literal_u64`
11
- * / `literal_u32`), or null for a non-numeric literal (address / symbol / bytes
12
- * / vec). Callers fail closed on null. */
13
- export function literalNumericBigInt(leaf: PredicateLeaf): bigint | null {
14
- switch (leaf.kind) {
15
- case 'literal_i128':
16
- case 'literal_u64':
17
- try {
18
- return BigInt(leaf.value)
19
- } catch {
20
- return null
21
- }
22
- case 'literal_u32':
23
- return BigInt(leaf.value)
24
- default:
25
- return null
26
- }
27
- }
@@ -1,82 +0,0 @@
1
- // src/synth/synthesize-from-mandate.ts - the deterministic Mandate front-end.
2
- //
3
- // synthesizeFromMandate is the clean end-to-end demo path: a declarative
4
- // MandateSpec is lowered deterministically to a PolicyIR and compiled by the OZ
5
- // adapter to a ProposedPolicy. No decoding, no inference, so parseConfidence is
6
- // the full/not-applicable value. Constructs the OZ built-in primitives cannot
7
- // express (compile's `uncovered`) are surfaced in `ProposedPolicy.warnings`
8
- // rather than failing the call - the covered primitives still install; the
9
- // uncovered ones are reported.
10
-
11
- import type { OzAdapterConfig } from '../adapters/oz/adapter.ts'
12
- import { createOzAdapter } from '../adapters/oz/adapter.ts'
13
- import type { ToolResponse } from '../errors.ts'
14
- import { mandateToPolicyIR } from '../mandate/to-ir.ts'
15
- import type { MandateSpec } from '../mandate/types.ts'
16
- import type { PredicateNode, ProposedPolicy } from '../types.ts'
17
- import type { SimulationResult } from '../verify/envelope.ts'
18
-
19
- const UNCOVERED_PREFIX = 'Not covered by OZ built-in primitives: '
20
-
21
- export function synthesizeFromMandate(
22
- spec: MandateSpec,
23
- ozConfig: OzAdapterConfig,
24
- /** --explain opt-in. When true, the success envelope carries the
25
- * in-memory predicate tree (always null for the mandate path - the
26
- * declarative MandateSpec lowers to OZ built-ins, not to an
27
- * interpreter predicate) + a minimal honest SimulationResult. The
28
- * flag is ADDITIVE: the existing ProposedPolicy fields are never
29
- * altered. */
30
- opts?: { explain?: true }
31
- ): ToolResponse<ProposedPolicy> & {
32
- explain?: {
33
- predicateTree: PredicateNode | null
34
- simulation: SimulationResult
35
- }
36
- } {
37
- const ir = mandateToPolicyIR(spec)
38
- const adapter = createOzAdapter(ozConfig)
39
- const result = adapter.compile(ir)
40
-
41
- if (!result.proposed) {
42
- return {
43
- ok: false,
44
- error: {
45
- code: 'SYNTHESIS_ERROR',
46
- message: `mandate lowered to no installable OZ policy: ${result.uncovered.join('; ')}`,
47
- severity: 'error',
48
- retryable: false,
49
- details: { uncovered: result.uncovered },
50
- },
51
- }
52
- }
53
-
54
- const proposed: ProposedPolicy = {
55
- ...result.proposed,
56
- warnings: result.uncovered.map((u) => `${UNCOVERED_PREFIX}${u}`),
57
- }
58
- // Same --explain envelope pattern as the recording path. The mandate path
59
- // never produces an interpreter predicate, so predicateTree is null and
60
- // the simulation is a minimal honest deny (no self-verify was performed).
61
- const envelope: ToolResponse<ProposedPolicy> & {
62
- explain?: {
63
- predicateTree: PredicateNode | null
64
- simulation: SimulationResult
65
- }
66
- } = { ok: true, data: proposed }
67
- if (opts?.explain) {
68
- envelope.explain = {
69
- predicateTree: null,
70
- simulation: {
71
- permit: {
72
- tx: 'deny',
73
- reason: 'No self-verification was performed (mandate path is OZ-only)',
74
- },
75
- evaluatedCases: [],
76
- backend: 'ts-model',
77
- simulatorVersion: 'not-run',
78
- },
79
- }
80
- }
81
- return envelope
82
- }
@@ -1,28 +0,0 @@
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
- }
@@ -1,5 +0,0 @@
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'
@@ -1,311 +0,0 @@
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
- }