@cavelon/cli 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +43 -17
  2. package/dist/agent-env.js +24 -0
  3. package/dist/choose.js +8 -4
  4. package/dist/code-hints.js +74 -0
  5. package/dist/commands/api.js +174 -33
  6. package/dist/commands/async.js +26 -5
  7. package/dist/commands/docs.js +183 -37
  8. package/dist/commands/fmt.js +117 -0
  9. package/dist/commands/index.js +6 -1
  10. package/dist/commands/init.js +28 -6
  11. package/dist/commands/inventory.js +27 -5
  12. package/dist/commands/models.js +7 -1
  13. package/dist/commands/schema.js +193 -0
  14. package/dist/commands/session.js +69 -13
  15. package/dist/commands/solution.js +275 -36
  16. package/dist/commands/tenants.js +125 -15
  17. package/dist/commands/work.js +245 -24
  18. package/dist/contracts.js +3 -0
  19. package/dist/default-route.js +21 -0
  20. package/dist/errors.js +4 -0
  21. package/dist/git.js +14 -5
  22. package/dist/http.js +27 -4
  23. package/dist/invoke.js +8 -4
  24. package/dist/kit-codes.js +85 -0
  25. package/dist/limits.js +12 -1
  26. package/dist/local-state.js +9 -2
  27. package/dist/main.js +16 -3
  28. package/dist/mcp.js +19 -8
  29. package/dist/openapi.js +91 -21
  30. package/dist/operations.js +4 -3
  31. package/dist/package-check.js +193 -4
  32. package/dist/package-files.js +21 -10
  33. package/dist/package-format.js +149 -0
  34. package/dist/package-references.js +231 -0
  35. package/dist/paths.js +4 -3
  36. package/dist/preview-report.js +152 -0
  37. package/dist/results.js +65 -5
  38. package/dist/skills/cavelon-authoring/SKILL.md +67 -8
  39. package/dist/skills/cavelon-long-running/SKILL.md +3 -1
  40. package/dist/skills/cavelon-loop/SKILL.md +75 -13
  41. package/dist/skills/cavelon-testing/SKILL.md +85 -4
  42. package/dist/tenant-choice.js +12 -5
  43. package/package.json +3 -3
@@ -9,15 +9,20 @@ import { readTextFile, writeFileAtomic } from "../fsutil.js";
9
9
  import { uncommitted } from "../git.js";
10
10
  import { callStable } from "../invoke.js";
11
11
  import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
12
+ import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefaultRoute } from "../default-route.js";
12
13
  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";
14
+ import { deletePreview, digest, fileDigest, fileDigests, listPreviews, loadPreview, readPulledFiles, rememberAppliedFiles, savePreview, writePulledFiles, writeState, } from "../local-state.js";
14
15
  import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
16
+ import { cliFix, similarCodes } from "../code-hints.js";
17
+ import { KIT_ERROR_CODES } from "../kit-codes.js";
15
18
  import { pairOrderHint, pairOrderPointer } from "../pair-order.js";
16
19
  import { readPackage, writePackage } from "../package-files.js";
20
+ import { blockerDetails, blockerLines, changeLines, fieldChanges, locateBlockers, notApplied, notAppliedLines } from "../preview-report.js";
17
21
  import { readPrincipal } from "../principal.js";
22
+ import { CASE_STATUSES, caseStatus, TESTING_PAGE } from "../results.js";
18
23
  import { isUuid, requireInstance } from "../session.js";
19
24
  import { listedPages } from "./docs.js";
20
- import { writeInventory } from "./inventory.js";
25
+ import { readInventory, writeInventory } from "./inventory.js";
21
26
  import { cavelonCommand, shellWord } from "../shell.js";
22
27
  import { secretSetCommand, targetFlags, variableSetCommand } from "./values.js";
23
28
  const HARNESS_OPTION = { type: "string", value: "<harness>", description: "The solution (harness): its name, slug or id; default: env file, then cavelon.yaml." };
@@ -128,6 +133,15 @@ function uncommittedChanges(files, what) {
128
133
  details: { files },
129
134
  });
130
135
  }
