@crediolabs/policy-synth 0.2.0 → 0.3.1

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 (249) 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/errors.d.ts +1 -1
  5. package/dist/index.d.ts +1 -4
  6. package/dist/index.js +1 -4
  7. package/dist/install/build-add-context-rule.d.ts +3 -19
  8. package/dist/install/build-add-context-rule.js +3 -98
  9. package/dist/install/build-install-policy.d.ts +4 -53
  10. package/dist/install/build-install-policy.js +44 -123
  11. package/dist/install/index.d.ts +0 -2
  12. package/dist/install/index.js +0 -7
  13. package/dist/predicate/decode.d.ts +1 -1
  14. package/dist/predicate/decode.js +2 -70
  15. package/dist/predicate/encode.js +45 -229
  16. package/dist/predicate/from-json.js +1 -42
  17. package/dist/record/decode.js +3 -8
  18. package/dist/record/freshness.d.ts +17 -11
  19. package/dist/record/freshness.js +28 -18
  20. package/dist/review-card/builder.d.ts +4 -3
  21. package/dist/review-card/builder.js +18 -162
  22. package/dist/review-card/cross-check.js +2 -105
  23. package/dist/review-card/render-leaf.d.ts +4 -0
  24. package/dist/review-card/render-leaf.js +47 -0
  25. package/dist/run/index.d.ts +36 -139
  26. package/dist/run/index.js +125 -437
  27. package/dist/run/schemas.d.ts +168 -1929
  28. package/dist/run/schemas.js +40 -269
  29. package/dist/{synth → simulate}/deny-cases.d.ts +4 -8
  30. package/dist/simulate/deny-cases.js +282 -0
  31. package/dist/simulate/evaluate.d.ts +18 -0
  32. package/dist/simulate/evaluate.js +271 -0
  33. package/dist/simulate/index.d.ts +4 -0
  34. package/dist/simulate/index.js +8 -0
  35. package/dist/synth/compose-from-recording.d.ts +24 -51
  36. package/dist/synth/compose-from-recording.js +120 -282
  37. package/dist/synth/index.d.ts +0 -5
  38. package/dist/synth/index.js +0 -5
  39. package/dist/synth/synthesize-from-recording.d.ts +1 -29
  40. package/dist/synth/synthesize-from-recording.js +41 -356
  41. package/dist/types.d.ts +8 -60
  42. package/dist/types.js +5 -2
  43. package/dist-cjs/adapters/interpreter/adapter.d.ts +19 -25
  44. package/dist-cjs/adapters/interpreter/adapter.js +56 -489
  45. package/dist-cjs/errors.d.ts +1 -1
  46. package/dist-cjs/index.d.ts +1 -4
  47. package/dist-cjs/index.js +1 -4
  48. package/dist-cjs/install/build-add-context-rule.d.ts +3 -19
  49. package/dist-cjs/install/build-add-context-rule.js +1 -97
  50. package/dist-cjs/install/build-install-policy.d.ts +4 -53
  51. package/dist-cjs/install/build-install-policy.js +44 -122
  52. package/dist-cjs/install/index.d.ts +0 -2
  53. package/dist-cjs/install/index.js +2 -23
  54. package/dist-cjs/predicate/decode.d.ts +1 -1
  55. package/dist-cjs/predicate/decode.js +2 -70
  56. package/dist-cjs/predicate/encode.js +45 -229
  57. package/dist-cjs/predicate/from-json.js +1 -42
  58. package/dist-cjs/record/decode.js +3 -8
  59. package/dist-cjs/record/freshness.d.ts +17 -11
  60. package/dist-cjs/record/freshness.js +28 -18
  61. package/dist-cjs/review-card/builder.d.ts +4 -3
  62. package/dist-cjs/review-card/builder.js +23 -167
  63. package/dist-cjs/review-card/cross-check.js +7 -110
  64. package/dist-cjs/review-card/render-leaf.d.ts +4 -0
  65. package/dist-cjs/review-card/render-leaf.js +52 -0
  66. package/dist-cjs/run/index.d.ts +36 -139
  67. package/dist-cjs/run/index.js +125 -444
  68. package/dist-cjs/run/schemas.d.ts +168 -1929
  69. package/dist-cjs/run/schemas.js +41 -270
  70. package/dist-cjs/{synth → simulate}/deny-cases.d.ts +4 -8
  71. package/dist-cjs/simulate/deny-cases.js +286 -0
  72. package/dist-cjs/simulate/evaluate.d.ts +18 -0
  73. package/dist-cjs/simulate/evaluate.js +274 -0
  74. package/dist-cjs/simulate/index.d.ts +4 -0
  75. package/dist-cjs/simulate/index.js +13 -0
  76. package/dist-cjs/synth/compose-from-recording.d.ts +24 -51
  77. package/dist-cjs/synth/compose-from-recording.js +120 -282
  78. package/dist-cjs/synth/index.d.ts +0 -5
  79. package/dist-cjs/synth/index.js +1 -11
  80. package/dist-cjs/synth/synthesize-from-recording.d.ts +1 -29
  81. package/dist-cjs/synth/synthesize-from-recording.js +39 -354
  82. package/dist-cjs/types.d.ts +8 -60
  83. package/dist-cjs/types.js +6 -3
  84. package/package.json +5 -5
  85. package/src/adapters/interpreter/adapter.ts +76 -572
  86. package/src/errors.ts +0 -19
  87. package/src/index.ts +1 -4
  88. package/src/install/build-add-context-rule.ts +5 -139
  89. package/src/install/build-install-policy.ts +93 -214
  90. package/src/install/index.ts +0 -34
  91. package/src/predicate/decode.ts +2 -70
  92. package/src/predicate/encode.ts +49 -261
  93. package/src/predicate/from-json.ts +1 -43
  94. package/src/record/decode.ts +3 -8
  95. package/src/record/freshness.ts +29 -18
  96. package/src/review-card/builder.ts +19 -168
  97. package/src/review-card/cross-check.ts +3 -105
  98. package/src/review-card/render-leaf.ts +48 -0
  99. package/src/run/index.ts +144 -572
  100. package/src/run/schemas.ts +42 -291
  101. package/src/simulate/deny-cases.ts +334 -0
  102. package/src/simulate/evaluate.ts +284 -0
  103. package/src/simulate/index.ts +11 -0
  104. package/src/synth/compose-from-recording.ts +148 -347
  105. package/src/synth/index.ts +0 -13
  106. package/src/synth/synthesize-from-recording.ts +43 -456
  107. package/src/types.ts +13 -49
  108. package/dist/adapters/interpreter/index.d.ts +0 -1
  109. package/dist/adapters/interpreter/index.js +0 -2
  110. package/dist/adapters/oz/adapter.d.ts +0 -20
  111. package/dist/adapters/oz/adapter.js +0 -295
  112. package/dist/adapters/oz/index.d.ts +0 -1
  113. package/dist/adapters/oz/index.js +0 -2
  114. package/dist/codegen/compile-gate.d.ts +0 -33
  115. package/dist/codegen/compile-gate.js +0 -124
  116. package/dist/codegen/index.d.ts +0 -2
  117. package/dist/codegen/index.js +0 -8
  118. package/dist/codegen/template.d.ts +0 -18
  119. package/dist/codegen/template.js +0 -148
  120. package/dist/install/authority-overlap.d.ts +0 -134
  121. package/dist/install/authority-overlap.js +0 -0
  122. package/dist/install/build-install-predicate.d.ts +0 -96
  123. package/dist/install/build-install-predicate.js +0 -444
  124. package/dist/install/build-merge-policy.d.ts +0 -70
  125. package/dist/install/build-merge-policy.js +0 -130
  126. package/dist/install/plan-merge-policy.d.ts +0 -49
  127. package/dist/install/plan-merge-policy.js +0 -86
  128. package/dist/install/read-account-rules.d.ts +0 -100
  129. package/dist/install/read-account-rules.js +0 -283
  130. package/dist/ir/index.d.ts +0 -1
  131. package/dist/ir/index.js +0 -2
  132. package/dist/ir/types.d.ts +0 -140
  133. package/dist/ir/types.js +0 -11
  134. package/dist/mandate/index.d.ts +0 -2
  135. package/dist/mandate/index.js +0 -2
  136. package/dist/mandate/to-ir.d.ts +0 -3
  137. package/dist/mandate/to-ir.js +0 -60
  138. package/dist/mandate/types.d.ts +0 -20
  139. package/dist/mandate/types.js +0 -8
  140. package/dist/seams/index.d.ts +0 -1
  141. package/dist/seams/index.js +0 -2
  142. package/dist/seams/types.d.ts +0 -66
  143. package/dist/seams/types.js +0 -11
  144. package/dist/synth/deny-cases.js +0 -562
  145. package/dist/synth/evaluate.d.ts +0 -39
  146. package/dist/synth/evaluate.js +0 -551
  147. package/dist/synth/harness.d.ts +0 -28
  148. package/dist/synth/harness.js +0 -47
  149. package/dist/synth/minimize.d.ts +0 -4
  150. package/dist/synth/minimize.js +0 -38
  151. package/dist/synth/permit-context.d.ts +0 -15
  152. package/dist/synth/permit-context.js +0 -116
  153. package/dist/synth/predicate-literals.d.ts +0 -5
  154. package/dist/synth/predicate-literals.js +0 -25
  155. package/dist/synth/synthesize-from-mandate.d.ts +0 -20
  156. package/dist/synth/synthesize-from-mandate.js +0 -59
  157. package/dist/verify/envelope.d.ts +0 -15
  158. package/dist/verify/envelope.js +0 -22
  159. package/dist/verify/index.d.ts +0 -3
  160. package/dist/verify/index.js +0 -3
  161. package/dist/verify/simulate.d.ts +0 -31
  162. package/dist/verify/simulate.js +0 -258
  163. package/dist/verify/verify.d.ts +0 -21
  164. package/dist/verify/verify.js +0 -189
  165. package/dist-cjs/adapters/interpreter/index.d.ts +0 -1
  166. package/dist-cjs/adapters/interpreter/index.js +0 -8
  167. package/dist-cjs/adapters/oz/adapter.d.ts +0 -20
  168. package/dist-cjs/adapters/oz/adapter.js +0 -300
  169. package/dist-cjs/adapters/oz/index.d.ts +0 -1
  170. package/dist-cjs/adapters/oz/index.js +0 -8
  171. package/dist-cjs/codegen/compile-gate.d.ts +0 -33
  172. package/dist-cjs/codegen/compile-gate.js +0 -128
  173. package/dist-cjs/codegen/index.d.ts +0 -2
  174. package/dist-cjs/codegen/index.js +0 -14
  175. package/dist-cjs/codegen/template.d.ts +0 -18
  176. package/dist-cjs/codegen/template.js +0 -151
  177. package/dist-cjs/install/authority-overlap.d.ts +0 -134
  178. package/dist-cjs/install/authority-overlap.js +0 -0
  179. package/dist-cjs/install/build-install-predicate.d.ts +0 -96
  180. package/dist-cjs/install/build-install-predicate.js +0 -479
  181. package/dist-cjs/install/build-merge-policy.d.ts +0 -70
  182. package/dist-cjs/install/build-merge-policy.js +0 -134
  183. package/dist-cjs/install/plan-merge-policy.d.ts +0 -49
  184. package/dist-cjs/install/plan-merge-policy.js +0 -90
  185. package/dist-cjs/install/read-account-rules.d.ts +0 -100
  186. package/dist-cjs/install/read-account-rules.js +0 -296
  187. package/dist-cjs/ir/index.d.ts +0 -1
  188. package/dist-cjs/ir/index.js +0 -3
  189. package/dist-cjs/ir/types.d.ts +0 -140
  190. package/dist-cjs/ir/types.js +0 -12
  191. package/dist-cjs/mandate/index.d.ts +0 -2
  192. package/dist-cjs/mandate/index.js +0 -6
  193. package/dist-cjs/mandate/to-ir.d.ts +0 -3
  194. package/dist-cjs/mandate/to-ir.js +0 -63
  195. package/dist-cjs/mandate/types.d.ts +0 -20
  196. package/dist-cjs/mandate/types.js +0 -9
  197. package/dist-cjs/seams/index.d.ts +0 -1
  198. package/dist-cjs/seams/index.js +0 -3
  199. package/dist-cjs/seams/types.d.ts +0 -66
  200. package/dist-cjs/seams/types.js +0 -12
  201. package/dist-cjs/synth/deny-cases.js +0 -568
  202. package/dist-cjs/synth/evaluate.d.ts +0 -39
  203. package/dist-cjs/synth/evaluate.js +0 -554
  204. package/dist-cjs/synth/harness.d.ts +0 -28
  205. package/dist-cjs/synth/harness.js +0 -50
  206. package/dist-cjs/synth/minimize.d.ts +0 -4
  207. package/dist-cjs/synth/minimize.js +0 -41
  208. package/dist-cjs/synth/permit-context.d.ts +0 -15
  209. package/dist-cjs/synth/permit-context.js +0 -119
  210. package/dist-cjs/synth/predicate-literals.d.ts +0 -5
  211. package/dist-cjs/synth/predicate-literals.js +0 -28
  212. package/dist-cjs/synth/synthesize-from-mandate.d.ts +0 -20
  213. package/dist-cjs/synth/synthesize-from-mandate.js +0 -62
  214. package/dist-cjs/verify/envelope.d.ts +0 -15
  215. package/dist-cjs/verify/envelope.js +0 -23
  216. package/dist-cjs/verify/index.d.ts +0 -3
  217. package/dist-cjs/verify/index.js +0 -8
  218. package/dist-cjs/verify/simulate.d.ts +0 -31
  219. package/dist-cjs/verify/simulate.js +0 -261
  220. package/dist-cjs/verify/verify.d.ts +0 -21
  221. package/dist-cjs/verify/verify.js +0 -192
  222. package/src/adapters/interpreter/index.ts +0 -8
  223. package/src/adapters/oz/adapter.ts +0 -376
  224. package/src/adapters/oz/index.ts +0 -9
  225. package/src/codegen/compile-gate.ts +0 -167
  226. package/src/codegen/index.ts +0 -17
  227. package/src/codegen/template.ts +0 -165
  228. package/src/install/authority-overlap.ts +0 -0
  229. package/src/install/build-merge-policy.ts +0 -219
  230. package/src/install/plan-merge-policy.ts +0 -133
  231. package/src/install/read-account-rules.ts +0 -376
  232. package/src/ir/index.ts +0 -13
  233. package/src/ir/types.ts +0 -132
  234. package/src/mandate/index.ts +0 -4
  235. package/src/mandate/to-ir.ts +0 -71
  236. package/src/mandate/types.ts +0 -21
  237. package/src/seams/index.ts +0 -11
  238. package/src/seams/types.ts +0 -81
  239. package/src/synth/deny-cases.ts +0 -663
  240. package/src/synth/evaluate.ts +0 -613
  241. package/src/synth/harness.ts +0 -68
  242. package/src/synth/minimize.ts +0 -48
  243. package/src/synth/permit-context.ts +0 -136
  244. package/src/synth/predicate-literals.ts +0 -27
  245. package/src/synth/synthesize-from-mandate.ts +0 -82
  246. package/src/verify/envelope.ts +0 -28
  247. package/src/verify/index.ts +0 -5
  248. package/src/verify/simulate.ts +0 -311
  249. package/src/verify/verify.ts +0 -243
