@crediolabs/policy-synth 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +193 -5
  2. package/dist/adapters/interpreter/adapter.d.ts +38 -0
  3. package/dist/adapters/interpreter/adapter.js +522 -0
  4. package/dist/adapters/interpreter/index.d.ts +1 -0
  5. package/dist/adapters/interpreter/index.js +2 -0
  6. package/dist/adapters/oz/adapter.js +20 -18
  7. package/dist/codegen/compile-gate.d.ts +33 -0
  8. package/dist/codegen/compile-gate.js +119 -0
  9. package/dist/codegen/index.d.ts +2 -0
  10. package/dist/codegen/index.js +8 -0
  11. package/dist/codegen/template.d.ts +18 -0
  12. package/dist/codegen/template.js +131 -0
  13. package/dist/errors.d.ts +1 -1
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +2 -0
  16. package/dist/ir/types.d.ts +13 -2
  17. package/dist/mandate/to-ir.js +4 -4
  18. package/dist/mandate/types.d.ts +1 -1
  19. package/dist/predicate/encode.d.ts +10 -0
  20. package/dist/predicate/encode.js +249 -0
  21. package/dist/predicate/index.d.ts +1 -0
  22. package/dist/predicate/index.js +2 -0
  23. package/dist/review-card/builder.d.ts +14 -0
  24. package/dist/review-card/builder.js +261 -0
  25. package/dist/review-card/conflict.d.ts +40 -0
  26. package/dist/review-card/conflict.js +111 -0
  27. package/dist/review-card/cross-check.d.ts +11 -0
  28. package/dist/review-card/cross-check.js +148 -0
  29. package/dist/review-card/index.d.ts +3 -0
  30. package/dist/review-card/index.js +4 -0
  31. package/dist/seams/types.d.ts +1 -1
  32. package/dist/synth/compose-from-recording.d.ts +35 -7
  33. package/dist/synth/compose-from-recording.js +231 -40
  34. package/dist/synth/deny-cases.d.ts +12 -0
  35. package/dist/synth/deny-cases.js +361 -0
  36. package/dist/synth/evaluate.d.ts +39 -0
  37. package/dist/synth/evaluate.js +425 -0
  38. package/dist/synth/harness.d.ts +16 -0
  39. package/dist/synth/harness.js +26 -0
  40. package/dist/synth/index.d.ts +4 -0
  41. package/dist/synth/index.js +4 -0
  42. package/dist/synth/lower.d.ts +2 -2
  43. package/dist/synth/minimize.d.ts +4 -0
  44. package/dist/synth/minimize.js +38 -0
  45. package/dist/synth/predicate-literals.d.ts +5 -0
  46. package/dist/synth/predicate-literals.js +25 -0
  47. package/dist/synth/synthesize-from-mandate.js +5 -5
  48. package/dist/synth/synthesize-from-recording.d.ts +32 -3
  49. package/dist/synth/synthesize-from-recording.js +491 -17
  50. package/dist/types.d.ts +23 -1
  51. package/dist/verify/envelope.d.ts +15 -0
  52. package/dist/verify/envelope.js +22 -0
  53. package/dist/verify/index.d.ts +3 -0
  54. package/dist/verify/index.js +3 -0
  55. package/dist/verify/simulate.d.ts +31 -0
  56. package/dist/verify/simulate.js +242 -0
  57. package/dist/verify/verify.d.ts +21 -0
  58. package/dist/verify/verify.js +173 -0
  59. package/package.json +1 -1
  60. package/src/adapters/interpreter/adapter.ts +642 -0
  61. package/src/adapters/interpreter/index.ts +8 -0
  62. package/src/adapters/oz/adapter.ts +20 -18
  63. package/src/codegen/compile-gate.ts +162 -0
  64. package/src/codegen/index.ts +17 -0
  65. package/src/codegen/template.ts +148 -0
  66. package/src/errors.ts +2 -0
  67. package/src/index.ts +2 -0
  68. package/src/ir/types.ts +9 -2
  69. package/src/mandate/to-ir.ts +4 -4
  70. package/src/mandate/types.ts +1 -1
  71. package/src/predicate/encode.ts +307 -0
  72. package/src/predicate/index.ts +3 -0
  73. package/src/review-card/builder.ts +303 -0
  74. package/src/review-card/conflict.ts +143 -0
  75. package/src/review-card/cross-check.ts +158 -0
  76. package/src/review-card/index.ts +12 -0
  77. package/src/seams/types.ts +1 -1
  78. package/src/synth/compose-from-recording.ts +283 -49
  79. package/src/synth/deny-cases.ts +447 -0
  80. package/src/synth/evaluate.ts +493 -0
  81. package/src/synth/harness.ts +40 -0
  82. package/src/synth/index.ts +12 -0
  83. package/src/synth/lower.ts +2 -2
  84. package/src/synth/minimize.ts +44 -0
  85. package/src/synth/predicate-literals.ts +27 -0
  86. package/src/synth/synthesize-from-mandate.ts +5 -5
  87. package/src/synth/synthesize-from-recording.ts +575 -18
  88. package/src/types.ts +19 -2
  89. package/src/verify/envelope.ts +28 -0
  90. package/src/verify/index.ts +5 -0
  91. package/src/verify/simulate.ts +292 -0
  92. package/src/verify/verify.ts +224 -0
