@crediolabs/policy-synth 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +193 -5
  3. package/dist/adapters/interpreter/adapter.d.ts +38 -0
  4. package/dist/adapters/interpreter/adapter.js +522 -0
  5. package/dist/adapters/interpreter/index.d.ts +1 -0
  6. package/dist/adapters/interpreter/index.js +2 -0
  7. package/dist/adapters/oz/adapter.js +2 -0
  8. package/dist/codegen/compile-gate.d.ts +33 -0
  9. package/dist/codegen/compile-gate.js +119 -0
  10. package/dist/codegen/index.d.ts +2 -0
  11. package/dist/codegen/index.js +8 -0
  12. package/dist/codegen/template.d.ts +18 -0
  13. package/dist/codegen/template.js +131 -0
  14. package/dist/errors.d.ts +1 -1
  15. package/dist/index.d.ts +2 -0
  16. package/dist/index.js +2 -0
  17. package/dist/ir/types.d.ts +13 -2
  18. package/dist/predicate/encode.d.ts +10 -0
  19. package/dist/predicate/encode.js +249 -0
  20. package/dist/predicate/index.d.ts +1 -0
  21. package/dist/predicate/index.js +2 -0
  22. package/dist/record/decode.d.ts +6 -3
  23. package/dist/record/decode.js +13 -3
  24. package/dist/review-card/builder.d.ts +14 -0
  25. package/dist/review-card/builder.js +261 -0
  26. package/dist/review-card/conflict.d.ts +40 -0
  27. package/dist/review-card/conflict.js +111 -0
  28. package/dist/review-card/cross-check.d.ts +11 -0
  29. package/dist/review-card/cross-check.js +148 -0
  30. package/dist/review-card/index.d.ts +3 -0
  31. package/dist/review-card/index.js +4 -0
  32. package/dist/run/index.d.ts +31 -0
  33. package/dist/run/index.js +164 -0
  34. package/dist/run/schemas.d.ts +2003 -0
  35. package/dist/run/schemas.js +215 -0
  36. package/dist/synth/compose-from-recording.d.ts +35 -7
  37. package/dist/synth/compose-from-recording.js +225 -34
  38. package/dist/synth/deny-cases.d.ts +12 -0
  39. package/dist/synth/deny-cases.js +377 -0
  40. package/dist/synth/evaluate.d.ts +39 -0
  41. package/dist/synth/evaluate.js +425 -0
  42. package/dist/synth/harness.d.ts +16 -0
  43. package/dist/synth/harness.js +26 -0
  44. package/dist/synth/index.d.ts +4 -0
  45. package/dist/synth/index.js +4 -0
  46. package/dist/synth/minimize.d.ts +4 -0
  47. package/dist/synth/minimize.js +38 -0
  48. package/dist/synth/predicate-literals.d.ts +5 -0
  49. package/dist/synth/predicate-literals.js +25 -0
  50. package/dist/synth/synthesize-from-recording.d.ts +37 -5
  51. package/dist/synth/synthesize-from-recording.js +550 -18
  52. package/dist/types.d.ts +40 -1
  53. package/dist/types.js +17 -0
  54. package/dist/verify/envelope.d.ts +15 -0
  55. package/dist/verify/envelope.js +22 -0
  56. package/dist/verify/index.d.ts +3 -0
  57. package/dist/verify/index.js +3 -0
  58. package/dist/verify/simulate.d.ts +31 -0
  59. package/dist/verify/simulate.js +258 -0
  60. package/dist/verify/verify.d.ts +21 -0
  61. package/dist/verify/verify.js +189 -0
  62. package/dist-cjs/adapters/interpreter/adapter.d.ts +38 -0
  63. package/dist-cjs/adapters/interpreter/adapter.js +527 -0
  64. package/dist-cjs/adapters/interpreter/index.d.ts +1 -0
  65. package/dist-cjs/adapters/interpreter/index.js +8 -0
  66. package/dist-cjs/adapters/oz/adapter.d.ts +20 -0
  67. package/dist-cjs/adapters/oz/adapter.js +289 -0
  68. package/dist-cjs/adapters/oz/index.d.ts +1 -0
  69. package/dist-cjs/adapters/oz/index.js +8 -0
  70. package/dist-cjs/codegen/compile-gate.d.ts +33 -0
  71. package/dist-cjs/codegen/compile-gate.js +123 -0
  72. package/dist-cjs/codegen/index.d.ts +2 -0
  73. package/dist-cjs/codegen/index.js +14 -0
  74. package/dist-cjs/codegen/template.d.ts +18 -0
  75. package/dist-cjs/codegen/template.js +134 -0
  76. package/dist-cjs/errors.d.ts +37 -0
  77. package/dist-cjs/errors.js +3 -0
  78. package/dist-cjs/index.d.ts +11 -0
  79. package/dist-cjs/index.js +27 -0
  80. package/dist-cjs/ir/index.d.ts +1 -0
  81. package/dist-cjs/ir/index.js +3 -0
  82. package/dist-cjs/ir/types.d.ts +108 -0
  83. package/dist-cjs/ir/types.js +12 -0
  84. package/dist-cjs/mandate/index.d.ts +2 -0
  85. package/dist-cjs/mandate/index.js +6 -0
  86. package/dist-cjs/mandate/to-ir.d.ts +3 -0
  87. package/dist-cjs/mandate/to-ir.js +63 -0
  88. package/dist-cjs/mandate/types.d.ts +20 -0
  89. package/dist-cjs/mandate/types.js +9 -0
  90. package/dist-cjs/package.json +3 -0
  91. package/dist-cjs/predicate/encode.d.ts +10 -0
  92. package/dist-cjs/predicate/encode.js +252 -0
  93. package/dist-cjs/predicate/index.d.ts +1 -0
  94. package/dist-cjs/predicate/index.js +6 -0
  95. package/dist-cjs/record/decode.d.ts +79 -0
  96. package/dist-cjs/record/decode.js +398 -0
  97. package/dist-cjs/record/freshness.d.ts +17 -0
  98. package/dist-cjs/record/freshness.js +55 -0
  99. package/dist-cjs/record/index.d.ts +21 -0
  100. package/dist-cjs/record/index.js +166 -0
  101. package/dist-cjs/record/movements.d.ts +20 -0
  102. package/dist-cjs/record/movements.js +192 -0
  103. package/dist-cjs/record/rpc.d.ts +22 -0
  104. package/dist-cjs/record/rpc.js +74 -0
  105. package/dist-cjs/record/validate.d.ts +22 -0
  106. package/dist-cjs/record/validate.js +63 -0
  107. package/dist-cjs/registry/identify.d.ts +11 -0
  108. package/dist-cjs/registry/identify.js +87 -0
  109. package/dist-cjs/registry/index.d.ts +3 -0
  110. package/dist-cjs/registry/index.js +15 -0
  111. package/dist-cjs/registry/known-addresses.d.ts +16 -0
  112. package/dist-cjs/registry/known-addresses.js +53 -0
  113. package/dist-cjs/registry/protocols.d.ts +38 -0
  114. package/dist-cjs/registry/protocols.js +153 -0
  115. package/dist-cjs/review-card/builder.d.ts +14 -0
  116. package/dist-cjs/review-card/builder.js +264 -0
  117. package/dist-cjs/review-card/conflict.d.ts +40 -0
  118. package/dist-cjs/review-card/conflict.js +114 -0
  119. package/dist-cjs/review-card/cross-check.d.ts +11 -0
  120. package/dist-cjs/review-card/cross-check.js +151 -0
  121. package/dist-cjs/review-card/index.d.ts +3 -0
  122. package/dist-cjs/review-card/index.js +10 -0
  123. package/dist-cjs/run/index.d.ts +31 -0
  124. package/dist-cjs/run/index.js +178 -0
  125. package/dist-cjs/run/schemas.d.ts +2003 -0
  126. package/dist-cjs/run/schemas.js +218 -0
  127. package/dist-cjs/seams/index.d.ts +1 -0
  128. package/dist-cjs/seams/index.js +3 -0
  129. package/dist-cjs/seams/types.d.ts +66 -0
  130. package/dist-cjs/seams/types.js +12 -0
  131. package/dist-cjs/synth/compose-from-recording.d.ts +64 -0
  132. package/dist-cjs/synth/compose-from-recording.js +356 -0
  133. package/dist-cjs/synth/deny-cases.d.ts +12 -0
  134. package/dist-cjs/synth/deny-cases.js +380 -0
  135. package/dist-cjs/synth/evaluate.d.ts +39 -0
  136. package/dist-cjs/synth/evaluate.js +428 -0
  137. package/dist-cjs/synth/harness.d.ts +16 -0
  138. package/dist-cjs/synth/harness.js +29 -0
  139. package/dist-cjs/synth/index.d.ts +9 -0
  140. package/dist-cjs/synth/index.js +23 -0
  141. package/dist-cjs/synth/lower.d.ts +23 -0
  142. package/dist-cjs/synth/lower.js +119 -0
  143. package/dist-cjs/synth/minimize.d.ts +4 -0
  144. package/dist-cjs/synth/minimize.js +41 -0
  145. package/dist-cjs/synth/predicate-literals.d.ts +5 -0
  146. package/dist-cjs/synth/predicate-literals.js +28 -0
  147. package/dist-cjs/synth/scope.d.ts +26 -0
  148. package/dist-cjs/synth/scope.js +81 -0
  149. package/dist-cjs/synth/synthesize-from-mandate.d.ts +5 -0
  150. package/dist-cjs/synth/synthesize-from-mandate.js +37 -0
  151. package/dist-cjs/synth/synthesize-from-recording.d.ts +49 -0
  152. package/dist-cjs/synth/synthesize-from-recording.js +711 -0
  153. package/dist-cjs/types.d.ts +288 -0
  154. package/dist-cjs/types.js +55 -0
  155. package/dist-cjs/verify/envelope.d.ts +15 -0
  156. package/dist-cjs/verify/envelope.js +23 -0
  157. package/dist-cjs/verify/index.d.ts +3 -0
  158. package/dist-cjs/verify/index.js +8 -0
  159. package/dist-cjs/verify/simulate.d.ts +31 -0
  160. package/dist-cjs/verify/simulate.js +261 -0
  161. package/dist-cjs/verify/verify.d.ts +21 -0
  162. package/dist-cjs/verify/verify.js +192 -0
  163. package/package.json +43 -3
  164. package/src/adapters/interpreter/adapter.ts +642 -0
  165. package/src/adapters/interpreter/index.ts +8 -0
  166. package/src/adapters/oz/adapter.ts +2 -0
  167. package/src/codegen/compile-gate.ts +162 -0
  168. package/src/codegen/index.ts +17 -0
  169. package/src/codegen/template.ts +148 -0
  170. package/src/errors.ts +2 -0
  171. package/src/index.ts +2 -0
  172. package/src/ir/types.ts +9 -2
  173. package/src/predicate/encode.ts +307 -0
  174. package/src/predicate/index.ts +3 -0
  175. package/src/record/decode.ts +21 -10
  176. package/src/review-card/builder.ts +303 -0
  177. package/src/review-card/conflict.ts +143 -0
  178. package/src/review-card/cross-check.ts +158 -0
  179. package/src/review-card/index.ts +12 -0
  180. package/src/run/index.ts +213 -0
  181. package/src/run/schemas.ts +242 -0
  182. package/src/synth/compose-from-recording.ts +277 -43
  183. package/src/synth/deny-cases.ts +466 -0
  184. package/src/synth/evaluate.ts +493 -0
  185. package/src/synth/harness.ts +40 -0
  186. package/src/synth/index.ts +12 -0
  187. package/src/synth/minimize.ts +44 -0
  188. package/src/synth/predicate-literals.ts +27 -0
  189. package/src/synth/synthesize-from-recording.ts +655 -19
  190. package/src/types.ts +38 -2
  191. package/src/verify/envelope.ts +28 -0
  192. package/src/verify/index.ts +5 -0
  193. package/src/verify/simulate.ts +311 -0
  194. package/src/verify/verify.ts +243 -0
