@crediolabs/policy-synth 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +193 -5
  2. package/dist/adapters/interpreter/adapter.d.ts +38 -0
  3. package/dist/adapters/interpreter/adapter.js +522 -0
  4. package/dist/adapters/interpreter/index.d.ts +1 -0
  5. package/dist/adapters/interpreter/index.js +2 -0
  6. package/dist/adapters/oz/adapter.js +20 -18
  7. package/dist/codegen/compile-gate.d.ts +33 -0
  8. package/dist/codegen/compile-gate.js +119 -0
  9. package/dist/codegen/index.d.ts +2 -0
  10. package/dist/codegen/index.js +8 -0
  11. package/dist/codegen/template.d.ts +18 -0
  12. package/dist/codegen/template.js +131 -0
  13. package/dist/errors.d.ts +1 -1
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +2 -0
  16. package/dist/ir/types.d.ts +13 -2
  17. package/dist/mandate/to-ir.js +4 -4
  18. package/dist/mandate/types.d.ts +1 -1
  19. package/dist/predicate/encode.d.ts +10 -0
  20. package/dist/predicate/encode.js +249 -0
  21. package/dist/predicate/index.d.ts +1 -0
  22. package/dist/predicate/index.js +2 -0
  23. package/dist/review-card/builder.d.ts +14 -0
  24. package/dist/review-card/builder.js +261 -0
  25. package/dist/review-card/conflict.d.ts +40 -0
  26. package/dist/review-card/conflict.js +111 -0
  27. package/dist/review-card/cross-check.d.ts +11 -0
  28. package/dist/review-card/cross-check.js +148 -0
  29. package/dist/review-card/index.d.ts +3 -0
  30. package/dist/review-card/index.js +4 -0
  31. package/dist/seams/types.d.ts +1 -1
  32. package/dist/synth/compose-from-recording.d.ts +35 -7
  33. package/dist/synth/compose-from-recording.js +231 -40
  34. package/dist/synth/deny-cases.d.ts +12 -0
  35. package/dist/synth/deny-cases.js +361 -0
  36. package/dist/synth/evaluate.d.ts +39 -0
  37. package/dist/synth/evaluate.js +425 -0
  38. package/dist/synth/harness.d.ts +16 -0
  39. package/dist/synth/harness.js +26 -0
  40. package/dist/synth/index.d.ts +4 -0
  41. package/dist/synth/index.js +4 -0
  42. package/dist/synth/lower.d.ts +2 -2
  43. package/dist/synth/minimize.d.ts +4 -0
  44. package/dist/synth/minimize.js +38 -0
  45. package/dist/synth/predicate-literals.d.ts +5 -0
  46. package/dist/synth/predicate-literals.js +25 -0
  47. package/dist/synth/synthesize-from-mandate.js +5 -5
  48. package/dist/synth/synthesize-from-recording.d.ts +32 -3
  49. package/dist/synth/synthesize-from-recording.js +491 -17
  50. package/dist/types.d.ts +23 -1
  51. package/dist/verify/envelope.d.ts +15 -0
  52. package/dist/verify/envelope.js +22 -0
  53. package/dist/verify/index.d.ts +3 -0
  54. package/dist/verify/index.js +3 -0
  55. package/dist/verify/simulate.d.ts +31 -0
  56. package/dist/verify/simulate.js +242 -0
  57. package/dist/verify/verify.d.ts +21 -0
  58. package/dist/verify/verify.js +173 -0
  59. package/package.json +1 -1
  60. package/src/adapters/interpreter/adapter.ts +642 -0
  61. package/src/adapters/interpreter/index.ts +8 -0
  62. package/src/adapters/oz/adapter.ts +20 -18
  63. package/src/codegen/compile-gate.ts +162 -0
  64. package/src/codegen/index.ts +17 -0
  65. package/src/codegen/template.ts +148 -0
  66. package/src/errors.ts +2 -0
  67. package/src/index.ts +2 -0
  68. package/src/ir/types.ts +9 -2
  69. package/src/mandate/to-ir.ts +4 -4
  70. package/src/mandate/types.ts +1 -1
  71. package/src/predicate/encode.ts +307 -0
  72. package/src/predicate/index.ts +3 -0
  73. package/src/review-card/builder.ts +303 -0
  74. package/src/review-card/conflict.ts +143 -0
  75. package/src/review-card/cross-check.ts +158 -0
  76. package/src/review-card/index.ts +12 -0
  77. package/src/seams/types.ts +1 -1
  78. package/src/synth/compose-from-recording.ts +283 -49
  79. package/src/synth/deny-cases.ts +447 -0
  80. package/src/synth/evaluate.ts +493 -0
  81. package/src/synth/harness.ts +40 -0
  82. package/src/synth/index.ts +12 -0
  83. package/src/synth/lower.ts +2 -2
  84. package/src/synth/minimize.ts +44 -0
  85. package/src/synth/predicate-literals.ts +27 -0
  86. package/src/synth/synthesize-from-mandate.ts +5 -5
  87. package/src/synth/synthesize-from-recording.ts +575 -18
  88. package/src/types.ts +19 -2
  89. package/src/verify/envelope.ts +28 -0
  90. package/src/verify/index.ts +5 -0
  91. package/src/verify/simulate.ts +292 -0
  92. package/src/verify/verify.ts +224 -0
