@cavelon/cli 0.1.4 → 0.1.6

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 (50) hide show
  1. package/README.md +58 -22
  2. package/dist/choose.js +8 -4
  3. package/dist/code-hints.js +74 -0
  4. package/dist/commands/api.js +83 -44
  5. package/dist/commands/async.js +26 -5
  6. package/dist/commands/chat.js +177 -0
  7. package/dist/commands/docs.js +240 -37
  8. package/dist/commands/fmt.js +120 -0
  9. package/dist/commands/index.js +9 -1
  10. package/dist/commands/init.js +64 -30
  11. package/dist/commands/inventory.js +48 -5
  12. package/dist/commands/limits-set.js +9 -6
  13. package/dist/commands/loops.js +15 -9
  14. package/dist/commands/models.js +16 -7
  15. package/dist/commands/sandboxes.js +8 -4
  16. package/dist/commands/schema.js +361 -0
  17. package/dist/commands/session.js +148 -24
  18. package/dist/commands/setup.js +22 -6
  19. package/dist/commands/solution.js +537 -76
  20. package/dist/commands/tenants.js +156 -15
  21. package/dist/commands/values.js +18 -9
  22. package/dist/commands/work.js +343 -35
  23. package/dist/confirm-token.js +72 -0
  24. package/dist/contracts.js +3 -0
  25. package/dist/default-route.js +21 -0
  26. package/dist/errors.js +4 -0
  27. package/dist/git.js +14 -5
  28. package/dist/harness-ref.js +14 -1
  29. package/dist/http.js +27 -4
  30. package/dist/invoke.js +8 -4
  31. package/dist/kit-codes.js +91 -0
  32. package/dist/limits.js +12 -1
  33. package/dist/local-state.js +32 -7
  34. package/dist/main.js +52 -4
  35. package/dist/mcp.js +72 -15
  36. package/dist/openapi.js +77 -21
  37. package/dist/operations.js +4 -3
  38. package/dist/package-check.js +361 -12
  39. package/dist/package-files.js +92 -45
  40. package/dist/package-format.js +222 -0
  41. package/dist/package-references.js +298 -0
  42. package/dist/preview-report.js +152 -0
  43. package/dist/results.js +21 -1
  44. package/dist/skills/cavelon-authoring/SKILL.md +98 -13
  45. package/dist/skills/cavelon-long-running/SKILL.md +3 -1
  46. package/dist/skills/cavelon-loop/SKILL.md +129 -21
  47. package/dist/skills/cavelon-testing/SKILL.md +130 -10
  48. package/dist/tenant-choice.js +31 -5
  49. package/dist/trace-view.js +172 -0
  50. package/package.json +1 -1
@@ -4,21 +4,29 @@ import { CAPACITY_CONCEPT_PAGE, CAPACITY_TUTORIAL_PAGE, capacityCodeIn, capacity
4
4
  import { boolOption, intOption, positional, stringOption } from "../command.js";
5
5
  import { Contracts } from "../contracts.js";
6
6
  import { CavelonError, ExitCode, usageError } from "../errors.js";
7
+ import { drivenByAgent } from "../agent-env.js";
8
+ import { confirmation, confirmGiven, confirmTokenRequired, shellTokenRequired } from "../confirm-token.js";
7
9
  import { clip, keyValues } from "../format.js";
8
10
  import { readTextFile, writeFileAtomic } from "../fsutil.js";
9
11
  import { uncommitted } from "../git.js";
10
12
  import { callStable } from "../invoke.js";
11
- import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
13
+ import { harnessNotFoundError, lookupHarness, SLUG } from "../harness-ref.js";
14
+ import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefaultRoute } from "../default-route.js";
12
15
  import { ceilingHint, LIMIT_ABOVE_CEILING, parseLimits, readLimits } from "../limits.js";
13
- import { deletePreview, digest, fileDigest, listPreviews, loadPreview, readPulledFiles, savePreview, writePulledFiles, writeState, } from "../local-state.js";
16
+ import { deletePreview, digest, fileDigest, fileDigests, listPreviews, loadPreview, previewExpiry, readItemFiles, readPulledFiles, rememberAppliedFiles, savePreview, writePulledFiles, writeState, } from "../local-state.js";
14
17
  import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
18
+ import { cliFix, similarCodes } from "../code-hints.js";
19
+ import { KIT_ERROR_CODES } from "../kit-codes.js";
15
20
  import { pairOrderHint, pairOrderPointer } from "../pair-order.js";
16
- import { readPackage, writePackage } from "../package-files.js";
21
+ import { readPackage, tenantWideSections, writePackage } from "../package-files.js";
22
+ import { blockerDetails, blockerLines, changeLines, fieldChanges, locateBlockers, notApplied, notAppliedLines } from "../preview-report.js";
17
23
  import { readPrincipal } from "../principal.js";
18
24
  import { CASE_STATUSES, caseStatus, TESTING_PAGE } from "../results.js";
25
+ import { KNOWLEDGE_OUTCOME_AREA, KNOWLEDGE_OUTCOME_PAGE, KNOWLEDGE_OUTCOMES, knowledgeOutcome } from "../trace-view.js";
19
26
  import { isUuid, requireInstance } from "../session.js";
20
27
  import { listedPages } from "./docs.js";
21
- import { writeInventory } from "./inventory.js";
28
+ import { readInventory, readInventoryKinds, writeInventory } from "./inventory.js";
29
+ import { checkedBy, MODEL_UNKNOWN_CODE, missingInventory, REFERENCE_UNKNOWN_CODE } from "../package-references.js";
22
30
  import { cavelonCommand, shellWord } from "../shell.js";
23
31
  import { secretSetCommand, targetFlags, variableSetCommand } from "./values.js";
24
32
  const HARNESS_OPTION = { type: "string", value: "<harness>", description: "The solution (harness): its name, slug or id; default: env file, then cavelon.yaml." };
@@ -108,6 +116,7 @@ async function limitsFor(ctx, offline) {
108
116
  async function acceptedVersions(ctx, offline) {
109
117
  return (await capabilitiesFor(ctx, offline))?.contracts?.package_versions?.accepted;
110
118
  }
119
+ const BLOCKING_WARNINGS = new Set([REFERENCE_UNKNOWN_CODE, MODEL_UNKNOWN_CODE]);
111
120
  function findingLine(f) {
112
121
  const where = f.file ? `${f.file}${f.line ? `:${f.line}` : ""}` : "";
113
122
  const at = f.path ? ` ${f.path}` : "";
@@ -129,8 +138,17 @@ function uncommittedChanges(files, what) {
129
138
  details: { files },
130
139
  });
131
140
  }