@@ -0,0 +1,162 @@
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
+
11
+ import { spawn } from 'node:child_process'
12
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
13
+ import { tmpdir } from 'node:os'
14
+ import { join } from 'node:path'
15
+
16
+ export type CompileGateResult =
17
+ | { code: 'COMPILE_OK' }
18
+ | { code: 'COMPILE_GATE_FAILED'; stderr: string }
19
+ | { code: 'SKIPPED'; reason: string }
20
+
21
+ export interface CompileGateOpts {
22
+ /** Caller-controlled abort signal; aborting before toolchain probe resolves
23
+ * the gate to `SKIPPED` rather than starting a cargo invocation. */
24
+ signal?: AbortSignal
25
+ /** Override the `cargo` binary (mostly for tests). */
26
+ cargoBin?: string
27
+ /** Override the target directory (mostly for tests). */
28
+ tempDir?: string
29
+ }
30
+
31
+ interface ToolchainProbe {
32
+ present: boolean
33
+ reason: string
34
+ }
35
+
36
+ /** Probe the host for the Rust toolchain the gate requires. We require BOTH
37
+ * `cargo` AND `stellar` (the Soroban CLI) because a real gate run invokes
38
+ * `stellar contract build`; absent either, the gate returns `SKIPPED`. */
39
+ export async function hasRustToolchain(): Promise<boolean> {
40
+ const probe = await probeToolchain()
41
+ return probe.present
42
+ }
43
+
44
+ async function probeToolchain(): Promise<ToolchainProbe> {
45
+ const cargo = await which('cargo')
46
+ if (!cargo) return { present: false, reason: 'cargo not found on PATH' }
47
+ const stellar = await which('stellar')
48
+ if (!stellar) return { present: false, reason: 'stellar not found on PATH' }
49
+ return { present: true, reason: `${cargo} + ${stellar}` }
50
+ }
51
+
52
+ async function which(bin: string): Promise<string | null> {
53
+ try {
54
+ const out = await runProcess('sh', ['-c', `command -v ${bin}`], { capture: true })
55
+ const path = out.stdout.trim()
56
+ return path.length > 0 ? path : null
57
+ } catch {
58
+ return null
59
+ }
60
+ }
61
+
62
+ interface RunOpts {
63
+ capture?: boolean
64
+ signal?: AbortSignal
65
+ }
66
+
67
+ function runProcess(
68
+ cmd: string,
69
+ args: string[],
70
+ opts: RunOpts
71
+ ): Promise<{ stdout: string; stderr: string; code: number }> {
72
+ return new Promise((resolve, reject) => {
73
+ if (opts.signal?.aborted) {
74
+ reject(new Error('aborted'))
75
+ return
76
+ }
77
+ const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] })
78
+ let stdout = ''
79
+ let stderr = ''
80
+ child.stdout.on('data', (b: Buffer) => {
81
+ stdout += b.toString('utf8')
82
+ })
83
+ child.stderr.on('data', (b: Buffer) => {
84
+ stderr += b.toString('utf8')
85
+ })
86
+ const onAbort = () => {
87
+ child.kill('SIGTERM')
88
+ reject(new Error('aborted'))
89
+ }
90
+ opts.signal?.addEventListener('abort', onAbort, { once: true })
91
+ child.on('error', (e) => {
92
+ opts.signal?.removeEventListener('abort', onAbort)
93
+ reject(e)
94
+ })
95
+ child.on('close', (code) => {
96
+ opts.signal?.removeEventListener('abort', onAbort)
97
+ resolve({ stdout, stderr, code: code ?? -1 })
98
+ })
99
+ })
100
+ }
101
+
102
+ const CARGO_MANIFEST = `[package]
103
+ name = "escape-hatch-gate"
104
+ version = "0.0.0"
105
+ edition = "2021"
106
+ publish = false
107
+
108
+ [lib]
109
+ crate-type = ["cdylib"]
110
+
111
+ [dependencies]
112
+ soroban-sdk = "22"
113
+
114
+ [workspace]
115
+ `
116
+
117
+ /** Compile-check a Rust source string against the pinned Soroban SDK.
118
+ *
119
+ * - Toolchain absent -> `{ code: 'SKIPPED', reason }` (NOT a failure).
120
+ * - Toolchain present, source compiles -> `{ code: 'COMPILE_OK' }`.
121
+ * - Toolchain present, source broken -> `{ code: 'COMPILE_GATE_FAILED', stderr }`.
122
+ *
123
+ * The gate writes the source to a temporary crate and runs `cargo check`
124
+ * against it; the crate is cleaned up whether or not compilation succeeds.
125
+ * The caller is expected to surface `COMPILE_GATE_FAILED.stderr` to the
126
+ * user (the LLM agent) so the user can iterate. */
127
+ export async function compileCheck(
128
+ rustSource: string,
129
+ opts: CompileGateOpts = {}
130
+ ): Promise<CompileGateResult> {
131
+ if (opts.signal?.aborted) {
132
+ return { code: 'SKIPPED', reason: 'aborted before probe' }
133
+ }
134
+
135
+ const probe = await probeToolchain()
136
+ if (!probe.present) {
137
+ return { code: 'SKIPPED', reason: probe.reason }
138
+ }
139
+
140
+ let dir: string | null = null
141
+ try {
142
+ dir = await mkdtemp(join(opts.tempDir ?? tmpdir(), 'codegen-gate-'))
143
+ await writeFile(join(dir, 'Cargo.toml'), CARGO_MANIFEST)
144
+ await writeFile(join(dir, 'lib.rs'), rustSource)
145
+
146
+ const runOpts: RunOpts = opts.signal ? { signal: opts.signal } : {}
147
+ const result = await runProcess(
148
+ opts.cargoBin ?? 'cargo',
149
+ ['check', '--quiet', '--offline', '--manifest-path', join(dir, 'Cargo.toml')],
150
+ runOpts
151
+ ).catch((e: Error) => ({ stdout: '', stderr: e.message, code: -1 }))
152
+
153
+ if (result.code === 0) {
154
+ return { code: 'COMPILE_OK' }
155
+ }
156
+ return { code: 'COMPILE_GATE_FAILED', stderr: result.stderr || result.stdout }
157
+ } finally {
158
+ if (dir) {
159
+ await rm(dir, { recursive: true, force: true }).catch(() => {})
160
+ }
161
+ }
162
+ }
@@ -0,0 +1,17 @@
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
+
8
+ export {
9
+ type CompileGateOpts,
10
+ type CompileGateResult,
11
+ compileCheck,
12
+ hasRustToolchain,
13
+ } from './compile-gate.ts'
14
+ export {
15
+ type EscapeHatchSpec,
16
+ generateRust,
17
+ } from './template.ts'
@@ -0,0 +1,148 @@
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
+
22
+ /** A small typed description of one uncovered constraint the v1 DSL refused
23
+ * to express. The synthesiser surfaces these from `CompileResult.uncovered`
24
+ * and the codegen escape hatch wraps them into a hand-auditable skeleton. */
25
+ export interface EscapeHatchSpec {
26
+ /** Address of the policy contract the skeleton is generated for. */
27
+ contract: string
28
+ /** The trait method the predicate lives inside (default: 'enforce'). */
29
+ fnName?: string
30
+ /** Human-readable description of each construct the DSL could not cover. */
31
+ uncovered: string[]
32
+ }
33
+
34
+ /** Format a name for use as a Rust identifier. The input is constrained by
35
+ * the caller (a kebab-case policy name + alphanumeric addresses); this is a
36
+ * belt-and-braces sanitiser that maps anything non-identifier to '_'. */
37
+ function asRustIdent(s: string): string {
38
+ let out = ''
39
+ for (let i = 0; i < s.length; i++) {
40
+ const ch = s.charCodeAt(i)
41
+ const ok =
42
+ (ch >= 48 && ch <= 57) || // 0-9
43
+ (ch >= 65 && ch <= 90) || // A-Z
44
+ (ch >= 97 && ch <= 122) || // a-z
45
+ ch === 95 // _
46
+ out += ok ? s[i] : '_'
47
+ }
48
+ // Identifiers may not start with a digit.
49
+ if (out.length > 0 && out.charCodeAt(0) >= 48 && out.charCodeAt(0) <= 57) {
50
+ out = `_${out}`
51
+ }
52
+ return out || 'policy'
53
+ }
54
+
55
+ /** Render the `uncovered` list as a `//` comment block (one line per item). */
56
+ function renderUncovered(uncovered: string[]): string {
57
+ if (uncovered.length === 0) {
58
+ return ' // (no specific uncovered constructs reported)'
59
+ }
60
+ return uncovered.map((line) => ` // - ${line}`).join('\n')
61
+ }
62
+
63
+ /** Generate a deterministic OZ `Policy` skeleton for an uncovered constraint.
64
+ *
65
+ * The skeleton is NOT a finished policy; the user fills in the predicate
66
+ * logic in the marked TODO(user) holes and audits the result themselves.
67
+ *
68
+ * Same `(spec, name)` always produces byte-identical output. */
69
+ export function generateRust(spec: EscapeHatchSpec, name: string): string {
70
+ const _contract = spec.contract
71
+ const _fnName = spec.fnName ?? 'enforce'
72
+ const structName = asRustIdent(name)
73
+ const _dataKeyName = `${asRustIdent(name)}_data`
74
+ const uncoveredBlock = renderUncovered(spec.uncovered)
75
+
76
+ return `// Auto-generated by the OZ Policy Builder codegen escape hatch.
77
+ // THIS OUTPUT IS THE USER'S TO COMPLETE AND AUDIT.
78
+ // The synthesiser never emits it on the happy path; reach for it only when
79
+ // a constraint cannot be expressed in the v1 DSL grammar (same shape as
80
+ // Zodiac Roles' \`Custom\` operator).
81
+
82
+ #![no_std]
83
+
84
+ use soroban_sdk::{contract, contractimpl, contracttype, Address, Env, Vec};
85
+
86
+ #[contracttype]
87
+ pub enum DataKey {
88
+ /// Composite key \`(smart_account, rule_id)\` so multiple policies on
89
+ /// one smart account coexist without collision.
90
+ State(Address, u32),
91
+ }
92
+
93
+ #[contract]
94
+ pub struct ${structName};
95
+
96
+ #[contractimpl]
97
+ impl ${structName} {
98
+ pub fn install(e: &Env, smart_account: Address, rule_id: u32) {
99
+ // TODO(user): initialise policy state for this (smart_account, rule_id).
100
+ // The skeleton leaves the stored value empty; the predicate body
101
+ // (in \`enforce\`) decides what to read.
102
+ e.storage().persistent().set(
103
+ &DataKey::State(smart_account.clone(), rule_id),
104
+ &(),
105
+ );
106
+ }
107
+
108
+ pub fn enforce(
109
+ e: &Env,
110
+ smart_account: Address,
111
+ rule_id: u32,
112
+ _signers: Vec<Address>,
113
+ ) {
114
+ // Invariant 1: authorise the smart account BEFORE any state read or
115
+ // predicate evaluation. Removing this call opens the policy to
116
+ // impersonation by any caller with a valid rule_id.
117
+ smart_account.require_auth();
118
+
119
+ // Invariant 2 + 4: read stored state through the composite key on
120
+ // \`persistent()\` storage. \`unwrap_or_default()\` (invariant 3)
121
+ // makes an empty key a permitted default rather than a panic.
122
+ let _state: () = e
123
+ .storage()
124
+ .persistent()
125
+ .get(&DataKey::State(smart_account.clone(), rule_id))
126
+ .unwrap_or_default();
127
+
128
+ // --- uncovered constraints the v1 DSL refused to express ---
129
+ ${uncoveredBlock}
130
+
131
+ // TODO(user): replace the placeholder below with the real predicate
132
+ // body. The recorded flow's \`(contract, fn_name, args)\` is the
133
+ // single authorised call \`Policy::enforce\` receives; match against
134
+ // \`e\` here.
135
+ let _ = (_state, &e);
136
+ }
137
+
138
+ pub fn uninstall(e: &Env, smart_account: Address, rule_id: u32) {
139
+ // Invariant 5: \`uninstall\` removes the stored state so a subsequent
140
+ // install starts from a clean slate (and the nonce returns to its
141
+ // post-uninstall value).
142
+ e.storage()
143
+ .persistent()
144
+ .remove(&DataKey::State(smart_account, rule_id));
145
+ }
146
+ }
147
+ `
148
+ }
package/src/errors.ts CHANGED
@@ -26,6 +26,8 @@ export type ErrorCode =
26
26
  // --- predicate caps (fail-closed at install) ---