@@ -1,15 +0,0 @@
1
- import type { PredicateNode, RecordedTransaction } from '../types.ts';
2
- import type { EvalContext } from './evaluate.ts';
3
- export interface PermitContextResponses {
4
- windowSeconds: number;
5
- invocationLimit?: number;
6
- limitAmount?: string;
7
- validUntilLedger: number;
8
- oraclePriceBound?: Array<{
9
- asset: string;
10
- operator: string;
11
- value: string;
12
- decimals: number;
13
- }>;
14
- }
15
- export declare function buildPermitContext(tx: RecordedTransaction, responses: PermitContextResponses, predicate: PredicateNode): EvalContext;
@@ -1,116 +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
- import { cloneScVal } from "./deny-cases.js";
10
- export function buildPermitContext(tx, responses, predicate) {
11
- const amountByToken = {};
12
- const totals = new Map();
13
- for (const m of tx.tokenMovements) {
14
- const current = totals.get(m.token) ?? 0n;
15
- totals.set(m.token, current + BigInt(m.amount));
16
- }
17
- for (const [token, total] of totals) {
18
- amountByToken[token] = total.toString();
19
- }
20
- const topLevel = tx.invocations[0];
21
- const scopeContract = topLevel?.contract ?? '';
22
- const oraclePriceByAsset = {};
23
- visitOracleLeaves(predicate, (asset, op, bound) => {
24
- let price;
25
- switch (op) {
26
- case 'lt':
27
- price = bound - 1n;
28
- break;
29
- case 'gt':
30
- price = bound + 1n;
31
- break;
32
- default:
33
- price = bound;
34
- }
35
- if (price < 0n)
36
- price = 0n;
37
- oraclePriceByAsset[asset] = { price: price.toString(), timestampSeconds: tx.fetchedAt };
38
- });
39
- const ctx = {
40
- contract: scopeContract,
41
- fn: topLevel?.fn ?? '',
42
- args: (topLevel?.args ?? []).map(cloneScVal),
43
- atLedger: tx.ledgerSequence,
44
- nowSeconds: tx.fetchedAt,
45
- amountByToken,
46
- windowSpentByToken: {},
47
- invocationCountByWindow: {},
48
- oraclePriceByAsset,
49
- };
50
- if (responses.validUntilLedger !== undefined) {
51
- ctx.validUntilLedger = responses.validUntilLedger;
52
- }
53
- return ctx;
54
- }
55
- function visitOracleLeaves(node, visit) {
56
- switch (node.op) {
57
- case 'and':
58
- case 'or':
59
- for (const child of node.children)
60
- visitOracleLeaves(child, visit);
61
- return;
62
- case 'not':
63
- visitOracleLeaves(node.child, visit);
64
- return;
65
- case 'eq':
66
- case 'lt':
67
- case 'lte':
68
- case 'gt':
69
- case 'gte': {
70
- const leftIsOracle = node.left.kind === 'oracle_price';
71
- const rightIsOracle = node.right.kind === 'oracle_price';
72
- let asset;
73
- let literal;
74
- if (leftIsOracle) {
75
- asset = node.left.kind === 'oracle_price' ? node.left.asset : undefined;
76
- literal = oracleThresholdNormalised(node.right);
77
- }
78
- else if (rightIsOracle) {
79
- asset = node.right.kind === 'oracle_price' ? node.right.asset : undefined;
80
- literal = oracleThresholdNormalised(node.left);
81
- }
82
- if (asset !== undefined && literal !== undefined) {
83
- visit(asset, node.op, literal);
84
- }
85
- return;
86
- }
87
- case 'in':
88
- return;
89
- }
90
- }
91
- /** Oracle prices normalise to 9 decimals; mirrors NORMALISED_DECIMALS in
92
- * oracle.rs. */
93
- const NORMALISED_DECIMALS = 9n;
94
- /** A threshold restated on the normalised basis, so a derived permit price is
95
- * comparable to it. Thresholds carry their own basis, so the conversion has
96
- * to happen here - reading the digits raw would build a context off by a
97
- * factor of 10^(decimals-9). Returns undefined for any other leaf. */
98
- function oracleThresholdNormalised(leaf) {
99
- if (leaf.kind !== 'oracle_threshold')
100
- return undefined;
101
- let value;
102
- try {
103
- value = BigInt(leaf.value);
104
- }
105
- catch {
106
- return undefined;
107
- }
108
- const decimals = BigInt(leaf.decimals);
109
- if (decimals <= NORMALISED_DECIMALS) {
110
- return value * 10n ** (NORMALISED_DECIMALS - decimals);
111
- }
112
- // Floor: a finer-grained threshold has no exact 9-dp representation. The
113
- // caller only needs a price that lands on the right side of the bound, and
114
- // it offsets by one from here.
115
- return value / 10n ** (decimals - NORMALISED_DECIMALS);
116
- }
@@ -1,5 +0,0 @@
1
- import type { PredicateLeaf } from '../types.ts';
2
- /** BigInt value of a numeric-integer literal leaf (`literal_i128` / `literal_u64`
3
- * / `literal_u32`), or null for a non-numeric literal (address / symbol / bytes
4
- * / vec). Callers fail closed on null. */
5
- export declare function literalNumericBigInt(leaf: PredicateLeaf): bigint | null;
@@ -1,25 +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
- /** BigInt value of a numeric-integer literal leaf (`literal_i128` / `literal_u64`
8
- * / `literal_u32`), or null for a non-numeric literal (address / symbol / bytes
9
- * / vec). Callers fail closed on null. */
10
- export function literalNumericBigInt(leaf) {
11
- switch (leaf.kind) {
12
- case 'literal_i128':
13
- case 'literal_u64':
14
- try {
15
- return BigInt(leaf.value);
16
- }
17
- catch {
18
- return null;
19
- }
20
- case 'literal_u32':
21
- return BigInt(leaf.value);
22
- default:
23
- return null;
24
- }
25
- }
@@ -1,20 +0,0 @@
1
- import type { OzAdapterConfig } from '../adapters/oz/adapter.ts';
2
- import type { ToolResponse } from '../errors.ts';
3
- import type { MandateSpec } from '../mandate/types.ts';
4
- import type { PredicateNode, ProposedPolicy } from '../types.ts';
5
- import type { SimulationResult } from '../verify/envelope.ts';
6
- export declare function synthesizeFromMandate(spec: MandateSpec, ozConfig: OzAdapterConfig,
7
- /** --explain opt-in. When true, the success envelope carries the
8
- * in-memory predicate tree (always null for the mandate path - the
9
- * declarative MandateSpec lowers to OZ built-ins, not to an
10
- * interpreter predicate) + a minimal honest SimulationResult. The
11
- * flag is ADDITIVE: the existing ProposedPolicy fields are never
12
- * altered. */
13
- opts?: {
14
- explain?: true;
15
- }): ToolResponse<ProposedPolicy> & {
16
- explain?: {
17
- predicateTree: PredicateNode | null;
18
- simulation: SimulationResult;
19
- };
20
- };
@@ -1,59 +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
- import { createOzAdapter } from "../adapters/oz/adapter.js";
11
- import { mandateToPolicyIR } from "../mandate/to-ir.js";
12
- const UNCOVERED_PREFIX = 'Not covered by OZ built-in primitives: ';
13
- export function synthesizeFromMandate(spec, ozConfig,
14
- /** --explain opt-in. When true, the success envelope carries the
15
- * in-memory predicate tree (always null for the mandate path - the
16
- * declarative MandateSpec lowers to OZ built-ins, not to an
17
- * interpreter predicate) + a minimal honest SimulationResult. The
18
- * flag is ADDITIVE: the existing ProposedPolicy fields are never
19
- * altered. */
20
- opts) {
21
- const ir = mandateToPolicyIR(spec);
22
- const adapter = createOzAdapter(ozConfig);
23
- const result = adapter.compile(ir);
24
- if (!result.proposed) {
25
- return {
26
- ok: false,
27
- error: {
28
- code: 'SYNTHESIS_ERROR',
29
- message: `mandate lowered to no installable OZ policy: ${result.uncovered.join('; ')}`,
30
- severity: 'error',
31
- retryable: false,
32
- details: { uncovered: result.uncovered },
33
- },
34
- };
35
- }
36
- const proposed = {
37
- ...result.proposed,
38
- warnings: result.uncovered.map((u) => `${UNCOVERED_PREFIX}${u}`),
39
- };
40
- // Same --explain envelope pattern as the recording path. The mandate path
41
- // never produces an interpreter predicate, so predicateTree is null and
42
- // the simulation is a minimal honest deny (no self-verify was performed).
43
- const envelope = { ok: true, data: proposed };
44
- if (opts?.explain) {
45
- envelope.explain = {
46
- predicateTree: null,
47
- simulation: {
48
- permit: {
49
- tx: 'deny',
50
- reason: 'No self-verification was performed (mandate path is OZ-only)',
51
- },
52
- evaluatedCases: [],
53
- backend: 'ts-model',
54
- simulatorVersion: 'not-run',
55
- },
56
- };
57
- }
58
- return envelope;
59
- }
@@ -1,15 +0,0 @@
1
- export type SimulationResult = {
2
- permit: {
3
- tx: 'permit';
4
- } | {
5
- tx: 'deny';
6
- reason: string;
7
- };
8
- evaluatedCases: Array<{
9
- dimension: string;
10
- outcome: 'permit' | 'deny';
11
- reason: string;
12
- }>;
13
- backend: 'interpreter-v1' | 'ts-model';
14
- simulatorVersion: string;
15
- };
@@ -1,22 +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
- export {};
@@ -1,3 +0,0 @@
1
- export type { SimulationResult } from './envelope.ts';
2
- export { type SimulateOptions, simulatePolicy } from './simulate.ts';
3
- export { type VerifyOptions, verifyPolicy } from './verify.ts';
@@ -1,3 +0,0 @@
1
- // src/verify/index.ts - re-export the simulation / verification surface.
2
- export { simulatePolicy } from "./simulate.js";
3
- export { verifyPolicy } from "./verify.js";
@@ -1,31 +0,0 @@
1
- import type { ToolResponse } from '../errors.ts';
2
- import type { PredicateNode, RecordedTransaction } from '../types.ts';
3
- import type { SimulationResult } from './envelope.ts';
4
- /** Options for `simulatePolicy`. `validUntilLedger` is propagated onto the
5
- * permit EvalContext so the simulator exercises the expiry gate; absent ->
6
- * no expiry check (mirrors the orchestrator's "no `validUntilLedger`
7
- * supplied" path). `oraclePricesByAsset` is the test fixture the simulator
8
- * uses to satisfy `oracle_price` leaves so the permit call evaluates under
9
- * the bound; absent -> derive satisfying prices from the predicate itself
10
- * (the orchestrator's oracle-satisfying-price logic). */
11
- export interface SimulateOptions {
12
- validUntilLedger?: number;
13
- /** Pre-populated oracle-price entries keyed by asset address. The fixture
14
- * must satisfy every `oracle_price` leaf in the predicate; absent or
15
- * unsatisfying entries cause `SIMULATION_ERROR`. */
16
- oraclePricesByAsset?: Record<string, {
17
- price: string;
18
- timestampSeconds: number;
19
- } | {
20
- error: 'stale' | 'missing' | 'deviation' | 'paused' | 'decimals' | 'fingerprint';
21
- }>;
22
- }
23
- /** Replay a recorded transaction against a proposed predicate and emit the
24
- * `SimulationResult` envelope. The simulator returns the SAME permit
25
- * verdict `runHarness` expects: the intended recorded call must permit; every
26
- * generated deny dimension must deny. A runtime evaluation failure
27
- * (malformed input, missing oracle fixture, etc.) returns a `SIMULATION_ERROR`
28
- * `ToolError` - NOT a deny verdict, NOT `VERIFICATION_FAILED`. The boundary
29
- * is pinned: minimality is a verify-time concern, runtime evaluation is a
30
- * simulate-time concern. */
31
- export declare function simulatePolicy(predicate: PredicateNode | null, permitTx: RecordedTransaction, opts?: SimulateOptions): ToolResponse<SimulationResult>;
@@ -1,258 +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
- import { generateCases } from "../synth/deny-cases.js";
30
- import { evaluate } from "../synth/evaluate.js";
31
- import { MAX_SCVAL_CLONE_DEPTH } from "../types.js";
32
- const SIMULATOR_VERSION = 'ts-model-1.0.0';
33
- /** Replay a recorded transaction against a proposed predicate and emit the
34
- * `SimulationResult` envelope. The simulator returns the SAME permit
35
- * verdict `runHarness` expects: the intended recorded call must permit; every
36
- * generated deny dimension must deny. A runtime evaluation failure
37
- * (malformed input, missing oracle fixture, etc.) returns a `SIMULATION_ERROR`
38
- * `ToolError` - NOT a deny verdict, NOT `VERIFICATION_FAILED`. The boundary
39
- * is pinned: minimality is a verify-time concern, runtime evaluation is a
40
- * simulate-time concern. */
41
- export function simulatePolicy(predicate, permitTx, opts = {}) {
42
- // The permit EvalContext requires a top-level invocation. A recorded tx
43
- // with no invocations is structurally malformed input - we surface a
44
- // runtime `SIMULATION_ERROR` rather than fabricating a permit verdict.
45
- const topLevel = permitTx.invocations[0];
46
- if (!topLevel) {
47
- return {
48
- ok: false,
49
- error: simulationError('recorded transaction has no top-level invocation to simulate'),
50
- };
51
- }
52
- let permitCtx;
53
- try {
54
- permitCtx = buildPermitContext(predicate, permitTx, topLevel, opts);
55
- }
56
- catch (e) {
57
- return {
58
- ok: false,
59
- error: simulationError(`could not build permit evaluation context: ${e.message}`),
60
- };
61
- }
62
- // `predicate === null` means the policy is OZ-only (no interpreter
63
- // predicate). We still emit the envelope so the review card + verifier
64
- // can consume it: the permit verdict evaluates an always-permit empty
65
- // tree, and the deny battery is empty (nothing to verify at the
66
- // interpreter layer).
67
- const evaluatePredicate = predicate ?? { op: 'and', children: [] };
68
- const evaluatedCases = [];
69
- let permitVerdict;
70
- try {
71
- permitVerdict = evaluate(evaluatePredicate, permitCtx);
72
- }
73
- catch (e) {
74
- return {
75
- ok: false,
76
- error: simulationError(`permit evaluation threw at runtime: ${e.message}`, e),
77
- };
78
- }
79
- evaluatedCases.push({
80
- dimension: 'permit',
81
- outcome: permitVerdict.permit ? 'permit' : 'deny',
82
- reason: permitVerdict.permit ? 'matches recorded call' : permitVerdict.reason,
83
- });
84
- // The deny battery is generated against the SAME permit context. A
85
- // runtime evaluation failure on ANY deny case is a `SIMULATION_ERROR` -
86
- // not a deny verdict (an evaluate-throws is not a deny) and not a
87
- // minimality problem.
88
- const cases = generateCases(evaluatePredicate, permitCtx);
89
- for (const deny of cases.denies) {
90
- let result;
91
- try {
92
- result = evaluate(evaluatePredicate, deny.ctx);
93
- }
94
- catch (e) {
95
- return {
96
- ok: false,
97
- error: simulationError(`deny case "${deny.dimension}" threw at runtime: ${e.message}`, e),
98
- };
99
- }
100
- evaluatedCases.push({
101
- dimension: deny.dimension,
102
- outcome: result.permit ? 'permit' : 'deny',
103
- reason: result.permit ? 'no matching deny' : result.reason,
104
- });
105
- }
106
- const envelope = {
107
- permit: permitVerdict.permit ? { tx: 'permit' } : { tx: 'deny', reason: permitVerdict.reason },
108
- evaluatedCases,
109
- backend: 'ts-model',
110
- simulatorVersion: SIMULATOR_VERSION,
111
- };
112
- return { ok: true, data: envelope };
113
- }
114
- /** Build the permit `EvalContext` the simulator drives. Mirrors the
115
- * helper in `synthesize-from-recording.ts` so the simulator sees the same
116
- * shape the orchestrator's self-verify pipeline sees; we mirror here
117
- * rather than import to keep `src/verify/` decoupled from the
118
- * orchestrator's private helpers. The shape is pinned by tests so the
119
- * two implementations stay in lockstep. */
120
- function buildPermitContext(predicate, tx, topLevel, opts) {
121
- const amountByToken = {};
122
- const totals = new Map();
123
- for (const m of tx.tokenMovements) {
124
- const current = totals.get(m.token) ?? 0n;
125
- totals.set(m.token, current + BigInt(m.amount));
126
- }
127
- for (const [token, total] of totals) {
128
- amountByToken[token] = total.toString();
129
- }
130
- // Oracle prices: when the caller supplies a fixture, use it; otherwise
131
- // derive a satisfying entry per `oracle_price` leaf in the predicate so
132
- // the permit call permits. Negatives are clamped at 0 (Stellar oracle
133
- // prices are non-negative).
134
- const oraclePriceByAsset = {};
135
- if (opts.oraclePricesByAsset) {
136
- for (const [asset, entry] of Object.entries(opts.oraclePricesByAsset)) {
137
- oraclePriceByAsset[asset] = entry;
138
- }
139
- }
140
- if (predicate !== null) {
141
- visitOracleLeaves(predicate, (asset, op, bound) => {
142
- // A caller-supplied fixture entry always wins; we only fill gaps.
143
- if (oraclePriceByAsset[asset] !== undefined)
144
- return;
145
- let price;
146
- switch (op) {
147
- case 'lt':
148
- case 'gt':
149
- price = op === 'lt' ? bound - 1n : bound + 1n;
150
- break;
151
- case 'lte':
152
- case 'gte':
153
- case 'eq':
154
- price = bound;
155
- break;
156
- }
157
- if (price < 0n)
158
- price = 0n;
159
- oraclePriceByAsset[asset] = {
160
- price: price.toString(),
161
- timestampSeconds: tx.fetchedAt,
162
- };
163
- });
164
- }
165
- const ctx = {
166
- contract: topLevel.contract,
167
- fn: topLevel.fn,
168
- args: topLevel.args.map(cloneScVal),
169
- atLedger: tx.ledgerSequence,
170
- nowSeconds: tx.fetchedAt,
171
- amountByToken,
172
- windowSpentByToken: {},
173
- invocationCountByWindow: {},
174
- oraclePriceByAsset,
175
- };
176
- if (opts.validUntilLedger !== undefined) {
177
- ctx.validUntilLedger = opts.validUntilLedger;
178
- }
179
- return ctx;
180
- }
181
- function cloneScVal(value, depth = 0) {
182
- // Recursion is bounded by MAX_SCVAL_CLONE_DEPTH so a hand-crafted nested-vec
183
- // payload cannot RangeError the JS stack during context building. Over-depth
184
- // throws a ToolError-shaped error that the simulator's existing try/catch
185
- // converts to a structured `{ok:false, error}` (not a thrown RangeError).
186
- if (value.type === 'vec') {
187
- if (depth >= MAX_SCVAL_CLONE_DEPTH) {
188
- throw cloneDepthError(value);
189
- }
190
- return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) };
191
- }
192
- return { ...value };
193
- }
194
- function cloneDepthError(value) {
195
- const err = new Error(`ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${MAX_SCVAL_CLONE_DEPTH})`);
196
- err.code = 'SIMULATION_ERROR';
197
- err.severity = 'error';
198
- err.retryable = false;
199
- err.depthContext = value.type;
200
- throw err;
201
- }
202
- function visitOracleLeaves(node, visit) {
203
- switch (node.op) {
204
- case 'and':
205
- case 'or':
206
- for (const child of node.children)
207
- visitOracleLeaves(child, visit);
208
- return;
209
- case 'not':
210
- visitOracleLeaves(node.child, visit);
211
- return;
212
- case 'eq':
213
- case 'lt':
214
- case 'lte':
215
- case 'gt':
216
- case 'gte': {
217
- const leftLeaf = node.left;
218
- const rightLeaf = node.right;
219
- let oracleAsset;
220
- let literal;
221
- if (leftLeaf.kind === 'oracle_price') {
222
- oracleAsset = leftLeaf.asset;
223
- literal = oracleLiteralFromLeaf(rightLeaf);
224
- }
225
- else if (rightLeaf.kind === 'oracle_price') {
226
- oracleAsset = rightLeaf.asset;
227
- literal = oracleLiteralFromLeaf(leftLeaf);
228
- }
229
- if (oracleAsset === undefined || literal === undefined)
230
- return;
231
- visit(oracleAsset, node.op, literal);
232
- return;
233
- }
234
- case 'in':
235
- return;
236
- }
237
- }
238
- function oracleLiteralFromLeaf(leaf) {
239
- if (leaf.kind !== 'literal_i128')
240
- return undefined;
241
- try {
242
- return BigInt(leaf.value);
243
- }
244
- catch {
245
- return undefined;
246
- }
247
- }
248
- function simulationError(message, cause) {
249
- const error = {
250
- code: 'SIMULATION_ERROR',
251
- message,
252
- severity: 'error',
253
- retryable: false,
254
- };
255
- if (cause !== undefined)
256
- error.details = { cause: String(cause) };
257
- return error;
258
- }
@@ -1,21 +0,0 @@
1
- import type { ToolResponse } from '../errors.ts';
2
- import type { PredicateNode, RecordedTransaction } from '../types.ts';
3
- /** Options for `verifyPolicy`. Mirrors the orchestrator's permit-context
4
- * knobs (expiry; oracle fixture) so verify sees the same shape
5
- * `simulatePolicy` sees. */
6
- export interface VerifyOptions {
7
- validUntilLedger?: number;
8
- oraclePricesByAsset?: Record<string, {
9
- price: string;
10
- timestampSeconds: number;
11
- } | {
12
- error: 'stale' | 'missing' | 'deviation' | 'paused' | 'decimals' | 'fingerprint';
13
- }>;
14
- }
15
- /** Run the static minimality check on a proposed predicate + recorded tx.
16
- * Returns `{ ok: true }` when the predicate is minimal (every top-level
17
- * conjunct carries load) and `VERIFICATION_FAILED` when a conjunct could
18
- * be dropped without losing a deny-case. The dropped conjuncts are
19
- * reported in `details.droppedConstraints` so the caller can render a
20
- * review-card warning. */
21
- export declare function verifyPolicy(predicate: PredicateNode, permitTx: RecordedTransaction, opts?: VerifyOptions): ToolResponse<true>;