@crediolabs/policy-synth 0.3.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 (102) hide show
  1. package/dist/record/freshness.d.ts +17 -11
  2. package/dist/record/freshness.js +28 -18
  3. package/dist-cjs/record/freshness.d.ts +17 -11
  4. package/dist-cjs/record/freshness.js +28 -18
  5. package/package.json +2 -2
  6. package/src/record/freshness.ts +29 -18
  7. package/dist/adapters/interpreter/index.d.ts +0 -1
  8. package/dist/adapters/interpreter/index.js +0 -2
  9. package/dist/adapters/oz/adapter.d.ts +0 -20
  10. package/dist/adapters/oz/adapter.js +0 -281
  11. package/dist/adapters/oz/index.d.ts +0 -1
  12. package/dist/adapters/oz/index.js +0 -2
  13. package/dist/codegen/compile-gate.d.ts +0 -33
  14. package/dist/codegen/compile-gate.js +0 -124
  15. package/dist/codegen/index.d.ts +0 -2
  16. package/dist/codegen/index.js +0 -8
  17. package/dist/codegen/template.d.ts +0 -18
  18. package/dist/codegen/template.js +0 -148
  19. package/dist/ir/index.d.ts +0 -1
  20. package/dist/ir/index.js +0 -2
  21. package/dist/ir/types.d.ts +0 -71
  22. package/dist/ir/types.js +0 -9
  23. package/dist/mandate/index.d.ts +0 -2
  24. package/dist/mandate/index.js +0 -2
  25. package/dist/mandate/to-ir.d.ts +0 -3
  26. package/dist/mandate/to-ir.js +0 -60
  27. package/dist/mandate/types.d.ts +0 -20
  28. package/dist/mandate/types.js +0 -8
  29. package/dist/seams/index.d.ts +0 -1
  30. package/dist/seams/index.js +0 -2
  31. package/dist/seams/types.d.ts +0 -64
  32. package/dist/seams/types.js +0 -11
  33. package/dist/synth/deny-cases.d.ts +0 -28
  34. package/dist/synth/deny-cases.js +0 -212
  35. package/dist/synth/evaluate.d.ts +0 -18
  36. package/dist/synth/evaluate.js +0 -271
  37. package/dist/synth/harness.d.ts +0 -28
  38. package/dist/synth/harness.js +0 -47
  39. package/dist/synth/minimize.d.ts +0 -4
  40. package/dist/synth/minimize.js +0 -38
  41. package/dist/synth/permit-context.d.ts +0 -8
  42. package/dist/synth/permit-context.js +0 -35
  43. package/dist/synth/predicate-literals.d.ts +0 -5
  44. package/dist/synth/predicate-literals.js +0 -25
  45. package/dist/synth/synthesize-from-mandate.d.ts +0 -20
  46. package/dist/synth/synthesize-from-mandate.js +0 -59
  47. package/dist/verify/envelope.d.ts +0 -15
  48. package/dist/verify/envelope.js +0 -22
  49. package/dist/verify/index.d.ts +0 -3
  50. package/dist/verify/index.js +0 -3
  51. package/dist/verify/simulate.d.ts +0 -18
  52. package/dist/verify/simulate.js +0 -172
  53. package/dist/verify/verify.d.ts +0 -15
  54. package/dist/verify/verify.js +0 -181
  55. package/dist-cjs/adapters/interpreter/index.d.ts +0 -1
  56. package/dist-cjs/adapters/interpreter/index.js +0 -7
  57. package/dist-cjs/adapters/oz/adapter.d.ts +0 -20
  58. package/dist-cjs/adapters/oz/adapter.js +0 -286
  59. package/dist-cjs/adapters/oz/index.d.ts +0 -1
  60. package/dist-cjs/adapters/oz/index.js +0 -8
  61. package/dist-cjs/codegen/compile-gate.d.ts +0 -33
  62. package/dist-cjs/codegen/compile-gate.js +0 -128
  63. package/dist-cjs/codegen/index.d.ts +0 -2
  64. package/dist-cjs/codegen/index.js +0 -14
  65. package/dist-cjs/codegen/template.d.ts +0 -18
  66. package/dist-cjs/codegen/template.js +0 -151
  67. package/dist-cjs/ir/index.d.ts +0 -1
  68. package/dist-cjs/ir/index.js +0 -3
  69. package/dist-cjs/ir/types.d.ts +0 -71
  70. package/dist-cjs/ir/types.js +0 -10
  71. package/dist-cjs/mandate/index.d.ts +0 -2
  72. package/dist-cjs/mandate/index.js +0 -6
  73. package/dist-cjs/mandate/to-ir.d.ts +0 -3
  74. package/dist-cjs/mandate/to-ir.js +0 -63
  75. package/dist-cjs/mandate/types.d.ts +0 -20
  76. package/dist-cjs/mandate/types.js +0 -9
  77. package/dist-cjs/seams/index.d.ts +0 -1
  78. package/dist-cjs/seams/index.js +0 -3
  79. package/dist-cjs/seams/types.d.ts +0 -64
  80. package/dist-cjs/seams/types.js +0 -12
  81. package/dist-cjs/synth/deny-cases.d.ts +0 -28
  82. package/dist-cjs/synth/deny-cases.js +0 -217
  83. package/dist-cjs/synth/evaluate.d.ts +0 -18
  84. package/dist-cjs/synth/evaluate.js +0 -274
  85. package/dist-cjs/synth/harness.d.ts +0 -28
  86. package/dist-cjs/synth/harness.js +0 -50
  87. package/dist-cjs/synth/minimize.d.ts +0 -4
  88. package/dist-cjs/synth/minimize.js +0 -41
  89. package/dist-cjs/synth/permit-context.d.ts +0 -8
  90. package/dist-cjs/synth/permit-context.js +0 -38
  91. package/dist-cjs/synth/predicate-literals.d.ts +0 -5
  92. package/dist-cjs/synth/predicate-literals.js +0 -28
  93. package/dist-cjs/synth/synthesize-from-mandate.d.ts +0 -20
  94. package/dist-cjs/synth/synthesize-from-mandate.js +0 -62
  95. package/dist-cjs/verify/envelope.d.ts +0 -15
  96. package/dist-cjs/verify/envelope.js +0 -23
  97. package/dist-cjs/verify/index.d.ts +0 -3
  98. package/dist-cjs/verify/index.js +0 -8
  99. package/dist-cjs/verify/simulate.d.ts +0 -18
  100. package/dist-cjs/verify/simulate.js +0 -175
  101. package/dist-cjs/verify/verify.d.ts +0 -15
  102. package/dist-cjs/verify/verify.js +0 -184