27
27
  | 'PREDICATE_TOO_LARGE'
28
28
  | 'PREDICATE_TOO_DEEP'
29
+ | 'TOO_MANY_LEAVES'
30
+ | 'IN_OPERAND_LIMIT'
29
31
  | 'PREDICATE_ORACLE_OVER_LIMIT'
30
32
  | 'POLICY_CAP_EXCEEDED'
31
33
  | 'WASM_TOO_LARGE'
package/src/index.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/src/ir/types.ts CHANGED
@@ -60,13 +60,20 @@ export interface IRCompare {
60
60
  }
61
61
 
62
62
  /** Condition tree. NEAR-V2 guard/constraint are flat And/Or; the IR allows
63
- * nesting + `not` + `in` so the same IR can later lower to the OZ predicate
64
- * DSL. Week-1 adapters only lower the flat supported subset and flag the rest. */
63
+ * nesting + `not` + `in` + `eq_seq` so the same IR can later lower to the OZ
64
+ * predicate DSL. Week-1 adapters only lower the flat supported subset and flag
65
+ * the rest. */
65
66
  export type IRCondition =
66
67
  | { op: 'and' | 'or'; children: IRCondition[] }
67
68
  | { op: 'not'; child: IRCondition }
68
69
  | { op: 'compare'; compare: IRCompare }
