@cavelon/cli 0.1.4 → 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.
@@ -9,16 +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";
18
22
  import { CASE_STATUSES, caseStatus, TESTING_PAGE } from "../results.js";
19
23
  import { isUuid, requireInstance } from "../session.js";
20
24
  import { listedPages } from "./docs.js";
21
- import { writeInventory } from "./inventory.js";
25
+ import { readInventory, writeInventory } from "./inventory.js";
22
26
  import { cavelonCommand, shellWord } from "../shell.js";
23
27
  import { secretSetCommand, targetFlags, variableSetCommand } from "./values.js";
24
28
  const HARNESS_OPTION = { type: "string", value: "<harness>", description: "The solution (harness): its name, slug or id; default: env file, then cavelon.yaml." };
@@ -129,6 +133,15 @@ function uncommittedChanges(files, what) {
129
133
  details: { files },
130
134
  });
131
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
+ }
132
145
  async function editedSincePull(project, pkg, schema) {
133
146
  const planned = await writePackage(project.root, project.layout, pkg, schema, { dryRun: true });
134
147
  const pulled = await readPulledFiles(project.root);
@@ -146,14 +159,17 @@ export const pull = {
146
159
  description: "With a solution (--harness, or cavelon.yaml's harness), exports that solution; without one, the tenant's full configuration.\n" +
147
160
  "A file whose content did not change keeps its bytes, so `git diff` shows what changed on the instance. Files of sections\n" +
148
161
  "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.",
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.",
150
164
  readOnly: false,
151
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.",
152
168
  idempotent: true,
153
169
  mcpTool: "pull",
154
170
  options: {
155
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." },
156
- 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." },
157
173
  },
158
174
  examples: ["cavelon pull --harness support", "cavelon pull && git diff -- package tests"],
159
175
  async run(ctx, input) {
@@ -162,7 +178,9 @@ export const pull = {
162
178
  const url = requireInstance(session);
163
179
  const layoutDirs = [project.layout.package, ...Object.values(project.layout.items)];
164
180
  const force = boolOption(input, "force");
165
- 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));
166
184
  if (dirty?.length)
167
185
  throw uncommittedChanges(dirty, "pull would overwrite uncommitted changes");
168
186
  const { ref } = harnessRef(session, input);
@@ -210,7 +228,7 @@ export const pull = {
210
228
  ctx.warn(`Kept ${file}: its section is not in this instance's package schema.`);
211
229
  for (const section of report.refused)
212
230
  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;
231
+ const rewritten = report.written.length + report.removed.length;
214
232
  const lines = [
215
233
  `Pulled ${harness ? `solution ${harness.name} (${harness.slug})` : "the tenant's full configuration"} into ${project.layout.package}/` +
216
234
  (Object.keys(project.layout.items).length ? ` and ${Object.values(project.layout.items).join("/, ")}/` : "") +
@@ -219,7 +237,7 @@ export const pull = {
219
237
  ...report.removed.map((f) => `removed ${f}`),
220
238
  `${report.unchanged.length} file${report.unchanged.length === 1 ? "" : "s"} unchanged.`,
221
239
  `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.",
240
+ rewritten ? `See what changed: git diff -- ${layoutDirs.join(" ")}` : "Nothing changed on the instance since the last pull.",
223
241
  ];
224
242
  return { data: { ...record, inventory }, text: lines.join("\n") };
225
243
  },
@@ -242,6 +260,7 @@ async function validatePackage(ctx, project, offline) {
242
260
  catalog: await catalogFor(ctx, offline),
243
261
  accepted: await acceptedVersions(ctx, offline),
244
262
  limits: await limitsFor(ctx, offline),
263
+ inventory: await readInventory(project.root),
245
264
  });
246
265
  return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null, used };
247
266
  }
@@ -365,7 +384,7 @@ function needsLines(needs, flags) {
365
384
  lines.push(["needs identities", triggers.map((t) => `\n - ${t}`).join("")]);
366
385
  return lines;
367
386
  }
368
- export function previewText(p, flags = "") {
387
+ export function previewText(p, flags = "", context = {}) {
369
388
  const lines = [["ready", p.ready ? "yes" : "no"]];
370
389
  const s = p.summary ?? {};
371
390
  for (const [label, map] of [["creates", s.creates], ["updates", s.updates], ["deletes", s.deletes]]) {
@@ -375,13 +394,22 @@ export function previewText(p, flags = "") {
375
394
  }
376
395
  if (lines.length === 1)
377
396
  lines.push(["changes", "none"]);
378
- 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)
379
404
  lines.push(["blockers", p.blockers.map((b) => `\n - ${clip(b, 300)}`).join("")]);
380
405
  if (p.warnings?.length)
381
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` : "")]);
382
407
  const ignored = [...(p.ignored?.sections ?? []), ...(p.ignored?.fields ?? [])];
383
408
  if (ignored.length)
384
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)]);
385
413
  const impact = p.impact ?? {};
