@crediolabs/policy-synth 0.1.3 → 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 (82) 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 +2 -0
  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/predicate/encode.d.ts +10 -0
  18. package/dist/predicate/encode.js +249 -0
  19. package/dist/predicate/index.d.ts +1 -0
  20. package/dist/predicate/index.js +2 -0
  21. package/dist/review-card/builder.d.ts +14 -0
  22. package/dist/review-card/builder.js +261 -0
  23. package/dist/review-card/conflict.d.ts +40 -0
  24. package/dist/review-card/conflict.js +111 -0
  25. package/dist/review-card/cross-check.d.ts +11 -0
  26. package/dist/review-card/cross-check.js +148 -0
  27. package/dist/review-card/index.d.ts +3 -0
  28. package/dist/review-card/index.js +4 -0
  29. package/dist/synth/compose-from-recording.d.ts +35 -7
  30. package/dist/synth/compose-from-recording.js +225 -34
  31. package/dist/synth/deny-cases.d.ts +12 -0
  32. package/dist/synth/deny-cases.js +361 -0
  33. package/dist/synth/evaluate.d.ts +39 -0
  34. package/dist/synth/evaluate.js +425 -0
  35. package/dist/synth/harness.d.ts +16 -0
  36. package/dist/synth/harness.js +26 -0
  37. package/dist/synth/index.d.ts +4 -0
  38. package/dist/synth/index.js +4 -0
  39. package/dist/synth/minimize.d.ts +4 -0
  40. package/dist/synth/minimize.js +38 -0
  41. package/dist/synth/predicate-literals.d.ts +5 -0
  42. package/dist/synth/predicate-literals.js +25 -0
  43. package/dist/synth/synthesize-from-recording.d.ts +32 -3
  44. package/dist/synth/synthesize-from-recording.js +488 -14
  45. package/dist/types.d.ts +23 -1
  46. package/dist/verify/envelope.d.ts +15 -0
  47. package/dist/verify/envelope.js +22 -0
  48. package/dist/verify/index.d.ts +3 -0
  49. package/dist/verify/index.js +3 -0
  50. package/dist/verify/simulate.d.ts +31 -0
  51. package/dist/verify/simulate.js +242 -0
  52. package/dist/verify/verify.d.ts +21 -0
  53. package/dist/verify/verify.js +173 -0
  54. package/package.json +1 -1
  55. package/src/adapters/interpreter/adapter.ts +642 -0
  56. package/src/adapters/interpreter/index.ts +8 -0
  57. package/src/adapters/oz/adapter.ts +2 -0
  58. package/src/codegen/compile-gate.ts +162 -0
  59. package/src/codegen/index.ts +17 -0
  60. package/src/codegen/template.ts +148 -0
  61. package/src/errors.ts +2 -0
  62. package/src/index.ts +2 -0
  63. package/src/ir/types.ts +9 -2
  64. package/src/predicate/encode.ts +307 -0
  65. package/src/predicate/index.ts +3 -0
  66. package/src/review-card/builder.ts +303 -0
  67. package/src/review-card/conflict.ts +143 -0
  68. package/src/review-card/cross-check.ts +158 -0
  69. package/src/review-card/index.ts +12 -0
  70. package/src/synth/compose-from-recording.ts +277 -43
  71. package/src/synth/deny-cases.ts +447 -0
  72. package/src/synth/evaluate.ts +493 -0
  73. package/src/synth/harness.ts +40 -0
  74. package/src/synth/index.ts +12 -0
  75. package/src/synth/minimize.ts +44 -0
  76. package/src/synth/predicate-literals.ts +27 -0
  77. package/src/synth/synthesize-from-recording.ts +572 -15
  78. package/src/types.ts +19 -2
  79. package/src/verify/envelope.ts +28 -0
  80. package/src/verify/index.ts +5 -0
  81. package/src/verify/simulate.ts +292 -0
  82. package/src/verify/verify.ts +224 -0
