@cavelon/cli 0.1.1 → 0.1.2

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.
@@ -9,7 +9,7 @@ import { readTextFile, writeFileAtomic } from "../fsutil.js";
9
9
  import { uncommitted } from "../git.js";
10
10
  import { callStable } from "../invoke.js";
11
11
  import { ceilingHint, LIMIT_ABOVE_CEILING, parseLimits, readLimits } from "../limits.js";
12
- import { deletePreview, digest, listPreviews, loadPreview, savePreview, writeState, } from "../local-state.js";
12
+ import { deletePreview, digest, fileDigest, listPreviews, loadPreview, readPulledFiles, savePreview, writePulledFiles, writeState, } from "../local-state.js";
13
13
  import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
14
14
  import { pairOrderHint, pairOrderPointer } from "../pair-order.js";
15
15
  import { readPackage, writePackage } from "../package-files.js";
@@ -68,37 +68,64 @@ function harnessNotFound(ref, source) {
68
68
  hint: "`cavelon harness list` shows them; `cavelon harness new <slug>` creates one, and an env file's harness is created by `apply`.",
69
69
  });
70
70
  }
71
+ async function cachedFirst(ctx, what, cached, offline, fetch) {
72
+ if (cached && (offline || !cached.stale))
73
+ return { value: cached.value, source: "cache" };
74
+ if (offline)
75
+ return { value: null, source: "none" };
76
+ try {
77
+ const value = await fetch();
78
+ if (value === null && cached)
79
+ return { value: cached.value, source: "cache" };
80
+ return { value, source: "instance" };
81
+ }
82
+ catch (error) {
83
+ if (!cached)
84
+ throw error;
85
+ ctx.warn(`Could not read the ${what} again from the instance (${error instanceof Error ? error.message : String(error)}); ` +
86
+ `using the copy cached at ${cached.fetched_at ?? "an unknown time"} for development build ${cached.version}.`);
87
+ return { value: cached.value, source: "cache" };
88
+ }
89
+ }
71
90
  export async function schemaFor(ctx, version, offline) {
72
91
  const contracts = await ctx.contracts();
73
- const wanted = version ?? (await contracts.cachedOnly("capabilities.json"))?.value?.contracts?.package_versions?.current;
74
- if (wanted) {
75
- const cached = await contracts.cachedOnly(Contracts.packageSchemaFile(wanted));
76
- if (cached)
77
- return { schema: cached.value, source: "cache" };
78
- }
79
- if (offline)
80
- return { schema: null, source: "none" };
81
- return { schema: await contracts.packageSchema(wanted), source: "instance" };
92
+ let wanted = version ?? (await contracts.cachedOnly("capabilities.json"))?.value?.contracts?.package_versions?.current;
93
+ const cached = wanted ? await contracts.cachedOnly(Contracts.packageSchemaFile(wanted)) : undefined;
94
+ const { value: schema, source } = await cachedFirst(ctx, "package schema", cached, offline, async () => {
95
+ wanted ??= (await contracts.capabilities())?.contracts?.package_versions?.current;
96
+ return contracts.packageSchema(wanted);
97
+ });
98
+ const copy = source === "instance" && schema ? await contracts.cachedOnly(Contracts.packageSchemaFile(wanted ?? "current")) : source === "cache" ? cached : undefined;
99
+ return {
100
+ schema,
101
+ used: {
102
+ package_version: schema?.["x-package-version"] ?? wanted ?? null,
103
+ source: schema ? source : "none",
104
+ instance_version: copy?.version ?? null,
105
+ fetched_at: copy?.fetched_at ?? null,
106
+ etag: copy?.etag ?? null,
107
+ sha256: copy?.sha256 ?? null,
108
+ stale: copy?.stale ?? false,
109
+ },
110
+ };
82
111
  }
83
112
  export async function catalogFor(ctx, offline) {
84
113
  const contracts = await ctx.contracts();
85
114
  const cached = await contracts.cachedOnly("error-catalog.json");
86
- if (cached || offline)
87
- return cached?.value ?? null;
88
- return contracts.errorCatalog().catch(() => null);
115
+ return (await cachedFirst(ctx, "error catalog", cached, offline, () => contracts.errorCatalog()).catch(() => ({ value: null }))).value;
89
116
  }