136
+ async function unknownStates(root, files, known) {
137
+ const out = [];
138
+ for (const file of files) {
139
+ const current = await fileDigest(path.join(root, file));
140
+ if (current === undefined || current !== known[file])
141
+ out.push(file);
142
+ }
143
+ return out;
144
+ }
131
145
  async function editedSincePull(project, pkg, schema) {
132
146
  const planned = await writePackage(project.root, project.layout, pkg, schema, { dryRun: true });
133
147
  const pulled = await readPulledFiles(project.root);
@@ -145,14 +159,17 @@ export const pull = {
145
159
  description: "With a solution (--harness, or cavelon.yaml's harness), exports that solution; without one, the tenant's full configuration.\n" +
146
160
  "A file whose content did not change keeps its bytes, so `git diff` shows what changed on the instance. Files of sections\n" +
147
161
  "the schema does not know are kept byte for byte. Refuses when package files have uncommitted changes, unless --force;\n" +
148
- "outside a git repository, when a file it would overwrite or remove changed since the last pull.",
162
+ "outside a git repository, when a file it would overwrite or remove changed since the last pull. A file as the last pull\n" +
163
+ "or apply left it (digests in .cavelon/) counts as unchanged, committed or not.",
149
164
  readOnly: false,
150
165
  destructive: true,
166
+ mcpEffect: "Reads the instance and changes nothing there. Writes the package files and .cavelon/ in the solution folder; refuses to " +
167
+ "overwrite or remove a package file that changed since the last pull or apply and is not committed, unless force.",
151
168
  idempotent: true,
152
169
  mcpTool: "pull",
153
170
  options: {
154
171
  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." },
155
- force: { type: "boolean", description: "Overwrite package files that have uncommitted changes (outside git: changes since the last pull)." },
172
+ force: { type: "boolean", description: "Overwrite package files that have uncommitted changes since the last pull or apply." },
156
173
  },
157
174
  examples: ["cavelon pull --harness support", "cavelon pull && git diff -- package tests"],
158
175
  async run(ctx, input) {
@@ -161,7 +178,9 @@ export const pull = {
161
178
  const url = requireInstance(session);
162
179
  const layoutDirs = [project.layout.package, ...Object.values(project.layout.items)];
163
180
  const force = boolOption(input, "force");
164
- const dirty = force ? [] : (await uncommitted(project.root, layoutDirs))?.filter((f) => /\.(ya?ml|json)"?$/i.test(f));
181
+ const known = force ? {} : await readPulledFiles(project.root);
182
+ const changed = force ? [] : (await uncommitted(project.root, layoutDirs))?.filter((f) => /\.(ya?ml|json)$/i.test(f));
183
+ const dirty = changed && (await unknownStates(project.root, changed, known));
165
184
  if (dirty?.length)
166
185
  throw uncommittedChanges(dirty, "pull would overwrite uncommitted changes");
167
186
  const { ref } = harnessRef(session, input);
@@ -209,7 +228,7 @@ export const pull = {
209
228
  ctx.warn(`Kept ${file}: its section is not in this instance's package schema.`);
210
229
  for (const section of report.refused)
211
230
  ctx.warn(`Did not write section ${JSON.stringify(section)}: its name is not a plain file name.`);
212
- const changed = report.written.length + report.removed.length;
231
+ const rewritten = report.written.length + report.removed.length;
213
232
  const lines = [
214
233
  `Pulled ${harness ? `solution ${harness.name} (${harness.slug})` : "the tenant's full configuration"} into ${project.layout.package}/` +
215
234
  (Object.keys(project.layout.items).length ? ` and ${Object.values(project.layout.items).join("/, ")}/` : "") +
@@ -218,7 +237,7 @@ export const pull = {
218
237
  ...report.removed.map((f) => `removed ${f}`),
219
238
  `${report.unchanged.length} file${report.unchanged.length === 1 ? "" : "s"} unchanged.`,
220
239
  `Inventory: ${inventory.file} (${inventory.counts.map((c) => `${c.count} ${c.label}`).join(", ")})`,
221
- changed ? `See what changed: git diff -- ${layoutDirs.join(" ")}` : "Nothing changed on the instance since the last pull.",
240
+ rewritten ? `See what changed: git diff -- ${layoutDirs.join(" ")}` : "Nothing changed on the instance since the last pull.",
222
241
  ];
223
242
  return { data: { ...record, inventory }, text: lines.join("\n") };
224
243
  },
@@ -241,6 +260,7 @@ async function validatePackage(ctx, project, offline) {
241
260
  catalog: await catalogFor(ctx, offline),
242
261
  accepted: await acceptedVersions(ctx, offline),
243
262
  limits: await limitsFor(ctx, offline),
263
+ inventory: await readInventory(project.root),
244
264
  });
245
265
  return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null, used };
246
266
  }
@@ -364,7 +384,7 @@ function needsLines(needs, flags) {
364
384
  lines.push(["needs identities", triggers.map((t) => `\n - ${t}`).join("")]);
365
385
  return lines;
366
386
  }
367
- export function previewText(p, flags = "") {
387
+ export function previewText(p, flags = "", context = {}) {
368
388
  const lines = [["ready", p.ready ? "yes" : "no"]];
369
389
  const s = p.summary ?? {};
370
390
  for (const [label, map] of [["creates", s.creates], ["updates", s.updates], ["deletes", s.deletes]]) {
@@ -374,13 +394,22 @@ export function previewText(p, flags = "") {
374
394
  }
375
395
  if (lines.length === 1)
376
396
  lines.push(["changes", "none"]);
377
- if (p.blockers?.length)
397
+ const changes = fieldChanges(p.changes);
398
+ if (changes.length)
399
+ lines.push(["field changes", changeLines(changes)]);
400
+ const details = blockerDetails(p.blocker_details, context.disk);
401
+ if (details.length)
402
+ lines.push(["blockers", blockerLines(details)]);
403
+ else if (p.blockers?.length)
378
404
  lines.push(["blockers", p.blockers.map((b) => `\n - ${clip(b, 300)}`).join("")]);
379
405
  if (p.warnings?.length)
380
406
  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` : "")]);
381
407
  const ignored = [...(p.ignored?.sections ?? []), ...(p.ignored?.fields ?? [])];
382
408
  if (ignored.length)
383
409
  lines.push(["ignored", list(ignored)]);
410
+ const skipped = notApplied(p.ignored?.not_applied, context.disk?.package, context.harness);
411
+ if (skipped.length)
412
+ lines.push(["not applied", notAppliedLines(skipped)]);
384
413
  const impact = p.impact ?? {};
385
414
  const active = (impact.active_harnesses ?? []).map((h) => {
386
415
  const via = [...(h.tools ?? []), ...(h.knowledge_bases ?? []), ...(h.sandboxes ?? [])];
@@ -397,6 +426,22 @@ export function previewText(p, flags = "") {
397
426
  lines.push(...needsLines(p.target_needs ?? {}, flags));
398
427
  return keyValues(lines);
399
428
  }
429
+ function previewReport(p, context) {
430
+ const out = {};
431
+ const details = blockerDetails(p.blocker_details, context.disk);
432
+ if (details.length)
433
+ out.blocker_details = details;
434
+ const changes = fieldChanges(p.changes);
435
+ if (changes.length)
436
+ out.field_changes = changes;
437
+ const skipped = notApplied(p.ignored?.not_applied, context.disk?.package, context.harness);
438
+ if (skipped.length)
439
+ out.not_applied = skipped;
440
+ return out;
441
+ }
442
+ function sourceFiles(disk) {
443
+ return Object.values(disk.sources).flatMap((source) => (Array.isArray(source) ? source : [source]).map((s) => s.file));
444
+ }
400
445
  function previewIdOption(input) {
401
446
  const id = stringOption(input, "confirm");
402
447
  if (id !== undefined && !id.trim())
@@ -441,6 +486,8 @@ async function confirmPreview(ctx, project, previewId) {
441
486
  });
442
487
  for (const other of await listPreviews(project.root))
443
488
  await deletePreview(project.root, other.preview_id);
489
+ if (stored.file_digests)
490
+ await rememberAppliedFiles(project.root, stored.file_digests);
444
491
  const summary = (result.summary ?? {});
445
492
  const flags = targetFlags(session, stored.env ?? session.envFile?.name);
446
493
  const still = setCommands(stored.preview, flags);
@@ -459,10 +506,12 @@ async function confirmPreview(ctx, project, previewId) {
459
506
  return { data, text };
460
507
  }
461
508
  catch (error) {
462
- if (error instanceof CavelonError && error.code === REQUIREMENTS_CHANGED && error.blockers?.length) {
509
+ if (error instanceof CavelonError && error.code === REQUIREMENTS_CHANGED && (error.blockers?.length || error.blockerDetails?.length)) {
463
510
  await deletePreview(project.root, stored.preview_id);
464
- throw requirementsChanged(error, stored, session, await catalogFor(ctx, false));
511
+ throw requirementsChanged(error, stored, session, await catalogFor(ctx, false), disk);
465
512
  }
513
+ if (error instanceof CavelonError && error.blockerDetails?.length)
514
+ throw withBlockersLocated(error, disk, stored, session);
466
515
  if (error instanceof CavelonError && (error.code === "import_preview_stale" || (error.status === 409 && /preview/i.test(error.message)))) {
467
516
  await deletePreview(project.root, stored.preview_id);
468
517
  throw new CavelonError(ExitCode.conflict, {
@@ -477,8 +526,9 @@ async function confirmPreview(ctx, project, previewId) {
477
526
  }
478
527
  }
479
528
  const REQUIREMENTS_CHANGED = "package_requirements_changed";
480
- function requirementsChanged(error, stored, session, catalog) {
481
- const blockers = error.blockers ?? [];
529
+ function requirementsChanged(error, stored, session, catalog, disk) {
530
+ const details = locateBlockers(error.blockerDetails ?? [], disk);
531
+ const blockers = error.blockers?.length ? error.blockers : details.map((b) => b.message);
482
532
  const known = new Map();
483
533
  for (const blocker of blockers) {
484
534
  const pair = pairOrderHint(catalog, [blocker]);
@@ -492,6 +542,19 @@ function requirementsChanged(error, stored, session, catalog) {
492
542
  hint: [...known.values(), `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`].join(" "),
493
543
  docs: error.docs,
494
544
  blockers,
545
+ blockerDetails: details.length ? details : undefined,
546
+ });
547
+ }
548
+ function withBlockersLocated(error, disk, stored, session) {
549
+ return new CavelonError(error.exitCode, {
550
+ code: error.code,
551
+ message: `The import's own check refused preview ${stored.preview_id} when it applied; nothing was imported.`,
552
+ hint: error.hint ?? `Fix what each blocker names, run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
553
+ docs: error.docs,
554
+ status: error.status,
555
+ details: error.details,
556
+ blockers: error.blockers,
557
+ blockerDetails: locateBlockers(error.blockerDetails ?? [], disk),
495
558
  });
496
559
  }
497
560
  function previewAgain(stored, session) {
@@ -519,7 +582,12 @@ function packageHarnessName(pkg, slug) {
519
582
  return name ? name.slice(0, 255) : undefined;
520
583
  }
521
584
  function personReason(preview, harness, mode, env) {
522
- if (preview.impact?.active_harnesses?.length || harness?.status === "active")
585
+ const active = (preview.impact?.active_harnesses ?? []).map((h) => h.harness_slug ?? h.name).filter((n) => Boolean(n));
586
+ if (harness?.status === "active" && !active.includes(harness.slug))
587
+ active.unshift(harness.slug);
588
+ if (active.length)
589
+ return `reaches the active solution${active.length === 1 ? "" : "s"} ${list(active, 5)}`;
590
+ if (preview.impact?.active_harnesses?.length)
523
591
  return "reaches an active solution";
524
592
  if (counts(preview.summary?.deletes) || mode === "replace")
525
593
  return "deletes";
@@ -591,17 +659,19 @@ export const apply = {
591
659
  const commands = setCommands(preview, flags);
592
660
  if (commands.secrets.length || commands.variables.length)
593
661
  data.set_commands = commands;
594
- if (!preview.preview_id) {
595
- ctx.warn("This instance's preview returns no preview id, so `apply --confirm` cannot import exactly it; update the instance.");
596
- }
662
+ const context = { disk, harness: harness?.slug };
663
+ Object.assign(data, previewReport(preview, context));
597
664
  if (!preview.ready) {
598
- const pair = pairOrderHint(await catalogFor(ctx, false), preview.blockers ?? []);
665
+ const pair = pairOrderHint(await catalogFor(ctx, false), [
666
+ ...(preview.blockers ?? []),
667
+ ...blockerDetails(preview.blocker_details).map((b) => `${b.code ?? ""}: ${b.message}`),
668
+ ]);
599
669
  if (pair)
600
670
  data.hint = pair.hint;
601
671
  return {
602
672
  data,
603
673
  text: [
604
- previewText(preview, flags),
674
+ previewText(preview, flags, context),
605
675
  "",
606
676
  ...(pair ? [`hint: ${pair.hint}`] : []),
607
677
  "The preview has blockers; fix them and run `cavelon apply` again.",
@@ -609,6 +679,9 @@ export const apply = {
609
679
  exitCode: ExitCode.validation,
610
680
  };
611
681
  }
682
+ if (!preview.preview_id) {
683
+ ctx.warn("This instance's preview returns no preview id, so `apply --confirm` cannot import exactly it; update the instance.");
684
+ }
612
685
  if (preview.preview_id) {
613
686
  const stored = {
614
687
  preview_id: preview.preview_id,
@@ -618,6 +691,7 @@ export const apply = {
618
691
  env: envFile?.name ?? null,
619
692
  harness: target,
620
693
  package_digest: digest(disk.package),
694
+ file_digests: await fileDigests(project.root, sourceFiles(disk)),
621
695
  request,
622
696
  preview,
623
697
  };
@@ -628,7 +702,7 @@ export const apply = {
628
702
  const confirmLine = preview.preview_id ? `${cavelonCommand("apply", "--confirm", preview.preview_id)}${flags}` : undefined;
629
703
  const text = [
630
704
  `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
631
- previewText(preview, flags),
705
+ previewText(preview, flags, context),
632
706
  "",
633
707
  ...(preview.preview_id ? [`preview id: ${preview.preview_id}`] : []),
634
708
  ...(reason ? [`This ${reason}: show this preview to a person before confirming.`] : []),
@@ -656,19 +730,51 @@ function processingStepCapHint(limits) {
656
730
  const resets = cap.period ? ` It resets at ${cap.period.resets_at}.` : "";
657
731
  return `monthly_processing_step_cap is ${value}${used} (state: ${cap.state}).${resets} ${raise}`;
658
732
  }
733
+ async function caseStatusAnswer(ctx, status) {
734
+ const instance = (await ctx.session().catch(() => undefined))?.url;
735
+ const page = `/docs/${TESTING_PAGE}#${status.section}`;
736
+ const data = {
737
+ code: status.status,
738
+ kind: "test_case_status",
739
+ message: status.meaning,
740
+ hint: status.next,
741
+ summary_counts: status.counts,
742
+ docs: instance ? `${instance}${page}` : page,
743
+ read: [{ page: TESTING_PAGE, command: cavelonCommand("docs", "get", TESTING_PAGE) }],
744
+ };
745
+ return {
746
+ data,
747
+ text: keyValues([
748
+ ["code", status.status],
749
+ ["kind", "test-case status (neither pass nor fail)"],
750
+ ["meaning", status.meaning],
751
+ ["next", status.next],
752
+ ["counted as", status.counts.join(", ")],
753
+ ["docs", data.docs],
754
+ ["read", data.read[0].command],
755
+ ]),
756
+ };
757
+ }
659
758
  export const explain = {
660
759
  name: "explain",
661
760
  summary: "Look a code up in the instance's error catalog: what it means and how to fix it.",
662
- description: "Rule codes come from the package and graph checks, API error codes from failed requests. Uses the cached catalog first.",
761
+ description: "Rule codes come from the package and graph checks, API error codes from failed requests; cavelon's own codes (validate's\n" +
762
+ "findings, and errors the CLI raises itself, such as operation_not_found or uncommitted_changes) are known too. Uses the\n" +
763
+ "cached catalog first. Where the instance's fix names an API route, the command that does the same is added. An unknown\n" +
764
+ "code gets the closest known ones (a typo away, the same start).\n" +
765
+ `Also explains the test-case statuses that are neither pass nor fail: ${CASE_STATUSES.map((s) => s.status).join(", ")}.`,
663
766
  readOnly: true,
664
767
  idempotent: true,
665
768
  mcpTool: "explain",
666
- positionals: [{ name: "code", description: "The code, e.g. from `cavelon validate` or an error's code.", required: true }],
769
+ positionals: [{ name: "code", description: "The code, e.g. from `cavelon validate` or an error's code, or a test-case status.", required: true }],
667
770
  async run(ctx, input) {
668
771
  const code = positional(input, "code").trim();
669
- let catalog = await catalogFor(ctx, false);
772
+ const status = caseStatus(code);
773
+ let catalog = status ? await catalogFor(ctx, false).catch(() => null) : await catalogFor(ctx, false);
670
774
  let entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code);
671
- if (!entry || entry.kind === "kit") {
775
+ if (!entry && status)
776
+ return caseStatusAnswer(ctx, status);
777
+ if (!entry || entry.kind === "kit" || entry.kind === "cli") {
672
778
  catalog = await (await ctx.contracts()).errorCatalog({ refresh: true }).catch(() => catalog);
673
779
  entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code) ?? entry;
674
780
  }
@@ -680,13 +786,19 @@ export const explain = {
680
786
  });
681
787
  }
682
788
  if (!entry) {
683
- const all = [...(catalog?.rule_codes ?? []), ...(catalog?.api_error_codes ?? []), ...KIT_CODES].map((e) => e.code);
684
- const words = code.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2);
685
- const similar = all.filter((c) => words.some((w) => c.toLowerCase().includes(w))).slice(0, 8);
789
+ const all = [
790
+ ...(catalog?.rule_codes ?? []),
791
+ ...(catalog?.api_error_codes ?? []),
792
+ ...KIT_CODES,
793
+ ...KIT_ERROR_CODES,
794
+ ...CASE_STATUSES.map((s) => ({ code: s.status })),
795
+ ].map((e) => e.code);
796
+ const similar = similarCodes(code, all);
686
797
  throw new CavelonError(ExitCode.failure, {
687
798
  code: "code_unknown",
688
- message: `"${code}" is not in this instance's error catalog.`,
799
+ message: `"${code}" is neither in this instance's error catalog nor one of cavelon's own codes.`,
689
800
  hint: similar.length ? `Similar codes: ${similar.join(", ")}.` : `Try \`cavelon docs search ${code}\`.`,
801
+ details: { similar },
690
802
  });
691
803
  }
692
804
  const docs = entry.docs?.startsWith("/") ? `${requireInstance(await ctx.session())}${entry.docs}` : entry.docs;
@@ -702,7 +814,8 @@ export const explain = {
702
814
  : pairOrderPointer(entry.code);
703
815
  const pages = capacity === MODEL_ENDPOINT_BUSY ? [CAPACITY_TUTORIAL_PAGE, CAPACITY_CONCEPT_PAGE] : [CAPACITY_CONCEPT_PAGE, CAPACITY_TUTORIAL_PAGE];
704
816
  const read = capacity ? (await listedPages(ctx, pages)).map((page) => ({ page, command: cavelonCommand("docs", "get", page) })) : [];
705
- const data = { ...entry, docs, ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
817
+ const cli = entry.kind === "cli" ? undefined : cliFix(entry);
818
+ const data = { ...entry, docs, ...(cli ? { cli_fix: cli } : {}), ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
706
819
  return {
707
820
  data,
708
821
  text: keyValues([
@@ -713,10 +826,13 @@ export const explain = {
713
826
  ? `rule code${entry.rule ? ` (rule ${entry.rule})` : ""}`
714
827
  : entry.kind === "kit"
715
828
  ? "cavelon validate code"
716
- : `API error code${entry.area ? ` (${entry.area})` : ""}`,
829
+ : entry.kind === "cli"
830
+ ? "cavelon error code (raised by the CLI, not the instance)"
831
+ : `API error code${entry.area ? ` (${entry.area})` : ""}`,
717
832
  ],
718
833
  ["meaning", entry.message],
719
834
  ["fix", entry.hint ?? undefined],
835
+ ["with the CLI", cli],
720
836
  [capacity || stepCap || ceiling ? "raise" : "order", kitHint],
721
837
  ["why", entry.explanation ? clip(entry.explanation.replace(/\s+/g, " "), 600) : undefined],
722
838
  ["docs", docs],
@@ -725,6 +841,66 @@ export const explain = {
725
841
  };
726
842
  },
727
843
  };
844
+ const count = (value) => (typeof value === "number" ? value : null);
845
+ export async function solutionState(ctx, ref) {
846
+ let harness;
847
+ try {
848
+ harness = (await lookupHarness(ctx, ref)).harness;
849
+ }
850
+ catch (error) {
851
+ return { harness: null, unavailable: error instanceof Error ? error.message : String(error) };
852
+ }
853
+ if (!harness)
854
+ return { harness: null, unavailable: `This tenant has no solution "${ref}".` };
855
+ const state = { harness: { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status } };
856
+ try {
857
+ const readiness = await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}/readiness", "reading readiness", {
858
+ params: { harness_id: [harness.id] },
859
+ });
860
+ state.ready_to_activate = typeof readiness.ready_to_activate === "boolean" ? readiness.ready_to_activate : null;
861
+ state.blockers = (readiness.blockers ?? []).map((b) => clip(String(b.label ?? b.key ?? b.detail ?? "?"), 80));
862
+ if ("latest_test_run" in readiness) {
863
+ const run = readiness.latest_test_run;
864
+ const summary = run?.summary ?? {};
865
+ state.latest_test_run = run
866
+ ? {
867
+ id: run.id ?? null,
868
+ status: run.status ?? null,
869
+ passed: count(summary.passed),
870
+ failed: count(summary.failed),
871
+ total: count(summary.total_cases) ?? count(summary.total),
872
+ at: run.completed_at ?? run.created_at ?? null,
873
+ }
874
+ : null;
875
+ }
876
+ }
877
+ catch (error) {
878
+ state.unavailable = `readiness: ${error instanceof Error ? error.message : String(error)}`;
879
+ }
880
+ return state;
881
+ }
882
+ export function solutionStateLines(state) {
883
+ if (!state.harness)
884
+ return [["state", `not readable: ${state.unavailable ?? "unknown"}`]];
885
+ const ready = state.ready_to_activate === true
886
+ ? "ready to activate"
887
+ : state.ready_to_activate === false
888
+ ? `not ready to activate${state.blockers?.length ? ` (${list(state.blockers, 3)})` : ""}`
889
+ : undefined;
890
+ const lines = [["state", [state.harness.status, ready].filter(Boolean).join(", ")]];
891
+ const run = state.latest_test_run;
892
+ if (run === null)
893
+ lines.push(["last test run", "none yet (`cavelon test run`)"]);
894
+ else if (run) {
895
+ const counts = run.total !== null ? `: ${run.passed ?? "?"} of ${run.total} passed${run.failed ? `, ${run.failed} failed` : ""}` : "";
896
+ lines.push(["last test run", `${run.status ?? "?"}${counts}${run.at ? ` (${run.at})` : ""}${run.id ? ` ${run.id}` : ""}`]);
897
+ }
898
+ else if (!state.unavailable)
899
+ lines.push(["last test run", "not published by this instance"]);
900
+ if (state.unavailable)
901
+ lines.push(["state error", state.unavailable]);
902
+ return lines;
903
+ }
728
904
  function checkLine(c) {
729
905
  return clip([c.label ?? c.key, c.message ?? c.detail].filter(Boolean).join(": "), 300);
730
906
  }
@@ -747,20 +923,76 @@ function readinessText(checks, warnings) {
747
923
  ...(warnings.length ? ["Warnings:", ...warnings.map((w) => ` - ${w}`)] : []),
748
924
  ];
749
925
  }
926
+ async function defaultRouteAfterActivation(ctx, harness, input) {
927
+ const make = boolOption(input, "make-default");
928
+ let route;
929
+ try {
930
+ route = await readDefaultRoute(ctx);
931
+ }
932
+ catch (error) {
933
+ ctx.warn(`Could not read the tenant's default route: ${error instanceof Error ? error.message : String(error)}`);
934
+ return { data: {}, lines: [] };
935
+ }
936
+ const current = route.current ? { id: route.current.id, slug: route.current.slug, name: route.current.name } : null;
937
+ if (route.current?.id === harness.id)
938
+ return { data: { default_route: { is_default: true, current } }, lines: [`${named(harness)} is the tenant's default route.`] };
939
+ const commands = defaultCommands(harness.slug);
940
+ if (make && boolOption(input, "confirm")) {
941
+ try {
942
+ await setDefaultRoute(ctx, harness.id);
943
+ }
944
+ catch (error) {
945
+ const said = error instanceof Error ? error.message : String(error);
946
+ const code = error instanceof CavelonError ? error.code : undefined;
947
+ ctx.warn(`The default route was not changed: ${said}`);
948
+ return {
949
+ data: { default_route: { is_default: false, changed: false, current, error: { code: code ?? null, message: said } } },
950
+ lines: [`The default route stays ${current ? named(current) : "as it was"}: ${said}`],
951
+ failed: true,
952
+ };
953
+ }
954
+ return {
955
+ data: { default_route: { is_default: true, changed: true, previous: current } },
956
+ lines: [`Default route: ${named(harness)}${current ? ` (was ${named(current)})` : ""}.`],
957
+ };
958
+ }
959
+ if (!route.known && !make)
960
+ return { data: { default_route: { is_default: null, known: false } }, lines: [] };
961
+ const lines = make
962
+ ? [defaultChangeLine(harness, route), `Show this to a person; with their yes: ${cavelonCommand("activate", "--harness", harness.slug, "--make-default", "--confirm")}`]
963
+ : [
964
+ `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.`,
965
+ `Ask the person whether ${named(harness)} should answer there; that changes live traffic. Preview: ${commands.preview}`,
966
+ ];
967
+ return { data: { default_route: { is_default: false, known: route.known, current, preview: commands.preview, confirm: commands.confirm } }, lines };
968
+ }
750
969
  export const activate = {
751
970
  name: "activate",
752
- summary: "Activate a solution through the readiness gate (never by force).",
971
+ summary: "Activate a solution through the readiness gate (never by force); says whether it is the tenant's default route.",
753
972
  description: "Only when every readiness check passes, and with a personal access token only when it was created with \"may activate\".\n" +
754
- "Activating without the evidence stays a person's decision in the Admin.",
973
+ "Activating without the evidence stays a person's decision in the Admin.\n" +
974
+ "Afterwards it says whether the solution is the tenant's default route (the one the tenant's chat and widget answer with\n" +
975
+ "where no solution is named). --make-default previews making it the default; with --confirm as well, it changes it. That\n" +
976
+ "changes live traffic: show the preview to a person and confirm only with their yes. `cavelon harness default` does the\n" +
977
+ "same for an active solution.",
755
978
  readOnly: false,
756
979
  idempotent: true,
757
980
  mcpTool: "activate",
758
- options: { harness: HARNESS_OPTION, env: ENV_OPTION },
981
+ options: {
982
+ harness: HARNESS_OPTION,
983
+ env: ENV_OPTION,
984
+ "make-default": { type: "boolean", description: "Also make it the tenant's default route: previews the change; with --confirm, makes it." },
985
+ confirm: { type: "boolean", description: "With --make-default: change the default route (after a person saw the preview)." },
986
+ },
987
+ examples: ["cavelon activate", "cavelon activate --make-default", "cavelon activate --make-default --confirm"],
759
988
  async run(ctx, input) {
760
989
  const session = await ctx.session();
761
990
  const { ref, source } = harnessRef(session, input);
762
991
  if (!ref)
763
992
  throw usageError("Which solution?", "Pass --harness <name or slug> (`cavelon harness list` shows them), or set harness in cavelon.yaml or the env file.");
993
+ if (boolOption(input, "confirm") && !boolOption(input, "make-default")) {
994
+ throw usageError("--confirm only applies to --make-default.", "Activation itself needs no confirmation; the default route does.");
995
+ }
764
996
  const client = await ctx.client();
765
997
  const principal = await readPrincipal(client);
766
998
  if (principal?.kind === "personal_access_token" && principal.token && !principal.token.may_activate) {
@@ -772,7 +1004,12 @@ export const activate = {
772
1004
  }
773
1005
  const harness = await findHarness(ctx, ref, source);
774
1006
  if (harness.status === "active") {
775
- return { data: { activated: false, already_active: true, harness }, text: `${harness.name} (${harness.slug}) is already active.` };
1007
+ const route = await defaultRouteAfterActivation(ctx, harness, input);
1008
+ return {
1009
+ data: { activated: false, already_active: true, harness, ...route.data },
1010
+ text: [`${harness.name} (${harness.slug}) is already active.`, ...route.lines].join("\n"),
1011
+ ...(route.failed ? { exitCode: ExitCode.failure } : {}),
1012
+ };
776
1013
  }
777
1014
  const readiness = await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}/readiness", "reading readiness", {
778
1015
  params: { harness_id: [harness.id] },
@@ -798,9 +1035,11 @@ export const activate = {
798
1035
  params: { harness_id: [harness.id] },
799
1036
  body: { force: false },
800
1037
  });
1038
+ const route = await defaultRouteAfterActivation(ctx, activated, input);
801
1039
  return {
802
- data: { activated: true, harness: activated, checks, warnings, readiness },
803
- text: [`Activated ${activated.name} (${activated.slug}); status ${activated.status}.`, ...readinessText(checks, warnings)].join("\n"),
1040
+ data: { activated: true, harness: activated, checks, warnings, readiness, ...route.data },
1041
+ text: [`Activated ${activated.name} (${activated.slug}); status ${activated.status}.`, ...readinessText(checks, warnings), ...route.lines].join("\n"),
1042
+ ...(route.failed ? { exitCode: ExitCode.failure } : {}),
804
1043
  };
805
1044
  },
806
1045
  };