@crediolabs/policy-builder-cli 0.1.6 → 0.1.7

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.
@@ -7,11 +7,23 @@
7
7
  //
8
8
  // The CLI mirrors the MCP tool's discriminated union: one subcommand, two
9
9
  // front-ends, mutually exclusive.
10
+ //
11
+ // Per-field response flags (--window-seconds, --valid-until, --limit-amount,
12
+ // --invocation-limit) merge into `userResponses`. A flag overrides the same
13
+ // field from --responses (CLI flags are explicit; the file is a default bag).
14
+ // Oracle params (--oracle-max-staleness, --oracle-max-deviation) are part of
15
+ // the interpreter opt-in and are rejected without --smart-account; tighten-only
16
+ // bounds are validated by the core.
10
17
 
11
- import { runSynthesizePolicy } from '@crediolabs/policy-builder-mcp'
12
18
  import type { ProposedPolicy } from '@crediolabs/policy-synth'
19
+ import { runSynthesizePolicy } from '@crediolabs/policy-synth/run'
13
20
  import { CliError, type CliFlags, formatToolResponse, parsePairs, readJsonFile } from '../output.ts'
14
21
 
22
+ // Positive-int flags and i128 amount strings share the same wire shape: a
23
+ // base-10 unsigned decimal, no sign. The i128 stays a string at the boundary
24
+ // because it is wider than Number.MAX_SAFE_INTEGER.
25
+ const POSITIVE_INT_RE = /^[0-9]+$/
26
+
15
27
  export async function runSynthesizeCommand(
16
28
  argv: ReadonlyArray<string>,
17
29
  flags: CliFlags
@@ -30,7 +42,14 @@ export async function runSynthesizeCommand(
30
42
 
31
43
  if (hasMandate) {
32
44
  const mandate = readJsonFile(pairs.mandate as string) as Record<string, unknown>
33
- const res = await runSynthesizePolicy({ source: 'mandate', mandate })
45
+ const args: Record<string, unknown> = { source: 'mandate', mandate }
46
+ if (pairs['oz-config'] !== undefined) {
47
+ args.ozConfig = readOzConfigFile(pairs['oz-config'] as string)
48
+ }
49
+ if (pairs.confidence !== undefined) {
50
+ args.confidenceOverride = { threshold: parseConfidence(pairs.confidence as string) }
51
+ }
52
+ const res = await runSynthesizePolicy(args)
34
53
  return formatToolResponse(res, flags, 'synthesize(mandate)')
35
54
  }
36
55
 
@@ -53,20 +72,214 @@ export async function runSynthesizeCommand(
53
72
  })
54
73
  }
55
74
  const args: Record<string, unknown> = { source: 'recording', recordedTx, network }
75
+
76
+ // userResponses precedence: --responses file is the base; per-field flags
77
+ // override the same field. Only the override'd fields are merged in.
78
+ const userResponses: Record<string, unknown> = {}
56
79
  if (pairs.responses) {
57
- args.userResponses = readJsonFile(pairs.responses)
80
+ const file = readJsonFile(pairs.responses)
81
+ if (file !== null && typeof file === 'object' && !Array.isArray(file)) {
82
+ Object.assign(userResponses, file as Record<string, unknown>)
83
+ } else {
84
+ throw new CliError({
85
+ code: 'CLI_INVALID_JSON',
86
+ message: `synthesize: --responses ${pairs.responses} must be a JSON object`,
87
+ severity: 'error',
88
+ retryable: false,
89
+ })
90
+ }
91
+ }
92
+ if (pairs['window-seconds'] !== undefined) {
93
+ userResponses.windowSeconds = parsePositiveInt(
94
+ pairs['window-seconds'] as string,
95
+ '--window-seconds'
96
+ )
97
+ }
98
+ if (pairs['valid-until'] !== undefined) {
99
+ userResponses.validUntilLedger = parsePositiveInt(
100
+ pairs['valid-until'] as string,
101
+ '--valid-until'
102
+ )
103
+ }
104
+ if (pairs['limit-amount'] !== undefined) {
105
+ userResponses.limitAmount = parseI128String(pairs['limit-amount'] as string, '--limit-amount')
58
106
  }
107
+ if (pairs['invocation-limit'] !== undefined) {
108
+ userResponses.invocationLimit = parsePositiveInt(
109
+ pairs['invocation-limit'] as string,
110
+ '--invocation-limit'
111
+ )
112
+ }
113
+ if (Object.keys(userResponses).length > 0) {
114
+ args.userResponses = userResponses
115
+ }
116
+
117
+ if (pairs['oz-config'] !== undefined) {
118
+ args.ozConfig = readOzConfigFile(pairs['oz-config'] as string)
119
+ }
120
+ if (pairs.confidence !== undefined) {
121
+ args.confidenceOverride = { threshold: parseConfidence(pairs.confidence as string) }
122
+ }
123
+
59
124
  // --smart-account <C...> opts into the interpreter adapter, so constraints OZ
60
125
  // cannot express (per-method scoping, invocation-count windows, oracle bounds,