@@ -0,0 +1,119 @@
1
+ // src/codegen/compile-gate.ts - toolchain-gated `cargo check` for the
2
+ // codegen escape hatch.
3
+ //
4
+ // The escape hatch ships as the `policy-builder escape-hatch` CLI subcommand
5
+ // (a later phase). This gate is its safety net, NOT the happy path. Property:
6
+ // generated Rust compiles against the pinned OZ crate; broken source returns
7
+ // `COMPILE_GATE_FAILED` with `stderr`; an absent toolchain returns `SKIPPED`
8
+ // (does NOT fail - we cannot make build tools a hard runtime requirement for
9
+ // a TypeScript package).
10
+ import { spawn } from 'node:child_process';
11
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ /** Probe the host for the Rust toolchain the gate requires. We require BOTH
15
+ * `cargo` AND `stellar` (the Soroban CLI) because a real gate run invokes
16
+ * `stellar contract build`; absent either, the gate returns `SKIPPED`. */
17
+ export async function hasRustToolchain() {
18
+ const probe = await probeToolchain();
19
+ return probe.present;
20
+ }
21
+ async function probeToolchain() {
22
+ const cargo = await which('cargo');
23
+ if (!cargo)
24
+ return { present: false, reason: 'cargo not found on PATH' };
25
+ const stellar = await which('stellar');
26
+ if (!stellar)
27
+ return { present: false, reason: 'stellar not found on PATH' };
28
+ return { present: true, reason: `${cargo} + ${stellar}` };
29
+ }
30
+ async function which(bin) {
31
+ try {
32
+ const out = await runProcess('sh', ['-c', `command -v ${bin}`], { capture: true });
33
+ const path = out.stdout.trim();
34
+ return path.length > 0 ? path : null;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ function runProcess(cmd, args, opts) {
41
+ return new Promise((resolve, reject) => {
42
+ if (opts.signal?.aborted) {
43
+ reject(new Error('aborted'));
44
+ return;
45
+ }
46
+ const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
47
+ let stdout = '';
48
+ let stderr = '';
49
+ child.stdout.on('data', (b) => {
50
+ stdout += b.toString('utf8');
51
+ });
52
+ child.stderr.on('data', (b) => {
53
+ stderr += b.toString('utf8');
54
+ });
55
+ const onAbort = () => {
56
+ child.kill('SIGTERM');
57
+ reject(new Error('aborted'));
58
+ };
59
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
60
+ child.on('error', (e) => {
61
+ opts.signal?.removeEventListener('abort', onAbort);
62
+ reject(e);
63
+ });
64
+ child.on('close', (code) => {
65
+ opts.signal?.removeEventListener('abort', onAbort);
66
+ resolve({ stdout, stderr, code: code ?? -1 });
67
+ });
68
+ });
69
+ }
70
+ const CARGO_MANIFEST = `[package]
71
+ name = "escape-hatch-gate"
72
+ version = "0.0.0"
73
+ edition = "2021"
74
+ publish = false
75
+
76
+ [lib]
77
+ crate-type = ["cdylib"]
78
+
79
+ [dependencies]
80
+ soroban-sdk = "22"
81
+
82
+ [workspace]
83
+ `;
84
+ /** Compile-check a Rust source string against the pinned Soroban SDK.
85
+ *
86
+ * - Toolchain absent -> `{ code: 'SKIPPED', reason }` (NOT a failure).
87
+ * - Toolchain present, source compiles -> `{ code: 'COMPILE_OK' }`.
88
+ * - Toolchain present, source broken -> `{ code: 'COMPILE_GATE_FAILED', stderr }`.
89
+ *
90
+ * The gate writes the source to a temporary crate and runs `cargo check`
91
+ * against it; the crate is cleaned up whether or not compilation succeeds.
92
+ * The caller is expected to surface `COMPILE_GATE_FAILED.stderr` to the
93
+ * user (the LLM agent) so the user can iterate. */
94
+ export async function compileCheck(rustSource, opts = {}) {
95
+ if (opts.signal?.aborted) {
96
+ return { code: 'SKIPPED', reason: 'aborted before probe' };
97
+ }
98
+ const probe = await probeToolchain();
99
+ if (!probe.present) {
100
+ return { code: 'SKIPPED', reason: probe.reason };
101
+ }
102
+ let dir = null;
103
+ try {
104
+ dir = await mkdtemp(join(opts.tempDir ?? tmpdir(), 'codegen-gate-'));
105
+ await writeFile(join(dir, 'Cargo.toml'), CARGO_MANIFEST);
106
+ await writeFile(join(dir, 'lib.rs'), rustSource);
107
+ const runOpts = opts.signal ? { signal: opts.signal } : {};
108
+ const result = await runProcess(opts.cargoBin ?? 'cargo', ['check', '--quiet', '--offline', '--manifest-path', join(dir, 'Cargo.toml')], runOpts).catch((e) => ({ stdout: '', stderr: e.message, code: -1 }));
109
+ if (result.code === 0) {
110
+ return { code: 'COMPILE_OK' };
111
+ }
112
+ return { code: 'COMPILE_GATE_FAILED', stderr: result.stderr || result.stdout };
113
+ }
114
+ finally {
115
+ if (dir) {
116
+ await rm(dir, { recursive: true, force: true }).catch(() => { });
117
+ }
118
+ }
119
+ }
@@ -0,0 +1,2 @@
1
+ export { type CompileGateOpts, type CompileGateResult, compileCheck, hasRustToolchain, } from './compile-gate.ts';
2
+ export { type EscapeHatchSpec, generateRust, } from './template.ts';
@@ -0,0 +1,8 @@
1
+ // src/codegen/index.ts - re-export the codegen escape-hatch surface.
2
+ //
3
+ // The escape hatch is OUT of the audited happy path: the synthesiser never
4
+ // calls `generateRust` itself; the CLI subcommand (a later phase) is the only
5
+ // entry point. Keeping the surface in one file makes that boundary visible
6
+ // in import statements.
7
+ export { compileCheck, hasRustToolchain, } from "./compile-gate.js";
8
+ export { generateRust, } from "./template.js";
@@ -0,0 +1,18 @@
1
+ /** A small typed description of one uncovered constraint the v1 DSL refused
2
+ * to express. The synthesiser surfaces these from `CompileResult.uncovered`
3
+ * and the codegen escape hatch wraps them into a hand-auditable skeleton. */
4
+ export interface EscapeHatchSpec {
5
+ /** Address of the policy contract the skeleton is generated for. */
6
+ contract: string;
7
+ /** The trait method the predicate lives inside (default: 'enforce'). */
8
+ fnName?: string;
9
+ /** Human-readable description of each construct the DSL could not cover. */
10
+ uncovered: string[];
11
+ }
12
+ /** Generate a deterministic OZ `Policy` skeleton for an uncovered constraint.
13
+ *
14
+ * The skeleton is NOT a finished policy; the user fills in the predicate
15
+ * logic in the marked TODO(user) holes and audits the result themselves.
16
+ *
17
+ * Same `(spec, name)` always produces byte-identical output. */
18
+ export declare function generateRust(spec: EscapeHatchSpec, name: string): string;
@@ -0,0 +1,131 @@
1
+ // src/codegen/template.ts - deterministic Rust source generator for the OZ
2
+ // `Policy` escape-hatch skeleton.
3
+ //
4
+ // This is the LAST-RESORT tool for constraints the v1 DSL cannot express. It
5
+ // lives OUT of the audited happy-path surface; the synthesiser never emits it
6
+ // automatically. It mirrors Zodiac Roles' `Custom` operator: a hand-written
7
+ // (here: scaffolded) policy the operator assumes responsibility for.
8
+ //
9
+ // The skeleton carries five storage invariants the user MUST preserve when
10
+ // filling in the predicate logic:
11
+ // 1. `smart_account.require_auth()` is invoked INSIDE `enforce`.
12
+ // 2. Storage is keyed by the composite `(smart_account, rule_id)`.
13
+ // 3. Chain reads use `unwrap_or_default()` so a missing key is a permitted
14
+ // default, not a panic.
15
+ // 4. Storage is `persistent()` (NOT `instance()`) so the policy survives
16
+ // contract instance lifecycle changes.
17
+ // 5. `uninstall` removes the stored state.
18
+ //
19
+ // Determinism: same `(spec, name)` -> byte-identical output. No clock, no RNG,
20
+ // no environment reads.
21
+ /** Format a name for use as a Rust identifier. The input is constrained by
22
+ * the caller (a kebab-case policy name + alphanumeric addresses); this is a
23
+ * belt-and-braces sanitiser that maps anything non-identifier to '_'. */
24
+ function asRustIdent(s) {
25
+ let out = '';
26
+ for (let i = 0; i < s.length; i++) {
27
+ const ch = s.charCodeAt(i);
28
+ const ok = (ch >= 48 && ch <= 57) || // 0-9
29
+ (ch >= 65 && ch <= 90) || // A-Z
30
+ (ch >= 97 && ch <= 122) || // a-z
31
+ ch === 95; // _
32
+ out += ok ? s[i] : '_';
33
+ }
34
+ // Identifiers may not start with a digit.
35
+ if (out.length > 0 && out.charCodeAt(0) >= 48 && out.charCodeAt(0) <= 57) {
36
+ out = `_${out}`;
37
+ }
38
+ return out || 'policy';
39
+ }
40
+ /** Render the `uncovered` list as a `//` comment block (one line per item). */
41
+ function renderUncovered(uncovered) {
42
+ if (uncovered.length === 0) {
43
+ return ' // (no specific uncovered constructs reported)';
44
+ }
45
+ return uncovered.map((line) => ` // - ${line}`).join('\n');
46
+ }
47
+ /** Generate a deterministic OZ `Policy` skeleton for an uncovered constraint.
48
+ *
49
+ * The skeleton is NOT a finished policy; the user fills in the predicate
50
+ * logic in the marked TODO(user) holes and audits the result themselves.
51
+ *
52
+ * Same `(spec, name)` always produces byte-identical output. */
53
+ export function generateRust(spec, name) {
54
+ const contract = spec.contract;
55
+ const fnName = spec.fnName ?? 'enforce';
56
+ const structName = asRustIdent(name);
57
+ const dataKeyName = `${asRustIdent(name)}_data`;
58
+ const uncoveredBlock = renderUncovered(spec.uncovered);
59
+ return `// Auto-generated by the OZ Policy Builder codegen escape hatch.
60
+ // THIS OUTPUT IS THE USER'S TO COMPLETE AND AUDIT.
61
+ // The synthesiser never emits it on the happy path; reach for it only when
62
+ // a constraint cannot be expressed in the v1 DSL grammar (same shape as
63
+ // Zodiac Roles' \`Custom\` operator).
64
+
65
+ #![no_std]
66
+
67
+ use soroban_sdk::{contract, contractimpl, contracttype, Address, Env, Vec};
68
+
69
+ #[contracttype]
70
+ pub enum DataKey {
71
+ /// Composite key \`(smart_account, rule_id)\` so multiple policies on
72
+ /// one smart account coexist without collision.
73
+ State(Address, u32),
74
+ }
75
+
76
+ #[contract]
77
+ pub struct ${structName};
78
+
79
+ #[contractimpl]
80
+ impl ${structName} {
81
+ pub fn install(e: &Env, smart_account: Address, rule_id: u32) {
82
+ // TODO(user): initialise policy state for this (smart_account, rule_id).
83
+ // The skeleton leaves the stored value empty; the predicate body
84
+ // (in \`enforce\`) decides what to read.
85
+ e.storage().persistent().set(
86
+ &DataKey::State(smart_account.clone(), rule_id),
87
+ &(),
88
+ );
89
+ }
90
+
91
+ pub fn enforce(
92
+ e: &Env,
93
+ smart_account: Address,
94
+ rule_id: u32,
95
+ _signers: Vec<Address>,
96
+ ) {
97
+ // Invariant 1: authorise the smart account BEFORE any state read or
98
+ // predicate evaluation. Removing this call opens the policy to
99
+ // impersonation by any caller with a valid rule_id.
100
+ smart_account.require_auth();
101
+
102
+ // Invariant 2 + 4: read stored state through the composite key on
103
+ // \`persistent()\` storage. \`unwrap_or_default()\` (invariant 3)
104
+ // makes an empty key a permitted default rather than a panic.
105
+ let _state: () = e
106
+ .storage()
107
+ .persistent()
108
+ .get(&DataKey::State(smart_account.clone(), rule_id))
109
+ .unwrap_or_default();
110
+
111
+ // --- uncovered constraints the v1 DSL refused to express ---
112
+ ${uncoveredBlock}
113
+
114
+ // TODO(user): replace the placeholder below with the real predicate
115
+ // body. The recorded flow's \`(contract, fn_name, args)\` is the
116
+ // single authorised call \`Policy::enforce\` receives; match against
117
+ // \`e\` here.
118
+ let _ = (_state, &e);
119
+ }
120
+
121
+ pub fn uninstall(e: &Env, smart_account: Address, rule_id: u32) {
122
+ // Invariant 5: \`uninstall\` removes the stored state so a subsequent
123
+ // install starts from a clean slate (and the nonce returns to its
124
+ // post-uninstall value).
125
+ e.storage()
126
+ .persistent()
127
+ .remove(&DataKey::State(smart_account, rule_id));
128
+ }
129
+ }
130
+ `;
131
+ }
package/dist/errors.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type ErrorCode = 'RECORDING_FAILED' | 'RECORDING_VALIDATION_FAILED' | 'SCOPE_UNRESOLVED' | 'SYNTHESIS_ERROR' | 'MALFORMED_PREDICATE' | 'SIMULATION_ERROR' | 'VERIFICATION_FAILED' | 'DENY_CASE_FAILURE' | 'PERMIT_CASE_FAILED' | 'SUMMARY_DRIFT' | 'INSTALL_BUILD_FAILED' | 'INSTALL_CONFIRM_MISSING' | 'INSTALL_CONFIRM_EXPIRED' | 'REVOKE_BUILD_FAILED' | 'REVOKE_CONFIRM_MISSING' | 'USER_REJECTED_SIGN' | 'WALLET_TIMEOUT' | 'WALLET_UNAVAILABLE' | 'PREDICATE_TOO_LARGE' | 'PREDICATE_TOO_DEEP' | 'PREDICATE_ORACLE_OVER_LIMIT' | 'POLICY_CAP_EXCEEDED' | 'WASM_TOO_LARGE' | 'MASTER_AUTH_REQUIRED' | 'NONCE_REPLAY' | 'VERSION_MISMATCH' | 'ARITHMETIC_OVERFLOW' | 'AMOUNT_OVERFLOW' | 'RULE_SIGNERS_CHANGED' | 'SCOPE_SELF_CALL' | 'ORACLE_STALE' | 'ORACLE_MISSING' | 'ORACLE_DEVIATION_EXCEEDED' | 'ORACLE_MALFORMED_HISTORY' | 'ORACLE_FINGERPRINT_DRIFT' | 'ORACLE_PAUSED' | 'ORACLE_LEAF_INVALID_POSITION' | 'ORACLE_PARAMS_OUT_OF_RANGE' | 'ORACLE_DECIMALS_MISMATCH' | 'COMPILE_OK' | 'COMPILE_GATE_FAILED';
1
+ export type ErrorCode = 'RECORDING_FAILED' | 'RECORDING_VALIDATION_FAILED' | 'SCOPE_UNRESOLVED' | 'SYNTHESIS_ERROR' | 'MALFORMED_PREDICATE' | 'SIMULATION_ERROR' | 'VERIFICATION_FAILED' | 'DENY_CASE_FAILURE' | 'PERMIT_CASE_FAILED' | 'SUMMARY_DRIFT' | 'INSTALL_BUILD_FAILED' | 'INSTALL_CONFIRM_MISSING' | 'INSTALL_CONFIRM_EXPIRED' | 'REVOKE_BUILD_FAILED' | 'REVOKE_CONFIRM_MISSING' | 'USER_REJECTED_SIGN' | 'WALLET_TIMEOUT' | 'WALLET_UNAVAILABLE' | 'PREDICATE_TOO_LARGE' | 'PREDICATE_TOO_DEEP' | 'TOO_MANY_LEAVES' | 'IN_OPERAND_LIMIT' | 'PREDICATE_ORACLE_OVER_LIMIT' | 'POLICY_CAP_EXCEEDED' | 'WASM_TOO_LARGE' | 'MASTER_AUTH_REQUIRED' | 'NONCE_REPLAY' | 'VERSION_MISMATCH' | 'ARITHMETIC_OVERFLOW' | 'AMOUNT_OVERFLOW' | 'RULE_SIGNERS_CHANGED' | 'SCOPE_SELF_CALL' | 'ORACLE_STALE' | 'ORACLE_MISSING' | 'ORACLE_DEVIATION_EXCEEDED' | 'ORACLE_MALFORMED_HISTORY' | 'ORACLE_FINGERPRINT_DRIFT' | 'ORACLE_PAUSED' | 'ORACLE_LEAF_INVALID_POSITION' | 'ORACLE_PARAMS_OUT_OF_RANGE' | 'ORACLE_DECIMALS_MISMATCH' | 'COMPILE_OK' | 'COMPILE_GATE_FAILED';
2
2
  export interface ToolError {
3
3
  code: ErrorCode;
4
4
  message: string;
package/dist/index.d.ts CHANGED
@@ -2,8 +2,10 @@ export * from './adapters/oz/index.ts';
2
2
  export * from './errors.ts';
3
3
  export * from './ir/index.ts';
4
4
  export * from './mandate/index.ts';
5
+ export * from './predicate/index.ts';
5
6
  export * from './record/index.ts';
6
7
  export * from './registry/index.ts';
8
+ export * from './review-card/index.ts';
7
9
  export * from './seams/index.ts';
8
10
  export * from './synth/index.ts';
9
11
  export * from './types.ts';
package/dist/index.js CHANGED
@@ -2,8 +2,10 @@ export * from "./adapters/oz/index.js";
2
2
  export * from "./errors.js";
3
3
  export * from "./ir/index.js";
4
4
  export * from "./mandate/index.js";
5
+ export * from "./predicate/index.js";
5
6
  export * from "./record/index.js";
6
7
  export * from "./registry/index.js";
8
+ export * from "./review-card/index.js";
7
9
  export * from "./seams/index.js";
8
10
  export * from "./synth/index.js";
9
11
  export * from "./types.js";
@@ -46,8 +46,9 @@ export interface IRCompare {
46
46
  value: string;
47
47
  }
48
48
  /** Condition tree. NEAR-V2 guard/constraint are flat And/Or; the IR allows
49
- * nesting + `not` + `in` so the same IR can later lower to the OZ predicate
50
- * DSL. Week-1 adapters only lower the flat supported subset and flag the rest. */
49
+ * nesting + `not` + `in` + `eq_seq` so the same IR can later lower to the OZ
50
+ * predicate DSL. Week-1 adapters only lower the flat supported subset and flag
51
+ * the rest. */
51
52
  export type IRCondition = {
52
53
  op: 'and' | 'or';
53
54
  children: IRCondition[];
@@ -61,6 +62,16 @@ export type IRCondition = {
61
62
  op: 'in';
62
63
  selector: IRSelector;
63
64
  values: string[];
65
+ }
66
+ /** Exact ordered sequence equality. The IR-level selector value MUST EQUAL
67
+ * `values` as an ORDERED sequence (e.g. a swap hop `path`). `in` is pure
68
+ * set membership and cannot express order; `eq_seq` is the construct that
69
+ * does. Adapters that cannot express an exact ordered vector (OZ built-ins)
70
+ * flag this as `uncovered` rather than silently dropping it. */
71
+ | {
72
+ op: 'eq_seq';
73
+ selector: IRSelector;
74
+ values: string[];
64
75
  };
65
76
  export interface IRPolicyRule {
66
77
  /** NEAR-V2 roles whitelist (empty = any; owner exempt). */
@@ -0,0 +1,10 @@
1
+ import { type PredicateNode } from '../types.ts';
2
+ export interface EncodedPredicate {
3
+ /** base64 of the canonical ScVal XDR of the predicate root. */
4
+ encodedPredicate: string;
5
+ /** sha256 hex digest of the raw XDR bytes (post-canonicalisation). */
6
+ predicateHash: string;
7
+ }
8
+ /** Encode a `PredicateNode` to the canonical ScVal wire format and hash it.
9
+ * Pure function: same input -> byte-identical output every run. */
10
+ export declare function encodePredicate(node: PredicateNode): EncodedPredicate;
@@ -0,0 +1,249 @@
1
+ // src/predicate/encode.ts - canonical predicate encoder.
2
+ //
3
+ // Pure function. Maps a `PredicateNode` AST to the canonical ScVal wire format
4
+ // described in `packages/policy-interpreter/INTERPRETER_INSTALL_PARAMS.md`:
5
+ // - every node is a `ScVal::Vec` whose head element is the tag `ScVal::Symbol`
6
+ // - children of `and` / `or` are sorted ascending by their canonical XDR bytes
7
+ // - `in` haystacks are ALWAYS sorted by canonical XDR bytes (pure set
8
+ // membership); an EXACT ordered sequence is expressed as
9
+ // `eq(selector, literal_vec)` where the `literal_vec` element order is
10
+ // preserved verbatim (the order IS the semantic)
11
+ // - `literal_vec` encodes to a bare `ScVal::Vec` of its element encodings;
12
+ // order is preserved, NOT sorted
13
+ // - i128 uses `Int128Parts{hi: Int64 (signed), lo: Uint64 (unsigned)}`,
14
+ // value = hi*2^64 + lo (NOT signed-magnitude)
15
+ // - no `ScMap` anywhere in the predicate
16
+ // - `encodedPredicate = base64(root.toXDR())`,
17
+ // `predicateHash = sha256(raw XDR bytes)` as hex
18
+ //
19
+ // Caps from `PREDICATE_CAPS` are enforced BEFORE returning; a cap breach throws
20
+ // a `ToolError` with the matching error code and `severity: 'error'`.
21
+ import { createHash } from 'node:crypto';
22
+ import { Address, xdr } from '@stellar/stellar-sdk';
23
+ import { PREDICATE_CAPS } from "../types.js";
24
+ const INT64_MAX = (1n << 63n) - 1n;
25
+ const INT64_MIN = -(1n << 63n);
26
+ const UINT64_MAX = (1n << 64n) - 1n;
27
+ /** Encode a `PredicateNode` to the canonical ScVal wire format and hash it.
28
+ * Pure function: same input -> byte-identical output every run. */
29
+ export function encodePredicate(node) {
30
+ // --- pass 1: structural cap checks (no encoding needed) ---
31
+ const stats = computeStats(node);
32
+ if (stats.depth > PREDICATE_CAPS.MAX_DEPTH) {
33
+ throw capError('PREDICATE_TOO_DEEP', `predicate depth ${stats.depth} exceeds MAX_DEPTH ${PREDICATE_CAPS.MAX_DEPTH}`);
34
+ }
35
+ if (stats.leaves > PREDICATE_CAPS.MAX_LEAVES) {
36
+ throw capError('TOO_MANY_LEAVES', `predicate leaf count ${stats.leaves} exceeds MAX_LEAVES ${PREDICATE_CAPS.MAX_LEAVES}`);
37
+ }
38
+ for (const c of stats.inCounts) {
39
+ if (c.count > PREDICATE_CAPS.MAX_IN_OPERAND_COUNT) {
40
+ throw capError('IN_OPERAND_LIMIT', `\`in\` operand count ${c.count} exceeds MAX_IN_OPERAND_COUNT ${PREDICATE_CAPS.MAX_IN_OPERAND_COUNT}`);
41
+ }
42
+ }
43
+ // Two-round confirmation costs 2 oracle reads per UNIQUE asset referenced.
44
+ const oracleReads = stats.oracleAssets.size * 2;
45
+ if (oracleReads > PREDICATE_CAPS.MAX_ORACLE_READS) {
46
+ throw capError('PREDICATE_ORACLE_OVER_LIMIT', `oracle reads ${oracleReads} exceed MAX_ORACLE_READS ${PREDICATE_CAPS.MAX_ORACLE_READS}`);
47
+ }
48
+ // --- pass 2: build + canonicalise the ScVal ---
49
+ const root = encodeNode(node);
50
+ const rawBytes = root.toXDR();
51
+ if (rawBytes.length > PREDICATE_CAPS.MAX_PREDICATE_BYTES) {
52
+ throw capError('PREDICATE_TOO_LARGE', `predicate bytes ${rawBytes.length} exceed MAX_PREDICATE_BYTES ${PREDICATE_CAPS.MAX_PREDICATE_BYTES}`);
53
+ }
54
+ const encodedPredicate = rawBytes.toString('base64');
55
+ const predicateHash = createHash('sha256').update(rawBytes).digest('hex');
56
+ return { encodedPredicate, predicateHash };
57
+ }
58
+ function computeStats(node) {
59
+ const inCounts = [];
60
+ const oracleAssets = new Set();
61
+ const { depth, leaves } = walk(node, inCounts, oracleAssets);
62
+ return { depth, leaves, inCounts, oracleAssets };
63
+ }
64
+ function walk(node, inCounts, oracleAssets) {
65
+ switch (node.op) {
66
+ case 'and':
67
+ case 'or': {
68
+ if (node.children.length === 0)
69
+ return { depth: 1, leaves: 0 };
70
+ let maxChildDepth = 0;
71
+ let totalLeaves = 0;
72
+ for (const c of node.children) {
73
+ const child = walk(c, inCounts, oracleAssets);
74
+ if (child.depth > maxChildDepth)
75
+ maxChildDepth = child.depth;
76
+ totalLeaves += child.leaves;
77
+ }
78
+ return { depth: maxChildDepth + 1, leaves: totalLeaves };
79
+ }
80
+ case 'not': {
81
+ const child = walk(node.child, inCounts, oracleAssets);
82
+ return { depth: child.depth + 1, leaves: child.leaves };
83
+ }
84
+ case 'eq':
85
+ case 'lt':
86
+ case 'lte':
87
+ case 'gt':
88
+ case 'gte': {
89
+ collectOracle(node.left, oracleAssets);
90
+ collectOracle(node.right, oracleAssets);
91
+ return { depth: 1, leaves: leafCount(node.left) + leafCount(node.right) };
92
+ }
93
+ case 'in': {
94
+ inCounts.push({ count: node.haystack.length });
95
+ collectOracle(node.needle, oracleAssets);
96
+ let haystackLeaves = 0;
97
+ for (const h of node.haystack) {
98
+ collectOracle(h, oracleAssets);
99
+ haystackLeaves += leafCount(h);
100
+ }
101
+ return {
102
+ depth: 1,
103
+ leaves: leafCount(node.needle) + haystackLeaves,
104
+ };
105
+ }
106
+ }
107
+ }
108
+ /** Leaf-count contribution of one PredicateLeaf: 1 for any flat leaf, and the
109
+ * sum of element leaf counts for `literal_vec` so MAX_LEAVES caps see nested
110
+ * vector elements. */
111
+ function leafCount(leaf) {
112
+ if (leaf.kind === 'literal_vec') {
113
+ let total = 1; // the literal_vec itself counts as one leaf node
114
+ for (const el of leaf.elements)
115
+ total += leafCount(el);
116
+ return total;
117
+ }
118
+ return 1;
119
+ }
120
+ function collectOracle(leaf, oracleAssets) {
121
+ // literal_vec is the only nested leaf; recurse so an oracle_price buried in a
122
+ // vector literal (which the lowering would forbid, but the cap-walker must
123
+ // still see) is counted toward the oracle-read budget.
124
+ if (leaf.kind === 'oracle_price') {
125
+ oracleAssets.add(leaf.asset);
126
+ }
127
+ else if (leaf.kind === 'literal_vec') {
128
+ for (const el of leaf.elements)
129
+ collectOracle(el, oracleAssets);
130
+ }
131
+ }
132
+ function encodeNode(node) {
133
+ switch (node.op) {
134
+ case 'and':
135
+ case 'or': {
136
+ const encoded = node.children.map(encodeNode);
137
+ // sort children by their canonical XDR bytes ascending.
138
+ const sorted = sortByCanonicalBytes(encoded);
139
+ return xdr.ScVal.scvVec([symbol(node.op), xdr.ScVal.scvVec(sorted)]);
140
+ }
141
+ case 'not': {
142
+ return xdr.ScVal.scvVec([symbol('not'), encodeNode(node.child)]);
143
+ }
144
+ case 'eq':
145
+ case 'lt':
146
+ case 'lte':
147
+ case 'gt':
148
+ case 'gte': {
149
+ return xdr.ScVal.scvVec([symbol(node.op), encodeLeaf(node.left), encodeLeaf(node.right)]);
150
+ }
151
+ case 'in': {
152
+ const needle = encodeLeaf(node.needle);
153
+ // `in` is PURE set membership: the haystack is ALWAYS sorted by canonical
154
+ // XDR bytes ascending. An exact ordered sequence (e.g. a swap hop path)
155
+ // is expressed as `eq(selector, literal_vec)` where the vec's element
156
+ // order is preserved verbatim (handled in `encodeLeaf(literal_vec)`).
157
+ const haystack = sortByCanonicalBytes(node.haystack.map(encodeLeaf));
158
+ return xdr.ScVal.scvVec([symbol('in'), needle, xdr.ScVal.scvVec(haystack)]);
159
+ }
160
+ }
161
+ }
162
+ function encodeLeaf(leaf) {
163
+ switch (leaf.kind) {
164
+ case 'call_contract':
165
+ return xdr.ScVal.scvVec([symbol('call_contract')]);
166
+ case 'call_fn':
167
+ return xdr.ScVal.scvVec([symbol('call_fn')]);
168
+ case 'call_arg':
169
+ return xdr.ScVal.scvVec([symbol('call_arg'), xdr.ScVal.scvU32(leaf.index)]);
170
+ case 'amount':
171
+ return xdr.ScVal.scvVec([symbol('amount'), scvAddressFromStrkey(leaf.token)]);
172
+ case 'window_spent':
173
+ return xdr.ScVal.scvVec([
174
+ symbol('window_spent'),
175
+ scvAddressFromStrkey(leaf.token),
176
+ scvU64FromValue(leaf.windowSeconds),
177
+ ]);
178
+ case 'now':
179
+ return xdr.ScVal.scvVec([symbol('now')]);
180
+ case 'valid_until':
181
+ return xdr.ScVal.scvVec([symbol('valid_until')]);
182
+ case 'invocation_count_in_window':
183
+ return xdr.ScVal.scvVec([symbol('invocation_count'), scvU64FromValue(leaf.windowSecs)]);
184
+ case 'oracle_price':
185
+ return xdr.ScVal.scvVec([symbol('oracle_price'), scvAddressFromStrkey(leaf.asset)]);
186
+ case 'literal_address':
187
+ return scvAddressFromStrkey(leaf.value);
188
+ case 'literal_i128':
189
+ return scvI128FromDecimal(leaf.value);
190
+ case 'literal_symbol':
191
+ return xdr.ScVal.scvSymbol(leaf.value);
192
+ case 'literal_u32':
193
+ return xdr.ScVal.scvU32(leaf.value);
194
+ case 'literal_u64':
195
+ return scvU64FromValue(leaf.value);
196
+ case 'literal_bytes':
197
+ return xdr.ScVal.scvBytes(Buffer.from(leaf.value, 'hex'));
198
+ case 'literal_vec':
199
+ // Bare ScVal::Vec of element encodings - order is preserved verbatim
200
+ // because the order IS the semantic (exact ordered sequence equality).
201
+ return xdr.ScVal.scvVec(leaf.elements.map(encodeLeaf));
202
+ }
203
+ }
204
+ function symbol(s) {
205
+ return xdr.ScVal.scvSymbol(s);
206
+ }
207
+ function sortByCanonicalBytes(values) {
208
+ const pairs = values.map((v) => ({ v, bytes: v.toXDR() }));
209
+ pairs.sort((a, b) => Buffer.compare(a.bytes, b.bytes));
210
+ return pairs.map((p) => p.v);
211
+ }
212
+ function scvAddressFromStrkey(strkey) {
213
+ return xdr.ScVal.scvAddress(Address.fromString(strkey).toScAddress());
214
+ }
215
+ function scvU64FromValue(value) {
216
+ // The Uint64 (UnsignedHyper) constructor accepts string | bigint | number;
217
+ // string is safest for values > 2^53.
218
+ return xdr.ScVal.scvU64(new xdr.Uint64(String(value)));
219
+ }
220
+ /** Build `ScVal::I128(Int128Parts{hi, lo})` from a signed decimal string.
221
+ * `Int128Parts` encodes the value as `(hi << 64) + lo` with `hi` a SIGNED
222
+ * 64-bit int and `lo` an UNSIGNED 64-bit int (this is NOT signed-magnitude).
223
+ * The inverse split is `hi = v >> 64n` (arithmetic right shift) and
224
+ * `lo = v & 0xFFFF...`. The SDK's `Int64` constructor takes a signed
225
+ * bigint/string/number. */
226
+ function scvI128FromDecimal(decimal) {
227
+ const v = BigInt(decimal);
228
+ const hi = v >> 64n;
229
+ const lo = v & UINT64_MAX;
230
+ // Guard against accidental over-range. Int128Parts.hi must be a valid Int64
231
+ // (-2^63 .. 2^63-1); values outside this range are invalid i128 entirely.
232
+ if (hi < INT64_MIN || hi > INT64_MAX) {
233
+ throw capError('MALFORMED_PREDICATE', `literal_i128 value ${decimal} is outside the Int128 range`);
234
+ }
235
+ if (lo < 0n || lo > UINT64_MAX) {
236
+ throw capError('MALFORMED_PREDICATE', `literal_i128 value ${decimal} has an invalid Int128Parts.lo`);
237
+ }
238
+ return xdr.ScVal.scvI128(new xdr.Int128Parts({
239
+ hi: new xdr.Int64(hi),
240
+ lo: new xdr.Uint64(lo),
241
+ }));
242
+ }
243
+ function capError(code, message) {
244
+ const err = new Error(message);
245
+ err.code = code;
246
+ err.severity = 'error';
247
+ err.retryable = false;
248
+ throw err;
249
+ }
@@ -0,0 +1 @@
1
+ export { type EncodedPredicate, encodePredicate } from './encode.ts';
@@ -0,0 +1,2 @@
1
+ // src/predicate/index.ts - re-export the canonical predicate encoder.
2
+ export { encodePredicate } from "./encode.js";
@@ -0,0 +1,14 @@
1
+ import type { ContextRuleDraft, PolicyRef, PredicateNode } from '../types.ts';
2
+ import type { SimulationResult } from '../verify/envelope.ts';
3
+ export interface ReviewCardSummary {
4
+ ruleName: string;
5
+ plainEnglish: string;
6
+ constraints: string[];
7
+ expiry: string;
8
+ backend: 'interpreter-v1' | 'ts-model';
9
+ /** Stable hash of the builder inputs - identical policy + summary = identical hash. */
10
+ contentHash: string;
11
+ }
12
+ /** Build a deterministic review-card summary from a policy + context rule +
13
+ * simulation result. Pure: same inputs -> byte-identical output. */
14
+ export declare function buildReviewCardSummary(predicate: PredicateNode | null, policyRefs: PolicyRef[], contextRule: ContextRuleDraft, simulation: SimulationResult): ReviewCardSummary;