69
70
  | { op: 'in'; selector: IRSelector; values: string[] }
71
+ /** Exact ordered sequence equality. The IR-level selector value MUST EQUAL
72
+ * `values` as an ORDERED sequence (e.g. a swap hop `path`). `in` is pure
73
+ * set membership and cannot express order; `eq_seq` is the construct that
74
+ * does. Adapters that cannot express an exact ordered vector (OZ built-ins)
75
+ * flag this as `uncovered` rather than silently dropping it. */
76
+ | { op: 'eq_seq'; selector: IRSelector; values: string[] }
70
77
 
71
78
  export interface IRPolicyRule {
72
79
  /** NEAR-V2 roles whitelist (empty = any; owner exempt). */
@@ -0,0 +1,307 @@
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
+
22
+ import { createHash } from 'node:crypto'
23
+ import { Address, xdr } from '@stellar/stellar-sdk'
24
+ import type { ToolError } from '../errors.ts'
25
+ import { PREDICATE_CAPS, type PredicateLeaf, type PredicateNode } from '../types.ts'
26
+
27
+ export interface EncodedPredicate {
28
+ /** base64 of the canonical ScVal XDR of the predicate root. */
29
+ encodedPredicate: string
30
+ /** sha256 hex digest of the raw XDR bytes (post-canonicalisation). */
31
+ predicateHash: string
32
+ }
33
+
34
+ const INT64_MAX = (1n << 63n) - 1n
35
+ const INT64_MIN = -(1n << 63n)
36
+ const UINT64_MAX = (1n << 64n) - 1n
37
+
38
+ /** Encode a `PredicateNode` to the canonical ScVal wire format and hash it.
39
+ * Pure function: same input -> byte-identical output every run. */
40
+ export function encodePredicate(node: PredicateNode): EncodedPredicate {
41
+ // --- pass 1: structural cap checks (no encoding needed) ---
42
+ const stats = computeStats(node)
43
+ if (stats.depth > PREDICATE_CAPS.MAX_DEPTH) {
44
+ throw capError(
45
+ 'PREDICATE_TOO_DEEP',
46
+ `predicate depth ${stats.depth} exceeds MAX_DEPTH ${PREDICATE_CAPS.MAX_DEPTH}`
47
+ )
48
+ }
49
+ if (stats.leaves > PREDICATE_CAPS.MAX_LEAVES) {
50
+ throw capError(
51
+ 'TOO_MANY_LEAVES',
52
+ `predicate leaf count ${stats.leaves} exceeds MAX_LEAVES ${PREDICATE_CAPS.MAX_LEAVES}`
53
+ )
54
+ }
55
+ for (const c of stats.inCounts) {
56
+ if (c.count > PREDICATE_CAPS.MAX_IN_OPERAND_COUNT) {
57
+ throw capError(
58
+ 'IN_OPERAND_LIMIT',
59
+ `\`in\` operand count ${c.count} exceeds MAX_IN_OPERAND_COUNT ${PREDICATE_CAPS.MAX_IN_OPERAND_COUNT}`
60
+ )
61
+ }
62
+ }
63
+ // Two-round confirmation costs 2 oracle reads per UNIQUE asset referenced.
64
+ const oracleReads = stats.oracleAssets.size * 2
65
+ if (oracleReads > PREDICATE_CAPS.MAX_ORACLE_READS) {
66
+ throw capError(
67
+ 'PREDICATE_ORACLE_OVER_LIMIT',
68
+ `oracle reads ${oracleReads} exceed MAX_ORACLE_READS ${PREDICATE_CAPS.MAX_ORACLE_READS}`
69
+ )
70
+ }
71
+
72
+ // --- pass 2: build + canonicalise the ScVal ---
73
+ const root = encodeNode(node)
74
+ const rawBytes = root.toXDR()
75
+ if (rawBytes.length > PREDICATE_CAPS.MAX_PREDICATE_BYTES) {
76
+ throw capError(
77
+ 'PREDICATE_TOO_LARGE',
78
+ `predicate bytes ${rawBytes.length} exceed MAX_PREDICATE_BYTES ${PREDICATE_CAPS.MAX_PREDICATE_BYTES}`
79
+ )
80
+ }
81
+ const encodedPredicate = rawBytes.toString('base64')
82
+ const predicateHash = createHash('sha256').update(rawBytes).digest('hex')
83
+ return { encodedPredicate, predicateHash }
84
+ }
85
+
86
+ interface PredicateStats {
87
+ depth: number
88
+ leaves: number
89
+ inCounts: Array<{ count: number }>
90
+ /** Unique assets referenced by `oracle_price` leaves - each costs 2 reads. */
91
+ oracleAssets: Set<string>
92
+ }
93
+
94
+ function computeStats(node: PredicateNode): PredicateStats {
95
+ const inCounts: Array<{ count: number }> = []
96
+ const oracleAssets = new Set<string>()
97
+ const { depth, leaves } = walk(node, inCounts, oracleAssets)
98
+ return { depth, leaves, inCounts, oracleAssets }
99
+ }
100
+
101
+ function walk(
102
+ node: PredicateNode,
103
+ inCounts: Array<{ count: number }>,
104
+ oracleAssets: Set<string>
105
+ ): { depth: number; leaves: number } {
106
+ switch (node.op) {
107
+ case 'and':
108
+ case 'or': {
109
+ if (node.children.length === 0) return { depth: 1, leaves: 0 }
110
+ let maxChildDepth = 0
111
+ let totalLeaves = 0
112
+ for (const c of node.children) {
113
+ const child = walk(c, inCounts, oracleAssets)
114
+ if (child.depth > maxChildDepth) maxChildDepth = child.depth
115
+ totalLeaves += child.leaves
116
+ }
117
+ return { depth: maxChildDepth + 1, leaves: totalLeaves }
118
+ }
119
+ case 'not': {
120
+ const child = walk(node.child, inCounts, oracleAssets)
121
+ return { depth: child.depth + 1, leaves: child.leaves }
122
+ }
123
+ case 'eq':
124
+ case 'lt':
125
+ case 'lte':
126
+ case 'gt':
127
+ case 'gte': {
128
+ collectOracle(node.left, oracleAssets)
129
+ collectOracle(node.right, oracleAssets)
130
+ return { depth: 1, leaves: leafCount(node.left) + leafCount(node.right) }
131
+ }
132
+ case 'in': {
133
+ inCounts.push({ count: node.haystack.length })
134
+ collectOracle(node.needle, oracleAssets)
135
+ let haystackLeaves = 0
136
+ for (const h of node.haystack) {
137
+ collectOracle(h, oracleAssets)
138
+ haystackLeaves += leafCount(h)
139
+ }
140
+ return {
141
+ depth: 1,
142
+ leaves: leafCount(node.needle) + haystackLeaves,
143
+ }
144
+ }
145
+ }
146
+ }
147
+
148
+ /** Leaf-count contribution of one PredicateLeaf: 1 for any flat leaf, and the
149
+ * sum of element leaf counts for `literal_vec` so MAX_LEAVES caps see nested
150
+ * vector elements. */
151
+ function leafCount(leaf: PredicateLeaf): number {
152
+ if (leaf.kind === 'literal_vec') {
153
+ let total = 1 // the literal_vec itself counts as one leaf node
154
+ for (const el of leaf.elements) total += leafCount(el)
155
+ return total
156
+ }
157
+ return 1
158
+ }
159
+
160
+ function collectOracle(leaf: PredicateLeaf, oracleAssets: Set<string>): void {
161
+ // literal_vec is the only nested leaf; recurse so an oracle_price buried in a
162
+ // vector literal (which the lowering would forbid, but the cap-walker must
163
+ // still see) is counted toward the oracle-read budget.
164
+ if (leaf.kind === 'oracle_price') {
165
+ oracleAssets.add(leaf.asset)
166
+ } else if (leaf.kind === 'literal_vec') {
167
+ for (const el of leaf.elements) collectOracle(el, oracleAssets)
168
+ }
169
+ }
170
+
171
+ function encodeNode(node: PredicateNode): xdr.ScVal {
172
+ switch (node.op) {
173
+ case 'and':
174
+ case 'or': {
175
+ const encoded = node.children.map(encodeNode)
176
+ // sort children by their canonical XDR bytes ascending.
177
+ const sorted = sortByCanonicalBytes(encoded)
178
+ return xdr.ScVal.scvVec([symbol(node.op), xdr.ScVal.scvVec(sorted)])
179
+ }
180
+ case 'not': {
181
+ return xdr.ScVal.scvVec([symbol('not'), encodeNode(node.child)])
182
+ }
183
+ case 'eq':
184
+ case 'lt':
185
+ case 'lte':
186
+ case 'gt':
187
+ case 'gte': {
188
+ return xdr.ScVal.scvVec([symbol(node.op), encodeLeaf(node.left), encodeLeaf(node.right)])
189
+ }
190
+ case 'in': {
191
+ const needle = encodeLeaf(node.needle)
192
+ // `in` is PURE set membership: the haystack is ALWAYS sorted by canonical
193
+ // XDR bytes ascending. An exact ordered sequence (e.g. a swap hop path)
194
+ // is expressed as `eq(selector, literal_vec)` where the vec's element
195
+ // order is preserved verbatim (handled in `encodeLeaf(literal_vec)`).
196
+ const haystack = sortByCanonicalBytes(node.haystack.map(encodeLeaf))
197
+ return xdr.ScVal.scvVec([symbol('in'), needle, xdr.ScVal.scvVec(haystack)])
198
+ }
199
+ }
200
+ }
201
+
202
+ function encodeLeaf(leaf: PredicateLeaf): xdr.ScVal {
203
+ switch (leaf.kind) {
204
+ case 'call_contract':
205
+ return xdr.ScVal.scvVec([symbol('call_contract')])
206
+ case 'call_fn':
207
+ return xdr.ScVal.scvVec([symbol('call_fn')])
208
+ case 'call_arg':
209
+ return xdr.ScVal.scvVec([symbol('call_arg'), xdr.ScVal.scvU32(leaf.index)])
210
+ case 'amount':
211
+ return xdr.ScVal.scvVec([symbol('amount'), scvAddressFromStrkey(leaf.token)])
212
+ case 'window_spent':
213
+ return xdr.ScVal.scvVec([
214
+ symbol('window_spent'),
215
+ scvAddressFromStrkey(leaf.token),
216
+ scvU64FromValue(leaf.windowSeconds),
217
+ ])
218
+ case 'now':
219
+ return xdr.ScVal.scvVec([symbol('now')])
220
+ case 'valid_until':
221
+ return xdr.ScVal.scvVec([symbol('valid_until')])
222
+ case 'invocation_count_in_window':
223
+ return xdr.ScVal.scvVec([symbol('invocation_count'), scvU64FromValue(leaf.windowSecs)])
224
+ case 'oracle_price':
225
+ return xdr.ScVal.scvVec([symbol('oracle_price'), scvAddressFromStrkey(leaf.asset)])
226
+ case 'literal_address':
227
+ return scvAddressFromStrkey(leaf.value)
228
+ case 'literal_i128':
229
+ return scvI128FromDecimal(leaf.value)
230
+ case 'literal_symbol':
231
+ return xdr.ScVal.scvSymbol(leaf.value)
232
+ case 'literal_u32':
233
+ return xdr.ScVal.scvU32(leaf.value)
234
+ case 'literal_u64':
235
+ return scvU64FromValue(leaf.value)
236
+ case 'literal_bytes':
237
+ return xdr.ScVal.scvBytes(Buffer.from(leaf.value, 'hex'))
238
+ case 'literal_vec':
239
+ // Bare ScVal::Vec of element encodings - order is preserved verbatim
240
+ // because the order IS the semantic (exact ordered sequence equality).
241
+ return xdr.ScVal.scvVec(leaf.elements.map(encodeLeaf))
242
+ }
243
+ }
244
+
245
+ function symbol(s: string): xdr.ScVal {
246
+ return xdr.ScVal.scvSymbol(s)
247
+ }
248
+
249
+ function sortByCanonicalBytes(values: xdr.ScVal[]): xdr.ScVal[] {
250
+ const pairs = values.map((v) => ({ v, bytes: v.toXDR() }))
251
+ pairs.sort((a, b) => Buffer.compare(a.bytes, b.bytes))
252
+ return pairs.map((p) => p.v)
253
+ }
254
+
255
+ function scvAddressFromStrkey(strkey: string): xdr.ScVal {
256
+ return xdr.ScVal.scvAddress(Address.fromString(strkey).toScAddress())
257
+ }
258
+
259
+ function scvU64FromValue(value: number | string): xdr.ScVal {
260
+ // The Uint64 (UnsignedHyper) constructor accepts string | bigint | number;
261
+ // string is safest for values > 2^53.
262
+ return xdr.ScVal.scvU64(new xdr.Uint64(String(value)))
263
+ }
264
+
265
+ /** Build `ScVal::I128(Int128Parts{hi, lo})` from a signed decimal string.
266
+ * `Int128Parts` encodes the value as `(hi << 64) + lo` with `hi` a SIGNED
267
+ * 64-bit int and `lo` an UNSIGNED 64-bit int (this is NOT signed-magnitude).
268
+ * The inverse split is `hi = v >> 64n` (arithmetic right shift) and
269
+ * `lo = v & 0xFFFF...`. The SDK's `Int64` constructor takes a signed
270
+ * bigint/string/number. */
271
+ function scvI128FromDecimal(decimal: string): xdr.ScVal {
272
+ const v = BigInt(decimal)
273
+ const hi = v >> 64n
274
+ const lo = v & UINT64_MAX
275
+ // Guard against accidental over-range. Int128Parts.hi must be a valid Int64
276
+ // (-2^63 .. 2^63-1); values outside this range are invalid i128 entirely.
277
+ if (hi < INT64_MIN || hi > INT64_MAX) {
278
+ throw capError(
279
+ 'MALFORMED_PREDICATE',
280
+ `literal_i128 value ${decimal} is outside the Int128 range`
281
+ )
282
+ }
283
+ if (lo < 0n || lo > UINT64_MAX) {
284
+ throw capError(
285
+ 'MALFORMED_PREDICATE',
286
+ `literal_i128 value ${decimal} has an invalid Int128Parts.lo`
287
+ )
288
+ }
289
+ return xdr.ScVal.scvI128(
290
+ new xdr.Int128Parts({
291
+ hi: new xdr.Int64(hi),
292
+ lo: new xdr.Uint64(lo),
293
+ })
294
+ )
295
+ }
296
+
297
+ function capError(code: ToolError['code'], message: string): ToolError {
298
+ const err = new Error(message) as Error & {
299
+ code: ToolError['code']
300
+ severity: string
301
+ retryable: boolean
302
+ }
303
+ err.code = code
304
+ err.severity = 'error'
305
+ err.retryable = false
306
+ throw err
307
+ }
@@ -0,0 +1,3 @@
1
+ // src/predicate/index.ts - re-export the canonical predicate encoder.
2
+
3
+ export { type EncodedPredicate, encodePredicate } from './encode.ts'