90
- async function limitsFor(ctx, offline) {
117
+ async function capabilitiesFor(ctx, offline) {
91
118
  const contracts = await ctx.contracts();
92
119
  const cached = await contracts.cachedOnly("capabilities.json");
93
- if (cached || offline)
94
- return cached ? parseLimits(cached.value) : undefined;
95
- const live = await contracts.capabilities().catch(() => null);
96
- return live ? parseLimits(live) : undefined;
120
+ const read = () => contracts.capabilities();
121
+ return (await cachedFirst(ctx, "capabilities", cached, offline, read).catch(() => ({ value: null }))).value;
97
122
  }
98
- async function acceptedVersions(ctx) {
99
- const contracts = await ctx.contracts();
100
- const cached = await contracts.cachedOnly("capabilities.json");
101
- return cached?.value?.contracts?.package_versions?.accepted;
123
+ async function limitsFor(ctx, offline) {
124
+ const caps = await capabilitiesFor(ctx, offline);
125
+ return caps ? parseLimits(caps) : undefined;
126
+ }
127
+ async function acceptedVersions(ctx, offline) {
128
+ return (await capabilitiesFor(ctx, offline))?.contracts?.package_versions?.accepted;
102
129
  }
103
130
  function findingLine(f) {
104
131
  const where = f.file ? `${f.file}${f.line ? `:${f.line}` : ""}` : "";
@@ -113,19 +140,39 @@ export async function setProjectKey(project, key, value) {
113
140
  doc.set(key, value);
114
141
  await writeFileAtomic(project.file, doc.toString({ lineWidth: 0 }));
115
142
  }
143
+ function uncommittedChanges(files, what) {
144
+ return new CavelonError(ExitCode.conflict, {
145
+ code: "uncommitted_changes",
146
+ message: `${what}: ${files.slice(0, 5).join(", ")}${files.length > 5 ? ` and ${files.length - 5} more` : ""}.`,
147
+ hint: "Commit them first (then resolve the difference in git), apply them with `cavelon apply`, or pass --force to discard them.",
148
+ details: { files },
149
+ });
150
+ }
151
+ async function editedSincePull(project, pkg, schema) {
152
+ const planned = await writePackage(project.root, project.layout, pkg, schema, { dryRun: true });
153
+ const pulled = await readPulledFiles(project.root);
154
+ const edited = [];
155
+ for (const file of [...planned.written, ...planned.removed]) {
156
+ const current = await fileDigest(path.join(project.root, file));
157
+ if (current !== undefined && current !== pulled[file])
158
+ edited.push(file);
159
+ }
160
+ return edited.sort((a, b) => a.localeCompare(b, "en"));
161
+ }
116
162
  export const pull = {
117
163
  name: "pull",
118
164
  summary: "Write the instance's package into package/ (split along the schema's sections) and the inventory into .cavelon/.",
119
165
  description: "With a solution (--harness, or cavelon.yaml's harness), exports that solution; without one, the tenant's full configuration.\n" +
120
166
  "A file whose content did not change keeps its bytes, so `git diff` shows what changed on the instance. Files of sections\n" +
121
- "the schema does not know are kept byte for byte. Refuses when package files have uncommitted changes, unless --force.",
167
+ "the schema does not know are kept byte for byte. Refuses when package files have uncommitted changes, unless --force;\n" +
168
+ "outside a git repository, when a file it would overwrite or remove changed since the last pull.",
122
169
  readOnly: false,
123
170
  destructive: true,
124
171
  idempotent: true,
125
172
  mcpTool: "pull",
126
173
  options: {
127
174
  harness: { type: "string", value: "<slug>", description: "The solution to export; recorded in cavelon.yaml when it names none." },
128
- force: { type: "boolean", description: "Overwrite package files that have uncommitted changes." },
175
+ force: { type: "boolean", description: "Overwrite package files that have uncommitted changes (outside git: changes since the last pull)." },
129
176
  },
130
177
  examples: ["cavelon pull --harness support", "cavelon pull && git diff -- package tests"],
131
178
  async run(ctx, input) {
@@ -133,17 +180,10 @@ export const pull = {
133
180
  const project = requireSolution(session);
134
181
  const url = requireInstance(session);
135
182
  const layoutDirs = [project.layout.package, ...Object.values(project.layout.items)];
136
- if (!boolOption(input, "force")) {
137
- const dirty = (await uncommitted(project.root, layoutDirs))?.filter((f) => /\.(ya?ml|json)"?$/i.test(f));
138
- if (dirty?.length) {
139
- throw new CavelonError(ExitCode.conflict, {
140
- code: "uncommitted_changes",
141
- message: `pull would overwrite uncommitted changes: ${dirty.slice(0, 5).join(", ")}${dirty.length > 5 ? ` and ${dirty.length - 5} more` : ""}.`,
142
- hint: "Commit them first (then resolve the difference in git), or pass --force to discard them.",
143
- details: { files: dirty },
144
- });
145
- }
146
- }
183
+ const force = boolOption(input, "force");
184
+ const dirty = force ? [] : (await uncommitted(project.root, layoutDirs))?.filter((f) => /\.(ya?ml|json)"?$/i.test(f));
185
+ if (dirty?.length)
186
+ throw uncommittedChanges(dirty, "pull would overwrite uncommitted changes");
147
187
  const { ref } = harnessRef(session, input);
148
188
  let harness;
149
189
  if (ref) {
@@ -163,7 +203,14 @@ export const pull = {
163
203
  const { schema } = await schemaFor(ctx, version, false);
164
204
  if (!schema)
165
205
  ctx.warn("The instance does not publish its package schema; every top-level key became a file of its own.");
206
+ if (dirty === undefined) {
207
+ const edited = await editedSincePull(project, exported, schema);
208
+ if (edited.length) {
209
+ throw uncommittedChanges(edited, "This folder is not in a git repository, and pull would overwrite or remove files that changed since the last pull");
210
+ }
211
+ }
166
212
  const report = await writePackage(project.root, project.layout, exported, schema);
213
+ await writePulledFiles(project.root, [...report.written, ...report.unchanged]);
167
214
  if (harness && !project.harness)
168
215
  await setProjectKey(project, "harness", harness.slug);
169
216
  if (version && project.packageVersion !== version)
@@ -201,7 +248,7 @@ export const pull = {
201
248
  async function validatePackage(ctx, project, offline) {
202
249
  const disk = await readPackage(project.root, project.layout);
203
250
  const version = packageVersionOf(disk.package) ?? project.packageVersion;
204
- const { schema } = await schemaFor(ctx, version, offline);
251
+ const { schema, used } = await schemaFor(ctx, version, offline);
205
252
  if (!schema) {
206
253
  throw new CavelonError(ExitCode.failure, {
207
254
  code: "package_schema_unavailable",
@@ -214,46 +261,74 @@ async function validatePackage(ctx, project, offline) {
214
261
  const findings = checkPackage(disk, {
215
262
  schema,
216
263
  catalog: await catalogFor(ctx, offline),
217
- accepted: await acceptedVersions(ctx),
264
+ accepted: await acceptedVersions(ctx, offline),
218
265
  limits: await limitsFor(ctx, offline),
219
266
  });
220
- return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null };
267
+ return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null, used };
268
+ }
269
+ function schemaUsedLine(used, ttlSeconds) {
270
+ const from = used.source === "instance" ? "read from the instance now" : `cached at ${used.fetched_at ?? "an unknown time"}`;
271
+ const instance = used.instance_version ? `, instance ${used.instance_version}` : "";
272
+ const id = [used.sha256 ? `sha256 ${used.sha256}` : "", used.etag ? `ETag ${used.etag}` : ""].filter(Boolean).join(", ");
273
+ const kept = used.instance_version && Contracts.isDevelopment(used.instance_version)
274
+ ? used.etag
275
+ ? `; a development build: checked with its ETag after ${ttlSeconds(used.instance_version)} s`
276
+ : `; a development build: read again after ${ttlSeconds(used.instance_version)} s`
277
+ : "";
278
+ const stale = used.stale ? " (past its time-to-live; the instance was not read)" : "";
279
+ return `Schema: package format ${used.package_version ?? "?"}, ${from}${instance}${id ? ` (${id})` : ""}${kept}${stale}.`;
221
280
  }
222
281
  export const validate = {
223
282
  name: "validate",
224
283
  summary: "Check the package files against the instance's package schema, offline.",
225
- description: "Uses the schema and error catalog cached by init, pull or apply; fetches them only when none is cached (never with --offline).\n" +
284
+ description: "Uses the schema and error catalog cached by init, pull or apply; fetches them only when none is cached or a development\n" +
285
+ "build's copy is past its time-to-live, and never with --offline. A development build keeps one version while its schema\n" +
286
+ "changes, so its copy is read again after a minute (CAVELON_CONTRACT_TTL_SECONDS), or checked with the ETag the instance\n" +
287
+ "sent with it; --verbose says which copy was used.\n" +
226
288
  "Warns (never fails) when a fan-out or Map loop's max_concurrency is above the instance's branch width, and when the\n" +
227
289
  "tenant runs fan-outs and Map loops in sequence, from the limits the instance last published.\n" +
228
- "Each finding carries a code: `cavelon explain <code>` says more. The import preview checks everything again on the server.",
290
+ "Each finding carries a code: `cavelon explain <code>` says more. The import preview checks everything again on the server.\n\n" +
291
+ "With --json, `warnings` is always a list of `{code, message}` objects: the warning findings (at most --limit), then the\n" +
292
+ "warnings about the run, such as a stale copy of the schema, with code null. `warning_count` counts them all and\n" +
293
+ "`error_count` the errors (`errors` is the same number); `findings` has each finding's file, line and hint.",
229
294
  readOnly: true,
230
295
  idempotent: true,
231
296
  mcpTool: "validate",
232
297
  options: {
233
298
  offline: { type: "boolean", description: "Never contact the instance, even when nothing is cached." },
234
299
  limit: { type: "string", value: "<n>", description: "Print at most n findings (default 50)." },
300
+ verbose: { type: "boolean", description: "Also say which copy of the package schema was used: cached or read now, when, and its hash." },
235
301
  },
236
302
  async run(ctx, input) {
237
303
  const session = await ctx.session();
238
304
  const project = requireSolution(session);
239
305
  requireInstance(session);
240
306
  const limit = intOption(input, "limit", { min: 1, max: 1000, fallback: 50 });
241
- const { disk, findings, schemaVersion } = await validatePackage(ctx, project, boolOption(input, "offline"));
307
+ const { disk, findings, schemaVersion, used } = await validatePackage(ctx, project, boolOption(input, "offline"));
242
308
  const errors = findings.filter((f) => f.severity === "error");
243
309
  const warnings = findings.filter((f) => f.severity === "warning");
244
310
  if (disk.empty)
245
311
  ctx.warn(`No package files in ${project.layout.package}/ yet; \`cavelon pull\` brings an existing solution.`);
312
+ const contracts = await ctx.contracts();
246
313
  const shown = findings.slice(0, limit);
314
+ const listed = [
315
+ ...warnings.slice(0, limit).map((f) => ({ code: f.code, message: f.message })),
316
+ ...ctx.warnings.map((message) => ({ code: null, message })),
317
+ ];
247
318
  const data = {
248
319
  valid: errors.length === 0,
249
320
  schema_version: schemaVersion,
321
+ schema: used,
250
322
  sections: Object.keys(disk.package).length,
323
+ error_count: errors.length,
324
+ warning_count: warnings.length + ctx.warnings.length,
251
325
  errors: errors.length,
252
- warnings: warnings.length,
326
+ warnings: listed,
253
327
  findings: shown,
254
328
  more: Math.max(0, findings.length - shown.length),
255
329
  };
256
330
  const text = [
331
+ ...(boolOption(input, "verbose") ? [schemaUsedLine(used, (v) => contracts.ttlSeconds(v))] : []),
257
332
  ...shown.map(findingLine),
258
333
  ...(data.more ? [`… and ${data.more} more (--limit).`] : []),
259
334
  errors.length
@@ -372,7 +447,7 @@ async function confirmPreview(ctx, project, previewId) {
372
447
  throw new CavelonError(ExitCode.conflict, {
373
448
  code: "preview_other_tenant",
374
449
  message: `Preview ${previewId} was made for tenant ${stored.tenant_id}, but this command acts in ${client.target.tenantId}.`,
375
- hint: stored.env ? `Pass the same --env ${stored.env} as the preview.` : "Use the tenant of the preview, or preview again here.",
450
+ hint: "Run the confirm command the preview printed; it names the preview's --env and --tenant. Or preview again here.",
376
451
  });
377
452
  }
378
453
  if (stored.tenant_id && session.tokenKind !== "api_key")
@@ -389,7 +464,7 @@ async function confirmPreview(ctx, project, previewId) {
389
464
  for (const other of await listPreviews(project.root))
390
465
  await deletePreview(project.root, other.preview_id);
391
466
  const summary = (result.summary ?? {});
392
- const flags = stored.env ? ` --env ${shellWord(stored.env)}` : targetFlags(session);
467
+ const flags = targetFlags(session, stored.env ?? session.envFile?.name);
393
468
  const still = setCommands(stored.preview, flags);
394
469
  const text = keyValues([
395
470
  ["applied", `preview ${stored.preview_id}${stored.harness ? ` to ${stored.harness.slug}` : ""}${stored.env ? ` (env ${stored.env})` : ""}`],
@@ -408,7 +483,7 @@ async function confirmPreview(ctx, project, previewId) {
408
483
  catch (error) {
409
484
  if (error instanceof CavelonError && error.code === REQUIREMENTS_CHANGED && error.blockers?.length) {
410
485
  await deletePreview(project.root, stored.preview_id);
411
- throw requirementsChanged(error, stored, await catalogFor(ctx, false));
486
+ throw requirementsChanged(error, stored, session, await catalogFor(ctx, false));
412
487
  }
413
488
  if (error instanceof CavelonError && (error.code === "import_preview_stale" || (error.status === 409 && /preview/i.test(error.message)))) {
414
489
  await deletePreview(project.root, stored.preview_id);
@@ -416,7 +491,7 @@ async function confirmPreview(ctx, project, previewId) {
416
491
  code: error.code === "conflict" ? "import_preview_stale" : error.code,
417
492
  status: 409,
418
493
  message: `The target changed since preview ${stored.preview_id}; nothing was imported.`,
419
- hint: `Run \`${cavelonCommand("apply", ...previewTarget(stored))}\` again, show the new preview, and confirm its id.`,
494
+ hint: `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
420
495
  docs: error.docs,
421
496
  });
422
497
  }
@@ -424,7 +499,7 @@ async function confirmPreview(ctx, project, previewId) {
424
499
  }
425
500
  }
426
501
  const REQUIREMENTS_CHANGED = "package_requirements_changed";
427
- function requirementsChanged(error, stored, catalog) {
502
+ function requirementsChanged(error, stored, session, catalog) {
428
503
  const blockers = error.blockers ?? [];
429
504
  const known = new Map();
430
505
  for (const blocker of blockers) {
@@ -436,15 +511,14 @@ function requirementsChanged(error, stored, catalog) {
436
511
  code: error.code,
437
512
  status: error.status,
438
513
  message: `The import's requirements changed since preview ${stored.preview_id}; nothing was imported; preview again.`,
439
- hint: [...known.values(), `Run \`${cavelonCommand("apply", ...previewTarget(stored))}\` again, show the new preview, and confirm its id.`].join(" "),
514
+ hint: [...known.values(), `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`].join(" "),
440
515
  docs: error.docs,
441
516
  blockers,
442
517
  });
443
518
  }
444
- function previewTarget(stored) {
445
- if (stored.env)
446
- return ["--env", stored.env];
447
- return stored.harness ? ["--harness", stored.harness.slug] : [];
519
+ function previewAgain(stored, session) {
520
+ const harness = !stored.env && stored.harness ? ` --harness ${shellWord(stored.harness.slug)}` : "";
521
+ return `cavelon apply${harness}${targetFlags(session, stored.env)}`;
448
522
  }
449
523
  async function applyTarget(ctx, session, input, pkg) {
450
524
  const { ref, source } = harnessRef(session, input);
@@ -502,9 +576,6 @@ export const apply = {
502
576
  if (confirm)
503
577
  return confirmPreview(ctx, project, confirm);
504
578
  const envFile = session.envFile;
505
- if (envFile && !envFile.exists) {
506
- throw usageError(`No ${path.relative(project.root, envFile.file).split(path.sep).join("/")}.`, "`cavelon init` writes env/test.yaml and env/prod.yaml.");
507
- }
508
579
  if (envFile?.tenant && session.tenantSource !== `env/${envFile.name}.yaml`) {
509
580
  ctx.warn(`${session.tenantSource} names tenant "${session.tenant}" and takes precedence over ${envFile.name}.yaml's "${envFile.tenant}".`);
510
581
  }
@@ -576,8 +647,7 @@ export const apply = {
576
647
  }
577
648
  const reason = personReason(preview, harness, mode, envFile?.name);
578
649
  data.show_to_person = Boolean(reason);
579
- const envFlags = envFile ? ["--env", envFile.name] : [];
580
- const confirmLine = preview.preview_id ? cavelonCommand("apply", "--confirm", preview.preview_id, ...envFlags) : undefined;
650
+ const confirmLine = preview.preview_id ? `${cavelonCommand("apply", "--confirm", preview.preview_id)}${flags}` : undefined;
581
651
  const text = [
582
652
  `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
583
653
  previewText(preview, flags),
@@ -12,12 +12,15 @@ export const ENV_OPTION = { type: "string", value: "<name>", description: "Act i
12
12
  const CONFIRM_OPTION = { type: "boolean", description: "Delete it; without this nothing is deleted." };
13
13
  const TOKEN_PREFIXES = ["cbp_", "cvpat_"];
14
14
  const LIST_VALUE_CHARS = 200;
15
- export function targetFlags(session) {
16
- if (session.envFile)
17
- return ` --env ${shellWord(session.envFile.name)}`;
15
+ export function targetFlags(session, env = session.envFile?.name) {
16
+ let flags = "";
17
+ if (session.urlSource === "option" && session.url)
18
+ flags += ` --instance ${shellWord(session.url)}`;
19
+ if (env)
20
+ flags += ` --env ${shellWord(env)}`;
18
21
  if (session.tenantSource === "option" && session.tenant)
19
- return ` --tenant ${shellWord(session.tenant)}`;
20
- return "";
22
+ flags += ` --tenant ${shellWord(session.tenant)}`;
23
+ return flags;
21
24
  }
22
25
  export function secretSetCommand(name, flags = "") {
23
26
  return `cavelon secrets set ${shellWord(name)}${flags}`;
@@ -3,11 +3,12 @@ import path from "node:path";
3
3
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
4
4
  import { capacityCodeIn, capacityHint, noteLines, runCapacityNote } from "../capacity.js";
5
5
  import { CavelonError, ExitCode, usageError } from "../errors.js";
6
+ import { confinedPath } from "../paths.js";
6
7
  import { clip, keyValues, moreHint, table } from "../format.js";
7
8
  import { callStable } from "../invoke.js";
8
9
  import { bindsNow, changedBy, limitError, limitsOrWarn, readLimits } from "../limits.js";
9
10
  import { getOperation } from "../operations.js";
10
- import { caseCounts, caseLabel, failedCase, NOT_PASSED } from "../results.js";
11
+ import { caseCounts, caseLabel, countsText, failedCase, NOT_PASSED, runVerdict } from "../results.js";
11
12
  import { isUuid } from "../session.js";
12
13
  import { cavelonCommand, shellWord } from "../shell.js";
13
14
  import { readZipSummary, ZipError } from "../zip.js";
@@ -253,7 +254,7 @@ export const kbUpload = {
253
254
  },
254
255
  examples: ["cavelon kb upload ./docs --kb FAQ", "cavelon kb upload ./manuals --kb FAQ -r --ext pdf --wait --timeout 5m"],
255
256
  async run(ctx, input) {
256
- const dir = path.resolve(ctx.io.cwd, positional(input, "dir"));
257
+ const dir = await confinedPath(ctx, positional(input, "dir"), "The folder");
257
258
  const kbRef = stringOption(input, "kb");
258
259
  if (!kbRef)
259
260
  throw usageError("Which knowledge base?", "Pass --kb <name-or-id>.");
@@ -341,10 +342,17 @@ export const kbUpload = {
341
342
  },
342
343
  };
343
344
  function summaryText(summary) {
344
- return ["passed", "failed", "errors", "pass_rate"]
345
- .filter((k) => k in summary)
346
- .map((k) => k + " " + String(summary[k]))
347
- .join(" ");
345
+ const verdict = runVerdict(summary);
346
+ const shown = ["passed", "failed", "errors"].filter((k) => k in summary).map((k) => k + " " + String(summary[k]));
347
+ const others = Object.fromEntries(Object.entries(verdict.counts).filter(([k]) => !["failed", "errors"].includes(k)));
348
+ if (Object.keys(others).length)
349
+ shown.push(countsText(others));
350
+ if ("pass_rate" in summary)
351
+ shown.push(`pass_rate ${String(summary.pass_rate)}`);
352
+ if (verdict.comparable === false) {
353
+ shown.push(`not comparable${verdict.non_comparable_reasons.length ? ` (${verdict.non_comparable_reasons.join(", ")})` : ""}`);
354
+ }
355
+ return shown.join(" ");
348
356
  }
349
357
  function resumeCommand(pending, timeout) {
350
358
  return cavelonCommand("wait", ...pending, ...(timeout ? ["--timeout", timeout] : []));
@@ -353,7 +361,8 @@ export const testRun = {
353
361
  name: "test run",
354
362
  summary: "Start test-suite runs; returns operation ids.",
355
363
  description: "Without --suite, runs every suite of the solution (--harness, or cavelon.yaml's harness).\n" +
356
- "With --wait, exits 1 when a case failed, 5 when answers wait for a manual verdict.",
364
+ "With --wait, exits 1 when a case failed or a run measured nothing comparable (cases not run, technical errors),\n" +
365
+ "5 when answers wait for a manual verdict or a value a case needs.",
357
366
  readOnly: false,
358
367
  mcpTool: "test_run",
359
368
  options: {
@@ -416,15 +425,21 @@ export const testRun = {
416
425
  const waited = await waitAndReport(ctx, operationIds, timeoutMs(ctx, rawTimeout));
417
426
  const results = [];
418
427
  let failedCases = 0;
428
+ let verdictCode = ExitCode.ok;
419
429
  for (const run of runs) {
420
430
  const latest = await callStable(ctx, "GET", "/api/v1/test-runs/{run_id}", "test runs", { params: { run_id: [run.id] } });
421
431
  const { failed, errors } = caseCounts(latest.summary);
422
432
  failedCases += failed + errors;
433
+ if (!waited.pending.includes(run.operation_id ?? "")) {
434
+ const code = runVerdict(latest.summary).exit_code;
435
+ if (code === ExitCode.failure || (code === ExitCode.needsAction && verdictCode === ExitCode.ok))
436
+ verdictCode = code;
437
+ }
423
438
  results.push({ run_id: latest.id, suite: latest.suite_name ?? latest.suite_id, status: latest.status, summary: latest.summary ?? {} });
424
439
  }
425
440
  let exitCode = waited.exitCode;
426
- if (exitCode === ExitCode.ok && failedCases > 0)
427
- exitCode = ExitCode.failure;
441
+ if (exitCode === ExitCode.ok)
442
+ exitCode = verdictCode;
428
443
  const resume = waited.pending.length ? resumeCommand(waited.pending, rawTimeout) : undefined;
429
444
  const text = [
430
445
  waited.body,
@@ -615,16 +630,18 @@ export const trace = {
615
630
  const cursor = stringOption(input, "cursor");
616
631
  if (id.startsWith("op_")) {
617
632
  const op = await getOperation(await ctx.client(), id);
618
- if (!op.result_ref)
633
+ const ref = op.result_ref;
634
+ if (!ref)
619
635
  throw new CavelonError(ExitCode.failure, { code: "no_result", message: `${id} has no result yet (${op.status}).` });
620
- if (op.result_ref.type !== "test_run") {
636
+ const triggerRun = ref.type === "agent_run" || Boolean(ref.href?.startsWith("/api/v1/triggers/runs/"));
637
+ if (ref.type !== "test_run" && !triggerRun) {
621
638
  throw new CavelonError(ExitCode.failure, {
622
639
  code: "no_trace",
623
- message: `${id} is a ${op.kind}; its result is a ${op.result_ref.type}, which has no trace.`,
640
+ message: `${id} is a ${op.kind}; its result is a ${ref.type}, which has no trace.`,
624
641
  });
625
642
  }
626
- id = op.result_ref.id;
627
- kind = "test";
643
+ id = ref.id;
644
+ kind = triggerRun ? "trigger" : "test";
628
645
  }
629
646
  const traceId = stringOption(input, "trace");
630
647
  const spanId = stringOption(input, "span");
package/dist/context.js CHANGED
@@ -52,5 +52,9 @@ export function createContext(io, globals, mode = "cli") {
52
52
  }
53
53
  export function withWarnings(data, warnings) {
54
54
  const own = Array.isArray(data.warnings) ? data.warnings : [];
55
- return { ...data, warnings: [...own, ...warnings.filter((w) => !own.includes(w))] };
55
+ const messageOf = (entry) => (entry && typeof entry === "object" ? entry.message : entry);
56
+ const seen = new Set(own.map(messageOf));
57
+ const objects = own.some((entry) => entry && typeof entry === "object");
58
+ const added = warnings.filter((w) => !seen.has(w)).map((message) => (objects ? { code: null, message } : message));
59
+ return { ...data, warnings: [...own, ...added] };
56
60
  }