@cavelon/cli 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ export const AGENT_VARIABLES = [
2
+ { variable: "CAVELON_AGENT", agent: "any agent whose shell environment sets it" },
3
+ { variable: "CLAUDECODE", agent: "Claude Code" },
4
+ { variable: "CODEX_THREAD_ID", agent: "Codex" },
5
+ { variable: "CODEX_SANDBOX", agent: "Codex" },
6
+ { variable: "CURSOR_AGENT", agent: "Cursor" },
7
+ { variable: "GEMINI_CLI", agent: "Gemini CLI" },
8
+ { variable: "COPILOT_CLI", agent: "GitHub Copilot CLI" },
9
+ { variable: "COPILOT_AGENT", agent: "GitHub Copilot in VS Code" },
10
+ { variable: "AI_AGENT", agent: "an agent that follows the AI_AGENT convention" },
11
+ ];
12
+ function isSet(value) {
13
+ const text = value?.trim().toLowerCase();
14
+ return Boolean(text) && text !== "0" && text !== "false";
15
+ }
16
+ export function agentVariable(env) {
17
+ return AGENT_VARIABLES.find(({ variable }) => isSet(env[variable]))?.variable;
18
+ }
19
+ export function drivenByAgent(ctx) {
20
+ if (ctx.mode === "mcp")
21
+ return { by: "mcp" };
22
+ const variable = agentVariable(ctx.io.env);
23
+ return variable ? { by: "agent", variable } : undefined;
24
+ }
@@ -1,12 +1,15 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { promises as fs } from "node:fs";
2
3
  import path from "node:path";
4
+ import { AGENT_VARIABLES, drivenByAgent } from "../agent-env.js";
3
5
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
4
6
  import { CavelonError, ExitCode, usageError, validationError } from "../errors.js";
5
7
  import { clip, moreHint, table } from "../format.js";
6
8
  import { readAll } from "../io.js";
7
9
  import { callOperation, previewRequest } from "../invoke.js";
8
10
  import { confinedPath } from "../paths.js";
9
- import { describeSchema, findOperation, jsonBodySchema, operations, schemaTypes } from "../openapi.js";
11
+ import { describeSchema, findOperation, jsonBodySchema, operations, schemaTypes, secretFields } from "../openapi.js";
12
+ import { canonical } from "../package-files.js";
10
13
  import { cavelonCommand } from "../shell.js";
11
14
  export function splitJsonBody(args) {
12
15
  const out = [];
@@ -26,6 +29,25 @@ export function splitJsonBody(args) {
26
29
  }
27
30
  return out;
28
31
  }
