@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
@@ -18,13 +18,14 @@
18
18
 
19
19
  import { Address, StrKey, xdr } from '@stellar/stellar-sdk'
20
20
  import { identifyProtocol } from '../registry/identify.ts'
21
- import type {
22
- ContractInvocation,
23
- Network,
24
- OnChainEvent,
25
- ParseConfidence,
26
- ScVal,
27
- TokenMovement,
21
+ import {
22
+ type ContractInvocation,
23
+ MAX_SCVAL_DEPTH,
24
+ type Network,
25
+ type OnChainEvent,
26
+ type ParseConfidence,
27
+ type ScVal,
28
+ type TokenMovement,
28
29
  } from '../types.ts'
29
30
 
30
31
  /** Result of decoding an envelope XDR plus the surrounding metadata from
@@ -334,11 +335,15 @@ function symbolValueFromBufferOrString(s: string | Buffer): string {
334
335
  /** Map an arbitrary ScVal into the normalised `ScVal` subset defined in
335
336
  * types.ts. Anything outside the subset is wrapped as `{type:'other', value}`
336
337
  * AND recorded in `opaqueScVals` so the freshness module can reduce
337
- * parseConfidence. */
338
+ * parseConfidence. Recursion is bounded by `MAX_SCVAL_DEPTH` so a
339
+ * hand-crafted nested-vec payload cannot RangeError the JS stack; the
340
+ * over-depth branch is collapsed to a single opaque `depth-exceeded` token
341
+ * (the recorder's parseConfidence gate then fails the recording closed). */
338
342
  export function scValToSubset(
339
343
  val: xdr.ScVal,
340
344
  path: string,
341
- opaqueScVals: ParseConfidence['opaqueScVals']
345
+ opaqueScVals: ParseConfidence['opaqueScVals'],
346
+ depth = 0
342
347
  ): ScVal {
343
348
  const kind = val.switch().name
344
349
  switch (kind) {
@@ -364,11 +369,17 @@ export function scValToSubset(
364
369
  return { type: 'symbol', value: val.sym().toString() }
365
370
  }
366
371
  case 'scvVec': {
372
+ if (depth >= MAX_SCVAL_DEPTH) {
373
+ // Over-depth branch: collapse to a single opaque terminal so the
374
+ // downstream parseConfidence gate sees the fail-closed freshness hit.
375
+ opaqueScVals.push({ path, type: 'depth-exceeded' })
376
+ return { type: 'other', value: 'depth-exceeded' }
377
+ }
367
378
  const arr = (val.vec() ?? []) as xdr.ScVal[]
368
379
  return {
369
380
  type: 'vec',
370
381
  value: arr.map((v: xdr.ScVal, i: number) =>
371
- scValToSubset(v, `${path}[${i}]`, opaqueScVals)
382
+ scValToSubset(v, `${path}[${i}]`, opaqueScVals, depth + 1)
372
383
  ),
373
384
  }
374
385
  }
@@ -0,0 +1,303 @@
1
+ // src/review-card/builder.ts - deterministic, pure review-card summary
2
+ // builder.
3
+ //
4
+ // `buildReviewCardSummary` renders the per-policy text the user-facing review
5
+ // card quotes. The whole DX win of non-engineer reviewability hinges on the
6
+ // summary being REPRODUCIBLE + TESTABLE + NON-HALLUCINABLE, so this module is
7
+ // pure: same inputs -> byte-identical output, no clock, no randomness, no I/O.
8
+ //
9
+ // The builder walks two inputs and emits ONE constraint string per leaf or
10
+ // primitive, in a fixed deterministic order:
11
+ //
12
+ // 1. The OZ built-in `PolicyRef`s. Each `spending_limit` primitive becomes a
13
+ // `spending_limit(token, limitAmount, windowSecs)` line; other OZ
14
+ // primitives (threshold) are skipped - the review card does not quote
15
+ // them (they are signer-config concerns, not transactional bounds).
16
+ //
17
+ // 2. The interpreter `PredicateNode`. One string per constraint leaf,
18
+ // rendered by enclosing-comparison kind. Templates (Task 7b):
19
+ // - invocation_count_in_window <= N -> Invocations <= N per <window> seconds
20
+ // - call_arg[i] in [list] -> Recipient/arg must be one of [list]
21
+ // - eq(call_arg[i], literal_vec[...]) -> Path must be exactly [list]
22
+ // - oracle_price(asset) OP price -> Only when oracle_price(asset) OP price
23
+ // - call_fn == x -> Function must be x
24
+ // - call_contract == c -> Contract must be c
25
+ // - amount <= v -> Amount <= v
26
+ //
27
+ // The content hash is a stable sha256 hex of a canonical JSON of
28
+ // { ruleName, plainEnglish, constraints, expiry, backend } - identical
29
+ // inputs (incl. the context-rule expiry and simulation backend) -> identical
30
+ // hash. There is no clock; the hash never includes a timestamp.
31
+
32
+ import { createHash } from 'node:crypto'
33
+ import type {
34
+ ContextRuleDraft,
35
+ OZPrimitiveConfig,
36
+ PolicyRef,
37
+ PredicateLeaf,
38
+ PredicateNode,
39
+ } from '../types.ts'
40
+ import type { SimulationResult } from '../verify/envelope.ts'
41
+
42
+ export interface ReviewCardSummary {
43
+ ruleName: string
44
+ plainEnglish: string
45
+ constraints: string[]
46
+ expiry: string
47
+ backend: 'interpreter-v1' | 'ts-model'
48
+ /** Stable hash of the builder inputs - identical policy + summary = identical hash. */
49
+ contentHash: string
50
+ }
51
+
52
+ /** Build a deterministic review-card summary from a policy + context rule +
53
+ * simulation result. Pure: same inputs -> byte-identical output. */
54
+ export function buildReviewCardSummary(
55
+ predicate: PredicateNode | null,
56
+ policyRefs: PolicyRef[],
57
+ contextRule: ContextRuleDraft,
58
+ simulation: SimulationResult
59
+ ): ReviewCardSummary {
60
+ const constraints: string[] = []
61
+ for (const ref of policyRefs) {
62
+ const line = renderOzPrimitive(ref)
63
+ if (line !== null) constraints.push(line)
64
+ }
65
+ if (predicate !== null) {
66
+ walkPredicate(predicate, (node) => {
67
+ const line = renderConstraint(node)
68
+ if (line !== null) constraints.push(line)
69
+ })
70
+ }
71
+
72
+ const ruleName = contextRule.name
73
+ const plainEnglish = renderPlainEnglish(ruleName, constraints)
74
+ const expiry = renderExpiry(contextRule.validUntilLedger)
75
+ const backend = simulation.backend
76
+
77
+ const contentHash = computeContentHash({
78
+ ruleName,
79
+ plainEnglish,
80
+ constraints,
81
+ expiry,
82
+ backend,
83
+ })
84
+
85
+ return { ruleName, plainEnglish, constraints, expiry, backend, contentHash }
86
+ }
87
+
88
+ /** Render the OZ built-in primitive summary line. Only `spending_limit` is
89
+ * quoted by the review card (it is the only primitive that defines a
90
+ * transactional bound). Other primitives (threshold) are signer-config
91
+ * concerns handled by the OZ adapter's own `uncovered` machinery.
92
+ * Spending_limit takes `period_ledgers` on-chain (~5s/ledger); the card
93
+ * states the window in seconds so the user reads it consistently with the
94
+ * interpreter templates. */
95
+ function renderOzPrimitive(ref: PolicyRef): string | null {
96
+ if (ref.kind !== 'oz_builtin') return null
97
+ const primitive: OZPrimitiveConfig = ref.primitive
98
+ if (primitive.primitive !== 'spending_limit') return null
99
+ const params = primitive.params as { spending_limit?: string; period_ledgers?: number }
100
+ const limit = params.spending_limit ?? '0'
101
+ const periodLedgers = params.period_ledgers ?? 0
102
+ const windowSecs = periodLedgers * 5
103
+ return `spending_limit(${limit}, ${windowSecs})`
104
+ }
105
+
106
+ /** Walk every comparison / membership node of the predicate and invoke
107
+ * `visit` on each. The walk is depth-first, left-to-right, so the
108
+ * constraint list is stable across runs. Pure boolean nodes contribute no
109
+ * constraint lines themselves; their leaf children do, via the visitor. */
110
+ function walkPredicate(node: PredicateNode, visit: (node: PredicateNode) => void): void {
111
+ switch (node.op) {
112
+ case 'and':
113
+ case 'or':
114
+ for (const child of node.children) walkPredicate(child, visit)
115
+ return
116
+ case 'not':
117
+ walkPredicate(node.child, visit)
118
+ return
119
+ case 'in':
120
+ visit(node)
121
+ return
122
+ case 'eq':
123
+ case 'lt':
124
+ case 'lte':
125
+ case 'gt':
126
+ case 'gte':
127
+ visit(node)
128
+ return
129
+ }
130
+ }
131
+
132
+ /** Render ONE constraint sentence for ONE interpreter predicate node. The
133
+ * shape of the output is pinned by Task 7b so the test suite can assert
134
+ * byte-for-byte equality. Returns `null` when the node is a structural
135
+ * boolean (`and` / `or` / `not`) - those are not constraint leaves. */
136
+ function renderConstraint(node: PredicateNode): string | null {
137
+ switch (node.op) {
138
+ case 'and':
139
+ case 'or':
140
+ case 'not':
141
+ return null
142
+ case 'eq':
143
+ case 'lt':
144
+ case 'lte':
145
+ case 'gt':
146
+ case 'gte':
147
+ return renderComparison(node)
148
+ case 'in':
149
+ return renderMembership(node)
150
+ }
151
+ }
152
+
153
+ function renderComparison(
154
+ node: Extract<PredicateNode, { op: 'eq' | 'lt' | 'lte' | 'gt' | 'gte' }>
155
+ ): string | null {
156
+ const left = node.left
157
+ const right = node.right
158
+
159
+ // eq(call_contract, literal_address) -> Contract must be <addr>
160
+ if (left.kind === 'call_contract' && node.op === 'eq' && right.kind === 'literal_address') {
161
+ return `Contract must be ${right.value}`
162
+ }
163
+
164
+ // eq(call_fn, literal_symbol) -> Function must be <sym>
165
+ if (left.kind === 'call_fn' && node.op === 'eq' && right.kind === 'literal_symbol') {
166
+ return `Function must be ${right.value}`
167
+ }
168
+
169
+ // eq(call_arg[i], literal_vec) -> Path must be exactly [list]
170
+ if (left.kind === 'call_arg' && node.op === 'eq' && right.kind === 'literal_vec') {
171
+ return `Path must be exactly [${right.elements.map(renderVecElement).join(', ')}]`
172
+ }
173
+
174
+ // invocation_count_in_window <= N -> Invocations <= N per <window> seconds
175
+ if (left.kind === 'invocation_count_in_window' && right.kind === 'literal_u32') {
176
+ return `Invocations <= ${right.value} per ${left.windowSecs} seconds`
177
+ }
178
+
179
+ // amount <= v -> Amount <= v
180
+ if (left.kind === 'amount' && right.kind === 'literal_i128') {
181
+ return `Amount <= ${right.value}`
182
+ }
183
+
184
+ // oracle_price(asset) OP price -> Only when oracle_price(asset) OP price
185
+ if (left.kind === 'oracle_price' && right.kind === 'literal_i128') {
186
+ return `Only when oracle_price(${left.asset}) ${comparisonOpText(node.op)} ${right.value}`
187
+ }
188
+
189
+ // Any other comparison shape is a structural fail-closed: do not surface
190
+ // a misleading line. Cross-check still requires every leaf produce a
191
+ // constraint string; the only leaves we emit lines for are the ones we
192
+ // recognise above, so the test fixtures cover exactly the supported
193
+ // shapes.
194
+ return null
195
+ }
196
+
197
+ function renderMembership(node: Extract<PredicateNode, { op: 'in' }>): string | null {
198
+ // call_arg[i] in [list] -> Recipient/arg must be one of [list]
199
+ if (node.needle.kind === 'call_arg') {
200
+ const list = node.haystack.map(renderHaystackElement).join(', ')
201
+ return `Recipient/arg must be one of [${list}]`
202
+ }
203
+ return null
204
+ }
205
+
206
+ function renderVecElement(leaf: PredicateLeaf): string {
207
+ switch (leaf.kind) {
208
+ case 'literal_address':
209
+ return leaf.value
210
+ case 'literal_i128':
211
+ return leaf.value
212
+ case 'literal_symbol':
213
+ return leaf.value
214
+ case 'literal_u32':
215
+ return String(leaf.value)
216
+ case 'literal_u64':
217
+ return leaf.value
218
+ case 'literal_bytes':
219
+ return leaf.value
220
+ case 'literal_vec':
221
+ return `[${leaf.elements.map(renderVecElement).join(', ')}]`
222
+ case 'call_contract':
223
+ case 'call_fn':
224
+ case 'call_arg':
225
+ case 'amount':
226
+ case 'window_spent':
227
+ case 'now':
228
+ case 'valid_until':
229
+ case 'invocation_count_in_window':
230
+ case 'oracle_price':
231
+ return `<${leaf.kind}>`
232
+ }
233
+ }
234
+
235
+ function renderHaystackElement(leaf: PredicateLeaf): string {
236
+ if (leaf.kind === 'literal_address') return leaf.value
237
+ if (leaf.kind === 'literal_i128') return leaf.value
238
+ if (leaf.kind === 'literal_symbol') return leaf.value
239
+ if (leaf.kind === 'literal_u32') return String(leaf.value)
240
+ if (leaf.kind === 'literal_u64') return leaf.value
241
+ if (leaf.kind === 'literal_bytes') return leaf.value
242
+ if (leaf.kind === 'literal_vec') {
243
+ return `[${leaf.elements.map(renderHaystackElement).join(', ')}]`
244
+ }
245
+ return `<${leaf.kind}>`
246
+ }
247
+
248
+ function comparisonOpText(op: 'eq' | 'lt' | 'lte' | 'gt' | 'gte'): string {
249
+ switch (op) {
250
+ case 'lt':
251
+ return '<'
252
+ case 'lte':
253
+ return '<='
254
+ case 'gt':
255
+ return '>'
256
+ case 'gte':
257
+ return '>='
258
+ case 'eq':
259
+ return '=='
260
+ }
261
+ }
262
+
263
+ /** Render the plain-English one-liner. Format: `<ruleName>: <constraints>`,
264
+ * joined by `; ` so the user reads one sentence per constraint. */
265
+ function renderPlainEnglish(ruleName: string, constraints: string[]): string {
266
+ if (constraints.length === 0) return `${ruleName}: (no constraints)`
267
+ return `${ruleName}: ${constraints.join('; ')}`
268
+ }
269
+
270
+ /** Render the expiry line. `null` -> "No expiry"; a ledger sequence -> the
271
+ * ledger number so the user reads it in the same units the OZ context rule
272
+ * applies it. */
273
+ function renderExpiry(validUntilLedger: number | null): string {
274
+ if (validUntilLedger === null) return 'No expiry'
275
+ return `Valid until ledger ${validUntilLedger}`
276
+ }
277
+
278
+ function computeContentHash(input: {
279
+ ruleName: string
280
+ plainEnglish: string
281
+ constraints: string[]
282
+ expiry: string
283
+ backend: 'interpreter-v1' | 'ts-model'
284
+ }): string {
285
+ return createHash('sha256').update(canonicalStringify(input)).digest('hex')
286
+ }
287
+
288
+ /** Canonical JSON with recursively sorted object keys (stable across runs). */
289
+ function canonicalStringify(value: unknown): string {
290
+ return JSON.stringify(sortKeys(value))
291
+ }
292
+
293
+ function sortKeys(value: unknown): unknown {
294
+ if (Array.isArray(value)) return value.map(sortKeys)
295
+ if (value && typeof value === 'object') {
296
+ const out: Record<string, unknown> = {}
297
+ for (const key of Object.keys(value as Record<string, unknown>).sort()) {
298
+ out[key] = sortKeys((value as Record<string, unknown>)[key])
299
+ }
300
+ return out
301
+ }
302
+ return value
303
+ }
@@ -0,0 +1,143 @@
1
+ // src/review-card/conflict.ts - the ConflictAnnotation 4-kind enum + the
2
+ // `classifyConflict` classifier.
3
+ //
4
+ // When a user installs a new policy alongside an existing rule set, the
5
+ // review card surfaces the relationship between the new rule and each
6
+ // existing rule as a structured annotation. A boolean (conflict / no
7
+ // conflict) is wrong: four qualitatively different shapes are possible, and
8
+ // each one tells the user something different about what would happen if
9
+ // both rules installed together.
10
+ //
11
+ // - subsume new rule's scope is a SUPERSET of an existing
12
+ // rule's. The new rule is broader; installing it on
13
+ // top of the existing rule weakens the existing
14
+ // restriction. The existing rule becomes a no-op.
15
+ // - disjoint new rule and existing rule are unrelated: their
16
+ // scopes do not overlap. Safe to install both.
17
+ // - counter_permissive new rule and existing rule allow CONFLICTING
18
+ // things at the same scope (one caps lower than the
19
+ // other on the same axis). The stricter one wins
20
+ // at evaluate; the looser is dead weight.
21
+ // - window_divergent new rule and existing rule have the same scope
22
+ // and the same per-window limit but DIFFERENT
23
+ // rolling windows. Effective union = sum (the user
24
+ // can spend `limit` per each window, independently).
25
+ //
26
+ // The classifier consumes a minimal `RuleRef` shape: the rule id, scope
27
+ // (contract + method), and an optional spending limit + window. Shapes
28
+ // without a limit fall back to scope-only classification.
29
+
30
+ /** Minimal rule reference the classifier needs to compute the conflict kind.
31
+ * Carries the rule id (used in the annotation), the scope (contract +
32
+ * method), and an optional spending cap. The cap captures both the
33
+ * amount and the window so the classifier can compare apples to apples. */
34
+ export interface RuleRef {
35
+ id: string
36
+ scope: { contract?: string; method?: string }
37
+ /** When set, the rule enforces this per-window spend cap (token +
38
+ * decimal-string amount + seconds window). */
39
+ spendingLimit?: { token: string; amount: string; windowSeconds: number }
40
+ }
41
+
42
+ /** Structured annotation a single new-vs-existing rule comparison yields.
43
+ * Four mutually exclusive kinds; the union is exhaustive (the classifier
44
+ * never throws). */
45
+ export type ConflictAnnotation =
46
+ | { kind: 'subsume'; existingRuleId: string; detail: string }
47
+ | { kind: 'disjoint' }
48
+ | { kind: 'counter_permissive'; existingRuleId: string; newLimit: string; existingLimit: string }
49
+ | { kind: 'window_divergent'; existingRuleId: string; effectiveUnion: string }
50
+
51
+ /** Classify the relationship between a new rule and one existing rule.
52
+ * Pure: same pair -> same annotation. */
53
+ export function classifyConflict(newRule: RuleRef, existingRule: RuleRef): ConflictAnnotation {
54
+ // --- step 1: subsume? (new.scope ⊋ existing.scope) ---
55
+ //
56
+ // Subsume requires existing to be fully scoped (both contract AND method
57
+ // pinned) AND new to be at least partially broader than existing. A new
58
+ // rule with identical scope to existing is NOT a superset - it is the
59
+ // same rule and falls through to the same-scope branch below. If existing
60
+ // is "any contract" / "any method" then it is the wildest rule in the
61
+ // rule set; a new rule covering it is just a duplicate, not a subsume -
62
+ // fall through to disjoint.
63
+ const existingHasContract = existingRule.scope.contract !== undefined
64
+ const existingHasMethod = existingRule.scope.method !== undefined
65
+ const newIsBroaderOnContract = newRule.scope.contract === undefined && existingHasContract
66
+ const newIsBroaderOnMethod = newRule.scope.method === undefined && existingHasMethod
67
+ const newMatchesOnContract =
68
+ newRule.scope.contract === undefined ||
69
+ (existingHasContract && newRule.scope.contract === existingRule.scope.contract)
70
+ const newMatchesOnMethod =
71
+ newRule.scope.method === undefined ||
72
+ (existingHasMethod && newRule.scope.method === existingRule.scope.method)
73
+ if (
74
+ existingHasContract &&
75
+ existingHasMethod &&
76
+ newMatchesOnContract &&
77
+ newMatchesOnMethod &&
78
+ (newIsBroaderOnContract || newIsBroaderOnMethod)
79
+ ) {
80
+ return {
81
+ kind: 'subsume',
82
+ existingRuleId: existingRule.id,
83
+ detail: `new rule scope (${describeScope(newRule)}) is a superset of existing rule (${describeScope(existingRule)})`,
84
+ }
85
+ }
86
+
87
+ // --- step 2: disjoint by scope? ---
88
+ if (existingHasContract && newRule.scope.contract !== undefined) {
89
+ if (newRule.scope.contract !== existingRule.scope.contract) {
90
+ return { kind: 'disjoint' }
91
+ }
92
+ }
93
+ if (
94
+ existingHasMethod &&
95
+ newRule.scope.method !== undefined &&
96
+ newRule.scope.method !== existingRule.scope.method
97
+ ) {
98
+ return { kind: 'disjoint' }
99
+ }
100
+
101
+ // --- step 3: same scope -> compare spend caps (when both sides carry them) ---
102
+ if (newRule.spendingLimit && existingRule.spendingLimit) {
103
+ const a = newRule.spendingLimit
104
+ const b = existingRule.spendingLimit
105
+ if (a.token !== b.token) {
106
+ // Same scope, different tokens: each binds a different axis. They
107
+ // do not counter each other; treat as disjoint.
108
+ return { kind: 'disjoint' }
109
+ }
110
+ if (a.windowSeconds === b.windowSeconds) {
111
+ // Same scope, same token, same window: counter-permissive when the
112
+ // amounts disagree (the stricter wins at evaluate; the looser is
113
+ // dead weight). Equal amounts -> duplicate rule, treat as disjoint.
114
+ if (a.amount === b.amount) {
115
+ return { kind: 'disjoint' }
116
+ }
117
+ return {
118
+ kind: 'counter_permissive',
119
+ existingRuleId: existingRule.id,
120
+ newLimit: `${a.amount} ${a.token} / ${a.windowSeconds}s`,
121
+ existingLimit: `${b.amount} ${b.token} / ${b.windowSeconds}s`,
122
+ }
123
+ }
124
+ // Same scope + token, different windows: effective union is the sum
125
+ // of the two per-window caps (each window ticks independently).
126
+ const union = (BigInt(a.amount) + BigInt(b.amount)).toString()
127
+ return {
128
+ kind: 'window_divergent',
129
+ existingRuleId: existingRule.id,
130
+ effectiveUnion: `${union} ${a.token} per ${a.windowSeconds}s (new) + ${b.windowSeconds}s (existing)`,
131
+ }
132
+ }
133
+
134
+ // Same scope without comparable spend caps on both sides -> disjoint.
135
+ return { kind: 'disjoint' }
136
+ }
137
+
138
+ function describeScope(rule: RuleRef): string {
139
+ const parts: string[] = []
140
+ parts.push(rule.scope.contract ? `contract=${rule.scope.contract}` : 'contract=*')
141
+ parts.push(rule.scope.method ? `method=${rule.scope.method}` : 'method=*')
142
+ return parts.join(', ')
143
+ }
@@ -0,0 +1,158 @@
1
+ // src/review-card/cross-check.ts - the non-hallucination guard.
2
+ //
3
+ // `summaryCrossCheck` walks EVERY leaf of the predicate and asserts the
4
+ // review-card summary quoted a constraint string for it. Returns
5
+ // `{ ok: false, missingConstraints }` if any leaf was dropped (or rendered
6
+ // into a template shape the cross-check does not recognise). A
7
+ // `PredicateNode = null` is always ok - the policy is OZ-only and the
8
+ // interpreter predicate did not exist.
9
+ //
10
+ // The guard is structural: every leaf the builder is supposed to render has
11
+ // exactly one template shape. The cross-check enumerates those shapes and
12
+ // demands the summary carries the corresponding string. A naive summary
13
+ // that drops a leaf (or fabricates a string not in the predicate) trips the
14
+ // guard.
15
+
16
+ import type { PredicateLeaf, PredicateNode } from '../types.ts'
17
+ import type { ReviewCardSummary } from './builder.ts'
18
+
19
+ /** Assert every leaf in the predicate appears as a constraint string in
20
+ * `summary.constraints`. Returns the missing templates (without the leaf
21
+ * values filled in) when any leaf was dropped. */
22
+ export function summaryCrossCheck(
23
+ predicate: PredicateNode | null,
24
+ summary: ReviewCardSummary
25
+ ): { ok: true } | { ok: false; missingConstraints: string[] } {
26
+ if (predicate === null) return { ok: true }
27
+
28
+ const expected: string[] = []
29
+ collect(predicate, expected)
30
+
31
+ if (expected.length === 0) return { ok: true }
32
+
33
+ const present = new Set(summary.constraints)
34
+ const missing = expected.filter((s) => !present.has(s))
35
+ if (missing.length === 0) return { ok: true }
36
+ return { ok: false, missingConstraints: missing }
37
+ }
38
+
39
+ /** Walk the predicate and emit the EXACT constraint string the builder is
40
+ * expected to produce for each leaf, in walk order. Strings here MUST
41
+ * match the templates in `builder.ts` byte-for-byte; the cross-check is
42
+ * the structural claim that "every supported leaf shape is rendered". */
43
+ function collect(node: PredicateNode, out: string[]): void {
44
+ switch (node.op) {
45
+ case 'and':
46
+ case 'or':
47
+ for (const child of node.children) collect(child, out)
48
+ return
49
+ case 'not':
50
+ collect(node.child, out)
51
+ return
52
+ case 'eq':
53
+ case 'lt':
54
+ case 'lte':
55
+ case 'gt':
56
+ case 'gte':
57
+ pushComparison(node.left, node.right, node.op, out)
58
+ return
59
+ case 'in':
60
+ pushMembership(node.needle, node.haystack, out)
61
+ return
62
+ }
63
+ }
64
+
65
+ function pushComparison(
66
+ left: PredicateLeaf,
67
+ right: PredicateLeaf,
68
+ op: 'eq' | 'lt' | 'lte' | 'gt' | 'gte',
69
+ out: string[]
70
+ ): void {
71
+ if (left.kind === 'call_contract' && op === 'eq' && right.kind === 'literal_address') {
72
+ out.push(`Contract must be ${right.value}`)
73
+ return
74
+ }
75
+ if (left.kind === 'call_fn' && op === 'eq' && right.kind === 'literal_symbol') {
76
+ out.push(`Function must be ${right.value}`)
77
+ return
78
+ }
79
+ if (left.kind === 'call_arg' && op === 'eq' && right.kind === 'literal_vec') {
80
+ out.push(`Path must be exactly [${right.elements.map(renderVecElement).join(', ')}]`)
81
+ return
82
+ }
83
+ if (left.kind === 'invocation_count_in_window' && right.kind === 'literal_u32') {
84
+ out.push(`Invocations <= ${right.value} per ${left.windowSecs} seconds`)
85
+ return
86
+ }
87
+ if (left.kind === 'amount' && right.kind === 'literal_i128') {
88
+ out.push(`Amount <= ${right.value}`)
89
+ return
90
+ }
91
+ if (left.kind === 'oracle_price' && right.kind === 'literal_i128') {
92
+ out.push(`Only when oracle_price(${left.asset}) ${comparisonOpText(op)} ${right.value}`)
93
+ return
94
+ }
95
+ }
96
+
97
+ function pushMembership(needle: PredicateLeaf, haystack: PredicateLeaf[], out: string[]): void {
98
+ if (needle.kind !== 'call_arg') return
99
+ const list = haystack.map(renderHaystackElement).join(', ')
100
+ out.push(`Recipient/arg must be one of [${list}]`)
101
+ }
102
+
103
+ function renderVecElement(leaf: PredicateLeaf): string {
104
+ switch (leaf.kind) {
105
+ case 'literal_address':
106
+ return leaf.value
107
+ case 'literal_i128':
108
+ return leaf.value
109
+ case 'literal_symbol':
110
+ return leaf.value
111
+ case 'literal_u32':
112
+ return String(leaf.value)
113
+ case 'literal_u64':
114
+ return leaf.value
115
+ case 'literal_bytes':
116
+ return leaf.value
117
+ case 'literal_vec':
118
+ return `[${leaf.elements.map(renderVecElement).join(', ')}]`
119
+ case 'call_contract':
120
+ case 'call_fn':
121
+ case 'call_arg':
122
+ case 'amount':
123
+ case 'window_spent':
124
+ case 'now':
125
+ case 'valid_until':
126
+ case 'invocation_count_in_window':
127
+ case 'oracle_price':
128
+ return `<${leaf.kind}>`
129
+ }
130
+ }
131
+
132
+ function renderHaystackElement(leaf: PredicateLeaf): string {
133
+ if (leaf.kind === 'literal_address') return leaf.value
134
+ if (leaf.kind === 'literal_i128') return leaf.value
135
+ if (leaf.kind === 'literal_symbol') return leaf.value
136
+ if (leaf.kind === 'literal_u32') return String(leaf.value)
137
+ if (leaf.kind === 'literal_u64') return leaf.value
138
+ if (leaf.kind === 'literal_bytes') return leaf.value
139
+ if (leaf.kind === 'literal_vec') {
140
+ return `[${leaf.elements.map(renderHaystackElement).join(', ')}]`
141
+ }
142
+ return `<${leaf.kind}>`
143
+ }
144
+
145
+ function comparisonOpText(op: 'eq' | 'lt' | 'lte' | 'gt' | 'gte'): string {
146
+ switch (op) {
147
+ case 'lt':
148
+ return '<'
149
+ case 'lte':
150
+ return '<='
151
+ case 'gt':
152
+ return '>'
153
+ case 'gte':
154
+ return '>='
155
+ case 'eq':
156
+ return '=='
157
+ }
158
+ }
@@ -0,0 +1,12 @@
1
+ // src/review-card/index.ts - re-export the deterministic review-card surface.
2
+
3
+ export {
4
+ buildReviewCardSummary,
5
+ type ReviewCardSummary,
6
+ } from './builder.ts'
7
+ export {
8
+ type ConflictAnnotation,
9
+ classifyConflict,
10
+ type RuleRef,
11
+ } from './conflict.ts'
12
+ export { summaryCrossCheck } from './cross-check.ts'