@@ -1,7 +1,7 @@
1
- // src/adapters/oz/adapter.ts - the OZ Accounts CustodyAdapter (Path-A lowering).
1
+ // src/adapters/oz/adapter.ts - the OZ Accounts CustodyAdapter.
2
2
  //
3
3
  // Compiles a PolicyIR to an OZ `ProposedPolicy` using OZ built-in policy
4
- // primitives (Path A). Only the constructs OZ can express natively are lowered:
4
+ // primitives. Only the constructs OZ can express natively are lowered:
5
5
  // scope.contract -> ContextRuleType.call_contract (else default)
6
6
  // expiry.validUntilLedger -> ContextRuleDraft.validUntilLedger
7
7
  // window_spent(t,w) <= L -> `spending_limit` primitive
@@ -9,7 +9,7 @@
9
9
  // Anything needing a capability this backend lacks (oracle price, invocation
10
10
  // count, per-arg comparison/allowlist, guard, nested boolean predicate) is NOT
11
11
  // emitted: it is named in `uncovered` and `covered` is set false. Nothing is
12
- // silently dropped - the uncovered constructs are the Path-B markers.
12
+ // silently dropped - the uncovered constructs are named instead.
13
13
  //
14
14
  // OZ built-in policy instance addresses are per-network deploy artifacts we do
15
15
  // not have yet (install is a later phase). They are injected via config; week-1
@@ -132,8 +132,8 @@ function lowerRule(rule: IRPolicyRule, config: OzAdapterConfig): LoweredRule {
132
132
  const policyRefs: PolicyRef[] = []
133
133
 
134
134
  // scope -> context rule type. OZ scopes by contract (CallContract); a finer
135
- // method-level restriction is a predicate concern and must be flagged Path-B
136
- // because CallContract alone permits other methods on the same contract
135
+ // method-level restriction is a predicate concern and must be flagged as not
136
+ // covered because CallContract alone permits other methods on the same contract
137
137
  // (e.g. an unbounded approve alongside a capped transfer).
138
138
  const contextRuleType: ContextRuleDraft['contextRuleType'] =
139
139
  rule.scope.contract !== undefined
@@ -171,12 +171,12 @@ function lowerRule(rule: IRPolicyRule, config: OzAdapterConfig): LoweredRule {
171
171
  }
172
172
  }
173
173
 
174
- // guard -> Path B (applicability predicates are not an OZ built-in).
174
+ // guard -> not covered (applicability predicates are not an OZ built-in).
175
175
  if (rule.guard) {
176
176
  uncovered.push(`guard: ${describeCondition(rule.guard)}`)
177
177
  }
178
178
 
179
- // constraints -> spending_limit where they match; else Path B. The OZ
179
+ // constraints -> spending_limit where they match; else not covered. The OZ
180
180
  // spending_limit policy takes `{ spending_limit: i128, period_ledgers: u32 }`
181
181
  // and has NO token param: it only accepts a CallContract context rule
182
182
  // (OnlyCallContractAllowed) and limits transfers of that context's contract,