32
+ const CONFIRM_TOKEN = /^[0-9a-f]{12}$/;
33
+ export function splitConfirm(args) {
34
+ const out = [];
35
+ for (let i = 0; i < args.length; i++) {
36
+ const arg = args[i];
37
+ if (arg !== "--confirm") {
38
+ out.push(arg);
39
+ continue;
40
+ }
41
+ const next = args[i + 1];
42
+ if (next !== undefined && CONFIRM_TOKEN.test(next)) {
43
+ out.push(`--confirm=${next}`);
44
+ i++;
45
+ }
46
+ else
47
+ out.push("--confirm=");
48
+ }
49
+ return out;
50
+ }
29
51
  function looksLikeBody(value) {
30
52
  if (value === "-" || value.startsWith("@") || /^\s*[[{"]/.test(value))
31
53
  return true;
@@ -37,7 +59,7 @@ function looksLikeBody(value) {
37
59
  return false;
38
60
  }
39
61
  }
40
- export async function readBody(ctx, raw) {
62
+ export async function readBody(ctx, raw, confine = ctx.mode === "mcp") {
41
63
  let text = raw;
42
64
  if (raw === "-" && ctx.mode === "mcp") {
43
65
  throw usageError("A body from standard input is not available over MCP; pass the JSON itself.");
@@ -45,7 +67,7 @@ export async function readBody(ctx, raw) {
45
67
  if (raw === "-")
46
68
  text = await readAll(ctx.io.stdin);
47
69
  else if (raw.startsWith("@"))
48
- text = await fs.readFile(await confinedPath(ctx, raw.slice(1), "The body file"), "utf8");
70
+ text = await fs.readFile(await confinedPath(ctx, raw.slice(1), "The body file", confine), "utf8");
49
71
  try {
50
72
  return JSON.parse(text);
51
73
  }
@@ -98,13 +120,50 @@ export function keptForPerson(op, all) {
98
120
  const rule = byPathWords(op);
99
121
  return rule ? { source: "kit", reason: rule.does, hint: rule.hint } : undefined;
100
122
  }
101
- function refusal(op, kept) {
123
+ function notSentBy(driven) {
124
+ return driven.by === "mcp"
125
+ ? "no tool sends it, with or without confirm."
126
+ : `cavelon api does not send it when a coding agent runs it (${driven.variable} is set), with or without --confirm.`;
127
+ }
128
+ function personHint(hint, driven) {
129
+ return driven.by === "mcp" ? hint : `${hint} A person's own terminal is not guarded: it does not set ${driven.variable}.`;
130
+ }
131
+ function refusal(op, kept, driven) {
102
132
  const named = `${op.alias} (${op.method} ${op.path})`;
103
- const after = "no tool sends it, with or without confirm.";
133
+ const after = notSentBy(driven);
104
134
  if (kept.source === "kit")
105
135
  return `${named} ${kept.reason}; that stays with a person, so ${after}`;
106
136
  return `${named} is for a person only, as the instance marks it${kept.reason ? ` (${kept.reason})` : ""}; ${after}`;
107
137
  }
138
+ function secretsIn(doc, op, args) {
139
+ const found = new Set();
140
+ const fileFields = args.files?.length ? Object.fromEntries(args.files.map((f) => [f.field, f.path])) : undefined;
141
+ for (const media of Object.values(op.requestBody?.content ?? {})) {
142
+ if (args.body !== undefined)
143
+ for (const field of secretFields(doc, media.schema, args.body))
144
+ found.add(field);
145
+ if (fileFields)
146
+ for (const field of secretFields(doc, media.schema, fileFields))
147
+ found.add(field);
148
+ }
149
+ return [...found];
150
+ }
151
+ function secretRefusal(op, fields, driven) {
152
+ const named = fields.map((f) => `"${f}"`).join(", ");
153
+ return new CavelonError(ExitCode.usage, {
154
+ code: "secret_field_for_a_person",
155
+ message: `The request to ${op.alias} sets ${named}, which the instance marks as a secret value (x-cavelon-secret); ` +
156
+ `a person enters secret values, so ${notSentBy(driven)}`,
157
+ hint: personHint("A person sets a secret value in their terminal with `cavelon secrets set <name>`, or enters it in the Admin. Leave the field out to send the rest.", driven),
158
+ details: { fields },
159
+ });
160
+ }
161
+ function confirmToken(target, request, files) {
162
+ return createHash("sha256")
163
+ .update(canonical({ instance: target.url ?? null, tenant: target.tenant ?? null, request, files }))
164
+ .digest("hex")
165
+ .slice(0, 12);
166
+ }
108
167
  function truncate(data, limit) {
109
168
  if (limit <= 0)
110
169
  return { data };
@@ -123,10 +182,14 @@ export const api = {
123
182
  description: "The operation is its operationId or the short name before FastAPI's path suffix (list_harnesses).\n" +
124
183
  "Parameters: -p name=value or name=value. Body: --json '<json>', --json @file.json or --json - (stdin).\n" +
125
184
  "The body is checked against the operation's schema before it is sent.\n" +
126
- "As an MCP tool, an operation that changes something returns what it would send and sends it only with confirm;\n" +
127
- "one the instance marks for a person only (x-cavelon-person-only) is refused, as are files outside the solution\n" +
128
- "folder. On an instance that marks none, one that changes a secret, creates or revokes a credential or decides an\n" +
129
- "approval is refused.",
185
+ "As an MCP tool, or run by a coding agent (" +
186
+ AGENT_VARIABLES.filter((v) => v.variable !== "CAVELON_AGENT").map((v) => v.variable).join(", ") +
187
+ "\nor CAVELON_AGENT=1 is set), an operation that changes something returns what it would send and sends it only\n" +
188
+ "with confirm (as an MCP tool) or --confirm <token> (the token the preview printed).\n" +
189
+ "Run by an agent, one the instance marks for a person only (x-cavelon-person-only) is refused, as is a body that\n" +
190
+ "sets a field the instance marks as a secret value (x-cavelon-secret) and a file outside the solution folder. On an\n" +
191
+ "instance that marks no operation, one that changes a secret, creates or revokes a credential or decides an\n" +
192
+ "approval is refused. A person's own terminal sends at once.",
130
193
  readOnly: false,
131
194
  destructive: true,
132
195
  mcpTool: "api",
@@ -140,8 +203,11 @@ export const api = {
140
203
  file: { type: "string", multiple: true, value: "<field=path>", description: "Attach a file to a multipart body." },
141
204
  output: { type: "string", value: "<file>", description: "Write the response body to a file instead of printing it.", cliOnly: true },
142
205
  confirm: {
143
- type: "boolean",
144
- description: "As an MCP tool: send an operation that changes something; without it, nothing is sent. The CLI sends at once.",
206
+ type: "string",
207
+ value: "<token>",
208
+ mcpBoolean: true,
209
+ description: "Send an operation that changes something: run by a coding agent, the token its preview printed; as an MCP tool, true. " +
210
+ "Without it, nothing is sent. A person's terminal sends at once.",
145
211
  },
146
212
  limit: { type: "string", value: "<n>", description: "Show at most n items of a list response (default 50, 0 for all)." },
147
213
  },
@@ -150,49 +216,52 @@ export const api = {
150
216
  "cavelon api get_harness_by_slug slug=support",
151
217
  "cavelon api create_knowledge_base --json '{\"name\": \"FAQ\"}'",
152
218
  ],
153
- preprocess: splitJsonBody,
219
+ preprocess: (args) => splitConfirm(splitJsonBody(args)),
154
220
  async run(ctx, input) {
155
221
  const name = positional(input, "operation");
156
222
  const doc = await (await ctx.contracts()).openapi();
157
223
  const op = findOperation(doc, name);
224
+ const driven = drivenByAgent(ctx);
225
+ const confine = driven !== undefined;
158
226
  const args = { params: parseParams(input) };
159
227
  const rawBody = stringOption(input, "body");
160
228
  if (rawBody !== undefined)
161
- args.body = await readBody(ctx, rawBody);
229
+ args.body = await readBody(ctx, rawBody, confine);
162
230
  for (const spec of listOption(input, "file")) {
163
231
  const at = spec.indexOf("=");
164
232
  if (at <= 0)
165
233
  throw usageError(`--file "${spec}" is not field=path.`);
166
- const file = await confinedPath(ctx, spec.slice(at + 1), "The file");
234
+ const file = await confinedPath(ctx, spec.slice(at + 1), "The file", confine);
167
235
  args.files = [...(args.files ?? []), { field: spec.slice(0, at), path: file }];
168
236
  }
169
- if (ctx.mode === "mcp") {
237
+ const rawOutput = stringOption(input, "output");
238
+ const output = rawOutput ? await confinedPath(ctx, rawOutput, "The output file", confine) : undefined;
239
+ if (driven) {
170
240
  const kept = keptForPerson(op, operations(doc));
171
241
  if (kept) {
172
242
  throw new CavelonError(ExitCode.usage, {
173
243
  code: "operation_for_a_person",
174
- message: refusal(op, kept),
175
- hint: kept.hint,
176
- details: { source: kept.source, ...(kept.reason ? { reason: kept.reason } : {}) },
244
+ message: refusal(op, kept, driven),
245
+ hint: personHint(kept.hint, driven),
246
+ details: { source: kept.source, ...(kept.reason ? { reason: kept.reason } : {}), ...(driven.by === "agent" ? { agent_variable: driven.variable } : {}) },
177
247
  });
178
248
  }
249
+ const secrets = secretsIn(doc, op, args);
250
+ if (secrets.length)
251
+ throw secretRefusal(op, secrets, driven);
179
252
  }
180
- if (ctx.mode === "mcp" && !op.readOnly && !boolOption(input, "confirm")) {
181
- const request = previewRequest(doc, op, args);
182
- const files = (args.files ?? []).map((f) => ({ field: f.field, file: path.relative(ctx.io.cwd, f.path) || f.path }));
183
- return {
184
- data: { operation: op.alias, ...request, ...(files.length ? { files } : {}), sent: false, confirm: "Call api again with the same arguments and confirm: true." },
185
- text: `Would send ${request.method} ${request.path}. Nothing was sent.`,
186
- };
253
+ if (driven && !op.readOnly) {
254
+ const preview = await previewUnlessConfirmed(ctx, input, doc, op, args, driven);
255
+ if (preview)
256
+ return preview;
187
257
  }
188
258
  const client = await ctx.client();
189
259
  const result = await callOperation(ctx, client, doc, op, args);
190
- const output = stringOption(input, "output");
191
260
  if (output) {
192
261
  const content = result.bytes ?? (typeof result.data === "string" ? result.data : JSON.stringify(result.data, null, 2));
193
262
  await fs.writeFile(output, content);
194
263
  const size = typeof content === "string" ? Buffer.byteLength(content) : content.length;
195
- return { data: { status: result.status, written: output, bytes: size }, text: `Wrote ${size} bytes to ${output}.` };
264
+ return { data: { status: result.status, written: rawOutput, bytes: size }, text: `Wrote ${size} bytes to ${rawOutput}.` };
196
265
  }
197
266
  if (result.bytes) {
198
267
  throw validationError(`${op.alias} answered ${result.contentType} (${result.bytes.length} bytes).`, undefined, "Save it with --output <file>.");
@@ -205,6 +274,43 @@ export const api = {
205
274
  return { data, text };
206
275
  },
207
276
  };
277
+ async function previewUnlessConfirmed(ctx, input, doc, op, args, driven) {
278
+ if (driven.by === "mcp" && boolOption(input, "confirm"))
279
+ return undefined;
280
+ const request = previewRequest(doc, op, args);
281
+ const files = (args.files ?? []).map((f) => ({ field: f.field, file: path.relative(ctx.io.cwd, f.path) || f.path }));
282
+ const shown = { operation: op.alias, ...request, ...(files.length ? { files } : {}), sent: false };
283
+ if (driven.by === "mcp") {
284
+ return {
285
+ data: { ...shown, confirm: "Call api again with the same arguments and confirm: true." },
286
+ text: `Would send ${request.method} ${request.path}. Nothing was sent.`,
287
+ };
288
+ }
289
+ const session = await ctx.session();
290
+ const token = confirmToken({ url: session.url, tenant: session.tenant }, request, files);
291
+ const given = stringOption(input, "confirm");
292
+ if (given === token)
293
+ return undefined;
294
+ const stale = Boolean(given);
295
+ const confirm = `Show the person this request, then run the same command again with --confirm ${token} to send exactly it.`;
296
+ const lines = [`Would send ${request.method} ${request.path}. Nothing was sent.`];
297
+ if (stale)
298
+ lines.push("The --confirm token is not this request's: the request changed since its preview, or the token is another one's.");
299
+ if (Object.keys(request.query).length)
300
+ lines.push(`Query: ${JSON.stringify(request.query)}`);
301
+ if (Object.keys(request.headers).length)
302
+ lines.push(`Headers: ${JSON.stringify(request.headers)}`);
303
+ if (request.body !== null)
304
+ lines.push("Body:", JSON.stringify(request.body, null, 2));
305
+ for (const f of files)
306
+ lines.push(`File: ${f.field} = ${f.file}`);
307
+ lines.push(confirm);
308
+ return {
309
+ data: { ...shown, confirm_token: token, confirm, ...(stale ? { token_mismatch: true } : {}) },
310
+ text: lines.join("\n"),
311
+ ...(stale ? { exitCode: ExitCode.conflict } : {}),
312
+ };
313
+ }
208
314
  export const apiList = {
209
315
  name: "api list",
210
316
  summary: "List the operations the instance publishes.",
@@ -129,7 +129,7 @@ async function writeMcp(root, target, onlyExisting) {
129
129
  if (target.format === "toml")
130
130
  return applyBlock(root, file, upsertBlock(existing, target.block, "hash", { onlyExisting }));
131
131
  if (onlyExisting) {
132
- let present = false;
132
+ let present;
133
133
  try {
134
134
  present = Boolean(existing && JSON.parse(existing)[target.keys[0]]?.[target.keys[1]]);
135
135
  }
@@ -15,6 +15,7 @@ import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../pack
15
15
  import { pairOrderHint, pairOrderPointer } from "../pair-order.js";
16
16
  import { readPackage, writePackage } from "../package-files.js";
17
17
  import { readPrincipal } from "../principal.js";
18
+ import { CASE_STATUSES, caseStatus, TESTING_PAGE } from "../results.js";
18
19
  import { isUuid, requireInstance } from "../session.js";
19
20
  import { listedPages } from "./docs.js";
20
21
  import { writeInventory } from "./inventory.js";
@@ -656,18 +657,47 @@ function processingStepCapHint(limits) {
656
657
  const resets = cap.period ? ` It resets at ${cap.period.resets_at}.` : "";
657
658
  return `monthly_processing_step_cap is ${value}${used} (state: ${cap.state}).${resets} ${raise}`;
658
659
  }
660
+ async function caseStatusAnswer(ctx, status) {
661
+ const instance = (await ctx.session().catch(() => undefined))?.url;
662
+ const page = `/docs/${TESTING_PAGE}#${status.section}`;
663
+ const data = {
664
+ code: status.status,
665
+ kind: "test_case_status",
666
+ message: status.meaning,
667
+ hint: status.next,
668
+ summary_counts: status.counts,
669
+ docs: instance ? `${instance}${page}` : page,
670
+ read: [{ page: TESTING_PAGE, command: cavelonCommand("docs", "get", TESTING_PAGE) }],
671
+ };
672
+ return {
673
+ data,
674
+ text: keyValues([
675
+ ["code", status.status],
676
+ ["kind", "test-case status (neither pass nor fail)"],
677
+ ["meaning", status.meaning],
678
+ ["next", status.next],
679
+ ["counted as", status.counts.join(", ")],
680
+ ["docs", data.docs],
681
+ ["read", data.read[0].command],
682
+ ]),
683
+ };
684
+ }
659
685
  export const explain = {
660
686
  name: "explain",
661
687
  summary: "Look a code up in the instance's error catalog: what it means and how to fix it.",
662
- description: "Rule codes come from the package and graph checks, API error codes from failed requests. Uses the cached catalog first.",
688
+ description: "Rule codes come from the package and graph checks, API error codes from failed requests. Uses the cached catalog first.\n" +
689
+ `Also explains the test-case statuses that are neither pass nor fail: ${CASE_STATUSES.map((s) => s.status).join(", ")}.`,
663
690
  readOnly: true,
664
691
  idempotent: true,
665
692
  mcpTool: "explain",
666
- positionals: [{ name: "code", description: "The code, e.g. from `cavelon validate` or an error's code.", required: true }],
693
+ positionals: [{ name: "code", description: "The code, e.g. from `cavelon validate` or an error's code, or a test-case status.", required: true }],
667
694
  async run(ctx, input) {
668
695
  const code = positional(input, "code").trim();
669
- let catalog = await catalogFor(ctx, false);
696
+ const status = caseStatus(code);
697
+ let catalog = status ? await catalogFor(ctx, false).catch(() => null) : await catalogFor(ctx, false);
670
698
  let entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code);
699
+ if (!entry && status)
700
+ return caseStatusAnswer(ctx, status);
671
701
  if (!entry || entry.kind === "kit") {
672
702
  catalog = await (await ctx.contracts()).errorCatalog({ refresh: true }).catch(() => catalog);
673
703
  entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code) ?? entry;
@@ -680,7 +710,7 @@ export const explain = {
680
710
  });
681
711
  }
682
712
  if (!entry) {
683
- const all = [...(catalog?.rule_codes ?? []), ...(catalog?.api_error_codes ?? []), ...KIT_CODES].map((e) => e.code);
713
+ const all = [...(catalog?.rule_codes ?? []), ...(catalog?.api_error_codes ?? []), ...KIT_CODES, ...CASE_STATUSES.map((s) => ({ code: s.status }))].map((e) => e.code);
684
714
  const words = code.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2);
685
715
  const similar = all.filter((c) => words.some((w) => c.toLowerCase().includes(w))).slice(0, 8);
686
716
  throw new CavelonError(ExitCode.failure, {
package/dist/mcp.js CHANGED
@@ -12,7 +12,10 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
12
12
  "init and pull write files in the solution folder without confirm (pull refuses to replace package files with uncommitted changes unless force), " +
13
13
  "and the other changing tools act at once. api refuses, even with confirm, an operation the instance marks for a person " +
14
14
  "(x-cavelon-person-only; its reason is in the error), or on an instance that marks none, one that changes a secret, " +
15
- "creates or revokes a credential (tokens, API keys, sign-in) or decides an approval. Tools read and write files only " +
15
+ "creates or revokes a credential (tokens, API keys, sign-in) or decides an approval; it also refuses a body that sets a field " +
16
+ "the instance marks as a secret value (x-cavelon-secret): leave the field out and let a person enter the value. " +
17
+ "`cavelon api` run from your shell applies the same guards, and sends a changing operation only with --confirm and the token " +
18
+ "its preview printed. Tools read and write files only " +
16
19
  "inside the solution folder (the folder of cavelon.yaml, or the one the server started in), never in cavelon's own " +
17
20
  "config or cache directory. Read limits before planning a solution: it lists what the " +
18
21
  "instance allows this tenant (upload sizes and types, run and tool limits, timeouts, quotas) and who changes each. " +
@@ -43,7 +46,7 @@ export function inputSchema(spec) {
43
46
  if (option.cliOnly)
44
47
  continue;
45
48
  properties[name] =
46
- option.type === "boolean"
49
+ option.type === "boolean" || option.mcpBoolean
47
50
  ? { type: "boolean", description: option.description }
48
51
  : option.multiple
49
52
  ? { type: "array", items: { type: "string" }, description: option.description }
@@ -83,7 +86,7 @@ function inputFrom(spec, args) {
83
86
  const value = args[name];
84
87
  if (value === undefined || value === null)
85
88
  continue;
86
- if (option.type === "boolean")
89
+ if (option.type === "boolean" || option.mcpBoolean)
87
90
  input.options[name] = value === true || value === "true";
88
91
  else if (option.multiple)
89
92
  input.options[name] = Array.isArray(value) ? value.map(String) : [String(value)];
package/dist/openapi.js CHANGED
@@ -174,6 +174,50 @@ export function validateBody(doc, op, body) {
174
174
  throw validationError(`The body does not match ${op.alias}'s schema: ${errors.join("; ")}`, errors, `See \`cavelon api describe ${op.alias}\`.`);
175
175
  }
176
176
  }
177
+ export function secretFields(doc, schema, body) {
178
+ const found = new Set();
179
+ let budget = 10_000;
180
+ const list = (value) => (Array.isArray(value) ? value : []);
181
+ const walk = (raw, value, where, depth) => {
182
+ if (value === undefined || value === null || depth > 64 || --budget < 0)
183
+ return;
184
+ const node = deref(doc, raw);
185
+ if (!node || typeof node !== "object")
186
+ return;
187
+ const s = node;
188
+ if (s["x-cavelon-secret"] === true) {
189
+ found.add(where || "(body)");
190
+ return;
191
+ }
192
+ for (const key of ["allOf", "anyOf", "oneOf"])
193
+ for (const sub of list(s[key]))
194
+ walk(sub, value, where, depth + 1);
195
+ if (Array.isArray(value)) {
196
+ const prefix = list(s.prefixItems);
197
+ value.forEach((item, i) => walk(prefix[i] ?? s.items, item, `${where}[${i}]`, depth + 1));
198
+ }
199
+ else if (typeof value === "object") {
200
+ const props = (s.properties ?? {});
201
+ const patterns = Object.entries((s.patternProperties ?? {}));
202
+ for (const [key, item] of Object.entries(value)) {
203
+ const named = Object.hasOwn(props, key) ? [props[key]] : patterns.filter(([pattern]) => matches(pattern, key)).map(([, sub]) => sub);
204
+ const subs = named.length ? named : [s.additionalProperties];
205
+ for (const sub of subs)
206
+ walk(sub, item, where ? `${where}.${key}` : key, depth + 1);
207
+ }
208
+ }
209
+ };
210
+ walk(schema, body, "", 0);
211
+ return [...found];
212
+ }
213
+ function matches(pattern, key) {
214
+ try {
215
+ return new RegExp(pattern, "u").test(key);
216
+ }
217
+ catch {
218
+ return false;
219
+ }
220
+ }
177
221
  export function coerceParameter(param, raw) {
178
222
  const types = schemaTypes(param.schema);
179
223
  if (types.includes("integer") && /^-?\d+$/.test(raw))
package/dist/paths.js CHANGED
@@ -31,16 +31,17 @@ export function instanceKey(url) {
31
31
  const readable = parts.join("_").replace(/[^A-Za-z0-9._-]+/g, "_");
32
32
  return `${readable}-${createHash("sha256").update(url).digest("hex").slice(0, 8)}`;
33
33
  }
34
- export async function confinedPath(ctx, raw, what) {
34
+ export async function confinedPath(ctx, raw, what, confine = ctx.mode === "mcp") {
35
35
  const resolved = path.resolve(ctx.io.cwd, raw);
36
- if (ctx.mode !== "mcp")
36
+ if (!confine)
37
37
  return resolved;
38
38
  const root = (await findProject(ctx.io.cwd))?.root ?? ctx.io.cwd;
39
39
  const real = await realPath(resolved);
40
40
  if (!within(await realPath(root), real)) {
41
+ const who = ctx.mode === "mcp" ? "over MCP a tool" : "run by a coding agent, cavelon";
41
42
  throw new CavelonError(ExitCode.usage, {
42
43
  code: "path_outside_solution",
43
- message: `${what} ${raw} is outside the solution folder ${root}; over MCP a tool reads and writes only there.`,
44
+ message: `${what} ${raw} is outside the solution folder ${root}; ${who} reads and writes only there.`,
44
45
  hint: "Name a file inside the solution folder, or ask the person to run the command in their terminal.",
45
46
  });
46
47
  }
package/dist/results.js CHANGED
@@ -10,8 +10,55 @@ function summaryCount(summary, key) {
10
10
  const value = Number(summary?.[key] ?? 0);
11
11
  return Number.isFinite(value) && value > 0 ? value : 0;
12
12
  }
13
- const NOT_PASSED_COUNTS = ["failed", "errors", "technical_errors", "not_run", "cases_not_run", "missing_results", "unmeasurable_cases", "skipped"];
14
- const WAITING_COUNTS = ["pending_review", "calibration_required"];
13
+ export const NOT_PASSED_COUNTS = ["failed", "errors", "technical_errors", "not_run", "cases_not_run", "missing_results", "unmeasurable_cases", "skipped"];
14
+ export const WAITING_COUNTS = ["pending_review", "calibration_required"];
15
+ export const TESTING_PAGE = "concepts/regression-testing";
16
+ export const CASE_STATUSES = [
17
+ {
18
+ status: "calibration_required",
19
+ counts: ["calibration_required"],
20
+ short: "a knowledge base or value the case needs was not ready",
21
+ meaning: "The instance did not run the case. When it accepted the run (its preflight), a knowledge base the case needs had no ready documents (knowledge_base_not_ready), or a {{var:…}} value the case refers to was not set (tenant_value_missing); the result's reason names which. The run keeps that verdict even if the documents become ready while it runs.",
22
+ next: "Wait until the knowledge base's documents are processed (`cavelon wait` on the upload's operation), or set the value (`cavelon variables set`), then start a new run.",
23
+ section: "preflight-is-decided-when-the-run-is-accepted",
24
+ },
25
+ {
26
+ status: "pending_review",
27
+ counts: ["pending_review"],
28
+ short: "the answer waits for a person's verdict",
29
+ meaning: "The case ran, and its answer waits for a manual verdict: Auto-Evaluate is off for the suite, so no judge scored it.",
30
+ next: "Tell the person: they set Pass, Fail or Skip on the result in the instance. To have the judge score it, turn Auto-Evaluate on for the suite and run it again.",
31
+ section: "reviewing-results",
32
+ },
33
+ {
34
+ status: "not_run",
35
+ counts: ["not_run", "cases_not_run", "missing_results"],
36
+ short: "the step produced no result",
37
+ meaning: "The step produced no result: the run was cancelled or stopped before it (after repeated provider refusals, for example), or the case was held back before any step ran. The run is not comparable and has no pass rate.",
38
+ next: "`cavelon trace <test-run-id>` shows which steps ran and the reasons recorded; fix the cause and start a new run.",
39
+ section: "reviewing-results",
40
+ },
41
+ {
42
+ status: "not_evaluated",
43
+ counts: ["unevaluated_steps"],
44
+ short: "a preparation step, not scored",
45
+ meaning: "A preparation step (`evaluate: false`, or a fixed response): it sets up the dialog for a later step and is not scored, so it counts toward neither side of the pass rate. It does not fail a run.",
46
+ next: "Nothing, unless the step should be judged: then give it `evaluate: true` and a reference answer or criteria.",
47
+ section: "reviewing-results",
48
+ },
49
+ {
50
+ status: "skip",
51
+ counts: ["skipped"],
52
+ short: "the step was skipped",
53
+ meaning: "The step was skipped: a person set a Skip verdict to park the case, or the run was cancelled before the step. The run is not comparable and has no pass rate.",
54
+ next: "When the case applies again, a person replaces the Skip verdict in the instance; after a cancelled run, start a new one.",
55
+ section: "reviewing-results",
56
+ },
57
+ ];
58
+ export function caseStatus(name) {
59
+ const wanted = name.trim().toLowerCase().replaceAll(" ", "_").replaceAll("-", "_");
60
+ return CASE_STATUSES.find((s) => s.status === wanted || s.counts.includes(wanted));
61
+ }
15
62
  export function runVerdict(summary) {
16
63
  const counts = {};
17
64
  for (const key of [...NOT_PASSED_COUNTS, ...WAITING_COUNTS]) {
@@ -33,9 +80,16 @@ export function runVerdict(summary) {
33
80
  }
34
81
  export function countsText(counts) {
35
82
  return Object.entries(counts)
36
- .map(([key, value]) => `${value} ${key === "errors" ? "errored" : key.replaceAll("_", " ")}`)
83
+ .map(([key, value]) => {
84
+ const why = WAITING_COUNTS.includes(key) ? caseStatus(key)?.short : undefined;
85
+ return `${value} ${key === "errors" ? "errored" : key.replaceAll("_", " ")}${why ? ` (${why})` : ""}`;
86
+ })
37
87
  .join(", ");
38
88
  }
89
+ function explainedStatuses(counts) {
90
+ const statuses = Object.keys(counts).map((key) => caseStatus(key)?.status);
91
+ return [...new Set(statuses.filter((s) => Boolean(s)))];
92
+ }
39
93
  const MAX_CASES = 5;
40
94
  const REASON_CHARS = 500;
41
95
  export function failedCase(r, max = REASON_CHARS) {
@@ -69,7 +123,10 @@ export async function resultFailure(ctx, op) {
69
123
  comparable: verdict.comparable,
70
124
  non_comparable_reasons: verdict.non_comparable_reasons,
71
125
  exit_code: verdict.exit_code,
72
- cases: results.filter((r) => NOT_PASSED.has(r.status)).slice(0, MAX_CASES).map((r) => failedCase(r)),
126
+ cases: results
127
+ .filter((r) => NOT_PASSED.has(r.status) || WAITING_COUNTS.includes(r.status))
128
+ .slice(0, MAX_CASES)
129
+ .map((r) => failedCase(r)),
73
130
  trace: cavelonCommand("trace", id),
74
131
  };
75
132
  }
@@ -96,9 +153,12 @@ export function failureLines(failure) {
96
153
  for (const c of failure.cases)
97
154
  lines.push(` ${caseLabel(c)} ${c.status}${c.reason ? ": " + c.reason : ""}`);
98
155
  const shown = failure.cases.length;
99
- const total = failure.failed_cases + failure.errored_cases;
156
+ const total = failure.failed_cases + failure.errored_cases + WAITING_COUNTS.reduce((sum, key) => sum + (failure.counts[key] ?? 0), 0);
100
157
  if (total > shown)
101
158
  lines.push(` … ${total - shown} more`);
159
+ const statuses = explainedStatuses(failure.counts);
160
+ if (statuses.length)
161
+ lines.push(` What to do: ${statuses.map((s) => cavelonCommand("explain", s)).join("; ")}`);
102
162
  lines.push(` Look closer: ${failure.trace}`);
103
163
  return lines.join("\n");
104
164
  }
@@ -155,7 +155,10 @@ version; leave it as `pull` wrote it.
155
155
  a slug creates a new entry and, with `--mode replace`, deletes the old one.
156
156
  - **Secrets and variables are references only:** write `{{secret:<name>}}` or
157
157
  `{{var:<name>}}` where a value is needed, and declare the name (below). Never
158
- write a secret value into any file, an argument or a message.
158
+ write a secret value into any file, an argument or a message. `cavelon api`
159
+ refuses a body that sets a field the instance marks as a secret value
160
+ (`x-cavelon-secret`: provider keys, passwords and the like): leave the field
161
+ out and let the person enter the value in the Admin.
159
162
  - **Environment specifics go into `env/`, not `package/`.** Runtime
160
163
  requirements (Sandboxes, other solutions) are bound per environment in
161
164
  `runtime_bindings`, keyed by the requirement's key, to the target tenant's
@@ -104,6 +104,24 @@ identity <trigger> <key> --confirm` (it gives a trigger standing authority), and
104
104
  before `cavelon sandbox seed … --confirm` or `cavelon loop cancel … --confirm` on
105
105
  anything but a test Sandbox or a run you started yourself.
106
106
 
107
+ **`cavelon api` from your shell has the guards of the MCP `api` tool**, since
108
+ `cavelon` sees that a coding agent runs it (`CLAUDECODE`, `CODEX_THREAD_ID`, `CODEX_SANDBOX`,
109
+ `CURSOR_AGENT`, `GEMINI_CLI`, `COPILOT_CLI`, `COPILOT_AGENT`, `AI_AGENT` or
110
+ `CAVELON_AGENT=1`):
111
+
112
+ - For an operation that is not read-only, it prints the request and a confirm
113
+ token and sends nothing. Show the request to the person when the rules above
114
+ say so, then run the same command again with `--confirm <token>`; it sends
115
+ exactly that request. A changed body or parameter needs a new preview (exit 4).
116
+ - It refuses an operation the instance keeps for a person
117
+ (`operation_for_a_person`) and a body that sets a field the instance marks as
118
+ a secret value (`secret_field_for_a_person`), with or without `--confirm`.
119
+ Tell the person what the error's hint says; for a secret field, send the rest
120
+ without it and let the person enter the value (`cavelon secrets set <name>`
121
+ or the Admin). Never work around a refusal, by unsetting the variable or by
122
+ any other way.
123
+ - Its `@file` body, `--file` and `--output` stay inside the solution folder.
124
+
107
125
  `activate` goes through the readiness gate only, and only with a token that
108
126
  may activate. It never forces: activating without the evidence stays a person's
109
127
  decision in the Admin, so do not ask for it as a shortcut.
@@ -61,6 +61,20 @@ errors, no pass rate): it is no evidence the solution works, so do not go on to
61
61
  `activate`; find the cause and run again. Exit 5 means answers wait for a
62
62
  person's verdict or a value a case needs: tell the person.
63
63
 
64
+ Besides `pass`, `fail` and `error`, a case's step can end in a status that is
65
+ no verdict; `cavelon explain <status>` says what it means and what to do next:
66
+
67
+ | Status | Means | Next |
68
+ |---|---|---|
69
+ | `calibration_required` | Not run: a knowledge base it needs had no ready documents, or a `{{var:…}}` value was not set, when the run started (exit 5) | Wait for the documents or set the value, then start a new run |
70
+ | `pending_review` | Ran; the answer waits for a person's verdict, because Auto-Evaluate is off (exit 5) | Tell the person |
71
+ | `not_run` | The step produced no result: the run stopped or was cancelled first (exit 1) | `cavelon trace <run>`, fix the cause, run again |
72
+ | `skip` | A person parked the case with a Skip verdict, or the run was cancelled before it (exit 1) | Run again, or leave it to the person |
73
+ | `not_evaluated` | A preparation step (`evaluate: false`): it ran and is not scored | Nothing |
74
+
75
+ The case's own reason (which knowledge base, which value) is in the output of
76
+ `test run --wait`, `wait` and `cavelon trace <run>`.
77
+
64
78
  ## Reading what happened
65
79
 
66
80
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cavelon/cli",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "The cavelon binary: CLI and local MCP server for building Cavelon solutions with a coding agent.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/goodguys-gmbh/cavelon-dev-kit",
@@ -41,9 +41,9 @@
41
41
  "@napi-rs/keyring": "^2.1.0"
42
42
  },
43
43
  "devDependencies": {
44
- "@eslint/js": "^9.39.0",
44
+ "@eslint/js": "^10.0.1",
45
45
  "@types/node": "^20.19.0",
46
- "eslint": "^9.39.0",
46
+ "eslint": "^10.12.0",
47
47
  "typescript": "~5.9.3",
48
48
  "typescript-eslint": "^8.71.0",
49
49
  "vitest": "^4.0.0"