61
126
  // exact hop paths) lower to a real predicate document instead of just warnings.
62
127
  // The core validates the address and installNonce; a bad value surfaces there.
63
- if (pairs['smart-account']) {
64
- const interpreter: Record<string, unknown> = { smartAccountAddress: pairs['smart-account'] }
65
- if (pairs['install-nonce']) {
66
- interpreter.installNonce = Number(pairs['install-nonce'])
128
+ //
129
+ // Use `!== undefined` (not truthy) so `--smart-account ""` and `--install-nonce`
130
+ // without `--smart-account` are rejected up front instead of being silently
131
+ // dropped. The foot-gun: an empty value previously produced an "ok" envelope
132
+ // with 0 policyDocuments, so callers thought the constraint had been enforced
133
+ // when in fact it had been silently skipped.
134
+ const smartAccountRaw = pairs['smart-account']
135
+ const installNonceRaw = pairs['install-nonce']
136
+ const oracleStalenessRaw = pairs['oracle-max-staleness']
137
+ const oracleDeviationRaw = pairs['oracle-max-deviation']
138
+ if (installNonceRaw !== undefined && smartAccountRaw === undefined) {
139
+ throw new CliError({
140
+ code: 'CLI_MISSING_ARG',
141
+ message: 'synthesize: --install-nonce requires --smart-account <C...> (interpreter opt-in)',
142
+ severity: 'error',
143
+ retryable: false,
144
+ })
145
+ }
146
+ // Oracle params are an interpreter-only knob; reject up front so they cannot
147
+ // be silently dropped when --smart-account is absent.
148
+ if (
149
+ (oracleStalenessRaw !== undefined || oracleDeviationRaw !== undefined) &&
150
+ smartAccountRaw === undefined
151
+ ) {
152
+ throw new CliError({
153
+ code: 'CLI_MISSING_ARG',
154
+ message:
155
+ 'synthesize: --oracle-max-staleness / --oracle-max-deviation require --smart-account <C...> (interpreter opt-in)',
156
+ severity: 'error',
157
+ retryable: false,
158
+ })
159
+ }
160
+ if (smartAccountRaw !== undefined) {
161
+ const smartAccount = smartAccountRaw.trim()
162
+ if (smartAccount.length === 0) {
163
+ throw new CliError({
164
+ code: 'CLI_MISSING_ARG',
165
+ message:
166
+ 'synthesize: --smart-account <C...> was passed empty; provide a 56-character contract strkey or omit the flag',
167
+ severity: 'error',
168
+ retryable: false,
169
+ })
170
+ }
171
+ if (!/^C[2-7A-Z]{55}$/.test(smartAccount)) {
172
+ throw new CliError({
173
+ code: 'CLI_MISSING_ARG',
174
+ message: `synthesize: --smart-account "${smartAccount}" is not a valid C... contract strkey (expected 56 chars starting with C)`,
175
+ severity: 'error',
176
+ retryable: false,
177
+ })
178
+ }
179
+ const interpreter: Record<string, unknown> = { smartAccountAddress: smartAccount }
180
+ if (installNonceRaw !== undefined) {
181
+ const nonce = Number(installNonceRaw)
182
+ if (!Number.isInteger(nonce) || nonce < 0) {
183
+ throw new CliError({
184
+ code: 'CLI_MISSING_ARG',
185
+ message: `synthesize: --install-nonce "${installNonceRaw}" is not a non-negative integer`,
186
+ severity: 'error',
187
+ retryable: false,
188
+ })
189
+ }
190
+ interpreter.installNonce = nonce
191
+ }
192
+ // Oracle params only attach when at least one bound was provided. The
193
+ // core validates tighten-only (maxStalenessSeconds <= 600,
194
+ // maxDeviationBps <= 200) - a too-loose value surfaces as SYNTHESIS_ERROR.
195
+ if (oracleStalenessRaw !== undefined || oracleDeviationRaw !== undefined) {
196
+ const oracleParams: Record<string, number> = {}
197
+ if (oracleStalenessRaw !== undefined) {
198
+ oracleParams.maxStalenessSeconds = parsePositiveInt(
199
+ oracleStalenessRaw,
200
+ '--oracle-max-staleness'
201
+ )
202
+ }
203
+ if (oracleDeviationRaw !== undefined) {
204
+ oracleParams.maxDeviationBps = parsePositiveInt(
205
+ oracleDeviationRaw,
206
+ '--oracle-max-deviation'
207
+ )
208
+ }
209
+ interpreter.oracleParams = oracleParams
67
210
  }
68
211
  args.interpreter = interpreter
69
212
  }
70
213
  const res = await runSynthesizePolicy(args)
71
214
  return formatToolResponse(res, flags, 'synthesize(recording)')
72
215
  }
216
+
217
+ /** Read and validate an OzAdapterConfig JSON file. Throws CLI_FILE_NOT_FOUND /
218
+ * CLI_INVALID_JSON for filesystem / parse failures; the core's strict schema
219
+ * on `ozConfig` catches shape mismatches downstream. */
220
+ function readOzConfigFile(path: string): Record<string, unknown> {
221
+ const value = readJsonFile(path)
222
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
223
+ throw new CliError({
224
+ code: 'CLI_INVALID_JSON',
225
+ message: `synthesize: --oz-config ${path} must be a JSON object`,
226
+ severity: 'error',
227
+ retryable: false,
228
+ })
229
+ }
230
+ return value as Record<string, unknown>
231
+ }
232
+
233
+ /** Parse and validate `--confidence <n>` as a finite number in [0, 1]. A
234
+ * threshold above 1 would disable the recorder gate; reject it up front. */
235
+ function parseConfidence(raw: string): number {
236
+ const n = Number(raw)
237
+ if (!Number.isFinite(n) || n < 0 || n > 1) {
238
+ throw new CliError({
239
+ code: 'CLI_MISSING_ARG',
240
+ message: `synthesize: --confidence "${raw}" must be a finite number within [0, 1]`,
241
+ severity: 'error',
242
+ retryable: false,
243
+ })
244
+ }
245
+ return n
246
+ }
247
+
248
+ /** Parse a strictly positive integer (windowSeconds, validUntilLedger,
249
+ * invocationLimit, oracleParams bounds). The core re-validates these with
250
+ * field-specific caps; the CLI just enforces "looks like an integer > 0". */
251
+ function parsePositiveInt(raw: string, flagName: string): number {
252
+ if (!POSITIVE_INT_RE.test(raw)) {
253
+ throw new CliError({
254
+ code: 'CLI_MISSING_ARG',
255
+ message: `synthesize: ${flagName} "${raw}" must be a positive integer`,
256
+ severity: 'error',
257
+ retryable: false,
258
+ })
259
+ }
260
+ const n = Number(raw)
261
+ if (!Number.isInteger(n) || n <= 0) {
262
+ throw new CliError({
263
+ code: 'CLI_MISSING_ARG',
264
+ message: `synthesize: ${flagName} "${raw}" must be a positive integer`,
265
+ severity: 'error',
266
+ retryable: false,
267
+ })
268
+ }
269
+ return n
270
+ }
271
+
272
+ /** Parse an i128 decimal string (positive, base 10). The synth gate, not the
273
+ * CLI, decides what to do with negatives - real recordings carry positive
274
+ * amounts on the wire for `limitAmount`. */
275
+ function parseI128String(raw: string, flagName: string): string {
276
+ if (!POSITIVE_INT_RE.test(raw)) {
277
+ throw new CliError({
278
+ code: 'CLI_MISSING_ARG',
279
+ message: `synthesize: ${flagName} "${raw}" must be a positive decimal integer string (base-10 i128)`,
280
+ severity: 'error',
281
+ retryable: false,
282
+ })
283
+ }
284
+ return raw
285
+ }
package/src/output.ts CHANGED
@@ -37,7 +37,14 @@ export function parseFlags(argv: ReadonlyArray<string>): CliFlags {
37
37
 
38
38
  /** Resolve `--value <v>` style pairs after the subcommand name. Returns
39
39
  * an object keyed by the option name (without `--`). Throws on missing
40
- * value or duplicate keys. */
40
+ * value or duplicate keys.
41
+ *
42
+ * Note: an empty value (`--smart-account ""`) IS captured as an empty
43
+ * string so the caller can distinguish "flag omitted" from "flag passed
44
+ * empty" - a foot-gun: silently dropping empty values caused callers to
45
+ * believe the interpreter adapter was engaged when it was not. The next
46
+ * token is treated as a value iff it is present and does not start with
47
+ * `--`; tokens starting with `--` are never consumed as values. */
41
48
  export function parsePairs(argv: ReadonlyArray<string>): Record<string, string> {
42
49
  const out: Record<string, string> = {}
43
50
  for (let i = 0; i < argv.length; i++) {
@@ -47,11 +54,21 @@ export function parsePairs(argv: ReadonlyArray<string>): Record<string, string>
47
54
  const key = a.slice(2, eq)
48
55
  const val = a.slice(eq + 1)
49
56
  if (key && val !== undefined) out[key] = val
50
- } else if (a?.startsWith('--') && argv[i + 1] && !argv[i + 1]?.startsWith('--')) {
57
+ } else if (a?.startsWith('--')) {
51
58
  const key = a.slice(2)
52
- const val = argv[i + 1] as string
53
- out[key] = val
54
- i++
59
+ if (!key) continue
60
+ const next = argv[i + 1]
61
+ // Only consume the next token if it is present AND does not look like
62
+ // another flag. Empty strings DO count as values so callers can
63
+ // distinguish "omitted" from "passed empty".
64
+ if (next !== undefined && !next.startsWith('--')) {
65
+ out[key] = next
66
+ i++
67
+ } else {
68
+ // Standalone flag (no value) - record as empty string so `!== undefined`
69
+ // checks upstream can detect presence.
70
+ out[key] = ''
71
+ }
55
72
  }
56
73
  }
57
74
  return out