132
- async function editedSincePull(project, pkg, schema) {
133
- const planned = await writePackage(project.root, project.layout, pkg, schema, { dryRun: true });
141
+ async function unknownStates(root, files, known) {
142
+ const out = [];
143
+ for (const file of files) {
144
+ const current = await fileDigest(path.join(root, file));
145
+ if (current === undefined || current !== known[file])
146
+ out.push(file);
147
+ }
148
+ return out;
149
+ }
150
+ async function editedSincePull(project, pkg, schema, options) {
151
+ const planned = await writePackage(project.root, project.layout, pkg, schema, { ...options, dryRun: true, placed: undefined });
134
152
  const pulled = await readPulledFiles(project.root);
135
153
  const edited = [];
136
154
  for (const file of [...planned.written, ...planned.removed]) {
@@ -144,25 +162,37 @@ export const pull = {
144
162
  name: "pull",
145
163
  summary: "Write the instance's package into package/ (split along the schema's sections) and the inventory into .cavelon/.",
146
164
  description: "With a solution (--harness, or cavelon.yaml's harness), exports that solution; without one, the tenant's full configuration.\n" +
147
- "A file whose content did not change keeps its bytes, so `git diff` shows what changed on the instance. Files of sections\n" +
148
- "the schema does not know are kept byte for byte. Refuses when package files have uncommitted changes, unless --force;\n" +
149
- "outside a git repository, when a file it would overwrite or remove changed since the last pull.",
165
+ "A file whose content did not change keeps its bytes, so `git diff` shows what changed on the instance; a field the export\n" +
166
+ "spells out that the file leaves out (an empty list, a default) is no change. A test suite goes back to the file it was\n" +
167
+ "pulled into or applied from, whatever its name. Files of sections the schema does not know are kept byte for byte.\n" +
168
+ "A solution's export leaves the tenant-wide sections (the tenant's settings, its model list) out of the folder, unless\n" +
169
+ "--tenant-wide. Refuses when package files have uncommitted changes, unless --force;\n" +
170
+ "outside a git repository, when a file it would overwrite or remove changed since the last pull. A file as the last pull\n" +
171
+ "or apply left it (digests in .cavelon/) counts as unchanged, committed or not.",
150
172
  readOnly: false,
151
173
  destructive: true,
174
+ mcpEffect: "Reads the instance and changes nothing there. Writes the package files and .cavelon/ in the solution folder; refuses to " +
175
+ "overwrite or remove a package file that changed since the last pull or apply and is not committed, unless force.",
152
176
  idempotent: true,
153
177
  mcpTool: "pull",
154
178
  options: {
155
179
  harness: { type: "string", value: "<harness>", description: "The solution to export, by name, slug or id; its slug is recorded in cavelon.yaml when it names none." },
156
- force: { type: "boolean", description: "Overwrite package files that have uncommitted changes (outside git: changes since the last pull)." },
180
+ force: { type: "boolean", description: "Overwrite package files that have uncommitted changes since the last pull or apply." },
181
+ "tenant-wide": {
182
+ type: "boolean",
183
+ description: "With a solution, also write the tenant-wide sections its export carries (tenant_settings, model_registry): apply then sends them for the whole tenant.",
184
+ },
157
185
  },
158
- examples: ["cavelon pull --harness support", "cavelon pull && git diff -- package tests"],
186
+ examples: ["cavelon pull --harness support", "cavelon pull && git status --short -- package tests"],
159
187
  async run(ctx, input) {
160
188
  const session = await ctx.session();
161
189
  const project = requireSolution(session);
162
190
  const url = requireInstance(session);
163
191
  const layoutDirs = [project.layout.package, ...Object.values(project.layout.items)];
164
192
  const force = boolOption(input, "force");
165
- const dirty = force ? [] : (await uncommitted(project.root, layoutDirs))?.filter((f) => /\.(ya?ml|json)"?$/i.test(f));
193
+ const known = force ? {} : await readPulledFiles(project.root);
194
+ const changed = force ? [] : (await uncommitted(project.root, layoutDirs))?.filter((f) => /\.(ya?ml|json)$/i.test(f));
195
+ const dirty = changed && (await unknownStates(project.root, changed, known));
166
196
  if (dirty?.length)
167
197
  throw uncommittedChanges(dirty, "pull would overwrite uncommitted changes");
168
198
  const { ref } = harnessRef(session, input);
@@ -182,14 +212,17 @@ export const pull = {
182
212
  const { schema } = await schemaFor(ctx, version, false);
183
213
  if (!schema)
184
214
  ctx.warn("The instance does not publish its package schema; every top-level key became a file of its own.");
215
+ const skip = harness && !boolOption(input, "tenant-wide") ? tenantWideSections(schema) : new Set();
216
+ const placed = {};
217
+ const options = { skip, itemFiles: await readItemFiles(project.root), placed };
185
218
  if (dirty === undefined) {
186
- const edited = await editedSincePull(project, exported, schema);
219
+ const edited = await editedSincePull(project, exported, schema, options);
187
220
  if (edited.length) {
188
221
  throw uncommittedChanges(edited, "This folder is not in a git repository, and pull would overwrite or remove files that changed since the last pull");
189
222
  }
190
223
  }
191
- const report = await writePackage(project.root, project.layout, exported, schema);
192
- await writePulledFiles(project.root, [...report.written, ...report.unchanged]);
224
+ const report = await writePackage(project.root, project.layout, exported, schema, options);
225
+ await writePulledFiles(project.root, [...report.written, ...report.unchanged], placed);
193
226
  if (harness && !project.harness)
194
227
  await setProjectKey(project, "harness", harness.slug);
195
228
  if (version && project.packageVersion !== version)
@@ -210,7 +243,13 @@ export const pull = {
210
243
  ctx.warn(`Kept ${file}: its section is not in this instance's package schema.`);
211
244
  for (const section of report.refused)
212
245
  ctx.warn(`Did not write section ${JSON.stringify(section)}: its name is not a plain file name.`);
213
- const changed = report.written.length + report.removed.length;
246
+ const tenantFiles = report.tenant_wide.flatMap((section) => [".yaml", ".yml", ".json"].map((ext) => `${project.layout.package}/${section}${ext}`));
247
+ for (const file of tenantFiles) {
248
+ if ((await readTextFile(path.join(project.root, file))) === undefined)
249
+ continue;
250
+ ctx.warn(`Kept ${file} as it is: it holds a tenant-wide section, which pull leaves out of a solution's folder. apply sends it for the whole tenant; remove the file unless you mean that.`);
251
+ }
252
+ const rewritten = report.written.length + report.removed.length;
214
253
  const lines = [
215
254
  `Pulled ${harness ? `solution ${harness.name} (${harness.slug})` : "the tenant's full configuration"} into ${project.layout.package}/` +
216
255
  (Object.keys(project.layout.items).length ? ` and ${Object.values(project.layout.items).join("/, ")}/` : "") +
@@ -218,12 +257,36 @@ export const pull = {
218
257
  ...report.written.map((f) => `written ${f}`),
219
258
  ...report.removed.map((f) => `removed ${f}`),
220
259
  `${report.unchanged.length} file${report.unchanged.length === 1 ? "" : "s"} unchanged.`,
260
+ ...(report.tenant_wide.length
261
+ ? [`Left out the tenant-wide section${report.tenant_wide.length === 1 ? "" : "s"} ${report.tenant_wide.join(", ")} (--tenant-wide writes them).`]
262
+ : []),
221
263
  `Inventory: ${inventory.file} (${inventory.counts.map((c) => `${c.count} ${c.label}`).join(", ")})`,
222
- changed ? `See what changed: git diff -- ${layoutDirs.join(" ")}` : "Nothing changed on the instance since the last pull.",
264
+ !rewritten
265
+ ? "Nothing changed on the instance since the last pull."
266
+ : dirty === undefined
267
+ ? "See what changed: the files listed above (this folder is not in a git repository)."
268
+ : `See what changed: git status --short -- ${layoutDirs.join(" ")} (new files), then git diff -- ${layoutDirs.join(" ")}`,
223
269
  ];
224
270
  return { data: { ...record, inventory }, text: lines.join("\n") };
225
271
  },
226
272
  };
273
+ async function inventoryFor(ctx, project, disk, offline) {
274
+ let inventory = await readInventory(project.root);
275
+ const missing = missingInventory(disk, inventory);
276
+ let failed = missing;
277
+ if (missing.length && !offline) {
278
+ failed = await readInventoryKinds(ctx, project.root, missing, ctx.io.now());
279
+ inventory = await readInventory(project.root);
280
+ }
281
+ const skipped = failed.map((kind) => ({
282
+ check: checkedBy(kind),
283
+ kind,
284
+ reason: offline
285
+ ? `--offline, and no list of the tenant's ${kind.replace("_", " ")} is cached; \`cavelon ${kind === "models" ? "models list" : "pull"}\` reads it`
286
+ : `the tenant's ${kind.replace("_", " ")} could not be read`,
287
+ }));
288
+ return { inventory, skipped };
289
+ }
227
290
  async function validatePackage(ctx, project, offline) {
228
291
  const disk = await readPackage(project.root, project.layout);
229
292
  const version = packageVersionOf(disk.package) ?? project.packageVersion;
@@ -237,13 +300,16 @@ async function validatePackage(ctx, project, offline) {
237
300
  : "The instance does not publish its package schema (/api/v1/meta/package-schema).",
238
301
  });
239
302
  }
303
+ const { inventory, skipped } = await inventoryFor(ctx, project, disk, offline);
240
304
  const findings = checkPackage(disk, {
241
305
  schema,
242
306
  catalog: await catalogFor(ctx, offline),
243
307
  accepted: await acceptedVersions(ctx, offline),
244
308
  limits: await limitsFor(ctx, offline),
309
+ inventory,
310
+ solution: project.harness,
245
311
  });
246
- return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null, used };
312
+ return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null, used, skipped };
247
313
  }
248
314
  function schemaUsedLine(used, ttlSeconds) {
249
315
  const from = used.source === "instance" ? "read from the instance now" : `cached at ${used.fetched_at ?? "an unknown time"}`;
@@ -266,10 +332,16 @@ export const validate = {
266
332
  "sent with it; --verbose says which copy was used.\n" +
267
333
  "Warns (never fails) when a fan-out or Map loop's max_concurrency is above the instance's branch width, and when the\n" +
268
334
  "tenant runs fan-outs and Map loops in sequence, from the limits the instance last published.\n" +
335
+ "References to skills, tools, knowledge bases, solutions and models outside the package are checked against the tenant's\n" +
336
+ "lists in .cavelon/inventory.json (pull, models list); a list no command has read yet is read now, unless --offline, and a\n" +
337
+ "check that cannot be made is named (`skipped` in --json). A reference that is in neither is a warning, as it may be created\n" +
338
+ "on the instance before the import; the import preview blocks it otherwise, so validate does not say \"Valid\" then, and\n" +
339
+ "--strict fails on every warning (exit 3).\n" +
269
340
  "Each finding carries a code: `cavelon explain <code>` says more. The import preview checks everything again on the server.\n\n" +
270
341
  "With --json, `warnings` is always a list of `{code, message}` objects: the warning findings (at most --limit), then the\n" +
271
342
  "warnings about the run, such as a stale copy of the schema, with code null. `warning_count` counts them all and\n" +
272
- "`error_count` the errors (`errors` is the same number); `findings` has each finding's file, line and hint.",
343
+ "`error_count` the errors (`errors` is the same number); `findings` has each finding's file, line and hint; `blocking_count`\n" +
344
+ "counts the warnings the import preview blocks on.",
273
345
  readOnly: true,
274
346
  idempotent: true,
275
347
  mcpTool: "validate",
@@ -277,15 +349,19 @@ export const validate = {
277
349
  offline: { type: "boolean", description: "Never contact the instance, even when nothing is cached." },
278
350
  limit: { type: "string", value: "<n>", description: "Print at most n findings (default 50)." },
279
351
  verbose: { type: "boolean", description: "Also say which copy of the package schema was used: cached or read now, when, and its hash." },
352
+ strict: { type: "boolean", description: "Fail (exit 3) on warnings too, such as a reference the import preview will block unless it exists by then." },
280
353
  },
281
354
  async run(ctx, input) {
282
355
  const session = await ctx.session();
283
356
  const project = requireSolution(session);
284
357
  requireInstance(session);
285
358
  const limit = intOption(input, "limit", { min: 1, max: 1000, fallback: 50 });
286
- const { disk, findings, schemaVersion, used } = await validatePackage(ctx, project, boolOption(input, "offline"));
359
+ const strict = boolOption(input, "strict");
360
+ const { disk, findings, schemaVersion, used, skipped } = await validatePackage(ctx, project, boolOption(input, "offline"));
287
361
  const errors = findings.filter((f) => f.severity === "error");
288
362
  const warnings = findings.filter((f) => f.severity === "warning");
363
+ const blocking = warnings.filter((f) => BLOCKING_WARNINGS.has(f.code));
364
+ const failed = errors.length > 0 || (strict && warnings.length > 0);
289
365
  if (disk.empty)
290
366
  ctx.warn(`No package files in ${project.layout.package}/ yet; \`cavelon pull\` brings an existing solution.`);
291
367
  const contracts = await ctx.contracts();
@@ -295,26 +371,37 @@ export const validate = {
295
371
  ...ctx.warnings.map((message) => ({ code: null, message })),
296
372
  ];
297
373
  const data = {
298
- valid: errors.length === 0,
374
+ valid: !failed,
375
+ strict,
299
376
  schema_version: schemaVersion,
300
377
  schema: used,
301
378
  sections: Object.keys(disk.package).length,
302
379
  error_count: errors.length,
303
380
  warning_count: warnings.length + ctx.warnings.length,
381
+ blocking_count: blocking.length,
304
382
  errors: errors.length,
305
383
  warnings: listed,
306
384
  findings: shown,
307
385
  more: Math.max(0, findings.length - shown.length),
386
+ skipped,
308
387
  };
388
+ const counts = `${errors.length} error${errors.length === 1 ? "" : "s"}, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}`;
389
+ const verdict = errors.length
390
+ ? `${counts}. \`cavelon explain <code>\` says more.`
391
+ : strict && warnings.length
392
+ ? `${counts}; --strict fails on warnings. \`cavelon explain <code>\` says more.`
393
+ : blocking.length
394
+ ? `No errors against package schema ${schemaVersion ?? "?"} (${data.sections} sections), but ${blocking.length === 1 ? "one reference" : `${blocking.length} references`} ` +
395
+ `the import preview will block unless ${blocking.length === 1 ? "it exists" : "they exist"} on the instance by then (${counts}; --strict fails on warnings).`
396
+ : `Valid against package schema ${schemaVersion ?? "?"} (${data.sections} sections${warnings.length ? `, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}` : ""}).`;
309
397
  const text = [
310
398
  ...(boolOption(input, "verbose") ? [schemaUsedLine(used, (v) => contracts.ttlSeconds(v))] : []),
311
399
  ...shown.map(findingLine),
312
400
  ...(data.more ? [`… and ${data.more} more (--limit).`] : []),
313
- errors.length
314
- ? `${errors.length} error${errors.length === 1 ? "" : "s"}, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}. \`cavelon explain <code>\` says more.`
315
- : `Valid against package schema ${schemaVersion ?? "?"} (${data.sections} sections${warnings.length ? `, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}` : ""}).`,
401
+ ...skipped.map((s) => `Not checked: ${s.check} (${s.reason}).`),
402
+ verdict,
316
403
  ].join("\n");
317
- return { data, text, exitCode: errors.length ? ExitCode.validation : ExitCode.ok };
404
+ return { data, text, exitCode: failed ? ExitCode.validation : ExitCode.ok };
318
405
  },
319
406
  };
320
407
  function valueNeeds(list) {
@@ -365,7 +452,7 @@ function needsLines(needs, flags) {
365
452
  lines.push(["needs identities", triggers.map((t) => `\n - ${t}`).join("")]);
366
453
  return lines;
367
454
  }
368
- export function previewText(p, flags = "") {
455
+ export function previewText(p, flags = "", context = {}) {
369
456
  const lines = [["ready", p.ready ? "yes" : "no"]];
370
457
  const s = p.summary ?? {};
371
458
  for (const [label, map] of [["creates", s.creates], ["updates", s.updates], ["deletes", s.deletes]]) {
@@ -375,13 +462,22 @@ export function previewText(p, flags = "") {
375
462
  }
376
463
  if (lines.length === 1)
377
464
  lines.push(["changes", "none"]);
378
- if (p.blockers?.length)
465
+ const changes = fieldChanges(p.changes);
466
+ if (changes.length)
467
+ lines.push(["field changes", changeLines(changes)]);
468
+ const details = blockerDetails(p.blocker_details, context.disk);
469
+ if (details.length)
470
+ lines.push(["blockers", blockerLines(details)]);
471
+ else if (p.blockers?.length)
379
472
  lines.push(["blockers", p.blockers.map((b) => `\n - ${clip(b, 300)}`).join("")]);
380
473
  if (p.warnings?.length)
381
474
  lines.push(["warnings", p.warnings.slice(0, 10).map((w) => `\n - ${clip(w, 300)}`).join("") + (p.warnings.length > 10 ? `\n … ${p.warnings.length - 10} more` : "")]);
382
475
  const ignored = [...(p.ignored?.sections ?? []), ...(p.ignored?.fields ?? [])];
383
476
  if (ignored.length)
384
477
  lines.push(["ignored", list(ignored)]);
478
+ const skipped = notApplied(p.ignored?.not_applied, context.disk?.package, context.harness);
479
+ if (skipped.length)
480
+ lines.push(["not applied", notAppliedLines(skipped)]);
385
481
  const impact = p.impact ?? {};
386
482
  const active = (impact.active_harnesses ?? []).map((h) => {
387
483
  const via = [...(h.tools ?? []), ...(h.knowledge_bases ?? []), ...(h.sandboxes ?? [])];
@@ -398,22 +494,111 @@ export function previewText(p, flags = "") {
398
494
  lines.push(...needsLines(p.target_needs ?? {}, flags));
399
495
  return keyValues(lines);
400
496
  }
497
+ function previewReport(p, context) {
498
+ const out = {};
499
+ const details = blockerDetails(p.blocker_details, context.disk);
500
+ if (details.length)
501
+ out.blocker_details = details;
502
+ const changes = fieldChanges(p.changes);
503
+ if (changes.length)
504
+ out.field_changes = changes;
505
+ const skipped = notApplied(p.ignored?.not_applied, context.disk?.package, context.harness);
506
+ if (skipped.length)
507
+ out.not_applied = skipped;
508
+ return out;
509
+ }
510
+ function sourceFiles(disk) {
511
+ return Object.values(disk.sources).flatMap((source) => (Array.isArray(source) ? source : [source]).map((s) => s.file));
512
+ }
401
513
  function previewIdOption(input) {
402
514
  const id = stringOption(input, "confirm");
403
515
  if (id !== undefined && !id.trim())
404
516
  throw usageError("--confirm needs the preview id that `cavelon apply` printed.");
405
517
  return id?.trim();
406
518
  }
407
- async function confirmPreview(ctx, project, previewId) {
519
+ function previewUnknown(previewId) {
520
+ return new CavelonError(ExitCode.usage, {
521
+ code: "preview_unknown",
522
+ message: `No open preview ${previewId} in this solution.`,
523
+ hint: "Run `cavelon apply` (with the same --env or --harness) for a new preview and confirm its id; `cavelon status` lists the open ones.",
524
+ });
525
+ }
526
+ async function discardPreviews(ctx, project, which) {
527
+ const open = await listPreviews(project.root, ctx.io.now());
528
+ const chosen = which === "all" ? open : open.filter((p) => p.preview_id === which);
529
+ if (which !== "all" && chosen.length === 0)
530
+ throw previewUnknown(which);
531
+ for (const p of chosen)
532
+ await deletePreview(project.root, p.preview_id);
533
+ const ids = chosen.map((p) => p.preview_id);
534
+ return {
535
+ data: { discarded: ids, count: ids.length },
536
+ text: ids.length ? `Discarded ${ids.length === 1 ? "preview" : `${ids.length} previews`}: ${ids.join(", ")}. Nothing changed on the instance.` : "No open previews to discard.",
537
+ };
538
+ }
539
+ async function filesChangedSince(project, stored, disk) {
540
+ if (!stored.file_digests)
541
+ return [];
542
+ const previewed = stored.file_digests;
543
+ const now = await fileDigests(project.root, sourceFiles(disk));
544
+ const files = new Set([...Object.keys(previewed), ...Object.keys(now)]);
545
+ return [...files].filter((file) => previewed[file] !== now[file]).sort((a, b) => a.localeCompare(b, "en"));
546
+ }
547
+ async function rememberImported(ctx, project, stored, disk, changed) {
548
+ if (!stored.file_digests)
549
+ return;
550
+ const now = await fileDigests(project.root, sourceFiles(disk));
551
+ const known = {};
552
+ for (const [file, value] of Object.entries(stored.file_digests))
553
+ if (now[file] === value)
554
+ known[file] = value;
555
+ if (!changed.length)
556
+ return rememberAppliedFiles(project.root, known);
557
+ const holds = await instanceHolds(ctx, project, stored).catch((error) => {
558
+ ctx.warn(`Could not read what the instance holds after the import (${error instanceof Error ? error.message : String(error)}); pull treats ${changed.join(", ")} as local changes.`);
559
+ return undefined;
560
+ });
561
+ const unknown = [];
562
+ for (const file of changed) {
563
+ if (holds?.has(file) && now[file])
564
+ known[file] = now[file];
565
+ else
566
+ unknown.push(file);
567
+ }
568
+ await rememberAppliedFiles(project.root, known, unknown);
569
+ }
570
+ async function instanceHolds(ctx, project, stored) {
571
+ const harnessId = stored.request.harness_id;
572
+ const scope = harnessId ? "agent_graph" : stored.request.package.manifest?.scope;
573
+ if (scope !== "agent_graph" && scope !== "full_config")
574
+ return undefined;
575
+ if (scope === "agent_graph" && !harnessId)
576
+ return undefined;
577
+ const exported = await callStable(ctx, "GET", "/api/v1/agent-graph/export", "exporting packages", {
578
+ query: { scope, harness_id: harnessId },
579
+ timeoutMs: 120_000,
580
+ });
581
+ if (!exported || typeof exported !== "object" || Array.isArray(exported))
582
+ return undefined;
583
+ const { schema } = await schemaFor(ctx, packageVersionOf(exported), false);
584
+ const planned = await writePackage(project.root, project.layout, exported, schema, { dryRun: true });
585
+ return new Set(planned.unchanged);
586
+ }
587
+ async function confirmPreview(ctx, project, previewId, allowStale) {
408
588
  const stored = await loadPreview(project.root, previewId);
409
- if (!stored) {
410
- throw new CavelonError(ExitCode.usage, {
411
- code: "preview_unknown",
412
- message: `No open preview ${previewId} in this solution.`,
413
- hint: "Run `cavelon apply` (with the same --env or --harness) for a new preview and confirm its id; `cavelon status` lists the open ones.",
589
+ if (!stored)
590
+ throw previewUnknown(previewId);
591
+ const session = await ctx.session();
592
+ const expiry = previewExpiry(stored.created_at, ctx.io.now());
593
+ if (expiry.expired) {
594
+ await deletePreview(project.root, stored.preview_id);
595
+ throw new CavelonError(ExitCode.conflict, {
596
+ code: "preview_expired",
597
+ message: `Preview ${previewId} was made at ${stored.created_at} and expired${expiry.expires_at ? ` at ${expiry.expires_at}` : ""}; nothing was imported.`,
598
+ hint: `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
599
+ details: { preview_id: stored.preview_id, created_at: stored.created_at, expires_at: expiry.expires_at },
414
600
  });
415
601
  }
416
- const session = await ctx.session();
417
602
  if (requireInstance(session) !== stored.instance) {
418
603
  throw new CavelonError(ExitCode.conflict, {
419
604
  code: "preview_other_instance",
@@ -432,16 +617,28 @@ async function confirmPreview(ctx, project, previewId) {
432
617
  if (stored.tenant_id && session.tokenKind !== "api_key")
433
618
  client.target.tenantId = stored.tenant_id;
434
619
  const disk = await readPackage(project.root, project.layout);
620
+ const changed = await filesChangedSince(project, stored, disk);
435
621
  if (digest(disk.package) !== stored.package_digest) {
436
- ctx.warn("The package files changed since this preview; importing what the preview showed. Run `cavelon apply` to preview the files as they are now.");
622
+ if (!allowStale) {
623
+ throw new CavelonError(ExitCode.conflict, {
624
+ code: "preview_files_changed",
625
+ message: `The package files changed since preview ${previewId}${changed.length ? ` (${list(changed, 5)})` : ""}; nothing was imported.`,
626
+ hint: `Run \`${previewAgain(stored, session)}\` for a preview of the files as they are now, show it, and confirm its id. ` +
627
+ `To import what preview ${previewId} showed instead, add --allow-stale to the confirm.`,
628
+ details: { preview_id: stored.preview_id, files: changed },
629
+ });
630
+ }
631
+ ctx.warn(`The package files changed since this preview${changed.length ? ` (${list(changed, 5)})` : ""}; importing what the preview showed (--allow-stale). ` +
632
+ "The files keep their changes, which the instance does not hold; run `cavelon apply` to preview them.");
437
633
  }
438
634
  try {
439
635
  const result = await callStable(ctx, "POST", "/api/v1/agent-graph/import", "importing packages", {
440
636
  body: { ...stored.request, preview_id: stored.preview_id },
441
637
  timeoutMs: 300_000,
442
638
  });
443
- for (const other of await listPreviews(project.root))
639
+ for (const other of await listPreviews(project.root, ctx.io.now()))
444
640
  await deletePreview(project.root, other.preview_id);
641
+ await rememberImported(ctx, project, stored, disk, changed);
445
642
  const summary = (result.summary ?? {});
446
643
  const flags = targetFlags(session, stored.env ?? session.envFile?.name);
447
644
  const still = setCommands(stored.preview, flags);
@@ -460,10 +657,12 @@ async function confirmPreview(ctx, project, previewId) {
460
657
  return { data, text };
461
658
  }
462
659
  catch (error) {
463
- if (error instanceof CavelonError && error.code === REQUIREMENTS_CHANGED && error.blockers?.length) {
660
+ if (error instanceof CavelonError && error.code === REQUIREMENTS_CHANGED && (error.blockers?.length || error.blockerDetails?.length)) {
464
661
  await deletePreview(project.root, stored.preview_id);
465
- throw requirementsChanged(error, stored, session, await catalogFor(ctx, false));
662
+ throw requirementsChanged(error, stored, session, await catalogFor(ctx, false), disk);
466
663
  }
664
+ if (error instanceof CavelonError && error.blockerDetails?.length)
665
+ throw withBlockersLocated(error, disk, stored, session);
467
666
  if (error instanceof CavelonError && (error.code === "import_preview_stale" || (error.status === 409 && /preview/i.test(error.message)))) {
468
667
  await deletePreview(project.root, stored.preview_id);
469
668
  throw new CavelonError(ExitCode.conflict, {
@@ -478,8 +677,9 @@ async function confirmPreview(ctx, project, previewId) {
478
677
  }
479
678
  }
480
679
  const REQUIREMENTS_CHANGED = "package_requirements_changed";
481
- function requirementsChanged(error, stored, session, catalog) {
482
- const blockers = error.blockers ?? [];
680
+ function requirementsChanged(error, stored, session, catalog, disk) {
681
+ const details = locateBlockers(error.blockerDetails ?? [], disk);
682
+ const blockers = error.blockers?.length ? error.blockers : details.map((b) => b.message);
483
683
  const known = new Map();
484
684
  for (const blocker of blockers) {
485
685
  const pair = pairOrderHint(catalog, [blocker]);
@@ -493,6 +693,19 @@ function requirementsChanged(error, stored, session, catalog) {
493
693
  hint: [...known.values(), `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`].join(" "),
494
694
  docs: error.docs,
495
695
  blockers,
696
+ blockerDetails: details.length ? details : undefined,
697
+ });
698
+ }
699
+ function withBlockersLocated(error, disk, stored, session) {
700
+ return new CavelonError(error.exitCode, {
701
+ code: error.code,
702
+ message: `The import's own check refused preview ${stored.preview_id} when it applied; nothing was imported.`,
703
+ hint: error.hint ?? `Fix what each blocker names, run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
704
+ docs: error.docs,
705
+ status: error.status,
706
+ details: error.details,
707
+ blockers: error.blockers,
708
+ blockerDetails: locateBlockers(error.blockerDetails ?? [], disk),
496
709
  });
497
710
  }
498
711
  function previewAgain(stored, session) {
@@ -505,22 +718,31 @@ async function applyTarget(ctx, session, input, pkg) {
505
718
  return undefined;
506
719
  const { harness: found, candidates } = await lookupHarness(ctx, ref);
507
720
  if (found)
508
- return { ...found, created: false };
509
- if (!source?.startsWith("env/") || isUuid(ref))
721
+ return found;
722
+ if (!source || source === "option" || isUuid(ref) || !SLUG.test(ref))
510
723
  throw harnessNotFoundError(ref, candidates, source);
511
724
  const name = packageHarnessName(pkg, ref) ?? ref;
512
- const created = await callStable(ctx, "POST", "/api/v1/harnesses", "creating solutions", { body: { slug: ref, name } });
513
- ctx.warn(`Created the draft solution ${created.name} (${created.slug}) that ${source} names.`);
514
- return { ...created, created: true };
725
+ const create = cavelonCommand("harness", "new", ref, ...(name !== ref ? ["--name", name] : []));
726
+ throw new CavelonError(ExitCode.failure, {
727
+ code: "solution_not_found",
728
+ message: `Solution ${ref}, which ${source} names, is not on the instance yet; apply previews into an existing solution and creates none.`,
729
+ hint: `Create it as a draft: ${create}, then run \`${cavelonCommand("apply")}${targetFlags(session)}\` again.`,
730
+ details: { slug: ref, name, create },
731
+ });
515
732
  }
516
733
  function packageHarnessName(pkg, slug) {
517
734
  const entries = (Array.isArray(pkg.harnesses) ? pkg.harnesses : []).filter((h) => Boolean(h) && typeof h === "object" && !Array.isArray(h));
518
- const entry = entries.find((h) => h.slug === slug) ?? (entries.length === 1 ? entries[0] : undefined);
735
+ const entry = entries.find((h) => h.slug === slug);
519
736
  const name = typeof entry?.name === "string" ? entry.name.trim() : "";
520
737
  return name ? name.slice(0, 255) : undefined;
521
738
  }
522
739
  function personReason(preview, harness, mode, env) {
523
- if (preview.impact?.active_harnesses?.length || harness?.status === "active")
740
+ const active = (preview.impact?.active_harnesses ?? []).map((h) => h.harness_slug ?? h.name).filter((n) => Boolean(n));
741
+ if (harness?.status === "active" && !active.includes(harness.slug))
742
+ active.unshift(harness.slug);
743
+ if (active.length)
744
+ return `reaches the active solution${active.length === 1 ? "" : "s"} ${list(active, 5)}`;
745
+ if (preview.impact?.active_harnesses?.length)
524
746
  return "reaches an active solution";
525
747
  if (counts(preview.summary?.deletes) || mode === "replace")
526
748
  return "deletes";
@@ -533,10 +755,14 @@ export const apply = {
533
755
  summary: "Preview the package files against the instance and print a preview id; --confirm <id> imports exactly that preview.",
534
756
  description: "Without --confirm nothing is imported: the preview shows what changes, which active solutions it reaches, what the target\n" +
535
757
  "still needs (secrets and variables with the command that sets each, grants, runtime bindings, trigger identities), loop\n" +
536
- "budgets and ignored sections, and is stored in .cavelon/. When the env file names a solution that does not exist yet,\n" +
537
- "apply creates it as a draft first. A person sets the secrets (`cavelon secrets set <name>`), never the agent.\n" +
538
- "Show a preview that reaches an active solution or env/prod to a person before confirming. A stale preview exits 4;\n" +
539
- "so does an import its own check refuses when it applies, naming each blocker.",
758
+ "budgets and ignored sections, and is stored in .cavelon/. A preview never creates the solution: one the env file names\n" +
759
+ "that is not on the instance yet gets the `cavelon harness new` command that creates it as a draft. A person sets the\n" +
760
+ "secrets (`cavelon secrets set <name>`), never the agent.\n" +
761
+ "Show a preview that reaches an active solution or env/prod to a person before confirming. A stale preview exits 4 and\n" +
762
+ "imports nothing: one whose target changed on the instance since, one whose package files changed since (what they\n" +
763
+ "hold, not their formatting; --allow-stale imports what the preview showed anyway), and one older than a day. So does\n" +
764
+ "an import its own check refuses when it applies, naming each blocker. --discard <id|all> forgets stored previews;\n" +
765
+ "`cavelon status` lists them with when each expires.",
540
766
  readOnly: false,
541
767
  destructive: true,
542
768
  mcpTool: "apply",
@@ -544,16 +770,32 @@ export const apply = {
544
770
  env: ENV_OPTION,
545
771
  harness: HARNESS_OPTION,
546
772
  confirm: { type: "string", value: "<preview-id>", description: "Import exactly this stored preview." },
773
+ "allow-stale": {
774
+ type: "boolean",
775
+ description: "With --confirm: import what the preview showed although the package files changed since it.",
776
+ },
777
+ discard: { type: "string", value: "<preview-id|all>", description: "Forget this stored preview, or all of them; changes nothing on the instance." },
547
778
  mode: { type: "string", value: "<mode>", description: "overwrite (default) or replace (deletes what the package does not hold)." },
548
779
  },
549
- examples: ["cavelon apply --env test", "cavelon apply --confirm <preview-id>", "cavelon apply --env prod --json"],
780
+ examples: ["cavelon apply --env test", "cavelon apply --confirm <preview-id>", "cavelon apply --env prod --json", "cavelon apply --discard all"],
550
781
  async run(ctx, input) {
551
782
  const session = await ctx.session();
552
783
  const project = requireSolution(session);
553
784
  const url = requireInstance(session);
554
785
  const confirm = previewIdOption(input);
786
+ const discard = stringOption(input, "discard")?.trim();
787
+ const allowStale = boolOption(input, "allow-stale");
788
+ if (discard !== undefined && confirm)
789
+ throw usageError("Pass --confirm or --discard, not both.");
790
+ if (allowStale && !confirm)
791
+ throw usageError("--allow-stale only applies to --confirm <preview-id>.");
792
+ if (discard !== undefined) {
793
+ if (!discard)
794
+ throw usageError("--discard needs a preview id, or all.", "`cavelon status` lists the open previews.");
795
+ return discardPreviews(ctx, project, discard);
796
+ }
555
797
  if (confirm)
556
- return confirmPreview(ctx, project, confirm);
798
+ return confirmPreview(ctx, project, confirm, allowStale);
557
799
  const envFile = session.envFile;
558
800
  if (envFile?.tenant && session.tenantSource !== `env/${envFile.name}.yaml`) {
559
801
  ctx.warn(`${session.tenantSource} names tenant "${session.tenant}" and takes precedence over ${envFile.name}.yaml's "${envFile.tenant}".`);
@@ -586,23 +828,25 @@ export const apply = {
586
828
  body: request,
587
829
  timeoutMs: 120_000,
588
830
  });
589
- const target = harness ? { id: harness.id, slug: harness.slug, created: harness.created } : null;
831
+ const target = harness ? { id: harness.id, slug: harness.slug } : null;
590
832
  const data = { previewed: true, ...preview, env: envFile?.name ?? null, harness: target };
591
833
  const flags = targetFlags(session);
592
834
  const commands = setCommands(preview, flags);
593
835
  if (commands.secrets.length || commands.variables.length)
594
836
  data.set_commands = commands;
595
- if (!preview.preview_id) {
596
- ctx.warn("This instance's preview returns no preview id, so `apply --confirm` cannot import exactly it; update the instance.");
597
- }
837
+ const context = { disk, harness: harness?.slug };
838
+ Object.assign(data, previewReport(preview, context));
598
839
  if (!preview.ready) {
599
- const pair = pairOrderHint(await catalogFor(ctx, false), preview.blockers ?? []);
840
+ const pair = pairOrderHint(await catalogFor(ctx, false), [
841
+ ...(preview.blockers ?? []),
842
+ ...blockerDetails(preview.blocker_details).map((b) => `${b.code ?? ""}: ${b.message}`),
843
+ ]);
600
844
  if (pair)
601
845
  data.hint = pair.hint;
602
846
  return {
603
847
  data,
604
848
  text: [
605
- previewText(preview, flags),
849
+ previewText(preview, flags, context),
606
850
  "",
607
851
  ...(pair ? [`hint: ${pair.hint}`] : []),
608
852
  "The preview has blockers; fix them and run `cavelon apply` again.",
@@ -610,6 +854,9 @@ export const apply = {
610
854
  exitCode: ExitCode.validation,
611
855
  };
612
856
  }
857
+ if (!preview.preview_id) {
858
+ ctx.warn("This instance's preview returns no preview id, so `apply --confirm` cannot import exactly it; update the instance.");
859
+ }
613
860
  if (preview.preview_id) {
614
861
  const stored = {
615
862
  preview_id: preview.preview_id,
@@ -619,17 +866,21 @@ export const apply = {
619
866
  env: envFile?.name ?? null,
620
867
  harness: target,
621
868
  package_digest: digest(disk.package),
869
+ file_digests: await fileDigests(project.root, sourceFiles(disk)),
622
870
  request,
623
871
  preview,
624
872
  };
625
873
  await savePreview(project.root, stored);
874
+ for (const old of await listPreviews(project.root, ctx.io.now()))
875
+ if (old.expired)
876
+ await deletePreview(project.root, old.preview_id);
626
877
  }
627
878
  const reason = personReason(preview, harness, mode, envFile?.name);
628
879
  data.show_to_person = Boolean(reason);
629
880
  const confirmLine = preview.preview_id ? `${cavelonCommand("apply", "--confirm", preview.preview_id)}${flags}` : undefined;
630
881
  const text = [
631
882
  `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
632
- previewText(preview, flags),
883
+ previewText(preview, flags, context),
633
884
  "",
634
885
  ...(preview.preview_id ? [`preview id: ${preview.preview_id}`] : []),
635
886
  ...(reason ? [`This ${reason}: show this preview to a person before confirming.`] : []),
@@ -682,11 +933,42 @@ async function caseStatusAnswer(ctx, status) {
682
933
  ]),
683
934
  };
684
935
  }
936
+ async function knowledgeOutcomeAnswer(ctx, outcome) {
937
+ const instance = (await ctx.session().catch(() => undefined))?.url;
938
+ const page = `/docs/${KNOWLEDGE_OUTCOME_PAGE}`;
939
+ const data = {
940
+ code: outcome.value,
941
+ kind: "knowledge_outcome",
942
+ message: outcome.message,
943
+ hint: outcome.hint,
944
+ ...(outcome.recorded_as ? { recorded_as: outcome.recorded_as } : {}),
945
+ docs: instance ? `${instance}${page}` : page,
946
+ read: [{ page: KNOWLEDGE_OUTCOME_PAGE, command: cavelonCommand("docs", "get", KNOWLEDGE_OUTCOME_PAGE) }],
947
+ };
948
+ return {
949
+ data,
950
+ text: keyValues([
951
+ ["code", outcome.value],
952
+ ["kind", OUTCOME_KIND],
953
+ ["meaning", outcome.message],
954
+ ["next", outcome.hint],
955
+ ["recorded as", outcome.recorded_as],
956
+ ["docs", data.docs],
957
+ ["read", data.read[0].command],
958
+ ]),
959
+ };
960
+ }
961
+ const OUTCOME_KIND = "knowledge outcome (what a knowledge search found, as its retrieval span's knowledge_outcome says)";
685
962
  export const explain = {
686
963
  name: "explain",
687
964
  summary: "Look a code up in the instance's error catalog: what it means and how to fix it.",
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(", ")}.`,
965
+ description: "Rule codes come from the package and graph checks, API error codes from failed requests; cavelon's own codes (validate's\n" +
966
+ "findings, and errors the CLI raises itself, such as operation_not_found or uncommitted_changes) are known too. Uses the\n" +
967
+ "cached catalog first. Where the instance's fix names an API route, the command that does the same is added. An unknown\n" +
968
+ "code gets the closest known ones (a typo away, the same start).\n" +
969
+ `Also explains the test-case statuses that are neither pass nor fail: ${CASE_STATUSES.map((s) => s.status).join(", ")};\n` +
970
+ `and the values of a retrieval span's knowledge_outcome (${KNOWLEDGE_OUTCOMES.map((o) => o.value).join(", ")}), from the\n` +
971
+ "instance's catalog (area knowledge_outcome) where it lists them.",
690
972
  readOnly: true,
691
973
  idempotent: true,
692
974
  mcpTool: "explain",
@@ -694,11 +976,18 @@ export const explain = {
694
976
  async run(ctx, input) {
695
977
  const code = positional(input, "code").trim();
696
978
  const status = caseStatus(code);
697
- let catalog = status ? await catalogFor(ctx, false).catch(() => null) : await catalogFor(ctx, false);
979
+ const outcome = knowledgeOutcome(code);
980
+ let catalog = status || outcome ? await catalogFor(ctx, false).catch(() => null) : await catalogFor(ctx, false);
698
981
  let entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code);
982
+ if (!entry && outcome && catalog) {
983
+ catalog = await (await ctx.contracts()).errorCatalog({ refresh: true }).catch(() => catalog);
984
+ entry = catalogEntry(catalog, outcome.value);
985
+ }
699
986
  if (!entry && status)
700
987
  return caseStatusAnswer(ctx, status);
701
- if (!entry || entry.kind === "kit") {
988
+ if (!entry && outcome)
989
+ return knowledgeOutcomeAnswer(ctx, outcome);
990
+ if (!entry || entry.kind === "kit" || entry.kind === "cli") {
702
991
  catalog = await (await ctx.contracts()).errorCatalog({ refresh: true }).catch(() => catalog);
703
992
  entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code) ?? entry;
704
993
  }
@@ -710,13 +999,20 @@ export const explain = {
710
999
  });
711
1000
  }
712
1001
  if (!entry) {
713
- const all = [...(catalog?.rule_codes ?? []), ...(catalog?.api_error_codes ?? []), ...KIT_CODES, ...CASE_STATUSES.map((s) => ({ code: s.status }))].map((e) => e.code);
714
- const words = code.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2);
715
- const similar = all.filter((c) => words.some((w) => c.toLowerCase().includes(w))).slice(0, 8);
1002
+ const all = [
1003
+ ...(catalog?.rule_codes ?? []),
1004
+ ...(catalog?.api_error_codes ?? []),
1005
+ ...KIT_CODES,
1006
+ ...KIT_ERROR_CODES,
1007
+ ...CASE_STATUSES.map((s) => ({ code: s.status })),
1008
+ ...KNOWLEDGE_OUTCOMES.map((o) => ({ code: o.value })),
1009
+ ].map((e) => e.code);
1010
+ const similar = similarCodes(code, all);
716
1011
  throw new CavelonError(ExitCode.failure, {
717
1012
  code: "code_unknown",
718
- message: `"${code}" is not in this instance's error catalog.`,
1013
+ message: `"${code}" is neither in this instance's error catalog nor one of cavelon's own codes.`,
719
1014
  hint: similar.length ? `Similar codes: ${similar.join(", ")}.` : `Try \`cavelon docs search ${code}\`.`,
1015
+ details: { similar },
720
1016
  });
721
1017
  }
722
1018
  const docs = entry.docs?.startsWith("/") ? `${requireInstance(await ctx.session())}${entry.docs}` : entry.docs;
@@ -732,7 +1028,8 @@ export const explain = {
732
1028
  : pairOrderPointer(entry.code);
733
1029
  const pages = capacity === MODEL_ENDPOINT_BUSY ? [CAPACITY_TUTORIAL_PAGE, CAPACITY_CONCEPT_PAGE] : [CAPACITY_CONCEPT_PAGE, CAPACITY_TUTORIAL_PAGE];
734
1030
  const read = capacity ? (await listedPages(ctx, pages)).map((page) => ({ page, command: cavelonCommand("docs", "get", page) })) : [];
735
- const data = { ...entry, docs, ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
1031
+ const cli = entry.kind === "cli" ? undefined : cliFix(entry);
1032
+ const data = { ...entry, ...(entry.area === KNOWLEDGE_OUTCOME_AREA ? { kind: "knowledge_outcome" } : {}), docs, ...(cli ? { cli_fix: cli } : {}), ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
736
1033
  return {
737
1034
  data,
738
1035
  text: keyValues([
@@ -743,10 +1040,15 @@ export const explain = {
743
1040
  ? `rule code${entry.rule ? ` (rule ${entry.rule})` : ""}`
744
1041
  : entry.kind === "kit"
745
1042
  ? "cavelon validate code"
746
- : `API error code${entry.area ? ` (${entry.area})` : ""}`,
1043
+ : entry.kind === "cli"
1044
+ ? "cavelon error code (raised by the CLI, not the instance)"
1045
+ : entry.area === KNOWLEDGE_OUTCOME_AREA
1046
+ ? OUTCOME_KIND
1047
+ : `API error code${entry.area ? ` (${entry.area})` : ""}`,
747
1048
  ],
748
1049
  ["meaning", entry.message],
749
1050
  ["fix", entry.hint ?? undefined],
1051
+ ["with the CLI", cli],
750
1052
  [capacity || stepCap || ceiling ? "raise" : "order", kitHint],
751
1053
  ["why", entry.explanation ? clip(entry.explanation.replace(/\s+/g, " "), 600) : undefined],
752
1054
  ["docs", docs],
@@ -755,6 +1057,89 @@ export const explain = {
755
1057
  };
756
1058
  },
757
1059
  };
1060
+ const count = (value) => (typeof value === "number" ? value : null);
1061
+ export async function solutionState(ctx, ref) {
1062
+ let harness;
1063
+ try {
1064
+ harness = (await lookupHarness(ctx, ref)).harness;
1065
+ }
1066
+ catch (error) {
1067
+ return { harness: null, unavailable: error instanceof Error ? error.message : String(error) };
1068
+ }
1069
+ if (!harness)
1070
+ return { harness: null, unavailable: `This tenant has no solution "${ref}".` };
1071
+ const state = { harness: { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status } };
1072
+ try {
1073
+ const route = await readDefaultRoute(ctx);
1074
+ const current = route.current ? { id: route.current.id, slug: route.current.slug, name: route.current.name } : null;
1075
+ state.default_route = { is_default: route.known ? route.current?.id === harness.id : null, current };
1076
+ }
1077
+ catch (error) {
1078
+ ctx.warn(`Could not read the tenant's default route: ${error instanceof Error ? error.message : String(error)}`);
1079
+ }
1080
+ try {
1081
+ const readiness = await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}/readiness", "reading readiness", {
1082
+ params: { harness_id: [harness.id] },
1083
+ });
1084
+ state.ready_to_activate = typeof readiness.ready_to_activate === "boolean" ? readiness.ready_to_activate : null;
1085
+ state.blockers = (readiness.blockers ?? []).map((b) => clip(String(b.label ?? b.key ?? b.detail ?? "?"), 80));
1086
+ if ("latest_test_run" in readiness) {
1087
+ const run = readiness.latest_test_run;
1088
+ const summary = run?.summary ?? {};
1089
+ state.latest_test_run = run
1090
+ ? {
1091
+ id: run.id ?? null,
1092
+ status: run.status ?? null,
1093
+ passed: count(summary.passed),
1094
+ failed: count(summary.failed),
1095
+ total: count(summary.total_cases) ?? count(summary.total),
1096
+ at: run.completed_at ?? run.created_at ?? null,
1097
+ }
1098
+ : null;
1099
+ }
1100
+ }
1101
+ catch (error) {
1102
+ state.unavailable = `readiness: ${error instanceof Error ? error.message : String(error)}`;
1103
+ }
1104
+ return state;
1105
+ }
1106
+ export function solutionStateLines(state) {
1107
+ if (!state.harness)
1108
+ return [["state", `not readable: ${state.unavailable ?? "unknown"}`]];
1109
+ const active = state.harness.status === "active";
1110
+ const ready = active
1111
+ ? undefined
1112
+ : state.ready_to_activate === true
1113
+ ? "ready to activate"
1114
+ : state.ready_to_activate === false
1115
+ ? `not ready to activate${state.blockers?.length ? ` (${list(state.blockers, 3)})` : ""}`
1116
+ : undefined;
1117
+ const lines = [["state", [state.harness.status, ready].filter(Boolean).join(", ")]];
1118
+ const route = state.default_route;
1119
+ if (route)
1120
+ lines.push(["default route", defaultRouteText(state.harness, route)]);
1121
+ const run = state.latest_test_run;
1122
+ if (run === null)
1123
+ lines.push(["last test run", "none yet (`cavelon test run`)"]);
1124
+ else if (run) {
1125
+ const counts = run.total !== null ? `: ${run.passed ?? "?"} of ${run.total} passed${run.failed ? `, ${run.failed} failed` : ""}` : "";
1126
+ lines.push(["last test run", `${run.status ?? "?"}${counts}${run.at ? ` (${run.at})` : ""}${run.id ? ` ${run.id}` : ""}`]);
1127
+ }
1128
+ else if (!state.unavailable)
1129
+ lines.push(["last test run", "not published by this instance"]);
1130
+ if (state.unavailable)
1131
+ lines.push(["state error", state.unavailable]);
1132
+ return lines;
1133
+ }
1134
+ function defaultRouteText(harness, route) {
1135
+ if (route.is_default === null)
1136
+ return "unknown (this instance does not say which solution is the default)";
1137
+ if (route.is_default)
1138
+ return "yes: the tenant's chat and widget answer with it where a conversation names no solution";
1139
+ const now = route.current ? named(route.current) : "no solution";
1140
+ const how = harness.status === "active" ? cavelonCommand("harness", "default", harness.slug) : cavelonCommand("activate", "--harness", harness.slug, "--make-default");
1141
+ return `no: ${now} answers the tenant's chat and widget; preview a change with ${how}`;
1142
+ }
758
1143
  function checkLine(c) {
759
1144
  return clip([c.label ?? c.key, c.message ?? c.detail].filter(Boolean).join(": "), 300);
760
1145
  }
@@ -777,20 +1162,89 @@ function readinessText(checks, warnings) {
777
1162
  ...(warnings.length ? ["Warnings:", ...warnings.map((w) => ` - ${w}`)] : []),
778
1163
  ];
779
1164
  }
1165
+ async function defaultRouteAfterActivation(ctx, harness, input) {
1166
+ const make = boolOption(input, "make-default");
1167
+ let route;
1168
+ try {
1169
+ route = await readDefaultRoute(ctx);
1170
+ }
1171
+ catch (error) {
1172
+ ctx.warn(`Could not read the tenant's default route: ${error instanceof Error ? error.message : String(error)}`);
1173
+ return { data: {}, lines: [] };
1174
+ }
1175
+ const current = route.current ? { id: route.current.id, slug: route.current.slug, name: route.current.name } : null;
1176
+ if (route.current?.id === harness.id)
1177
+ return { data: { default_route: { is_default: true, current } }, lines: [`${named(harness)} is the tenant's default route.`] };
1178
+ const commands = defaultCommands(harness.slug);
1179
+ const gate = make ? await confirmation(ctx, input, "activate", { harness: harness.id, from: current?.id ?? null }) : undefined;
1180
+ if (gate?.confirmed) {
1181
+ try {
1182
+ await setDefaultRoute(ctx, harness.id);
1183
+ }
1184
+ catch (error) {
1185
+ const said = error instanceof Error ? error.message : String(error);
1186
+ const code = error instanceof CavelonError ? error.code : undefined;
1187
+ ctx.warn(`The default route was not changed: ${said}`);
1188
+ return {
1189
+ data: { default_route: { is_default: false, changed: false, current, error: { code: code ?? null, message: said } } },
1190
+ lines: [`The default route stays ${current ? named(current) : "as it was"}: ${said}`],
1191
+ failed: true,
1192
+ };
1193
+ }
1194
+ return {
1195
+ data: { default_route: { is_default: true, changed: true, previous: current } },
1196
+ lines: [`Default route: ${named(harness)}${current ? ` (was ${named(current)})` : ""}.`],
1197
+ };
1198
+ }
1199
+ if (!route.known && !make)
1200
+ return { data: { default_route: { is_default: null, known: false } }, lines: [] };
1201
+ if (gate) {
1202
+ const confirm = cavelonCommand("activate", "--harness", harness.slug, "--make-default", "--confirm");
1203
+ return {
1204
+ data: { default_route: { is_default: false, known: route.known, current, preview: commands.preview, confirm: gate.confirm(confirm), ...gate.fields } },
1205
+ lines: [defaultChangeLine(harness, route), ...(gate.mismatch ? [gate.mismatch] : []), `Show this to a person; with their yes: ${gate.confirm(confirm)}`],
1206
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
1207
+ };
1208
+ }
1209
+ const lines = [
1210
+ `Not the default route: ${current ? `the tenant's chat and widget answer with ${named(current)}` : "the tenant has none"} where a conversation names no solution.`,
1211
+ `Ask the person whether ${named(harness)} should answer there; that changes live traffic. Preview: ${commands.preview}`,
1212
+ ];
1213
+ return { data: { default_route: { is_default: false, known: route.known, current, preview: commands.preview, confirm: commands.confirm } }, lines };
1214
+ }
780
1215
  export const activate = {
781
1216
  name: "activate",
782
- summary: "Activate a solution through the readiness gate (never by force).",
1217
+ summary: "Activate a solution through the readiness gate (never by force); says whether it is the tenant's default route.",
783
1218
  description: "Only when every readiness check passes, and with a personal access token only when it was created with \"may activate\".\n" +
784
- "Activating without the evidence stays a person's decision in the Admin.",
1219
+ "Activating without the evidence stays a person's decision in the Admin.\n" +
1220
+ "Afterwards it says whether the solution is the tenant's default route (the one the tenant's chat and widget answer with\n" +
1221
+ "where no solution is named). --make-default previews making it the default; with --confirm as well, it changes it. That\n" +
1222
+ "changes live traffic: show the preview to a person and confirm only with their yes. `cavelon harness default` does the\n" +
1223
+ "same for an active solution.",
785
1224
  readOnly: false,
786
1225
  idempotent: true,
787
1226
  mcpTool: "activate",
788
- options: { harness: HARNESS_OPTION, env: ENV_OPTION },
1227
+ options: {
1228
+ harness: HARNESS_OPTION,
1229
+ env: ENV_OPTION,
1230
+ "make-default": { type: "boolean", description: "Also make it the tenant's default route: previews the change; with --confirm, makes it." },
1231
+ confirm: { type: "boolean", mcpToken: true, description: "With --make-default: change the default route (after a person saw the preview)." },
1232
+ },
1233
+ examples: ["cavelon activate", "cavelon activate --make-default", "cavelon activate --make-default --confirm"],
789
1234
  async run(ctx, input) {
790
1235
  const session = await ctx.session();
791
1236
  const { ref, source } = harnessRef(session, input);
792
1237
  if (!ref)
793
1238
  throw usageError("Which solution?", "Pass --harness <name or slug> (`cavelon harness list` shows them), or set harness in cavelon.yaml or the env file.");
1239
+ if (confirmGiven(input) && !boolOption(input, "make-default")) {
1240
+ throw usageError("--confirm only applies to --make-default.", "Activation itself needs no confirmation; the default route does.");
1241
+ }
1242
+ if (ctx.mode === "mcp" && input.options.confirm === true)
1243
+ throw confirmTokenRequired("activate");
1244
+ const driven = drivenByAgent(ctx);
1245
+ if (driven?.by === "agent" && input.options.confirm === true) {
1246
+ throw shellTokenRequired(cavelonCommand("activate", "--harness", ref, "--make-default"), driven.variable);
1247
+ }
794
1248
  const client = await ctx.client();
795
1249
  const principal = await readPrincipal(client);
796
1250
  if (principal?.kind === "personal_access_token" && principal.token && !principal.token.may_activate) {
@@ -802,7 +1256,12 @@ export const activate = {
802
1256
  }
803
1257
  const harness = await findHarness(ctx, ref, source);
804
1258
  if (harness.status === "active") {
805
- return { data: { activated: false, already_active: true, harness }, text: `${harness.name} (${harness.slug}) is already active.` };
1259
+ const route = await defaultRouteAfterActivation(ctx, harness, input);
1260
+ return {
1261
+ data: { activated: false, already_active: true, harness, ...route.data },
1262
+ text: [`${harness.name} (${harness.slug}) is already active.`, ...route.lines].join("\n"),
1263
+ ...(route.failed ? { exitCode: ExitCode.failure } : route.exitCode ? { exitCode: route.exitCode } : {}),
1264
+ };
806
1265
  }
807
1266
  const readiness = await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}/readiness", "reading readiness", {
808
1267
  params: { harness_id: [harness.id] },
@@ -828,9 +1287,11 @@ export const activate = {
828
1287
  params: { harness_id: [harness.id] },
829
1288
  body: { force: false },
830
1289
  });
1290
+ const route = await defaultRouteAfterActivation(ctx, activated, input);
831
1291
  return {
832
- data: { activated: true, harness: activated, checks, warnings, readiness },
833
- text: [`Activated ${activated.name} (${activated.slug}); status ${activated.status}.`, ...readinessText(checks, warnings)].join("\n"),
1292
+ data: { activated: true, harness: activated, checks, warnings, readiness, ...route.data },
1293
+ text: [`Activated ${activated.name} (${activated.slug}); status ${activated.status}.`, ...readinessText(checks, warnings), ...route.lines].join("\n"),
1294
+ ...(route.failed ? { exitCode: ExitCode.failure } : route.exitCode ? { exitCode: route.exitCode } : {}),
834
1295
  };
835
1296
  },
836
1297
  };