@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,289 @@
1
+ "use strict";
2
+ // src/adapters/oz/adapter.ts - the OZ Accounts CustodyAdapter.
3
+ //
4
+ // Compiles a PolicyIR to an OZ `ProposedPolicy` using OZ built-in policy
5
+ // primitives. Only the constructs OZ can express natively are lowered:
6
+ // scope.contract -> ContextRuleType.call_contract (else default)
7
+ // expiry.validUntilLedger -> ContextRuleDraft.validUntilLedger
8
+ // window_spent(t,w) <= L -> `spending_limit` primitive
9
+ // approval.threshold -> `simple_threshold` / `weighted_threshold`
10
+ // Anything needing a capability this backend lacks (oracle price, invocation
11
+ // count, per-arg comparison/allowlist, guard, nested boolean predicate) is NOT
12
+ // emitted: it is named in `uncovered` and `covered` is set false. Nothing is
13
+ // silently dropped - the uncovered constructs are named instead.
14
+ //
15
+ // OZ built-in policy instance addresses are per-network deploy artifacts we do
16
+ // not have yet (install is a later phase). They are injected via config; week-1
17
+ // ships a clearly-labelled [VERIFY] placeholder so nothing invents an address.
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.PLACEHOLDER_OZ_INSTANCES = void 0;
20
+ exports.placeholderOzConfig = placeholderOzConfig;
21
+ exports.createOzAdapter = createOzAdapter;
22
+ const types_ts_1 = require("../../types.js");
23
+ /** [VERIFY] NOT real deployed addresses. The OZ built-in policy instances are
24
+ * per-network deploy artifacts we do not have yet; install is a later phase.
25
+ * Injected so the adapter never invents a Stellar contract address. */
26
+ exports.PLACEHOLDER_OZ_INSTANCES = {
27
+ spending_limit: 'VERIFY-oz-spending-limit-instance-address',
28
+ simple_threshold: 'VERIFY-oz-simple-threshold-instance-address',
29
+ weighted_threshold: 'VERIFY-oz-weighted-threshold-instance-address',
30
+ };
31
+ /** Week-1 OZ adapter config with placeholder instance addresses. */
32
+ function placeholderOzConfig(network) {
33
+ return { network, instances: exports.PLACEHOLDER_OZ_INSTANCES };
34
+ }
35
+ /** Parse confidence for a deterministic (non-decoded) input: full, with an
36
+ * empty unknown/opaque breakdown. A mandate needs no decoding, so the gate is
37
+ * not applicable and confidence is 1. */
38
+ const FULL_PARSE_CONFIDENCE = {
39
+ overall: 1,
40
+ knownContracts: [],
41
+ unknownContracts: [],
42
+ opaqueScVals: [],
43
+ thresholdUsed: 1,
44
+ };
45
+ const CAPABILITIES = {
46
+ supportsSpendWindow: true,
47
+ supportsThreshold: true,
48
+ supportsTimeExpiry: true,
49
+ supportsOraclePrice: false,
50
+ supportsInvocationCount: false,
51
+ supportsGeneralPredicate: false,
52
+ };
53
+ function createOzAdapter(config) {
54
+ return {
55
+ name: 'oz-accounts',
56
+ mode: 'enforce',
57
+ capabilities: () => ({ ...CAPABILITIES }),
58
+ compile: (ir) => compile(ir, config),
59
+ simulate: () => simulateStub(),
60
+ export: (ir) => canonicalStringify(ir),
61
+ };
62
+ }
63
+ function compile(ir, config) {
64
+ const uncovered = [];
65
+ const firstRule = ir.rules[0];
66
+ if (!firstRule) {
67
+ return { covered: false, uncovered: ['empty PolicyIR (no rules to compile)'] };
68
+ }
69
+ if (ir.rules.length > 1) {
70
+ uncovered.push(`multi-rule PolicyIR: ${ir.rules.length - 1} rule(s) beyond the first are not compiled (a ProposedPolicy carries a single context rule in this slice)`);
71
+ }
72
+ const lowered = lowerRule(firstRule, config);
73
+ uncovered.push(...lowered.uncovered);
74
+ const result = { covered: uncovered.length === 0, uncovered };
75
+ if (!lowered.capExceeded) {
76
+ const proposed = {
77
+ contextRule: lowered.contextRule,
78
+ policyDocuments: [],
79
+ policyRefs: lowered.policyRefs,
80
+ parseConfidence: { ...FULL_PARSE_CONFIDENCE },
81
+ warnings: [],
82
+ ambiguities: [],
83
+ };
84
+ result.proposed = proposed;
85
+ }
86
+ return result;
87
+ }
88
+ function lowerRule(rule, config) {
89
+ const uncovered = [];
90
+ const policyRefs = [];
91
+ // scope -> context rule type. OZ scopes by contract (CallContract); a finer
92
+ // method-level restriction is a predicate concern and must be flagged as not
93
+ // covered because CallContract alone permits other methods on the same contract
94
+ // (e.g. an unbounded approve alongside a capped transfer).
95
+ const contextRuleType = rule.scope.contract !== undefined
96
+ ? { kind: 'call_contract', contract: rule.scope.contract }
97
+ : { kind: 'default' };
98
+ if (rule.scope.method !== undefined && rule.scope.contract !== undefined) {
99
+ uncovered.push(`per-method scoping to \`${rule.scope.method}\` (OZ CallContract scopes by contract only; requires the interpreter predicate)`);
100
+ }
101
+ if (rule.scope.chainId !== undefined) {
102
+ uncovered.push(`chainId \`${rule.scope.chainId}\` not bindable by the Stellar OZ adapter (network is per-context, not per-rule)`);
103
+ }
104
+ if (rule.roles.length > 0) {
105
+ uncovered.push(`roles [${rule.roles.join(', ')}] dropped (role-to-signer mapping is a later phase; OZ signers carry addresses, not role names)`);
106
+ }
107
+ // expiry -> validUntilLedger. Unix-timestamp expiry cannot be expressed by an
108
+ // OZ context rule (it expires by ledger sequence), so flag it.
109
+ let validUntilLedger = null;
110
+ if (rule.expiry) {
111
+ if (rule.expiry.validUntilLedger !== undefined) {
112
+ validUntilLedger = rule.expiry.validUntilLedger;
113
+ }
114
+ else if (rule.expiry.validUntilUnixSeconds !== undefined) {
115
+ uncovered.push('time expiry given as a unix timestamp (OZ context rules expire by ledger sequence; supply expiry.validUntilLedger)');
116
+ }
117
+ }
118
+ // guard -> not covered (applicability predicates are not an OZ built-in).
119
+ if (rule.guard) {
120
+ uncovered.push(`guard: ${describeCondition(rule.guard)}`);
121
+ }
122
+ // constraints -> spending_limit where they match; else not covered. The OZ
123
+ // spending_limit policy takes `{ spending_limit: i128, period_ledgers: u32 }`
124
+ // and has NO token param: it only accepts a CallContract context rule
125
+ // (OnlyCallContractAllowed) and limits transfers of that context's contract,
126
+ // so the spent token must equal the scope contract, and the window is a
127
+ // ledger count (~5s/ledger), not seconds.
128
+ for (const c of rule.constraints) {
129
+ const spend = matchSpendingLimit(c);
130
+ if (!spend) {
131
+ uncovered.push(describeCondition(c));
132
+ continue;
133
+ }
134
+ if (contextRuleType.kind !== 'call_contract' || spend.token !== contextRuleType.contract) {
135
+ uncovered.push(`spending_limit on token ${spend.token} needs a CallContract context scoped to that token (OZ pins the limit to the context contract, not a token param)`);
136
+ continue;
137
+ }
138
+ policyRefs.push({
139
+ kind: 'oz_builtin',
140
+ primitive: {
141
+ primitive: 'spending_limit',
142
+ params: {
143
+ spending_limit: spend.limit,
144
+ period_ledgers: secondsToLedgers(spend.windowSeconds),
145
+ },
146
+ },
147
+ instanceAddress: config.instances.spending_limit,
148
+ });
149
+ }
150
+ // approval.threshold -> simple/weighted threshold primitive. A threshold < 1
151
+ // is not a real M-of-N gate (0 approvals authorises everything), so refuse to
152
+ // emit a no-op primitive and flag it as not covered instead.
153
+ if (rule.approval) {
154
+ if (!Number.isInteger(rule.approval.threshold) || rule.approval.threshold < 1) {
155
+ uncovered.push(`approval threshold ${rule.approval.threshold} is not a positive integer (a 0 or negative threshold is not an M-of-N gate)`);
156
+ }
157
+ else {
158
+ const weights = rule.approval.weights;
159
+ if (weights && Object.keys(weights).length > 0) {
160
+ policyRefs.push({
161
+ kind: 'oz_builtin',
162
+ primitive: {
163
+ primitive: 'weighted_threshold',
164
+ params: { threshold: rule.approval.threshold, weights },
165
+ },
166
+ instanceAddress: config.instances.weighted_threshold,
167
+ });
168
+ }
169
+ else {
170
+ policyRefs.push({
171
+ kind: 'oz_builtin',
172
+ primitive: {
173
+ primitive: 'simple_threshold',
174
+ params: { threshold: rule.approval.threshold },
175
+ },
176
+ instanceAddress: config.instances.simple_threshold,
177
+ });
178
+ }
179
+ }
180
+ }
181
+ const capExceeded = policyRefs.length > types_ts_1.OZ_LIMITS.maxPoliciesPerRule;
182
+ if (capExceeded) {
183
+ uncovered.push(`policy count ${policyRefs.length} exceeds OZ maxPoliciesPerRule (${types_ts_1.OZ_LIMITS.maxPoliciesPerRule})`);
184
+ }
185
+ const contextRule = {
186
+ contextRuleType,
187
+ name: contextRuleType.kind === 'call_contract'
188
+ ? `call_contract:${contextRuleType.contract}`
189
+ : 'default',
190
+ validUntilLedger,
191
+ signers: [],
192
+ policies: policyRefs,
193
+ };
194
+ return { contextRule, policyRefs, uncovered, capExceeded };
195
+ }
196
+ /** Convert a spend window in seconds to OZ `period_ledgers` (u32, >= 1).
197
+ * Stellar targets a ~5s ledger close time. */
198
+ function secondsToLedgers(windowSeconds) {
199
+ return Math.max(1, Math.round(windowSeconds / types_ts_1.SOROBAN_LIMITS.secondsPerLedger));
200
+ }
201
+ /** Match the `window_spent(token, window) <= limit` compare that lowers to the
202
+ * OZ `spending_limit` primitive. Only `lte` matches (the spend-cap semantic). */
203
+ function matchSpendingLimit(c) {
204
+ if (c.op !== 'compare')
205
+ return null;
206
+ const { selector, operator, value } = c.compare;
207
+ if (selector.kind !== 'window_spent' || operator !== 'lte')
208
+ return null;
209
+ return { token: selector.token, limit: value, windowSeconds: selector.windowSeconds };
210
+ }
211
+ /** Human-readable descriptor for a construct the OZ built-in-primitive backend
212
+ * cannot express, used to populate `uncovered`. */
213
+ function describeCondition(cond) {
214
+ switch (cond.op) {
215
+ case 'in':
216
+ return `value allowlist on ${describeSelector(cond.selector)} (arg allowlist)`;
217
+ case 'eq_seq':
218
+ return `exact ordered sequence on ${describeSelector(cond.selector)} (OZ built-ins cannot express an exact vector)`;
219
+ case 'not':
220
+ return 'negated condition (predicate DSL)';
221
+ case 'and':
222
+ case 'or':
223
+ return `nested ${cond.op} condition (predicate DSL)`;
224
+ case 'compare': {
225
+ const s = cond.compare.selector;
226
+ switch (s.kind) {
227
+ case 'oracle_price':
228
+ return `oracle price condition on ${s.asset} (oracle price not supported in week-1)`;
229
+ case 'invocation_count':
230
+ return `invocation-count window (${s.windowSeconds}s) condition (not supported in week-1)`;
231
+ case 'window_spent':
232
+ return `spend-window comparison with operator '${cond.compare.operator}' (only 'lte' lowers to spending_limit)`;
233
+ case 'amount':
234
+ return `per-call amount comparison on ${s.token} (predicate DSL)`;
235
+ case 'arg':
236
+ return `argument comparison on arg ${s.argIndex} (predicate DSL)`;
237
+ case 'calldata':
238
+ return 'EVM calldata comparison (predicate DSL)';
239
+ case 'value':
240
+ return 'tx.value comparison (predicate DSL)';
241
+ case 'now':
242
+ case 'valid_until':
243
+ return 'time comparison (predicate DSL)';
244
+ }
245
+ }
246
+ }
247
+ }
248
+ function describeSelector(s) {
249
+ switch (s.kind) {
250
+ case 'arg':
251
+ return `arg ${s.argIndex}`;
252
+ case 'amount':
253
+ return `amount(${s.token})`;
254
+ case 'window_spent':
255
+ return `window_spent(${s.token})`;
256
+ case 'oracle_price':
257
+ return `oracle_price(${s.asset})`;
258
+ case 'invocation_count':
259
+ return `invocation_count(${s.windowSeconds}s)`;
260
+ case 'calldata':
261
+ return `calldata[${s.offset}:${s.offset + s.length}]`;
262
+ default:
263
+ return s.kind;
264
+ }
265
+ }
266
+ function simulateStub() {
267
+ return {
268
+ backend: 'ts-model',
269
+ permitted: null,
270
+ evaluations: [],
271
+ notes: ['stub: real permit/deny semantics wiring is a later phase'],
272
+ };
273
+ }
274
+ /** Canonical JSON with recursively sorted object keys (stable across runs). */
275
+ function canonicalStringify(value) {
276
+ return JSON.stringify(sortKeys(value));
277
+ }
278
+ function sortKeys(value) {
279
+ if (Array.isArray(value))
280
+ return value.map(sortKeys);
281
+ if (value && typeof value === 'object') {
282
+ const out = {};
283
+ for (const key of Object.keys(value).sort()) {
284
+ out[key] = sortKeys(value[key]);
285
+ }
286
+ return out;
287
+ }
288
+ return value;
289
+ }
@@ -0,0 +1 @@
1
+ export { createOzAdapter, type OzAdapterConfig, type OzPrimitiveInstances, PLACEHOLDER_OZ_INSTANCES, placeholderOzConfig, } from './adapter.ts';
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ // src/adapters/oz/index.ts - re-export the OZ Accounts CustodyAdapter.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.placeholderOzConfig = exports.PLACEHOLDER_OZ_INSTANCES = exports.createOzAdapter = void 0;
5
+ var adapter_ts_1 = require("./adapter.js");
6
+ Object.defineProperty(exports, "createOzAdapter", { enumerable: true, get: function () { return adapter_ts_1.createOzAdapter; } });
7
+ Object.defineProperty(exports, "PLACEHOLDER_OZ_INSTANCES", { enumerable: true, get: function () { return adapter_ts_1.PLACEHOLDER_OZ_INSTANCES; } });
8
+ Object.defineProperty(exports, "placeholderOzConfig", { enumerable: true, get: function () { return adapter_ts_1.placeholderOzConfig; } });
@@ -0,0 +1,33 @@
1
+ export type CompileGateResult = {
2
+ code: 'COMPILE_OK';
3
+ } | {
4
+ code: 'COMPILE_GATE_FAILED';
5
+ stderr: string;
6
+ } | {
7
+ code: 'SKIPPED';
8
+ reason: string;
9
+ };
10
+ export interface CompileGateOpts {
11
+ /** Caller-controlled abort signal; aborting before toolchain probe resolves
12
+ * the gate to `SKIPPED` rather than starting a cargo invocation. */
13
+ signal?: AbortSignal;
14
+ /** Override the `cargo` binary (mostly for tests). */
15
+ cargoBin?: string;
16
+ /** Override the target directory (mostly for tests). */
17
+ tempDir?: string;
18
+ }
19
+ /** Probe the host for the Rust toolchain the gate requires. We require BOTH
20
+ * `cargo` AND `stellar` (the Soroban CLI) because a real gate run invokes
21
+ * `stellar contract build`; absent either, the gate returns `SKIPPED`. */
22
+ export declare function hasRustToolchain(): Promise<boolean>;
23
+ /** Compile-check a Rust source string against the pinned Soroban SDK.
24
+ *
25
+ * - Toolchain absent -> `{ code: 'SKIPPED', reason }` (NOT a failure).
26
+ * - Toolchain present, source compiles -> `{ code: 'COMPILE_OK' }`.
27
+ * - Toolchain present, source broken -> `{ code: 'COMPILE_GATE_FAILED', stderr }`.
28
+ *
29
+ * The gate writes the source to a temporary crate and runs `cargo check`
30
+ * against it; the crate is cleaned up whether or not compilation succeeds.
31
+ * The caller is expected to surface `COMPILE_GATE_FAILED.stderr` to the
32
+ * user (the LLM agent) so the user can iterate. */
33
+ export declare function compileCheck(rustSource: string, opts?: CompileGateOpts): Promise<CompileGateResult>;
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ // src/codegen/compile-gate.ts - toolchain-gated `cargo check` for the
3
+ // codegen escape hatch.
4
+ //
5
+ // The escape hatch ships as the `policy-builder escape-hatch` CLI subcommand
6
+ // (a later phase). This gate is its safety net, NOT the happy path. Property:
7
+ // generated Rust compiles against the pinned OZ crate; broken source returns
8
+ // `COMPILE_GATE_FAILED` with `stderr`; an absent toolchain returns `SKIPPED`
9
+ // (does NOT fail - we cannot make build tools a hard runtime requirement for
10
+ // a TypeScript package).
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.hasRustToolchain = hasRustToolchain;
13
+ exports.compileCheck = compileCheck;
14
+ const node_child_process_1 = require("node:child_process");
15
+ const promises_1 = require("node:fs/promises");
16
+ const node_os_1 = require("node:os");
17
+ const node_path_1 = require("node:path");
18
+ /** Probe the host for the Rust toolchain the gate requires. We require BOTH
19
+ * `cargo` AND `stellar` (the Soroban CLI) because a real gate run invokes
20
+ * `stellar contract build`; absent either, the gate returns `SKIPPED`. */
21
+ async function hasRustToolchain() {
22
+ const probe = await probeToolchain();
23
+ return probe.present;
24
+ }
25
+ async function probeToolchain() {
26
+ const cargo = await which('cargo');
27
+ if (!cargo)
28
+ return { present: false, reason: 'cargo not found on PATH' };
29
+ const stellar = await which('stellar');
30
+ if (!stellar)
31
+ return { present: false, reason: 'stellar not found on PATH' };
32
+ return { present: true, reason: `${cargo} + ${stellar}` };
33
+ }
34
+ async function which(bin) {
35
+ try {
36
+ const out = await runProcess('sh', ['-c', `command -v ${bin}`], { capture: true });
37
+ const path = out.stdout.trim();
38
+ return path.length > 0 ? path : null;
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }
44
+ function runProcess(cmd, args, opts) {
45
+ return new Promise((resolve, reject) => {
46
+ if (opts.signal?.aborted) {
47
+ reject(new Error('aborted'));
48
+ return;
49
+ }
50
+ const child = (0, node_child_process_1.spawn)(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
51
+ let stdout = '';
52
+ let stderr = '';
53
+ child.stdout.on('data', (b) => {
54
+ stdout += b.toString('utf8');
55
+ });
56
+ child.stderr.on('data', (b) => {
57
+ stderr += b.toString('utf8');
58
+ });
59
+ const onAbort = () => {
60
+ child.kill('SIGTERM');
61
+ reject(new Error('aborted'));
62
+ };
63
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
64
+ child.on('error', (e) => {
65
+ opts.signal?.removeEventListener('abort', onAbort);
66
+ reject(e);
67
+ });
68
+ child.on('close', (code) => {
69
+ opts.signal?.removeEventListener('abort', onAbort);
70
+ resolve({ stdout, stderr, code: code ?? -1 });
71
+ });
72
+ });
73
+ }
74
+ const CARGO_MANIFEST = `[package]
75
+ name = "escape-hatch-gate"
76
+ version = "0.0.0"
77
+ edition = "2021"
78
+ publish = false
79
+
80
+ [lib]
81
+ crate-type = ["cdylib"]
82
+
83
+ [dependencies]
84
+ soroban-sdk = "22"
85
+
86
+ [workspace]
87
+ `;
88
+ /** Compile-check a Rust source string against the pinned Soroban SDK.
89
+ *
90
+ * - Toolchain absent -> `{ code: 'SKIPPED', reason }` (NOT a failure).
91
+ * - Toolchain present, source compiles -> `{ code: 'COMPILE_OK' }`.
92
+ * - Toolchain present, source broken -> `{ code: 'COMPILE_GATE_FAILED', stderr }`.
93
+ *
94
+ * The gate writes the source to a temporary crate and runs `cargo check`
95
+ * against it; the crate is cleaned up whether or not compilation succeeds.
96
+ * The caller is expected to surface `COMPILE_GATE_FAILED.stderr` to the
97
+ * user (the LLM agent) so the user can iterate. */
98
+ async function compileCheck(rustSource, opts = {}) {
99
+ if (opts.signal?.aborted) {
100
+ return { code: 'SKIPPED', reason: 'aborted before probe' };
101
+ }
102
+ const probe = await probeToolchain();
103
+ if (!probe.present) {
104
+ return { code: 'SKIPPED', reason: probe.reason };
105
+ }
106
+ let dir = null;
107
+ try {
108
+ dir = await (0, promises_1.mkdtemp)((0, node_path_1.join)(opts.tempDir ?? (0, node_os_1.tmpdir)(), 'codegen-gate-'));
109
+ await (0, promises_1.writeFile)((0, node_path_1.join)(dir, 'Cargo.toml'), CARGO_MANIFEST);
110
+ await (0, promises_1.writeFile)((0, node_path_1.join)(dir, 'lib.rs'), rustSource);
111
+ const runOpts = opts.signal ? { signal: opts.signal } : {};
112
+ const result = await runProcess(opts.cargoBin ?? 'cargo', ['check', '--quiet', '--offline', '--manifest-path', (0, node_path_1.join)(dir, 'Cargo.toml')], runOpts).catch((e) => ({ stdout: '', stderr: e.message, code: -1 }));
113
+ if (result.code === 0) {
114
+ return { code: 'COMPILE_OK' };
115
+ }
116
+ return { code: 'COMPILE_GATE_FAILED', stderr: result.stderr || result.stdout };
117
+ }
118
+ finally {
119
+ if (dir) {
120
+ await (0, promises_1.rm)(dir, { recursive: true, force: true }).catch(() => { });
121
+ }
122
+ }
123
+ }
@@ -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,14 @@
1
+ "use strict";
2
+ // src/codegen/index.ts - re-export the codegen escape-hatch surface.
3
+ //
4
+ // The escape hatch is OUT of the audited happy path: the synthesiser never
5
+ // calls `generateRust` itself; the CLI subcommand (a later phase) is the only
6
+ // entry point. Keeping the surface in one file makes that boundary visible
7
+ // in import statements.
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.generateRust = exports.hasRustToolchain = exports.compileCheck = void 0;
10
+ var compile_gate_ts_1 = require("./compile-gate.js");
11
+ Object.defineProperty(exports, "compileCheck", { enumerable: true, get: function () { return compile_gate_ts_1.compileCheck; } });
12
+ Object.defineProperty(exports, "hasRustToolchain", { enumerable: true, get: function () { return compile_gate_ts_1.hasRustToolchain; } });
13
+ var template_ts_1 = require("./template.js");
14
+ Object.defineProperty(exports, "generateRust", { enumerable: true, get: function () { return template_ts_1.generateRust; } });
@@ -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,134 @@
1
+ "use strict";
2
+ // src/codegen/template.ts - deterministic Rust source generator for the OZ
3
+ // `Policy` escape-hatch skeleton.
4
+ //
5
+ // This is the LAST-RESORT tool for constraints the v1 DSL cannot express. It
6
+ // lives OUT of the audited happy-path surface; the synthesiser never emits it
7
+ // automatically. It mirrors Zodiac Roles' `Custom` operator: a hand-written
8
+ // (here: scaffolded) policy the operator assumes responsibility for.
9
+ //
10
+ // The skeleton carries five storage invariants the user MUST preserve when
11
+ // filling in the predicate logic:
12
+ // 1. `smart_account.require_auth()` is invoked INSIDE `enforce`.
13
+ // 2. Storage is keyed by the composite `(smart_account, rule_id)`.
14
+ // 3. Chain reads use `unwrap_or_default()` so a missing key is a permitted
15
+ // default, not a panic.
16
+ // 4. Storage is `persistent()` (NOT `instance()`) so the policy survives
17
+ // contract instance lifecycle changes.
18
+ // 5. `uninstall` removes the stored state.
19
+ //
20
+ // Determinism: same `(spec, name)` -> byte-identical output. No clock, no RNG,
21
+ // no environment reads.
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.generateRust = generateRust;
24
+ /** Format a name for use as a Rust identifier. The input is constrained by
25
+ * the caller (a kebab-case policy name + alphanumeric addresses); this is a
26
+ * belt-and-braces sanitiser that maps anything non-identifier to '_'. */
27
+ function asRustIdent(s) {
28
+ let out = '';
29
+ for (let i = 0; i < s.length; i++) {
30
+ const ch = s.charCodeAt(i);
31
+ const ok = (ch >= 48 && ch <= 57) || // 0-9
32
+ (ch >= 65 && ch <= 90) || // A-Z
33
+ (ch >= 97 && ch <= 122) || // a-z
34
+ ch === 95; // _
35
+ out += ok ? s[i] : '_';
36
+ }
37
+ // Identifiers may not start with a digit.
38
+ if (out.length > 0 && out.charCodeAt(0) >= 48 && out.charCodeAt(0) <= 57) {
39
+ out = `_${out}`;
40
+ }
41
+ return out || 'policy';
42
+ }
43
+ /** Render the `uncovered` list as a `//` comment block (one line per item). */
44
+ function renderUncovered(uncovered) {
45
+ if (uncovered.length === 0) {
46
+ return ' // (no specific uncovered constructs reported)';
47
+ }
48
+ return uncovered.map((line) => ` // - ${line}`).join('\n');
49
+ }
50
+ /** Generate a deterministic OZ `Policy` skeleton for an uncovered constraint.
51
+ *
52
+ * The skeleton is NOT a finished policy; the user fills in the predicate
53
+ * logic in the marked TODO(user) holes and audits the result themselves.
54
+ *
55
+ * Same `(spec, name)` always produces byte-identical output. */
56
+ function generateRust(spec, name) {
57
+ const _contract = spec.contract;
58
+ const _fnName = spec.fnName ?? 'enforce';
59
+ const structName = asRustIdent(name);
60
+ const _dataKeyName = `${asRustIdent(name)}_data`;
61
+ const uncoveredBlock = renderUncovered(spec.uncovered);
62
+ return `// Auto-generated by the OZ Policy Builder codegen escape hatch.
63
+ // THIS OUTPUT IS THE USER'S TO COMPLETE AND AUDIT.
64
+ // The synthesiser never emits it on the happy path; reach for it only when
65
+ // a constraint cannot be expressed in the v1 DSL grammar (same shape as
66
+ // Zodiac Roles' \`Custom\` operator).
67
+
68
+ #![no_std]
69
+
70
+ use soroban_sdk::{contract, contractimpl, contracttype, Address, Env, Vec};
71
+
72
+ #[contracttype]
73
+ pub enum DataKey {
74
+ /// Composite key \`(smart_account, rule_id)\` so multiple policies on
75
+ /// one smart account coexist without collision.
76
+ State(Address, u32),
77
+ }
78
+
79
+ #[contract]
80
+ pub struct ${structName};
81
+
82
+ #[contractimpl]
83
+ impl ${structName} {
84
+ pub fn install(e: &Env, smart_account: Address, rule_id: u32) {
85
+ // TODO(user): initialise policy state for this (smart_account, rule_id).
86
+ // The skeleton leaves the stored value empty; the predicate body
87
+ // (in \`enforce\`) decides what to read.
88
+ e.storage().persistent().set(
89
+ &DataKey::State(smart_account.clone(), rule_id),
90
+ &(),
91
+ );
92
+ }
93
+
94
+ pub fn enforce(
95
+ e: &Env,
96
+ smart_account: Address,
97
+ rule_id: u32,
98
+ _signers: Vec<Address>,
99
+ ) {
100
+ // Invariant 1: authorise the smart account BEFORE any state read or
101
+ // predicate evaluation. Removing this call opens the policy to
102
+ // impersonation by any caller with a valid rule_id.
103
+ smart_account.require_auth();
104
+
105
+ // Invariant 2 + 4: read stored state through the composite key on
106
+ // \`persistent()\` storage. \`unwrap_or_default()\` (invariant 3)
107
+ // makes an empty key a permitted default rather than a panic.
108
+ let _state: () = e
109
+ .storage()
110
+ .persistent()
111
+ .get(&DataKey::State(smart_account.clone(), rule_id))
112
+ .unwrap_or_default();
113
+
114
+ // --- uncovered constraints the v1 DSL refused to express ---
115
+ ${uncoveredBlock}
116
+
117
+ // TODO(user): replace the placeholder below with the real predicate
118
+ // body. The recorded flow's \`(contract, fn_name, args)\` is the
119
+ // single authorised call \`Policy::enforce\` receives; match against
120
+ // \`e\` here.
121
+ let _ = (_state, &e);
122
+ }
123
+
124
+ pub fn uninstall(e: &Env, smart_account: Address, rule_id: u32) {
125
+ // Invariant 5: \`uninstall\` removes the stored state so a subsequent
126
+ // install starts from a clean slate (and the nonce returns to its
127
+ // post-uninstall value).
128
+ e.storage()
129
+ .persistent()
130
+ .remove(&DataKey::State(smart_account, rule_id));
131
+ }
132
+ }
133
+ `;
134
+ }
@@ -0,0 +1,37 @@
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
+ export interface ToolError {
3
+ code: ErrorCode;
4
+ message: string;
5
+ /** LLM-actionable hint for the agent skill. Per-code severity is pinned
6
+ * in CODE_SEVERITY below; this field is the resolved value at runtime. */
7
+ severity: 'info' | 'warning' | 'error' | 'fatal';
8
+ retryable: boolean;
9
+ remediation?: {
10
+ toolCall?: {
11
+ name: string;
12
+ args: Record<string, unknown>;
13
+ };
14
+ userQuestion?: {
15
+ code: string;
16
+ question: string;
17
+ };
18
+ docsUrl?: string;
19
+ };
20
+ /** Precedence rule for an LLM agent that sees BOTH toolCall AND userQuestion:
21
+ * - toolCall + userQuestion together = userQuestion wins (the human decides).
22
+ * - toolCall alone = agent proceeds.
23
+ * - userQuestion alone = agent stops and asks.
24
+ * No silent ambiguity. */
25
+ details?: unknown;
26
+ }
27
+ export type ToolResponse<T> = {
28
+ ok: true;
29
+ data: T;
30
+ } | {
31
+ ok: false;
32
+ error: ToolError;
33
+ };
34
+ /** Unsigned Soroban transaction envelope, base64-encoded XDR (Soroban SDK convention).
35
+ * Pinned for CLI + MCP + WalletAdapter compatibility. Hex / raw-bytes / TS objects
36
+ * are NOT accepted - the contract is base64 string, full stop. */
37
+ export type UnsignedXdrB64 = string;