386
414
  const active = (impact.active_harnesses ?? []).map((h) => {
387
415
  const via = [...(h.tools ?? []), ...(h.knowledge_bases ?? []), ...(h.sandboxes ?? [])];
@@ -398,6 +426,22 @@ export function previewText(p, flags = "") {
398
426
  lines.push(...needsLines(p.target_needs ?? {}, flags));
399
427
  return keyValues(lines);
400
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
+ }
401
445
  function previewIdOption(input) {
402
446
  const id = stringOption(input, "confirm");
403
447
  if (id !== undefined && !id.trim())
@@ -442,6 +486,8 @@ async function confirmPreview(ctx, project, previewId) {
442
486
  });
443
487
  for (const other of await listPreviews(project.root))
444
488
  await deletePreview(project.root, other.preview_id);
489
+ if (stored.file_digests)
490
+ await rememberAppliedFiles(project.root, stored.file_digests);
445
491
  const summary = (result.summary ?? {});
446
492
  const flags = targetFlags(session, stored.env ?? session.envFile?.name);
447
493
  const still = setCommands(stored.preview, flags);
@@ -460,10 +506,12 @@ async function confirmPreview(ctx, project, previewId) {
460
506
  return { data, text };
461
507
  }
462
508
  catch (error) {
463
- 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)) {
464
510
  await deletePreview(project.root, stored.preview_id);
465
- throw requirementsChanged(error, stored, session, await catalogFor(ctx, false));
511
+ throw requirementsChanged(error, stored, session, await catalogFor(ctx, false), disk);
466
512
  }
513
+ if (error instanceof CavelonError && error.blockerDetails?.length)
514
+ throw withBlockersLocated(error, disk, stored, session);
467
515
  if (error instanceof CavelonError && (error.code === "import_preview_stale" || (error.status === 409 && /preview/i.test(error.message)))) {
468
516
  await deletePreview(project.root, stored.preview_id);
469
517
  throw new CavelonError(ExitCode.conflict, {
@@ -478,8 +526,9 @@ async function confirmPreview(ctx, project, previewId) {
478
526
  }
479
527
  }
480
528
  const REQUIREMENTS_CHANGED = "package_requirements_changed";
481
- function requirementsChanged(error, stored, session, catalog) {
482
- 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);
483
532
  const known = new Map();
484
533
  for (const blocker of blockers) {
485
534
  const pair = pairOrderHint(catalog, [blocker]);
@@ -493,6 +542,19 @@ function requirementsChanged(error, stored, session, catalog) {
493
542
  hint: [...known.values(), `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`].join(" "),
494
543
  docs: error.docs,
495
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),
496
558
  });
497
559
  }
498
560
  function previewAgain(stored, session) {
@@ -520,7 +582,12 @@ function packageHarnessName(pkg, slug) {
520
582
  return name ? name.slice(0, 255) : undefined;
521
583
  }
522
584
  function personReason(preview, harness, mode, env) {
523
- 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)
524
591
  return "reaches an active solution";
525
592
  if (counts(preview.summary?.deletes) || mode === "replace")
526
593
  return "deletes";
@@ -592,17 +659,19 @@ export const apply = {
592
659
  const commands = setCommands(preview, flags);
593
660
  if (commands.secrets.length || commands.variables.length)
594
661
  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
- }
662
+ const context = { disk, harness: harness?.slug };
663
+ Object.assign(data, previewReport(preview, context));
598
664
  if (!preview.ready) {
599
- 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
+ ]);
600
669
  if (pair)
601
670
  data.hint = pair.hint;
602
671
  return {
603
672
  data,
604
673
  text: [
605
- previewText(preview, flags),
674
+ previewText(preview, flags, context),
606
675
  "",
607
676
  ...(pair ? [`hint: ${pair.hint}`] : []),
608
677
  "The preview has blockers; fix them and run `cavelon apply` again.",
@@ -610,6 +679,9 @@ export const apply = {
610
679
  exitCode: ExitCode.validation,
611
680
  };
612
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
+ }
613
685
  if (preview.preview_id) {
614
686
  const stored = {
615
687
  preview_id: preview.preview_id,
@@ -619,6 +691,7 @@ export const apply = {
619
691
  env: envFile?.name ?? null,
620
692
  harness: target,
621
693
  package_digest: digest(disk.package),
694
+ file_digests: await fileDigests(project.root, sourceFiles(disk)),
622
695
  request,
623
696
  preview,
624
697
  };
@@ -629,7 +702,7 @@ export const apply = {
629
702
  const confirmLine = preview.preview_id ? `${cavelonCommand("apply", "--confirm", preview.preview_id)}${flags}` : undefined;
630
703
  const text = [
631
704
  `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
632
- previewText(preview, flags),
705
+ previewText(preview, flags, context),
633
706
  "",
634
707
  ...(preview.preview_id ? [`preview id: ${preview.preview_id}`] : []),
635
708
  ...(reason ? [`This ${reason}: show this preview to a person before confirming.`] : []),
@@ -685,7 +758,10 @@ async function caseStatusAnswer(ctx, status) {
685
758
  export const explain = {
686
759
  name: "explain",
687
760
  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" +
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" +
689
765
  `Also explains the test-case statuses that are neither pass nor fail: ${CASE_STATUSES.map((s) => s.status).join(", ")}.`,
690
766
  readOnly: true,
691
767
  idempotent: true,
@@ -698,7 +774,7 @@ export const explain = {
698
774
  let entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code);
699
775
  if (!entry && status)
700
776
  return caseStatusAnswer(ctx, status);
701
- if (!entry || entry.kind === "kit") {
777
+ if (!entry || entry.kind === "kit" || entry.kind === "cli") {
702
778
  catalog = await (await ctx.contracts()).errorCatalog({ refresh: true }).catch(() => catalog);
703
779
  entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code) ?? entry;
704
780
  }
@@ -710,13 +786,19 @@ export const explain = {
710
786
  });
711
787
  }
712
788
  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);
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);
716
797
  throw new CavelonError(ExitCode.failure, {
717
798
  code: "code_unknown",
718
- 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.`,
719
800
  hint: similar.length ? `Similar codes: ${similar.join(", ")}.` : `Try \`cavelon docs search ${code}\`.`,
801
+ details: { similar },
720
802
  });
721
803
  }
722
804
  const docs = entry.docs?.startsWith("/") ? `${requireInstance(await ctx.session())}${entry.docs}` : entry.docs;
@@ -732,7 +814,8 @@ export const explain = {
732
814
  : pairOrderPointer(entry.code);
733
815
  const pages = capacity === MODEL_ENDPOINT_BUSY ? [CAPACITY_TUTORIAL_PAGE, CAPACITY_CONCEPT_PAGE] : [CAPACITY_CONCEPT_PAGE, CAPACITY_TUTORIAL_PAGE];
734
816
  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 } : {}) };
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 } : {}) };
736
819
  return {
737
820
  data,
738
821
  text: keyValues([
@@ -743,10 +826,13 @@ export const explain = {
743
826
  ? `rule code${entry.rule ? ` (rule ${entry.rule})` : ""}`
744
827
  : entry.kind === "kit"
745
828
  ? "cavelon validate code"
746
- : `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})` : ""}`,
747
832
  ],
748
833
  ["meaning", entry.message],
749
834
  ["fix", entry.hint ?? undefined],
835
+ ["with the CLI", cli],
750
836
  [capacity || stepCap || ceiling ? "raise" : "order", kitHint],
751
837
  ["why", entry.explanation ? clip(entry.explanation.replace(/\s+/g, " "), 600) : undefined],
752
838
  ["docs", docs],
@@ -755,6 +841,66 @@ export const explain = {
755
841
  };
756
842
  },
757
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
+ }
758
904
  function checkLine(c) {
759
905
  return clip([c.label ?? c.key, c.message ?? c.detail].filter(Boolean).join(": "), 300);
760
906
  }
@@ -777,20 +923,76 @@ function readinessText(checks, warnings) {
777
923
  ...(warnings.length ? ["Warnings:", ...warnings.map((w) => ` - ${w}`)] : []),
778
924
  ];
779
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
+ }
780
969
  export const activate = {
781
970
  name: "activate",
782
- 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.",
783
972
  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.",
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.",
785
978
  readOnly: false,
786
979
  idempotent: true,
787
980
  mcpTool: "activate",
788
- 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"],
789
988
  async run(ctx, input) {
790
989
  const session = await ctx.session();
791
990
  const { ref, source } = harnessRef(session, input);
792
991
  if (!ref)
793
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
+ }
794
996
  const client = await ctx.client();
795
997
  const principal = await readPrincipal(client);
796
998
  if (principal?.kind === "personal_access_token" && principal.token && !principal.token.may_activate) {
@@ -802,7 +1004,12 @@ export const activate = {
802
1004
  }
803
1005
  const harness = await findHarness(ctx, ref, source);
804
1006
  if (harness.status === "active") {
805
- 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
+ };
806
1013
  }
807
1014
  const readiness = await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}/readiness", "reading readiness", {
808
1015
  params: { harness_id: [harness.id] },
@@ -828,9 +1035,11 @@ export const activate = {
828
1035
  params: { harness_id: [harness.id] },
829
1036
  body: { force: false },
830
1037
  });
1038
+ const route = await defaultRouteAfterActivation(ctx, activated, input);
831
1039
  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"),
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 } : {}),
834
1043
  };
835
1044
  },
836
1045
  };