@@ -209,7 +209,7 @@ function lowerRule(rule: IRPolicyRule, config: OzAdapterConfig): LoweredRule {
209
209
 
210
210
  // approval.threshold -> simple/weighted threshold primitive. A threshold < 1
211
211
  // is not a real M-of-N gate (0 approvals authorises everything), so refuse to
212
- // emit a no-op primitive and flag it Path-B instead.
212
+ // emit a no-op primitive and flag it as not covered instead.
213
213
  if (rule.approval) {
214
214
  if (!Number.isInteger(rule.approval.threshold) || rule.approval.threshold < 1) {
215
215
  uncovered.push(
@@ -281,17 +281,19 @@ function matchSpendingLimit(c: IRCondition): SpendingLimitMatch | null {
281
281
  return { token: selector.token, limit: value, windowSeconds: selector.windowSeconds }
282
282
  }
283
283
 
284
- /** Human-readable descriptor for a construct the OZ Path-A backend cannot
285
- * express, used to populate `uncovered` (the Path-B markers). */
284
+ /** Human-readable descriptor for a construct the OZ built-in-primitive backend
285
+ * cannot express, used to populate `uncovered`. */
286
286
  function describeCondition(cond: IRCondition): string {
287
287
  switch (cond.op) {
288
288
  case 'in':
289
- return `value allowlist on ${describeSelector(cond.selector)} (arg allowlist, Path B)`
289
+ return `value allowlist on ${describeSelector(cond.selector)} (arg allowlist)`
290
+ case 'eq_seq':
291
+ return `exact ordered sequence on ${describeSelector(cond.selector)} (OZ built-ins cannot express an exact vector)`
290
292
  case 'not':
291
- return 'negated condition (predicate DSL, Path B)'
293
+ return 'negated condition (predicate DSL)'
292
294
  case 'and':
293
295
  case 'or':
294
- return `nested ${cond.op} condition (predicate DSL, Path B)`
296
+ return `nested ${cond.op} condition (predicate DSL)`
295
297
  case 'compare': {
296
298
  const s = cond.compare.selector
297
299
  switch (s.kind) {
@@ -302,16 +304,16 @@ function describeCondition(cond: IRCondition): string {
302
304
  case 'window_spent':
303
305
  return `spend-window comparison with operator '${cond.compare.operator}' (only 'lte' lowers to spending_limit)`
304
306
  case 'amount':
305
- return `per-call amount comparison on ${s.token} (predicate DSL, Path B)`
307
+ return `per-call amount comparison on ${s.token} (predicate DSL)`
306
308
  case 'arg':
307
- return `argument comparison on arg ${s.argIndex} (predicate DSL, Path B)`
309
+ return `argument comparison on arg ${s.argIndex} (predicate DSL)`
308
310
  case 'calldata':
309
- return 'EVM calldata comparison (predicate DSL, Path B)'
311
+ return 'EVM calldata comparison (predicate DSL)'
310
312
  case 'value':
311
- return 'tx.value comparison (predicate DSL, Path B)'
313
+ return 'tx.value comparison (predicate DSL)'
312
314
  case 'now':
313
315
  case 'valid_until':
314
- return 'time comparison (predicate DSL, Path B)'
316
+ return 'time comparison (predicate DSL)'
315
317
  }
316
318
  }
317
319
  }
@@ -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). */
@@ -6,8 +6,8 @@
6
6
  // contract/method -> rule.scope
7
7
  // spendingLimit -> a `window_spent(token,window) <= limit` compare
8
8
  // approvalThreshold-> rule.approval.threshold
9
- // recipients -> an `in` condition on the recipient arg (Path-B flagged
10
- // by the OZ adapter; that is expected)
9
+ // recipients -> an `in` condition on the recipient arg (flagged as not
10
+ // covered by the OZ adapter; that is expected)
11
11
  // expiry -> rule.expiry
12
12
  // The top-level default is `deny_all` (OZ context rules are deny-by-default).
13
13
 
@@ -16,8 +16,8 @@ import type { MandateSpec } from './types.ts'
16
16
 
17
17
  /** Arg index the recipient allowlist constrains. Pinned to the SEP-41
18
18
  * `transfer(from, to, amount)` convention where `to` is arg 1. This condition
19
- * is flagged Path-B by the OZ adapter (no built-in primitive expresses an arg
20
- * allowlist), so the index only needs to be deterministic in week-1. */
19
+ * is flagged as not covered by the OZ adapter (no built-in primitive expresses
20
+ * an arg allowlist), so the index only needs to be deterministic in week-1. */
21
21
  const RECIPIENT_ARG_INDEX = 1
22
22
 
23
23
  export function mandateToPolicyIR(spec: MandateSpec): PolicyIR {
@@ -14,7 +14,7 @@ export interface MandateSpec {
14
14
  spendingLimit?: { token: string; limit: string; windowSeconds: number }
15
15
  /** -> OZ `simple_threshold` / `weighted_threshold` primitive. */
16
16
  approvalThreshold?: number
17
- /** Recipient allowlist -> an `in` arg condition (flagged Path-B in week-1). */
17
+ /** Recipient allowlist -> an `in` arg condition (not covered by an OZ built-in). */
18
18
  recipients?: string[]
19
19
  /** -> OZ context-rule expiry. */
20
20
  expiry?: { validUntilLedger?: number; validUntilUnixSeconds?: number }