@@ -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,18 +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). */
8
- export interface SimulateOptions {
9
- validUntilLedger?: number;
10
- }
11
- /** Replay a recorded transaction against a proposed predicate and emit the
12
- * `SimulationResult` envelope. The simulator returns the SAME permit
13
- * verdict `runHarness` expects: the intended recorded call must permit; every
14
- * generated deny dimension must deny. A runtime evaluation failure
15
- * `ToolError` - NOT a deny verdict, NOT `VERIFICATION_FAILED`. The boundary
16
- * is pinned: minimality is a verify-time concern, runtime evaluation is a
17
- * simulate-time concern. */
18
- export declare function simulatePolicy(predicate: PredicateNode | null, permitTx: RecordedTransaction, opts?: SimulateOptions): ToolResponse<SimulationResult>;
@@ -1,172 +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
- // without a satisfying price fixture, or a non-runtime propagation (a
11
- // runtime evaluation failure is NOT a policy-minimality problem; the
12
- // policy may still be minimal. Re-running with a complete fixture MAY
13
- // succeed.
14
- // - `VERIFICATION_FAILED` = STATIC minimality check failed. Surfaced
15
- // by `verifyPolicy`. The minimiser identified a load-bearing-free
16
- // constraint; the policy is structurally over-broad regardless of how
17
- // any concrete call evaluates. Re-running with a different fixture
18
- // will NOT fix it; the policy must be trimmed.
19
- //
20
- // Determinism: same `(predicate, permitTx, opts)` -> byte-identical
21
- // envelope, no clock, no randomness.
22
- //
23
- // The permit EvalContext is built locally (mirror of the helper used in
24
- // `synthesize-from-recording.ts`) so this module does not couple to the
25
- // orchestrator's private build helpers. The shape is pinned by the test
26
- // suite to stay in lockstep.
27
- import { generateCases } from "../synth/deny-cases.js";
28
- import { evaluate } from "../synth/evaluate.js";
29
- import { MAX_SCVAL_CLONE_DEPTH } from "../types.js";
30
- const SIMULATOR_VERSION = 'ts-model-1.0.0';
31
- /** Replay a recorded transaction against a proposed predicate and emit the
32
- * `SimulationResult` envelope. The simulator returns the SAME permit
33
- * verdict `runHarness` expects: the intended recorded call must permit; every
34
- * generated deny dimension must deny. A runtime evaluation failure
35
- * `ToolError` - NOT a deny verdict, NOT `VERIFICATION_FAILED`. The boundary
36
- * is pinned: minimality is a verify-time concern, runtime evaluation is a
37
- * simulate-time concern. */
38
- export function simulatePolicy(predicate, permitTx, opts = {}) {
39
- // The permit EvalContext requires a top-level invocation. A recorded tx
40
- // with no invocations is structurally malformed input - we surface a
41
- // runtime `SIMULATION_ERROR` rather than fabricating a permit verdict.
42
- const topLevel = permitTx.invocations[0];
43
- if (!topLevel) {
44
- return {
45
- ok: false,
46
- error: simulationError('recorded transaction has no top-level invocation to simulate'),
47
- };
48
- }
49
- let permitCtx;
50
- try {
51
- permitCtx = buildPermitContext(permitTx, topLevel, opts);
52
- }
53
- catch (e) {
54
- return {
55
- ok: false,
56
- error: simulationError(`could not build permit evaluation context: ${e.message}`),
57
- };
58
- }
59
- // `predicate === null` means the policy is OZ-only (no interpreter
60
- // predicate). We still emit the envelope so the review card + verifier
61
- // can consume it: the permit verdict evaluates an always-permit empty
62
- // tree, and the deny battery is empty (nothing to verify at the
63
- // interpreter layer).
64
- const evaluatePredicate = predicate ?? { op: 'and', children: [] };
65
- const evaluatedCases = [];
66
- let permitVerdict;
67
- try {
68
- permitVerdict = evaluate(evaluatePredicate, permitCtx);
69
- }
70
- catch (e) {
71
- return {
72
- ok: false,
73
- error: simulationError(`permit evaluation threw at runtime: ${e.message}`, e),
74
- };
75
- }
76
- evaluatedCases.push({
77
- dimension: 'permit',
78
- outcome: permitVerdict.permit ? 'permit' : 'deny',
79
- reason: permitVerdict.permit ? 'matches recorded call' : permitVerdict.reason,
80
- });
81
- // The deny battery is generated against the SAME permit context. A
82
- // runtime evaluation failure on ANY deny case is a `SIMULATION_ERROR` -
83
- // not a deny verdict (an evaluate-throws is not a deny) and not a
84
- // minimality problem.
85
- const cases = generateCases(evaluatePredicate, permitCtx);
86
- for (const deny of cases.denies) {
87
- let result;
88
- try {
89
- result = evaluate(evaluatePredicate, deny.ctx);
90
- }
91
- catch (e) {
92
- return {
93
- ok: false,
94
- error: simulationError(`deny case "${deny.dimension}" threw at runtime: ${e.message}`, e),
95
- };
96
- }
97
- evaluatedCases.push({
98
- dimension: deny.dimension,
99
- outcome: result.permit ? 'permit' : 'deny',
100
- reason: result.permit ? 'no matching deny' : result.reason,
101
- });
102
- }
103
- const envelope = {
104
- permit: permitVerdict.permit ? { tx: 'permit' } : { tx: 'deny', reason: permitVerdict.reason },
105
- evaluatedCases,
106
- backend: 'ts-model',
107
- simulatorVersion: SIMULATOR_VERSION,
108
- };
109
- return { ok: true, data: envelope };
110
- }
111
- /** Build the permit `EvalContext` the simulator drives. Mirrors the
112
- * helper in `synthesize-from-recording.ts` so the simulator sees the same
113
- * shape the orchestrator's self-verify pipeline sees; we mirror here
114
- * rather than import to keep `src/verify/` decoupled from the
115
- * orchestrator's private helpers. The shape is pinned by tests so the
116
- * two implementations stay in lockstep. */
117
- function buildPermitContext(tx, topLevel, opts) {
118
- const amountByToken = {};
119
- const totals = new Map();
120
- for (const m of tx.tokenMovements) {
121
- const current = totals.get(m.token) ?? 0n;
122
- totals.set(m.token, current + BigInt(m.amount));
123
- }
124
- for (const [token, total] of totals) {
125
- amountByToken[token] = total.toString();
126
- }
127
- const ctx = {
128
- contract: topLevel.contract,
129
- fn: topLevel.fn,
130
- args: topLevel.args.map(cloneScVal),
131
- atLedger: tx.ledgerSequence,
132
- nowSeconds: tx.fetchedAt,
133
- amountByToken,
134
- windowSpentByToken: {},
135
- };
136
- if (opts.validUntilLedger !== undefined) {
137
- ctx.validUntilLedger = opts.validUntilLedger;
138
- }
139
- return ctx;
140
- }
141
- function cloneScVal(value, depth = 0) {
142
- // Recursion is bounded by MAX_SCVAL_CLONE_DEPTH so a hand-crafted nested-vec
143
- // payload cannot RangeError the JS stack during context building. Over-depth
144
- // throws a ToolError-shaped error that the simulator's existing try/catch
145
- // converts to a structured `{ok:false, error}` (not a thrown RangeError).
146
- if (value.type === 'vec') {
147
- if (depth >= MAX_SCVAL_CLONE_DEPTH) {
148
- throw cloneDepthError(value);
149
- }
150
- return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) };
151
- }
152
- return { ...value };
153
- }
154
- function cloneDepthError(value) {
155
- const err = new Error(`ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${MAX_SCVAL_CLONE_DEPTH})`);
156
- err.code = 'SIMULATION_ERROR';
157
- err.severity = 'error';
158
- err.retryable = false;
159
- err.depthContext = value.type;
160
- throw err;
161
- }
162
- function simulationError(message, cause) {
163
- const error = {
164
- code: 'SIMULATION_ERROR',
165
- message,
166
- severity: 'error',
167
- retryable: false,
168
- };
169
- if (cause !== undefined)
170
- error.details = { cause: String(cause) };
171
- return error;
172
- }
@@ -1,15 +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) so verify sees the same shape
5
- * `simulatePolicy` sees. */
6
- export interface VerifyOptions {
7
- validUntilLedger?: number;
8
- }
9
- /** Run the static minimality check on a proposed predicate + recorded tx.
10
- * Returns `{ ok: true }` when the predicate is minimal (every top-level
11
- * conjunct carries load) and `VERIFICATION_FAILED` when a conjunct could
12
- * be dropped without losing a deny-case. The dropped conjuncts are
13
- * reported in `details.droppedConstraints` so the caller can render a
14
- * review-card warning. */
15
- export declare function verifyPolicy(predicate: PredicateNode, permitTx: RecordedTransaction, opts?: VerifyOptions): ToolResponse<true>;
@@ -1,181 +0,0 @@
1
- // src/verify/verify.ts - the static minimality check for `verify_policy`.
2
- //
3
- // `verifyPolicy` proves the policy is MINIMAL: no top-level conjunct is
4
- // load-bearing-free. It is the static sibling of `simulatePolicy` and emits
5
- // `VERIFICATION_FAILED` (not `SIMULATION_ERROR`) on failure. The boundary is
6
- // pinned:
7
- //
8
- // - `VERIFICATION_FAILED` = STATIC minimality check failed. The policy is
9
- // structurally over-broad: a constraint could be dropped without losing
10
- // a deny-case. Surfaced by `verifyPolicy`. Runtime evaluation is not
11
- // part of this check; the policy may evaluate to a permit/deny just
12
- // fine, the failure is shape-only.
13
- //
14
- // - `SIMULATION_ERROR` = RUNTIME evaluation failed (see simulate.ts).
15
- // This module never emits SIMULATION_ERROR. A minimality failure is
16
- // never a simulation error and vice-versa.
17
- //
18
- // Algorithm:
19
- // 1. Build the permit EvalContext from `permitTx` (mirror of the
20
- // orchestrator's helper so verify is self-contained).
21
- // 2. Run `minimize(predicate, permitCtx)` to strip load-bearing-free
22
- // top-level conjuncts (only `and` predicates are minimisable; other
23
- // shapes are returned unchanged by `minimize`).
24
- // 3. If the minimised tree has fewer top-level conjuncts than the input,
25
- // return `VERIFICATION_FAILED` listing the dropped conjuncts by their
26
- // structural fingerprint.
27
- // 4. Otherwise `{ ok: true }`.
28
- //
29
- // Determinism: same `(predicate, permitTx)` -> byte-identical verdict.
30
- import { minimize } from "../synth/minimize.js";
31
- import { MAX_SCVAL_CLONE_DEPTH } from "../types.js";
32
- /** Run the static minimality check on a proposed predicate + recorded tx.
33
- * Returns `{ ok: true }` when the predicate is minimal (every top-level
34
- * conjunct carries load) and `VERIFICATION_FAILED` when a conjunct could
35
- * be dropped without losing a deny-case. The dropped conjuncts are
36
- * reported in `details.droppedConstraints` so the caller can render a
37
- * review-card warning. */
38
- export function verifyPolicy(predicate, permitTx, opts = {}) {
39
- const topLevel = permitTx.invocations[0];
40
- if (!topLevel) {
41
- return {
42
- ok: false,
43
- error: verificationFailed('recorded transaction has no top-level invocation to verify against', { droppedConstraints: [] }),
44
- };
45
- }
46
- let permitCtx;
47
- try {
48
- permitCtx = buildPermitContextForVerify(permitTx, topLevel, opts);
49
- }
50
- catch (e) {
51
- return {
52
- ok: false,
53
- error: verificationFailed(`could not build permit evaluation context: ${e.message}`, { droppedConstraints: [] }),
54
- };
55
- }
56
- // `minimize` only reduces `and` predicates; other shapes are returned
57
- // unchanged. A non-`and` predicate therefore trivially passes the static
58
- // minimality check (its top-level structure carries no removable
59
- // conjuncts). The runtime harness in `simulatePolicy` covers the
60
- // OR / NOT / comparison shapes.
61
- const minimised = minimize(predicate, permitCtx);
62
- // Drop count: only meaningful for `and`. For other shapes we already
63
- // returned the input unchanged; report ok.
64
- if (predicate.op !== 'and' || minimised.op !== 'and') {
65
- if (!structuralEqual(predicate, minimised)) {
66
- return {
67
- ok: false,
68
- error: verificationFailed('minimizer returned a structurally different tree for a non-and predicate', { droppedConstraints: [fingerprint(minimised)] }),
69
- };
70
- }
71
- return { ok: true, data: true };
72
- }
73
- const inputChildren = predicate.children;
74
- const minimisedChildren = minimised.children;
75
- if (minimisedChildren.length >= inputChildren.length) {
76
- return { ok: true, data: true };
77
- }
78
- // Over-broad: identify the dropped conjuncts by structural fingerprint
79
- // (so the review card can quote exactly which constraint was redundant).
80
- // We use a multiset comparison because two structurally identical
81
- // conjuncts (e.g. a duplicate `call_fn == transfer`) collapse to the
82
- // same fingerprint - the dropped item is the one whose fingerprint
83
- // count drops between input and minimised.
84
- const inputCounts = fingerprintCounts(inputChildren);
85
- const minimisedCounts = fingerprintCounts(minimisedChildren);
86
- const dropped = [];
87
- for (const [fp, count] of inputCounts) {
88
- const kept = minimisedCounts.get(fp) ?? 0;
89
- for (let i = 0; i < count - kept; i++)
90
- dropped.push(fp);
91
- }
92
- return {
93
- ok: false,
94
- error: verificationFailed(`policy is structurally over-broad: ${dropped.length} redundant conjunct(s) can be dropped without losing a deny case`, { droppedConstraints: dropped }),
95
- };
96
- }
97
- function buildPermitContextForVerify(tx, topLevel, opts) {
98
- const amountByToken = {};
99
- const totals = new Map();
100
- for (const m of tx.tokenMovements) {
101
- const current = totals.get(m.token) ?? 0n;
102
- totals.set(m.token, current + BigInt(m.amount));
103
- }
104
- for (const [token, total] of totals) {
105
- amountByToken[token] = total.toString();
106
- }
107
- const ctx = {
108
- contract: topLevel.contract,
109
- fn: topLevel.fn,
110
- args: topLevel.args.map(cloneScVal),
111
- atLedger: tx.ledgerSequence,
112
- nowSeconds: tx.fetchedAt,
113
- amountByToken,
114
- windowSpentByToken: {},
115
- };
116
- if (opts.validUntilLedger !== undefined) {
117
- ctx.validUntilLedger = opts.validUntilLedger;
118
- }
119
- return ctx;
120
- }
121
- function cloneScVal(value, depth = 0) {
122
- // Recursion is bounded by MAX_SCVAL_CLONE_DEPTH so a hand-crafted nested-vec
123
- // payload cannot RangeError the JS stack during context building. Over-depth
124
- // throws a ToolError-shaped error that the verifier's existing try/catch
125
- // converts to a structured `{ok:false, error}` (not a thrown RangeError).
126
- if (value.type === 'vec') {
127
- if (depth >= MAX_SCVAL_CLONE_DEPTH) {
128
- throw cloneDepthError(value);
129
- }
130
- return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) };
131
- }
132
- return { ...value };
133
- }
134
- function cloneDepthError(value) {
135
- const err = new Error(`ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${MAX_SCVAL_CLONE_DEPTH})`);
136
- err.code = 'VERIFICATION_FAILED';
137
- err.severity = 'error';
138
- err.retryable = false;
139
- err.depthContext = value.type;
140
- throw err;
141
- }
142
- function fingerprint(node) {
143
- return JSON.stringify(node, replacer);
144
- }
145
- /** Multiset fingerprint counts for a list of conjuncts. Two structurally
146
- * identical conjuncts (e.g. a duplicate `call_fn == transfer`) each
147
- * contribute their own count. The minimiser may drop one of them; we
148
- * surface exactly the surplus via the count difference. */
149
- function fingerprintCounts(children) {
150
- const counts = new Map();
151
- for (const child of children) {
152
- const fp = fingerprint(child);
153
- counts.set(fp, (counts.get(fp) ?? 0) + 1);
154
- }
155
- return counts;
156
- }
157
- /** Deterministic JSON key order for fingerprinting. Object keys are sorted
158
- * recursively so the same shape produces the same string. */
159
- function replacer(_key, value) {
160
- if (value && typeof value === 'object' && !Array.isArray(value)) {
161
- const obj = value;
162
- const sorted = {};
163
- for (const k of Object.keys(obj).sort()) {
164
- sorted[k] = obj[k];
165
- }
166
- return sorted;
167
- }
168
- return value;
169
- }
170
- function structuralEqual(a, b) {
171
- return fingerprint(a) === fingerprint(b);
172
- }
173
- function verificationFailed(message, details) {
174
- return {
175
- code: 'VERIFICATION_FAILED',
176
- message,
177
- severity: 'error',
178
- retryable: false,
179
- details,
180
- };
181
- }
@@ -1 +0,0 @@
1
- export { createInterpreterAdapter, type InterpreterAdapterConfig, PLACEHOLDER_INTERPRETER_ADDRESS, } from './adapter.ts';
@@ -1,7 +0,0 @@
1
- "use strict";
2
- // src/adapters/interpreter/index.ts - re-export the interpreter-policy CustodyAdapter.
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.PLACEHOLDER_INTERPRETER_ADDRESS = exports.createInterpreterAdapter = void 0;
5
- var adapter_ts_1 = require("./adapter.js");
6
- Object.defineProperty(exports, "createInterpreterAdapter", { enumerable: true, get: function () { return adapter_ts_1.createInterpreterAdapter; } });
7
- Object.defineProperty(exports, "PLACEHOLDER_INTERPRETER_ADDRESS", { enumerable: true, get: function () { return adapter_ts_1.PLACEHOLDER_INTERPRETER_ADDRESS; } });
@@ -1,20 +0,0 @@
1
- import type { CustodyAdapter } from '../../seams/types.ts';
2
- import type { Network } from '../../types.ts';
3
- /** OZ built-in policy contract instance addresses, per primitive. */
4
- export interface OzPrimitiveInstances {
5
- spending_limit: string;
6
- simple_threshold: string;
7
- weighted_threshold: string;
8
- }
9
- /** Per-network config for the OZ adapter. */
10
- export interface OzAdapterConfig {
11
- network: Network;
12
- instances: OzPrimitiveInstances;
13
- }
14
- /** [VERIFY] NOT real deployed addresses. The OZ built-in policy instances are
15
- * per-network deploy artifacts we do not have yet; install is a later phase.
16
- * Injected so the adapter never invents a Stellar contract address. */
17
- export declare const PLACEHOLDER_OZ_INSTANCES: OzPrimitiveInstances;
18
- /** Week-1 OZ adapter config with placeholder instance addresses. */
19
- export declare function placeholderOzConfig(network: Network): OzAdapterConfig;
20
- export declare function createOzAdapter(config: OzAdapterConfig): CustodyAdapter;