@@ -0,0 +1,261 @@
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
+ import { createHash } from 'node:crypto';
32
+ /** Build a deterministic review-card summary from a policy + context rule +
33
+ * simulation result. Pure: same inputs -> byte-identical output. */
34
+ export function buildReviewCardSummary(predicate, policyRefs, contextRule, simulation) {
35
+ const constraints = [];
36
+ for (const ref of policyRefs) {
37
+ const line = renderOzPrimitive(ref);
38
+ if (line !== null)
39
+ constraints.push(line);
40
+ }
41
+ if (predicate !== null) {
42
+ walkPredicate(predicate, (node) => {
43
+ const line = renderConstraint(node);
44
+ if (line !== null)
45
+ constraints.push(line);
46
+ });
47
+ }
48
+ const ruleName = contextRule.name;
49
+ const plainEnglish = renderPlainEnglish(ruleName, constraints);
50
+ const expiry = renderExpiry(contextRule.validUntilLedger);
51
+ const backend = simulation.backend;
52
+ const contentHash = computeContentHash({
53
+ ruleName,
54
+ plainEnglish,
55
+ constraints,
56
+ expiry,
57
+ backend,
58
+ });
59
+ return { ruleName, plainEnglish, constraints, expiry, backend, contentHash };
60
+ }
61
+ /** Render the OZ built-in primitive summary line. Only `spending_limit` is
62
+ * quoted by the review card (it is the only primitive that defines a
63
+ * transactional bound). Other primitives (threshold) are signer-config
64
+ * concerns handled by the OZ adapter's own `uncovered` machinery.
65
+ * Spending_limit takes `period_ledgers` on-chain (~5s/ledger); the card
66
+ * states the window in seconds so the user reads it consistently with the
67
+ * interpreter templates. */
68
+ function renderOzPrimitive(ref) {
69
+ if (ref.kind !== 'oz_builtin')
70
+ return null;
71
+ const primitive = ref.primitive;
72
+ if (primitive.primitive !== 'spending_limit')
73
+ return null;
74
+ const params = primitive.params;
75
+ const limit = params.spending_limit ?? '0';
76
+ const periodLedgers = params.period_ledgers ?? 0;
77
+ const windowSecs = periodLedgers * 5;
78
+ return `spending_limit(${limit}, ${windowSecs})`;
79
+ }
80
+ /** Walk every comparison / membership node of the predicate and invoke
81
+ * `visit` on each. The walk is depth-first, left-to-right, so the
82
+ * constraint list is stable across runs. Pure boolean nodes contribute no
83
+ * constraint lines themselves; their leaf children do, via the visitor. */
84
+ function walkPredicate(node, visit) {
85
+ switch (node.op) {
86
+ case 'and':
87
+ case 'or':
88
+ for (const child of node.children)
89
+ walkPredicate(child, visit);
90
+ return;
91
+ case 'not':
92
+ walkPredicate(node.child, visit);
93
+ return;
94
+ case 'in':
95
+ visit(node);
96
+ return;
97
+ case 'eq':
98
+ case 'lt':
99
+ case 'lte':
100
+ case 'gt':
101
+ case 'gte':
102
+ visit(node);
103
+ return;
104
+ }
105
+ }
106
+ /** Render ONE constraint sentence for ONE interpreter predicate node. The
107
+ * shape of the output is pinned by Task 7b so the test suite can assert
108
+ * byte-for-byte equality. Returns `null` when the node is a structural
109
+ * boolean (`and` / `or` / `not`) - those are not constraint leaves. */
110
+ function renderConstraint(node) {
111
+ switch (node.op) {
112
+ case 'and':
113
+ case 'or':
114
+ case 'not':
115
+ return null;
116
+ case 'eq':
117
+ case 'lt':
118
+ case 'lte':
119
+ case 'gt':
120
+ case 'gte':
121
+ return renderComparison(node);
122
+ case 'in':
123
+ return renderMembership(node);
124
+ }
125
+ }
126
+ function renderComparison(node) {
127
+ const left = node.left;
128
+ const right = node.right;
129
+ // eq(call_contract, literal_address) -> Contract must be <addr>
130
+ if (left.kind === 'call_contract' && node.op === 'eq' && right.kind === 'literal_address') {
131
+ return `Contract must be ${right.value}`;
132
+ }
133
+ // eq(call_fn, literal_symbol) -> Function must be <sym>
134
+ if (left.kind === 'call_fn' && node.op === 'eq' && right.kind === 'literal_symbol') {
135
+ return `Function must be ${right.value}`;
136
+ }
137
+ // eq(call_arg[i], literal_vec) -> Path must be exactly [list]
138
+ if (left.kind === 'call_arg' && node.op === 'eq' && right.kind === 'literal_vec') {
139
+ return `Path must be exactly [${right.elements.map(renderVecElement).join(', ')}]`;
140
+ }
141
+ // invocation_count_in_window <= N -> Invocations <= N per <window> seconds
142
+ if (left.kind === 'invocation_count_in_window' && right.kind === 'literal_u32') {
143
+ return `Invocations <= ${right.value} per ${left.windowSecs} seconds`;
144
+ }
145
+ // amount <= v -> Amount <= v
146
+ if (left.kind === 'amount' && right.kind === 'literal_i128') {
147
+ return `Amount <= ${right.value}`;
148
+ }
149
+ // oracle_price(asset) OP price -> Only when oracle_price(asset) OP price
150
+ if (left.kind === 'oracle_price' && right.kind === 'literal_i128') {
151
+ return `Only when oracle_price(${left.asset}) ${comparisonOpText(node.op)} ${right.value}`;
152
+ }
153
+ // Any other comparison shape is a structural fail-closed: do not surface
154
+ // a misleading line. Cross-check still requires every leaf produce a
155
+ // constraint string; the only leaves we emit lines for are the ones we
156
+ // recognise above, so the test fixtures cover exactly the supported
157
+ // shapes.
158
+ return null;
159
+ }
160
+ function renderMembership(node) {
161
+ // call_arg[i] in [list] -> Recipient/arg must be one of [list]
162
+ if (node.needle.kind === 'call_arg') {
163
+ const list = node.haystack.map(renderHaystackElement).join(', ');
164
+ return `Recipient/arg must be one of [${list}]`;
165
+ }
166
+ return null;
167
+ }
168
+ function renderVecElement(leaf) {
169
+ switch (leaf.kind) {
170
+ case 'literal_address':
171
+ return leaf.value;
172
+ case 'literal_i128':
173
+ return leaf.value;
174
+ case 'literal_symbol':
175
+ return leaf.value;
176
+ case 'literal_u32':
177
+ return String(leaf.value);
178
+ case 'literal_u64':
179
+ return leaf.value;
180
+ case 'literal_bytes':
181
+ return leaf.value;
182
+ case 'literal_vec':
183
+ return `[${leaf.elements.map(renderVecElement).join(', ')}]`;
184
+ case 'call_contract':
185
+ case 'call_fn':
186
+ case 'call_arg':
187
+ case 'amount':
188
+ case 'window_spent':
189
+ case 'now':
190
+ case 'valid_until':
191
+ case 'invocation_count_in_window':
192
+ case 'oracle_price':
193
+ return `<${leaf.kind}>`;
194
+ }
195
+ }
196
+ function renderHaystackElement(leaf) {
197
+ if (leaf.kind === 'literal_address')
198
+ return leaf.value;
199
+ if (leaf.kind === 'literal_i128')
200
+ return leaf.value;
201
+ if (leaf.kind === 'literal_symbol')
202
+ return leaf.value;
203
+ if (leaf.kind === 'literal_u32')
204
+ return String(leaf.value);
205
+ if (leaf.kind === 'literal_u64')
206
+ return leaf.value;
207
+ if (leaf.kind === 'literal_bytes')
208
+ return leaf.value;
209
+ if (leaf.kind === 'literal_vec') {
210
+ return `[${leaf.elements.map(renderHaystackElement).join(', ')}]`;
211
+ }
212
+ return `<${leaf.kind}>`;
213
+ }
214
+ function comparisonOpText(op) {
215
+ switch (op) {
216
+ case 'lt':
217
+ return '<';
218
+ case 'lte':
219
+ return '<=';
220
+ case 'gt':
221
+ return '>';
222
+ case 'gte':
223
+ return '>=';
224
+ case 'eq':
225
+ return '==';
226
+ }
227
+ }
228
+ /** Render the plain-English one-liner. Format: `<ruleName>: <constraints>`,
229
+ * joined by `; ` so the user reads one sentence per constraint. */
230
+ function renderPlainEnglish(ruleName, constraints) {
231
+ if (constraints.length === 0)
232
+ return `${ruleName}: (no constraints)`;
233
+ return `${ruleName}: ${constraints.join('; ')}`;
234
+ }
235
+ /** Render the expiry line. `null` -> "No expiry"; a ledger sequence -> the
236
+ * ledger number so the user reads it in the same units the OZ context rule
237
+ * applies it. */
238
+ function renderExpiry(validUntilLedger) {
239
+ if (validUntilLedger === null)
240
+ return 'No expiry';
241
+ return `Valid until ledger ${validUntilLedger}`;
242
+ }
243
+ function computeContentHash(input) {
244
+ return createHash('sha256').update(canonicalStringify(input)).digest('hex');
245
+ }
246
+ /** Canonical JSON with recursively sorted object keys (stable across runs). */
247
+ function canonicalStringify(value) {
248
+ return JSON.stringify(sortKeys(value));
249
+ }
250
+ function sortKeys(value) {
251
+ if (Array.isArray(value))
252
+ return value.map(sortKeys);
253
+ if (value && typeof value === 'object') {
254
+ const out = {};
255
+ for (const key of Object.keys(value).sort()) {
256
+ out[key] = sortKeys(value[key]);
257
+ }
258
+ return out;
259
+ }
260
+ return value;
261
+ }
@@ -0,0 +1,40 @@
1
+ /** Minimal rule reference the classifier needs to compute the conflict kind.
2
+ * Carries the rule id (used in the annotation), the scope (contract +
3
+ * method), and an optional spending cap. The cap captures both the
4
+ * amount and the window so the classifier can compare apples to apples. */
5
+ export interface RuleRef {
6
+ id: string;
7
+ scope: {
8
+ contract?: string;
9
+ method?: string;
10
+ };
11
+ /** When set, the rule enforces this per-window spend cap (token +
12
+ * decimal-string amount + seconds window). */
13
+ spendingLimit?: {
14
+ token: string;
15
+ amount: string;
16
+ windowSeconds: number;
17
+ };
18
+ }
19
+ /** Structured annotation a single new-vs-existing rule comparison yields.
20
+ * Four mutually exclusive kinds; the union is exhaustive (the classifier
21
+ * never throws). */
22
+ export type ConflictAnnotation = {
23
+ kind: 'subsume';
24
+ existingRuleId: string;
25
+ detail: string;
26
+ } | {
27
+ kind: 'disjoint';
28
+ } | {
29
+ kind: 'counter_permissive';
30
+ existingRuleId: string;
31
+ newLimit: string;
32
+ existingLimit: string;
33
+ } | {
34
+ kind: 'window_divergent';
35
+ existingRuleId: string;
36
+ effectiveUnion: string;
37
+ };
38
+ /** Classify the relationship between a new rule and one existing rule.
39
+ * Pure: same pair -> same annotation. */
40
+ export declare function classifyConflict(newRule: RuleRef, existingRule: RuleRef): ConflictAnnotation;
@@ -0,0 +1,111 @@
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
+ /** Classify the relationship between a new rule and one existing rule.
30
+ * Pure: same pair -> same annotation. */
31
+ export function classifyConflict(newRule, existingRule) {
32
+ // --- step 1: subsume? (new.scope ⊋ existing.scope) ---
33
+ //
34
+ // Subsume requires existing to be fully scoped (both contract AND method
35
+ // pinned) AND new to be at least partially broader than existing. A new
36
+ // rule with identical scope to existing is NOT a superset - it is the
37
+ // same rule and falls through to the same-scope branch below. If existing
38
+ // is "any contract" / "any method" then it is the wildest rule in the
39
+ // rule set; a new rule covering it is just a duplicate, not a subsume -
40
+ // fall through to disjoint.
41
+ const existingHasContract = existingRule.scope.contract !== undefined;
42
+ const existingHasMethod = existingRule.scope.method !== undefined;
43
+ const newIsBroaderOnContract = newRule.scope.contract === undefined && existingHasContract;
44
+ const newIsBroaderOnMethod = newRule.scope.method === undefined && existingHasMethod;
45
+ const newMatchesOnContract = newRule.scope.contract === undefined ||
46
+ (existingHasContract && newRule.scope.contract === existingRule.scope.contract);
47
+ const newMatchesOnMethod = newRule.scope.method === undefined ||
48
+ (existingHasMethod && newRule.scope.method === existingRule.scope.method);
49
+ if (existingHasContract &&
50
+ existingHasMethod &&
51
+ newMatchesOnContract &&
52
+ newMatchesOnMethod &&
53
+ (newIsBroaderOnContract || newIsBroaderOnMethod)) {
54
+ return {
55
+ kind: 'subsume',
56
+ existingRuleId: existingRule.id,
57
+ detail: `new rule scope (${describeScope(newRule)}) is a superset of existing rule (${describeScope(existingRule)})`,
58
+ };
59
+ }
60
+ // --- step 2: disjoint by scope? ---
61
+ if (existingHasContract && newRule.scope.contract !== undefined) {
62
+ if (newRule.scope.contract !== existingRule.scope.contract) {
63
+ return { kind: 'disjoint' };
64
+ }
65
+ }
66
+ if (existingHasMethod &&
67
+ newRule.scope.method !== undefined &&
68
+ newRule.scope.method !== existingRule.scope.method) {
69
+ return { kind: 'disjoint' };
70
+ }
71
+ // --- step 3: same scope -> compare spend caps (when both sides carry them) ---
72
+ if (newRule.spendingLimit && existingRule.spendingLimit) {
73
+ const a = newRule.spendingLimit;
74
+ const b = existingRule.spendingLimit;
75
+ if (a.token !== b.token) {
76
+ // Same scope, different tokens: each binds a different axis. They
77
+ // do not counter each other; treat as disjoint.
78
+ return { kind: 'disjoint' };
79
+ }
80
+ if (a.windowSeconds === b.windowSeconds) {
81
+ // Same scope, same token, same window: counter-permissive when the
82
+ // amounts disagree (the stricter wins at evaluate; the looser is
83
+ // dead weight). Equal amounts -> duplicate rule, treat as disjoint.
84
+ if (a.amount === b.amount) {
85
+ return { kind: 'disjoint' };
86
+ }
87
+ return {
88
+ kind: 'counter_permissive',
89
+ existingRuleId: existingRule.id,
90
+ newLimit: `${a.amount} ${a.token} / ${a.windowSeconds}s`,
91
+ existingLimit: `${b.amount} ${b.token} / ${b.windowSeconds}s`,
92
+ };
93
+ }
94
+ // Same scope + token, different windows: effective union is the sum
95
+ // of the two per-window caps (each window ticks independently).
96
+ const union = (BigInt(a.amount) + BigInt(b.amount)).toString();
97
+ return {
98
+ kind: 'window_divergent',
99
+ existingRuleId: existingRule.id,
100
+ effectiveUnion: `${union} ${a.token} per ${a.windowSeconds}s (new) + ${b.windowSeconds}s (existing)`,
101
+ };
102
+ }
103
+ // Same scope without comparable spend caps on both sides -> disjoint.
104
+ return { kind: 'disjoint' };
105
+ }
106
+ function describeScope(rule) {
107
+ const parts = [];
108
+ parts.push(rule.scope.contract ? `contract=${rule.scope.contract}` : 'contract=*');
109
+ parts.push(rule.scope.method ? `method=${rule.scope.method}` : 'method=*');
110
+ return parts.join(', ');
111
+ }
@@ -0,0 +1,11 @@
1
+ import type { PredicateNode } from '../types.ts';
2
+ import type { ReviewCardSummary } from './builder.ts';
3
+ /** Assert every leaf in the predicate appears as a constraint string in
4
+ * `summary.constraints`. Returns the missing templates (without the leaf
5
+ * values filled in) when any leaf was dropped. */
6
+ export declare function summaryCrossCheck(predicate: PredicateNode | null, summary: ReviewCardSummary): {
7
+ ok: true;
8
+ } | {
9
+ ok: false;
10
+ missingConstraints: string[];
11
+ };
@@ -0,0 +1,148 @@
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
+ /** Assert every leaf in the predicate appears as a constraint string in
16
+ * `summary.constraints`. Returns the missing templates (without the leaf
17
+ * values filled in) when any leaf was dropped. */
18
+ export function summaryCrossCheck(predicate, summary) {
19
+ if (predicate === null)
20
+ return { ok: true };
21
+ const expected = [];
22
+ collect(predicate, expected);
23
+ if (expected.length === 0)
24
+ return { ok: true };
25
+ const present = new Set(summary.constraints);
26
+ const missing = expected.filter((s) => !present.has(s));
27
+ if (missing.length === 0)
28
+ return { ok: true };
29
+ return { ok: false, missingConstraints: missing };
30
+ }
31
+ /** Walk the predicate and emit the EXACT constraint string the builder is
32
+ * expected to produce for each leaf, in walk order. Strings here MUST
33
+ * match the templates in `builder.ts` byte-for-byte; the cross-check is
34
+ * the structural claim that "every supported leaf shape is rendered". */
35
+ function collect(node, out) {
36
+ switch (node.op) {
37
+ case 'and':
38
+ case 'or':
39
+ for (const child of node.children)
40
+ collect(child, out);
41
+ return;
42
+ case 'not':
43
+ collect(node.child, out);
44
+ return;
45
+ case 'eq':
46
+ case 'lt':
47
+ case 'lte':
48
+ case 'gt':
49
+ case 'gte':
50
+ pushComparison(node.left, node.right, node.op, out);
51
+ return;
52
+ case 'in':
53
+ pushMembership(node.needle, node.haystack, out);
54
+ return;
55
+ }
56
+ }
57
+ function pushComparison(left, right, op, out) {
58
+ if (left.kind === 'call_contract' && op === 'eq' && right.kind === 'literal_address') {
59
+ out.push(`Contract must be ${right.value}`);
60
+ return;
61
+ }
62
+ if (left.kind === 'call_fn' && op === 'eq' && right.kind === 'literal_symbol') {
63
+ out.push(`Function must be ${right.value}`);
64
+ return;
65
+ }
66
+ if (left.kind === 'call_arg' && op === 'eq' && right.kind === 'literal_vec') {
67
+ out.push(`Path must be exactly [${right.elements.map(renderVecElement).join(', ')}]`);
68
+ return;
69
+ }
70
+ if (left.kind === 'invocation_count_in_window' && right.kind === 'literal_u32') {
71
+ out.push(`Invocations <= ${right.value} per ${left.windowSecs} seconds`);
72
+ return;
73
+ }
74
+ if (left.kind === 'amount' && right.kind === 'literal_i128') {
75
+ out.push(`Amount <= ${right.value}`);
76
+ return;
77
+ }
78
+ if (left.kind === 'oracle_price' && right.kind === 'literal_i128') {
79
+ out.push(`Only when oracle_price(${left.asset}) ${comparisonOpText(op)} ${right.value}`);
80
+ return;
81
+ }
82
+ }
83
+ function pushMembership(needle, haystack, out) {
84
+ if (needle.kind !== 'call_arg')
85
+ return;
86
+ const list = haystack.map(renderHaystackElement).join(', ');
87
+ out.push(`Recipient/arg must be one of [${list}]`);
88
+ }
89
+ function renderVecElement(leaf) {
90
+ switch (leaf.kind) {
91
+ case 'literal_address':
92
+ return leaf.value;
93
+ case 'literal_i128':
94
+ return leaf.value;
95
+ case 'literal_symbol':
96
+ return leaf.value;
97
+ case 'literal_u32':
98
+ return String(leaf.value);
99
+ case 'literal_u64':
100
+ return leaf.value;
101
+ case 'literal_bytes':
102
+ return leaf.value;
103
+ case 'literal_vec':
104
+ return `[${leaf.elements.map(renderVecElement).join(', ')}]`;
105
+ case 'call_contract':
106
+ case 'call_fn':
107
+ case 'call_arg':
108
+ case 'amount':
109
+ case 'window_spent':
110
+ case 'now':
111
+ case 'valid_until':
112
+ case 'invocation_count_in_window':
113
+ case 'oracle_price':
114
+ return `<${leaf.kind}>`;
115
+ }
116
+ }
117
+ function renderHaystackElement(leaf) {
118
+ if (leaf.kind === 'literal_address')
119
+ return leaf.value;
120
+ if (leaf.kind === 'literal_i128')
121
+ return leaf.value;
122
+ if (leaf.kind === 'literal_symbol')
123
+ return leaf.value;
124
+ if (leaf.kind === 'literal_u32')
125
+ return String(leaf.value);
126
+ if (leaf.kind === 'literal_u64')
127
+ return leaf.value;
128
+ if (leaf.kind === 'literal_bytes')
129
+ return leaf.value;
130
+ if (leaf.kind === 'literal_vec') {
131
+ return `[${leaf.elements.map(renderHaystackElement).join(', ')}]`;
132
+ }
133
+ return `<${leaf.kind}>`;
134
+ }
135
+ function comparisonOpText(op) {
136
+ switch (op) {
137
+ case 'lt':
138
+ return '<';
139
+ case 'lte':
140
+ return '<=';
141
+ case 'gt':
142
+ return '>';
143
+ case 'gte':
144
+ return '>=';
145
+ case 'eq':
146
+ return '==';
147
+ }
148
+ }
@@ -0,0 +1,3 @@
1
+ export { buildReviewCardSummary, type ReviewCardSummary, } from './builder.ts';
2
+ export { type ConflictAnnotation, classifyConflict, type RuleRef, } from './conflict.ts';
3
+ export { summaryCrossCheck } from './cross-check.ts';
@@ -0,0 +1,4 @@
1
+ // src/review-card/index.ts - re-export the deterministic review-card surface.
2
+ export { buildReviewCardSummary, } from "./builder.js";
3
+ export { classifyConflict, } from "./conflict.js";
4
+ export { summaryCrossCheck } from "./cross-check.js";
@@ -36,7 +36,7 @@ export interface CustodyCapabilities {
36
36
  export interface CompileResult {
37
37
  /** false => some IR construct this backend cannot express (see `uncovered`). */
38
38
  covered: boolean;
39
- /** Human-readable list of unsupported constructs (the Path-B markers). */
39
+ /** Human-readable list of unsupported constructs. */
40
40
  uncovered: string[];
41
41
  /** The backend-native installable policy, assembled when a rule lowered. */
42
42
  proposed?: ProposedPolicy;
@@ -1,6 +1,14 @@
1
- import type { PolicyIR } from '../ir/types.ts';
1
+ import type { IRCompOp, PolicyIR } from '../ir/types.ts';
2
2
  import type { AmbiguityPrompt, ContractInvocation, Network } from '../types.ts';
3
3
  import type { IntentFacts } from './lower.ts';
4
+ /** Per-asset oracle-price bound supplied by the caller (e.g. swap allowed only
5
+ * if oracle_price(XLM) < 5.00 USDC). One entry per asset; the recorder never
6
+ * fabricates a price bound from a slippage value (different units). */
7
+ export interface OraclePriceBound {
8
+ asset: string;
9
+ operator: IRCompOp;
10
+ value: string;
11
+ }
4
12
  /** Caller-supplied answers to the ambiguity prompts. Every numeric bound the
5
13
  * synth might apply must come from here - the recording supplies observed
6
14
  * amounts (offered only as suggestions), never authorised ceilings. */
@@ -15,22 +23,42 @@ export interface ComposeUserResponses {
15
23
  /** Max invocations per window for an incoming-only flow. Required to emit an
16
24
  * invocation_count bound; absent -> FREQUENCY_BOUND_MISSING. */
17
25
  invocationLimit?: number;
26
+ /** Per-asset oracle-price bound(s). Each entry lowers to a single
27
+ * `oracle_price(asset) OP value` compare in the interpreter IR. Multiple
28
+ * entries on the same asset emit multiple leaves. */
29
+ oraclePriceBound?: OraclePriceBound[];
30
+ /** Recipient allowlist for a swap (call_arg[3] on SoroSwap's
31
+ * swap_exact_tokens_for_tokens). Absent -> RECIPIENT_ALLOWLIST_EMPTY
32
+ * ambiguity (the caller is prompted; proceeding without an allowlist leaves
33
+ * the recipient unconstrained). */
34
+ swapRecipientAllowlist?: string[];
18
35
  }
19
36
  /** Composition options. */
20
37
  export interface ComposeOptions {
21
38
  network: Network;
22
39
  userResponses?: ComposeUserResponses;
40
+ /** When true, constraints the OZ adapter cannot lower are routed to
41
+ * `interpreterIr` (the predicate-shape IR) so the orchestrator can compile
42
+ * them via the interpreter adapter. When false (the default for callers
43
+ * who have not opted in), every constraint goes to `ir` and the OZ
44
+ * adapter's `uncovered` machinery generates the descriptive warnings -
45
+ * today's behaviour. The orchestrator passes this flag through based on
46
+ * whether `opts.interpreter` was supplied. */
47
+ interpreterEnabled?: boolean;
23
48
  }
24
- /** Result of composition: the PolicyIR, any ambiguities surfaced during
25
- * inference, and descriptive Path-B warnings for needs that are NOT expressed
26
- * as an IR node (so no fabricated constraint is emitted). The orchestrator
27
- * carries ambiguities into `ProposedPolicy.ambiguities` and merges warnings
28
- * into `ProposedPolicy.warnings`. */
49
+ /** Result of composition: the OZ-shape PolicyIR, the predicate-shape PolicyIR
50
+ * (contains the constraints the OZ adapter cannot lower; empty when
51
+ * `interpreterEnabled` is false), any ambiguities surfaced during inference,
52
+ * and descriptive warnings for needs that are NOT expressed as an IR node
53
+ * (so no fabricated constraint is emitted). The orchestrator carries
54
+ * ambiguities into `ProposedPolicy.ambiguities` and merges warnings into
55
+ * `ProposedPolicy.warnings`. */
29
56
  export interface ComposeResult {
30
57
  ir: PolicyIR;
58
+ interpreterIr: PolicyIR;
31
59
  ambiguities: AmbiguityPrompt[];
32
60
  warnings: string[];
33
61
  }
34
- /** Compose a PolicyIR from the lowered facts + the resolved scope.
62
+ /** Compose a PolicyIR pair from the lowered facts + the resolved scope.
35
63
  * Pure (no randomness, no clock); same inputs -> byte-identical result. */
36
64
  export declare function composeFromRecording(facts: IntentFacts, scopeContract: string, topLevel: ContractInvocation | null, opts: ComposeOptions): ComposeResult;