@cavelon/cli 0.1.9 → 0.1.11

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 (64) hide show
  1. package/README.md +23 -10
  2. package/dist/access.js +194 -0
  3. package/dist/acting.js +123 -0
  4. package/dist/agent-env.js +20 -2
  5. package/dist/branches.js +4 -3
  6. package/dist/capacity.js +3 -2
  7. package/dist/code-hints.js +5 -4
  8. package/dist/command.js +6 -0
  9. package/dist/commands/api.js +40 -21
  10. package/dist/commands/async.js +7 -4
  11. package/dist/commands/chat.js +18 -15
  12. package/dist/commands/db.js +367 -0
  13. package/dist/commands/docs.js +87 -9
  14. package/dist/commands/fmt.js +6 -4
  15. package/dist/commands/index.js +8 -0
  16. package/dist/commands/init.js +106 -28
  17. package/dist/commands/limits-set.js +12 -11
  18. package/dist/commands/limits.js +4 -3
  19. package/dist/commands/loops.js +75 -19
  20. package/dist/commands/models.js +12 -13
  21. package/dist/commands/sandboxes.js +22 -16
  22. package/dist/commands/schema.js +6 -5
  23. package/dist/commands/session.js +134 -37
  24. package/dist/commands/setup.js +4 -2
  25. package/dist/commands/solution.js +289 -93
  26. package/dist/commands/tenants.js +58 -22
  27. package/dist/commands/values.js +110 -45
  28. package/dist/commands/work.js +31 -17
  29. package/dist/confirm-token.js +15 -5
  30. package/dist/context.js +3 -1
  31. package/dist/contracts.js +39 -13
  32. package/dist/database-queries.js +301 -0
  33. package/dist/default-route.js +1 -1
  34. package/dist/features.js +2 -1
  35. package/dist/fsutil.js +14 -0
  36. package/dist/harness-ref.js +6 -4
  37. package/dist/http.js +39 -4
  38. package/dist/invoke.js +7 -2
  39. package/dist/kit-codes.js +14 -2
  40. package/dist/limits.js +1 -1
  41. package/dist/main.js +13 -1
  42. package/dist/mcp.js +105 -26
  43. package/dist/openapi.js +5 -2
  44. package/dist/operations.js +3 -2
  45. package/dist/package-check.js +29 -4
  46. package/dist/package-files.js +5 -1
  47. package/dist/package-format.js +10 -0
  48. package/dist/preview-report.js +46 -7
  49. package/dist/principal.js +24 -2
  50. package/dist/printed.js +182 -0
  51. package/dist/project.js +2 -1
  52. package/dist/results.js +1 -1
  53. package/dist/secret-access.js +42 -0
  54. package/dist/session.js +39 -19
  55. package/dist/shell.js +0 -3
  56. package/dist/skills/cavelon-authoring/SKILL.md +88 -4
  57. package/dist/skills/cavelon-long-running/SKILL.md +9 -3
  58. package/dist/skills/cavelon-loop/SKILL.md +81 -19
  59. package/dist/skills/cavelon-testing/SKILL.md +28 -1
  60. package/dist/tenant-choice.js +7 -7
  61. package/dist/trace-view.js +11 -1
  62. package/dist/update-check.js +2 -2
  63. package/dist/user-config.js +24 -0
  64. package/package.json +1 -1
@@ -5,7 +5,8 @@ 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
7
  import { drivenByAgent } from "../agent-env.js";
8
- import { confirmation, confirmGiven, confirmTokenRequired, shellTokenRequired } from "../confirm-token.js";
8
+ import { confirmation, confirmTokenRequired, shellTokenRequired } from "../confirm-token.js";
9
+ import { actingTarget, targetLine, targetText } from "../acting.js";
9
10
  import { clip, keyValues } from "../format.js";
10
11
  import { readTextFile, writeFileAtomic } from "../fsutil.js";
11
12
  import { uncommitted } from "../git.js";
@@ -16,6 +17,7 @@ import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefault
16
17
  import { ceilingHint, LIMIT_ABOVE_CEILING, parseLimits, readLimits } from "../limits.js";
17
18
  import { digest, fileDigest, fileDigests, listPreviews, loadPreview, previewExpiry, readItemFiles, readPulledFiles, rememberAppliedFiles, retiredPreview, retirePreviews, savePreview, writePulledFiles, writeState, } from "../local-state.js";
18
19
  import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
20
+ import { applyQueryNotes, connectorOffer, NEEDS_SUPERADMIN_CODE, queryBlockedHint, queryChanges, readQueryBaseline, rememberQueries } from "../database-queries.js";
19
21
  import { cliFix, similarCodes } from "../code-hints.js";
20
22
  import { KIT_ERROR_CODES } from "../kit-codes.js";
21
23
  import { pairOrderHint, pairOrderPointer } from "../pair-order.js";
@@ -24,23 +26,24 @@ import { blockerDetails, blockerLines, changeLines, fieldChanges, locateBlockers
24
26
  import { readPrincipal } from "../principal.js";
25
27
  import { CASE_STATUSES, caseStatus, TESTING_PAGE } from "../results.js";
26
28
  import { KNOWLEDGE_OUTCOME_AREA, KNOWLEDGE_OUTCOME_PAGE, KNOWLEDGE_OUTCOMES, knowledgeOutcome } from "../trace-view.js";
27
- import { contextFlags, isUuid, requireInstance } from "../session.js";
29
+ import { isUuid, requireInstance } from "../session.js";
28
30
  import { listedPages } from "./docs.js";
29
31
  import { readInventory, readInventoryKinds, writeInventory } from "./inventory.js";
30
32
  import { checkedBy, MODEL_UNKNOWN_CODE, missingInventory, REFERENCE_UNKNOWN_CODE } from "../package-references.js";
31
- import { cavelonCommand, shellWord } from "../shell.js";
32
- import { secretSetCommand, targetFlags, variableSetCommand } from "./values.js";
33
+ import { cavelonCommand, printedCommand, spoken } from "../printed.js";
34
+ import { secretSetCommand, variableSetCommand } from "./values.js";
35
+ import { maySetSecrets, SECRET_SETTER, VARIABLE_SETTER } from "../secret-access.js";
36
+ import { ACTIVATOR, accessFor, accessOf, mayActivate, operationAccess, principalOf } from "../access.js";
33
37
  const HARNESS_OPTION = { type: "string", value: "<harness>", description: "The solution (harness): its name, slug or id; default: env file, then cavelon.yaml." };
34
38
  const ENV_OPTION = { type: "string", value: "<name>", description: "Use env/<name>.yaml: its tenant, solution and runtime bindings." };
35
39
  export function requireSolution(session, harness) {
36
40
  if (!session.project) {
37
- const flags = contextFlags(session);
38
41
  throw new CavelonError(ExitCode.usage, {
39
42
  code: "no_solution",
40
43
  message: "This folder is not a Cavelon solution (no cavelon.yaml here or above).",
41
44
  hint: harness
42
- ? `Make it the folder of that solution first: ${cavelonCommand("init", "--harness", harness)}${flags}, then run this command again.`
43
- : `Run \`cavelon init${flags}\`: it asks which solution, or a new one, on a terminal. \`cavelon harness list${flags}\` shows the solutions.`,
45
+ ? `Make it the folder of that solution first: ${cavelonCommand("init", "--harness", harness)}, then run this command again.`
46
+ : `Run \`${cavelonCommand("init")}\`: it asks which solution, or a new one, on a terminal. \`${cavelonCommand("harness", "list")}\` shows the solutions.`,
44
47
  });
45
48
  }
46
49
  return session.project;
@@ -58,7 +61,7 @@ function harnessRef(session, input) {
58
61
  async function findHarness(ctx, ref, source) {
59
62
  const { harness, candidates } = await lookupHarness(ctx, ref);
60
63
  if (!harness)
61
- throw harnessNotFoundError(ref, candidates, source, undefined, contextFlags(await ctx.session()));
64
+ throw harnessNotFoundError(ref, candidates, source);
62
65
  return harness;
63
66
  }
64
67
  async function cachedFirst(ctx, what, cached, offline, fetch) {
@@ -252,6 +255,7 @@ export const pull = {
252
255
  }
253
256
  const report = await writePackage(project.root, project.layout, exported, schema, options);
254
257
  await writePulledFiles(project.root, [...report.written, ...report.unchanged], placed);
258
+ await rememberQueries(project.root, exported, schema, "pull", ctx.io.now());
255
259
  if (harness && !project.harness)
256
260
  await setProjectKey(project, "harness", harness.slug);
257
261
  if (version && project.packageVersion !== version)
@@ -276,7 +280,7 @@ export const pull = {
276
280
  }
277
281
  for (const section of report.refused)
278
282
  ctx.warn(`Did not write section ${JSON.stringify(section)}: its name is not a plain file name.`);
279
- const pulledShared = harness && tenantWide ? Object.keys(exported).filter((section) => shared.has(section)) : undefined;
283
+ const pulledShared = harness && tenantWide ? Object.keys(exported).filter((section) => shared.has(section) && !emptyValue(exported[section])) : undefined;
280
284
  const rewritten = report.written.length + report.removed.length;
281
285
  const lines = [
282
286
  `Pulled ${harness ? `solution ${harness.name} (${harness.slug})` : "the tenant's full configuration"} into ${project.layout.package}/` +
@@ -292,7 +296,9 @@ export const pull = {
292
296
  ? [
293
297
  pulledShared.length
294
298
  ? `Tenant-wide: ${pulledShared.join(", ")} (shared by every solution of the tenant; only \`apply --include-tenant-wide\` sends them back).`
295
- : `The export carries no tenant-wide sections${askTenantWide ? "" : " (this instance's export does not take include_tenant_wide)"}, so --include-tenant-wide wrote none.`,
299
+ : Object.keys(exported).some((section) => shared.has(section))
300
+ ? "The export's tenant-wide sections are empty: the tenant has none of their settings yet."
301
+ : `The export carries no tenant-wide sections${askTenantWide ? "" : " (this instance's export does not take include_tenant_wide)"}, so --include-tenant-wide wrote none.`,
296
302
  ]
297
303
  : []),
298
304
  `Inventory: ${inventory.file} (${inventory.counts.map((c) => `${c.count} ${c.label}`).join(", ")})`,
@@ -343,6 +349,7 @@ async function validatePackage(ctx, project, offline) {
343
349
  limits: await limitsFor(ctx, offline),
344
350
  inventory,
345
351
  solution: project.harness,
352
+ queryBaseline: await readQueryBaseline(project.root),
346
353
  });
347
354
  return { disk, findings, schema, schemaVersion: schema["x-package-version"] ?? version ?? null, used, skipped };
348
355
  }
@@ -366,7 +373,7 @@ export const validate = {
366
373
  "changes, so its copy is read again after a minute (CAVELON_CONTRACT_TTL_SECONDS), or checked with the ETag the instance\n" +
367
374
  "sent with it; --verbose says which copy was used.\n" +
368
375
  "Warns (never fails) when a fan-out or Map loop's max_concurrency is above the instance's branch width, and when the\n" +
369
- "tenant runs fan-outs and Map loops in sequence, from the limits the instance last published.\n" +
376
+ "tenant runs fan-outs and Map loops in sequence, from the limits the instance last published for the tenant.\n" +
370
377
  "References to skills, tools, knowledge bases, solutions and models outside the package are checked against the tenant's\n" +
371
378
  "lists in .cavelon/inventory.json (pull, models list); a list no command has read yet is read now, unless --offline, and a\n" +
372
379
  "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" +
@@ -442,11 +449,11 @@ export const validate = {
442
449
  function valueNeeds(list) {
443
450
  return (list ?? []).map((n) => (typeof n === "string" ? { name: n } : n)).filter((n) => typeof n.name === "string" && n.name !== "");
444
451
  }
445
- function setCommands(preview, flags) {
452
+ function setCommands(preview, env) {
446
453
  const needs = preview.target_needs ?? {};
447
454
  return {
448
- secrets: valueNeeds(needs.secrets).map((n) => secretSetCommand(n.name, flags)),
449
- variables: valueNeeds(needs.variables).map((n) => variableSetCommand(n.name, flags)),
455
+ secrets: valueNeeds(needs.secrets).map((n) => secretSetCommand(n.name, env)),
456
+ variables: valueNeeds(needs.variables).map((n) => variableSetCommand(n.name, env)),
450
457
  };
451
458
  }
452
459
  function needLines(needs, command, more) {
@@ -466,16 +473,19 @@ function counts(map) {
466
473
  function list(items, max = 10) {
467
474
  return items.length > max ? `${items.slice(0, max).join(", ")} and ${items.length - max} more` : items.join(", ");
468
475
  }
469
- function needsLines(needs, flags) {
476
+ function needsLines(needs, access) {
470
477
  const lines = [];
471
478
  const secrets = valueNeeds(needs.secrets);
472
479
  if (secrets.length) {
473
- const each = needLines(secrets, (name) => secretSetCommand(name, flags), "cavelon secrets list --missing" + flags);
480
+ const each = needLines(secrets, (name) => secretSetCommand(name), cavelonCommand("secrets", "list", "--missing"));
474
481
  lines.push(["needs secrets", `${each}\n (a person runs these in a terminal, or sets them in the Admin; never the agent)`]);
475
482
  }
476
483
  const variables = valueNeeds(needs.variables);
477
- if (variables.length)
478
- lines.push(["needs variables", needLines(variables, (name) => variableSetCommand(name, flags), "cavelon variables list" + flags)]);
484
+ if (variables.length) {
485
+ const each = needLines(variables, (name) => variableSetCommand(name), cavelonCommand("variables", "list"));
486
+ const who = operationAccess(access, "PUT /api/v1/variables/{name}").allowed === false ? `\n (this credential may not set variables. ${VARIABLE_SETTER})` : "";
487
+ lines.push(["needs variables", each + who]);
488
+ }
479
489
  const grants = (needs.oauth_grants ?? []).map((g) => [g.kind, g.tool_slug, g.capability].filter(Boolean).join(" "));
480
490
  if (grants.length)
481
491
  lines.push(["needs grants", `${list(grants)} (a person connects them in the Admin)`]);
@@ -487,13 +497,29 @@ function needsLines(needs, flags) {
487
497
  lines.push(["needs identities", triggers.map((t) => `\n - ${t}`).join("")]);
488
498
  return lines;
489
499
  }
500
+ function emptyValue(value) {
501
+ if (value === null || value === undefined)
502
+ return true;
503
+ if (Array.isArray(value))
504
+ return value.length === 0;
505
+ return typeof value === "object" && Object.keys(value).length === 0;
506
+ }
507
+ function sectionsChanging(p, sections) {
508
+ if (changesNothing(p))
509
+ return [];
510
+ const s = p.summary ?? {};
511
+ const counted = new Set([s.creates, s.updates, s.deletes].flatMap((map) => Object.entries(map ?? {}).filter(([, n]) => n > 0).map(([kind]) => kind)));
512
+ const objects = fieldChanges(p.changes).map((c) => c.object);
513
+ const found = sections.filter((section) => counted.has(section) || objects.some((o) => o === section || o.startsWith(`${section}:`) || o.startsWith(`${section}.`) || o.startsWith(`${section}[`)));
514
+ return found.length ? found : undefined;
515
+ }
490
516
  function changesNothing(p) {
491
517
  const s = p.summary;
492
518
  if (!s || typeof s !== "object")
493
519
  return false;
494
520
  return !counts(s.creates) && !counts(s.updates) && !counts(s.deletes) && fieldChanges(p.changes).length === 0;
495
521
  }
496
- export function previewText(p, flags = "", context = {}) {
522
+ export function previewText(p, context = {}) {
497
523
  const lines = [["ready", p.ready ? "yes" : "no"]];
498
524
  const s = p.summary ?? {};
499
525
  for (const [label, map] of [["creates", s.creates], ["updates", s.updates], ["deletes", s.deletes]]) {
@@ -516,7 +542,7 @@ export function previewText(p, flags = "", context = {}) {
516
542
  const ignored = [...(p.ignored?.sections ?? []), ...(p.ignored?.fields ?? [])];
517
543
  if (ignored.length)
518
544
  lines.push(["ignored", list(ignored)]);
519
- const skipped = notApplied(p.ignored?.not_applied, context.disk?.package, context.harness);
545
+ const skipped = notApplied(p.ignored?.not_applied, context.disk?.package, context.harness, mayActivate(context.access));
520
546
  if (skipped.length)
521
547
  lines.push(["not applied", notAppliedLines(skipped)]);
522
548
  const impact = p.impact ?? {};
@@ -532,7 +558,7 @@ export function previewText(p, flags = "", context = {}) {
532
558
  const limits = Object.entries(budget.limits ?? {}).map(([k, v]) => `${k} ${v}`).join(", ");
533
559
  lines.push([`loop ${budget.node_slug}`, `${limits}${budget.worst_case_cost != null ? `; worst case ${JSON.stringify(budget.worst_case_cost)}` : ""}`]);
534
560
  }
535
- lines.push(...needsLines(p.target_needs ?? {}, flags));
561
+ lines.push(...needsLines(p.target_needs ?? {}, context.access));
536
562
  return keyValues(lines);
537
563
  }
538
564
  function previewReport(p, context) {
@@ -543,7 +569,7 @@ function previewReport(p, context) {
543
569
  const changes = fieldChanges(p.changes);
544
570
  if (changes.length)
545
571
  out.field_changes = changes;
546
- const skipped = notApplied(p.ignored?.not_applied, context.disk?.package, context.harness);
572
+ const skipped = notApplied(p.ignored?.not_applied, context.disk?.package, context.harness, mayActivate(context.access));
547
573
  if (skipped.length)
548
574
  out.not_applied = skipped;
549
575
  return out;
@@ -554,14 +580,14 @@ function sourceFiles(disk) {
554
580
  function previewIdOption(input) {
555
581
  const id = stringOption(input, "confirm");
556
582
  if (id !== undefined && !id.trim())
557
- throw usageError("--confirm needs the preview id that `cavelon apply` printed.");
583
+ throw usageError(`--confirm needs the preview id that \`${cavelonCommand("apply")}\` printed.`);
558
584
  return id?.trim();
559
585
  }
560
586
  function previewUnknown(previewId) {
561
587
  return new CavelonError(ExitCode.usage, {
562
588
  code: "preview_unknown",
563
589
  message: `No open preview ${previewId} in this solution.`,
564
- hint: "Run `cavelon apply` (with the same --env or --harness) for a new preview and confirm its id; `cavelon status` lists the open ones.",
590
+ hint: `Run \`${cavelonCommand("apply")}\` (with the same --env or --harness) for a new preview and confirm its id; \`${cavelonCommand("status")}\` lists the open ones.`,
565
591
  });
566
592
  }
567
593
  const PREVIEW_STALE = "import_preview_stale";
@@ -674,7 +700,7 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
674
700
  const session = await ctx.session();
675
701
  if (!stored) {
676
702
  const retired = await retiredPreview(project.root, previewId);
677
- throw retired ? previewRetired(retired, `${cavelonCommand("apply")}${targetFlags(session)}`) : previewUnknown(previewId);
703
+ throw retired ? previewRetired(retired, cavelonCommand("apply")) : previewUnknown(previewId);
678
704
  }
679
705
  const now = ctx.io.now().toISOString();
680
706
  const retire = (reason) => retirePreviews(project.root, [{ preview_id: stored.preview_id, reason, at: now }]);
@@ -684,7 +710,7 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
684
710
  throw new CavelonError(ExitCode.conflict, {
685
711
  code: "preview_expired",
686
712
  message: `Preview ${previewId} was made at ${stored.created_at} and expired${expiry.expires_at ? ` at ${expiry.expires_at}` : ""}; nothing was imported.`,
687
- hint: `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
713
+ hint: `Run \`${previewAgain(stored)}\` again, show the new preview, and confirm its id.`,
688
714
  details: { preview_id: stored.preview_id, created_at: stored.created_at, expires_at: expiry.expires_at },
689
715
  });
690
716
  }
@@ -696,15 +722,18 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
696
722
  });
697
723
  }
698
724
  const client = await ctx.client();
699
- if (stored.tenant_id && session.tokenKind !== "api_key" && client.target.tenantId && client.target.tenantId !== stored.tenant_id) {
725
+ const keyTenant = session.tokenKind === "api_key" ? (await actingTarget(ctx)).tenant?.id : undefined;
726
+ const actsIn = client.target.tenantId ?? keyTenant;
727
+ if (stored.tenant_id && actsIn && actsIn !== stored.tenant_id) {
700
728
  throw new CavelonError(ExitCode.conflict, {
701
729
  code: "preview_other_tenant",
702
- message: `Preview ${previewId} was made for tenant ${stored.tenant_id}, but this command acts in ${client.target.tenantId}.`,
730
+ message: `Preview ${previewId} was made for tenant ${stored.tenant_id}, but this command acts in ${actsIn}.`,
703
731
  hint: "Run the confirm command the preview printed; it names the preview's --env and --tenant. Or preview again here.",
704
732
  });
705
733
  }
706
734
  if (stored.tenant_id && session.tokenKind !== "api_key")
707
735
  client.target.tenantId = stored.tenant_id;
736
+ const acting = await actingTarget(ctx);
708
737
  const disk = await readPackage(project.root, project.layout);
709
738
  const changed = await filesChangedSince(project, stored, disk);
710
739
  if (digest(disk.package) !== stored.package_digest) {
@@ -712,13 +741,13 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
712
741
  throw new CavelonError(ExitCode.conflict, {
713
742
  code: "preview_files_changed",
714
743
  message: `The package files changed since preview ${previewId}${changed.length ? ` (${list(changed, 5)})` : ""}; nothing was imported.`,
715
- hint: `Run \`${previewAgain(stored, session)}\` for a preview of the files as they are now, show it, and confirm its id. ` +
744
+ hint: `Run \`${previewAgain(stored)}\` for a preview of the files as they are now, show it, and confirm its id. ` +
716
745
  `To import what preview ${previewId} showed instead, add --allow-stale to the confirm.`,
717
746
  details: { preview_id: stored.preview_id, files: changed },
718
747
  });
719
748
  }
720
749
  ctx.warn(`The package files changed since this preview${changed.length ? ` (${list(changed, 5)})` : ""}; importing what the preview showed (--allow-stale). ` +
721
- "The files keep their changes, which the instance does not hold; run `cavelon apply` to preview them.");
750
+ `The files keep their changes, which the instance does not hold; run \`${cavelonCommand("apply")}\` to preview them.`);
722
751
  }
723
752
  try {
724
753
  const result = await callStable(ctx, "POST", "/api/v1/agent-graph/import", "importing packages", {
@@ -731,18 +760,22 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
731
760
  ...others.map((p) => ({ preview_id: p.preview_id, reason: "superseded", at: now, by: stored.preview_id })),
732
761
  ]);
733
762
  await rememberImported(ctx, project, stored, disk, changed);
763
+ await rememberQueries(project.root, stored.request.package, (await schemaFor(ctx, packageVersionOf(stored.request.package), false)).schema, "apply", ctx.io.now());
734
764
  const summary = (result.summary ?? {});
735
- const flags = targetFlags(session, stored.env ?? session.envFile?.name);
736
- const still = setCommands(stored.preview, flags);
765
+ const still = setCommands(stored.preview, stored.env ?? undefined);
737
766
  const sharedSent = stored.request[INCLUDE_TENANT_WIDE] === true;
738
- const sharedReport = sharedSent ? tenantWideReport(stored.preview.tenant_wide) : undefined;
767
+ const resultReport = tenantWideReport(result.tenant_wide);
768
+ const sharedReport = resultReport ?? (sharedSent ? tenantWideReport(stored.preview.tenant_wide) : undefined);
769
+ const sharedImported = sharedReport ? sharedReport.imports : [];
739
770
  const sharedReaches = sharedReport?.reaches_active_solutions ?? [];
740
- const sharedText = sharedSent
741
- ? `${sharedReport?.sections.length ? sharedReport.sections.join(", ") : "the package's tenant-wide sections"}, for every solution of the tenant` +
771
+ const sharedText = sharedSent || sharedImported.length
772
+ ? `${sharedImported.length ? sharedImported.join(", ") : resultReport ? "none" : "the package's tenant-wide sections"}` +
773
+ (sharedImported.length || !resultReport ? ", for every solution of the tenant" : "") +
742
774
  (sharedReaches.length ? ` (active: ${list(sharedReaches, 10)})` : "")
743
775
  : undefined;
744
776
  const text = keyValues([
745
777
  ["applied", `preview ${stored.preview_id}${stored.harness ? ` to ${stored.harness.slug}` : ""}${stored.env ? ` (env ${stored.env})` : ""}`],
778
+ ["acted on", targetText(acting)],
746
779
  ["tenant-wide", sharedText],
747
780
  ["created", counts(summary?.creates) || undefined],
748
781
  ["updated", counts(summary?.updates) || undefined],
@@ -751,9 +784,17 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
751
784
  ["set secrets", still.secrets.length ? indented(still.secrets) + "\n (a person runs these; never the agent)" : undefined],
752
785
  ["set variables", still.variables.length ? indented(still.variables) : undefined],
753
786
  ]);
754
- const data = { applied: true, preview_id: stored.preview_id, env: stored.env, harness: stored.harness, result };
755
- if (sharedSent)
756
- data.tenant_wide = { applied: true, sections: sharedReport?.sections ?? null, reaches_active_solutions: sharedReaches };
787
+ const data = { applied: true, preview_id: stored.preview_id, env: stored.env, harness: stored.harness, target: acting, result };
788
+ if (sharedSent || sharedImported.length) {
789
+ data.tenant_wide = {
790
+ applied: resultReport ? resultReport.applied : true,
791
+ sections: sharedReport?.sections ?? null,
792
+ imported: sharedReport ? sharedImported : null,
793
+ left_out: sharedReport ? sharedReport.left_out : null,
794
+ reaches_active_solutions: sharedReaches,
795
+ reported_by: resultReport ? "import" : sharedReport ? "preview" : "kit",
796
+ };
797
+ }
757
798
  if (still.secrets.length || still.variables.length)
758
799
  data.set_commands = still;
759
800
  return { data, text };
@@ -764,7 +805,7 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
764
805
  throw requirementsChanged(error, stored, session, await catalogFor(ctx, false), disk);
765
806
  }
766
807
  if (error instanceof CavelonError && error.blockerDetails?.length)
767
- throw withBlockersLocated(error, disk, stored, session);
808
+ throw withBlockersLocated(error, disk, stored);
768
809
  if (error instanceof CavelonError && (error.code === "import_preview_stale" || (error.status === 409 && /preview/i.test(error.message)))) {
769
810
  await retire("stale");
770
811
  const said = error.details?.changed;
@@ -773,7 +814,7 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
773
814
  code: error.code === "conflict" ? "import_preview_stale" : error.code,
774
815
  status: 409,
775
816
  message: `The target changed since preview ${stored.preview_id}${changed.length ? `: ${changed.join("; ")}` : ""}; nothing was imported.`,
776
- hint: `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
817
+ hint: `Run \`${previewAgain(stored)}\` again, show the new preview, and confirm its id.`,
777
818
  docs: error.docs,
778
819
  ...(changed.length ? { details: { preview_id: stored.preview_id, changed } } : {}),
779
820
  });
@@ -791,21 +832,23 @@ function requirementsChanged(error, stored, session, catalog, disk) {
791
832
  if (pair && !known.has(pair.code))
792
833
  known.set(pair.code, pair.hint);
793
834
  }
835
+ if (details.some((b) => b.code === NEEDS_SUPERADMIN_CODE))
836
+ known.set(NEEDS_SUPERADMIN_CODE, queryBlockedHint(sectionFiles(disk, ["tools"])));
794
837
  return new CavelonError(ExitCode.conflict, {
795
838
  code: error.code,
796
839
  status: error.status,
797
840
  message: `The import's requirements changed since preview ${stored.preview_id}; nothing was imported; preview again.`,
798
- hint: [...known.values(), `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`].join(" "),
841
+ hint: [...known.values(), `Run \`${previewAgain(stored)}\` again, show the new preview, and confirm its id.`].join(" "),
799
842
  docs: error.docs,
800
843
  blockers,
801
844
  blockerDetails: details.length ? details : undefined,
802
845
  });
803
846
  }
804
- function withBlockersLocated(error, disk, stored, session) {
847
+ function withBlockersLocated(error, disk, stored) {
805
848
  return new CavelonError(error.exitCode, {
806
849
  code: error.code,
807
850
  message: `The import's own check refused preview ${stored.preview_id} when it applied; nothing was imported.`,
808
- hint: error.hint ?? `Fix what each blocker names, run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
851
+ hint: error.hint ?? `Fix what each blocker names, run \`${previewAgain(stored)}\` again, show the new preview, and confirm its id.`,
809
852
  docs: error.docs,
810
853
  status: error.status,
811
854
  details: error.details,
@@ -813,9 +856,8 @@ function withBlockersLocated(error, disk, stored, session) {
813
856
  blockerDetails: locateBlockers(error.blockerDetails ?? [], disk),
814
857
  });
815
858
  }
816
- function previewAgain(stored, session) {
817
- const harness = !stored.env && stored.harness ? ` --harness ${shellWord(stored.harness.slug)}` : "";
818
- return `cavelon apply${harness}${targetFlags(session, stored.env)}`;
859
+ function previewAgain(stored) {
860
+ return printedCommand(["apply", ...(!stored.env && stored.harness ? ["--harness", stored.harness.slug] : [])], { env: stored.env });
819
861
  }
820
862
  async function applyTarget(ctx, session, input, pkg) {
821
863
  const { ref, source } = harnessRef(session, input);
@@ -825,13 +867,13 @@ async function applyTarget(ctx, session, input, pkg) {
825
867
  if (found)
826
868
  return found;
827
869
  if (!source || source === "option" || isUuid(ref) || !SLUG.test(ref))
828
- throw harnessNotFoundError(ref, candidates, source, undefined, contextFlags(session));
870
+ throw harnessNotFoundError(ref, candidates, source);
829
871
  const name = packageHarnessName(pkg, ref) ?? ref;
830
- const create = `${cavelonCommand("harness", "new", ref, ...(name !== ref ? ["--name", name] : []))}${targetFlags(session, null)}`;
872
+ const create = cavelonCommand("harness", "new", ref, ...(name !== ref ? ["--name", name] : []));
831
873
  throw new CavelonError(ExitCode.failure, {
832
874
  code: "solution_not_found",
833
875
  message: `Solution ${ref}, which ${source} names, is not on the instance yet; apply previews into an existing solution and creates none.`,
834
- hint: `Create it as a draft: ${create}, then run \`${cavelonCommand("apply")}${targetFlags(session)}\` again.`,
876
+ hint: `Create it as a draft: ${create}, then run \`${cavelonCommand("apply")}\` again.`,
835
877
  details: { slug: ref, name, create },
836
878
  });
837
879
  }
@@ -878,6 +920,7 @@ export const apply = {
878
920
  readOnly: false,
879
921
  destructive: true,
880
922
  mcpTool: "apply",
923
+ operations: ["POST /api/v1/agent-graph/import"],
881
924
  options: {
882
925
  env: ENV_OPTION,
883
926
  harness: HARNESS_OPTION,
@@ -956,45 +999,59 @@ export const apply = {
956
999
  request[INCLUDE_TENANT_WIDE] = true;
957
1000
  if (tenantWide && solutionImport && !shared.length)
958
1001
  ctx.warn("--include-tenant-wide: the package holds no tenant-wide section, so this import changes nothing the whole tenant shares.");
1002
+ const baseline = await readQueryBaseline(project.root);
1003
+ const queries = applyQueryNotes(disk.package, baseline ? queryChanges(disk.package, schema, baseline) : [], connectorOffer((await (await ctx.contracts()).capabilities())));
1004
+ for (const warning of queries.warnings)
1005
+ ctx.warn(warning);
959
1006
  const client = await ctx.client();
960
1007
  const preview = await callStable(ctx, "POST", "/api/v1/agent-graph/import/preview", "previewing imports", {
961
1008
  body: request,
962
1009
  timeoutMs: 120_000,
963
1010
  });
964
1011
  const target = harness ? { id: harness.id, slug: harness.slug } : null;
965
- const data = { previewed: true, ...preview, env: envFile?.name ?? null, harness: target };
1012
+ const acting = await actingTarget(ctx);
1013
+ const data = { previewed: true, ...preview, env: envFile?.name ?? null, harness: target, target: acting };
1014
+ if (queries.data)
1015
+ data.database_queries = queries.data;
966
1016
  const reported = solutionImport ? tenantWideReport(preview.tenant_wide) : undefined;
967
1017
  const sections = reported?.sections ?? shared;
968
1018
  const applied = reported ? reported.applied : tenantWide || !takes;
969
- const sharedImported = applied ? sections : [];
970
- const sharedLeftOut = applied ? [] : sections;
1019
+ const sharedImported = reported ? reported.imports : applied ? sections : [];
1020
+ const sharedLeftOut = reported ? reported.left_out : applied ? [] : sections;
971
1021
  const reaches = reported?.reaches_active_solutions ?? [];
972
- if (sharedImported.length) {
1022
+ const sharedChanging = sharedImported.length ? sectionsChanging(preview, sharedImported) : [];
1023
+ const sharedSame = sharedImported.length > 0 && sharedChanging !== undefined && !sharedChanging.length;
1024
+ if (sharedImported.length && !sharedSame) {
973
1025
  const files = sectionFiles(disk, sharedImported).join(", ") || sharedImported.join(", ");
974
- ctx.warn(`${files} ${sharedImported.length === 1 ? "holds a section" : "hold sections"} the whole tenant shares: this import changes ${sharedImported.join(", ")} for every solution of the tenant` +
1026
+ const what = sharedChanging?.length
1027
+ ? `this import changes ${sharedChanging.join(", ")} for every solution of the tenant`
1028
+ : `this import sends ${sharedImported.join(", ")}, and what in ${sharedImported.length === 1 ? "it" : "them"} differs from the instance changes for every solution of the tenant`;
1029
+ ctx.warn(`${files} ${sharedImported.length === 1 ? "holds a section" : "hold sections"} the whole tenant shares: ${what}` +
975
1030
  (takes ? "." : " (this instance does not publish include_tenant_wide and imports them with every solution's package); remove the file unless that is meant."));
976
1031
  }
977
1032
  if (sections.length || tenantWide) {
978
1033
  data.tenant_wide = {
979
1034
  sections,
980
- applied,
981
- imported: sharedImported,
1035
+ applied: false,
1036
+ would_import: sharedImported,
982
1037
  left_out: sharedLeftOut,
1038
+ changing: sharedImported.length ? (sharedChanging ?? null) : [],
983
1039
  reaches_active_solutions: reaches,
984
1040
  reported_by: reported ? "instance" : "kit",
985
1041
  };
986
1042
  }
987
1043
  const reachText = reaches.length ? `the active solution${reaches.length === 1 ? "" : "s"} ${list(reaches, 10)}` : "";
988
- const sharedLine = sharedImported.length
989
- ? `tenant-wide: ${sharedImported.join(", ")} change for every solution of the tenant${reachText ? `, reaching ${reachText}` : ""}`
990
- : sharedLeftOut.length
991
- ? `tenant-wide: ${sharedLeftOut.join(", ")} left out (\`cavelon apply --include-tenant-wide\` imports them, for every solution of the tenant${reachText ? `; they would reach ${reachText}` : ""})`
992
- : undefined;
993
- const flags = targetFlags(session);
994
- const commands = setCommands(preview, flags);
1044
+ const sharedLine = sharedSame
1045
+ ? `tenant-wide: ${sharedImported.join(", ")} sent as the instance holds ${sharedImported.length === 1 ? "it" : "them"}; nothing changes for the tenant's solutions`
1046
+ : sharedImported.length
1047
+ ? `tenant-wide: ${sharedChanging?.length ? sharedChanging.join(", ") : sharedImported.join(", ")} change for every solution of the tenant${reachText ? `, reaching ${reachText}` : ""}`
1048
+ : sharedLeftOut.length
1049
+ ? `tenant-wide: ${sharedLeftOut.join(", ")} left out (\`${cavelonCommand("apply", "--include-tenant-wide")}\` imports them, for every solution of the tenant${reachText ? `; they would reach ${reachText}` : ""})`
1050
+ : undefined;
1051
+ const commands = setCommands(preview);
995
1052
  if (commands.secrets.length || commands.variables.length)
996
1053
  data.set_commands = commands;
997
- const context = { disk, harness: harness?.slug };
1054
+ const context = { disk, harness: harness?.slug, access: await accessFor(await ctx.client()) };
998
1055
  Object.assign(data, previewReport(preview, context));
999
1056
  if (!preview.ready) {
1000
1057
  const pair = pairOrderHint(await catalogFor(ctx, false), [
@@ -1009,15 +1066,20 @@ export const apply = {
1009
1066
  : undefined;
1010
1067
  if (sharedHint)
1011
1068
  data.tenant_wide_hint = sharedHint;
1069
+ const queryBlocked = blockerDetails(preview.blocker_details).some((b) => b.code === NEEDS_SUPERADMIN_CODE);
1070
+ const queryHint = queryBlocked ? queryBlockedHint(sectionFiles(disk, ["tools"])) : undefined;
1071
+ if (queryHint)
1072
+ data.database_query_hint = queryHint;
1012
1073
  return {
1013
1074
  data,
1014
1075
  text: [
1015
- previewText(preview, flags, context),
1076
+ previewText(preview, context),
1016
1077
  ...(sharedLine ? [sharedLine] : []),
1017
1078
  "",
1018
1079
  ...(pair ? [`hint: ${pair.hint}`] : []),
1019
1080
  ...(sharedHint ? [`hint: ${sharedHint}`] : []),
1020
- "The preview has blockers; fix them and run `cavelon apply` again.",
1081
+ ...(queryHint ? [`hint: ${queryHint}`] : []),
1082
+ `The preview has blockers; fix them and run \`${cavelonCommand("apply")}\` again.`,
1021
1083
  ].join("\n"),
1022
1084
  exitCode: ExitCode.validation,
1023
1085
  };
@@ -1029,7 +1091,8 @@ export const apply = {
1029
1091
  data,
1030
1092
  text: [
1031
1093
  `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
1032
- previewText(preview, flags, context),
1094
+ previewText(preview, context),
1095
+ ...(sharedLine ? [sharedLine] : []),
1033
1096
  "",
1034
1097
  "Nothing to import: the instance already holds what the package files say. No preview was stored.",
1035
1098
  ].join("\n"),
@@ -1043,7 +1106,7 @@ export const apply = {
1043
1106
  preview_id: preview.preview_id,
1044
1107
  created_at: ctx.io.now().toISOString(),
1045
1108
  instance: url,
1046
- tenant_id: client.target.tenantId ?? null,
1109
+ tenant_id: client.target.tenantId ?? acting.tenant?.id ?? null,
1047
1110
  env: envFile?.name ?? null,
1048
1111
  harness: target,
1049
1112
  package_digest: digest(disk.package),
@@ -1058,12 +1121,13 @@ export const apply = {
1058
1121
  }
1059
1122
  const reason = personReason(preview, harness, mode, envFile?.name, sharedImported, reaches);
1060
1123
  data.show_to_person = Boolean(reason);
1061
- const confirmLine = preview.preview_id ? `${cavelonCommand("apply", "--confirm", preview.preview_id)}${flags}` : undefined;
1124
+ const confirmLine = preview.preview_id ? cavelonCommand("apply", "--confirm", preview.preview_id) : undefined;
1062
1125
  const text = [
1063
1126
  `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
1064
- previewText(preview, flags, context),
1127
+ previewText(preview, context),
1065
1128
  ...(sharedLine ? [sharedLine] : []),
1066
1129
  "",
1130
+ targetLine(acting),
1067
1131
  ...(preview.preview_id ? [`preview id: ${preview.preview_id}`] : []),
1068
1132
  ...(reason ? [`This ${reason}: show this preview to a person before confirming.`] : []),
1069
1133
  ...(confirmLine ? [`Import exactly this: ${confirmLine}`] : []),
@@ -1097,7 +1161,7 @@ async function caseStatusAnswer(ctx, status) {
1097
1161
  code: status.status,
1098
1162
  kind: "test_case_status",
1099
1163
  message: status.meaning,
1100
- hint: status.next,
1164
+ hint: spoken(status.next),
1101
1165
  summary_counts: status.counts,
1102
1166
  docs: instance ? `${instance}${page}` : page,
1103
1167
  read: [{ page: TESTING_PAGE, command: cavelonCommand("docs", "get", TESTING_PAGE) }],
@@ -1108,7 +1172,7 @@ async function caseStatusAnswer(ctx, status) {
1108
1172
  ["code", status.status],
1109
1173
  ["kind", "test-case status (neither pass nor fail)"],
1110
1174
  ["meaning", status.meaning],
1111
- ["next", status.next],
1175
+ ["next", data.hint],
1112
1176
  ["counted as", status.counts.join(", ")],
1113
1177
  ["docs", data.docs],
1114
1178
  ["read", data.read[0].command],
@@ -1122,7 +1186,7 @@ async function knowledgeOutcomeAnswer(ctx, outcome) {
1122
1186
  code: outcome.value,
1123
1187
  kind: "knowledge_outcome",
1124
1188
  message: outcome.message,
1125
- hint: outcome.hint,
1189
+ hint: spoken(outcome.hint),
1126
1190
  ...(outcome.recorded_as ? { recorded_as: outcome.recorded_as } : {}),
1127
1191
  docs: instance ? `${instance}${page}` : page,
1128
1192
  read: [{ page: KNOWLEDGE_OUTCOME_PAGE, command: cavelonCommand("docs", "get", KNOWLEDGE_OUTCOME_PAGE) }],
@@ -1133,7 +1197,7 @@ async function knowledgeOutcomeAnswer(ctx, outcome) {
1133
1197
  ["code", outcome.value],
1134
1198
  ["kind", OUTCOME_KIND],
1135
1199
  ["meaning", outcome.message],
1136
- ["next", outcome.hint],
1200
+ ["next", data.hint],
1137
1201
  ["recorded as", outcome.recorded_as],
1138
1202
  ["docs", data.docs],
1139
1203
  ["read", data.read[0].command],
@@ -1143,6 +1207,7 @@ async function knowledgeOutcomeAnswer(ctx, outcome) {
1143
1207
  const OUTCOME_KIND = "knowledge outcome (what a knowledge search found, as its retrieval span's knowledge_outcome says)";
1144
1208
  export const explain = {
1145
1209
  name: "explain",
1210
+ tenantless: true,
1146
1211
  summary: "Look a code up in the instance's error catalog: what it means and how to fix it.",
1147
1212
  description: "Rule codes come from the package and graph checks, API error codes from failed requests; cavelon's own codes (validate's\n" +
1148
1213
  "findings, and errors the CLI raises itself, such as operation_not_found or uncommitted_changes) are known too. Uses the\n" +
@@ -1201,17 +1266,20 @@ export const explain = {
1201
1266
  const capacity = capacityCodeIn(entry.code);
1202
1267
  const stepCap = entry.code.toUpperCase() === PROCESSING_STEP_CAP_CODE;
1203
1268
  const ceiling = entry.code === LIMIT_ABOVE_CEILING;
1204
- const kitHint = capacity
1269
+ const kitText = capacity
1205
1270
  ? capacityHint(capacity, await readLimits(ctx).catch(() => undefined))
1206
1271
  : stepCap
1207
1272
  ? processingStepCapHint(await readLimits(ctx).catch(() => undefined))
1208
1273
  : ceiling
1209
1274
  ? ceilingHint(await readLimits(ctx).catch(() => undefined))
1210
1275
  : pairOrderPointer(entry.code);
1276
+ const kitHint = kitText ? spoken(kitText) : undefined;
1211
1277
  const pages = capacity === MODEL_ENDPOINT_BUSY ? [CAPACITY_TUTORIAL_PAGE, CAPACITY_CONCEPT_PAGE] : [CAPACITY_CONCEPT_PAGE, CAPACITY_TUTORIAL_PAGE];
1212
1278
  const read = capacity ? (await listedPages(ctx, pages)).map((page) => ({ page, command: cavelonCommand("docs", "get", page) })) : [];
1213
- const cli = entry.kind === "cli" ? undefined : cliFix(entry);
1214
- const data = { ...entry, ...(entry.area === KNOWLEDGE_OUTCOME_AREA ? { kind: "knowledge_outcome" } : {}), docs, ...(cli ? { cli_fix: cli } : {}), ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
1279
+ const fix = cliFix(entry);
1280
+ const cli = entry.kind === "cli" || !fix ? undefined : spoken(fix);
1281
+ const hint = entry.hint ? spoken(entry.hint) : entry.hint;
1282
+ const data = { ...entry, hint, ...(entry.area === KNOWLEDGE_OUTCOME_AREA ? { kind: "knowledge_outcome" } : {}), docs, ...(cli ? { cli_fix: cli } : {}), ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
1215
1283
  return {
1216
1284
  data,
1217
1285
  text: keyValues([
@@ -1229,7 +1297,7 @@ export const explain = {
1229
1297
  : `API error code${entry.area ? ` (${entry.area})` : ""}`,
1230
1298
  ],
1231
1299
  ["meaning", entry.message],
1232
- ["fix", entry.hint ?? undefined],
1300
+ ["fix", hint ?? undefined],
1233
1301
  ["with the CLI", cli],
1234
1302
  [capacity || stepCap || ceiling ? "raise" : "order", kitHint],
1235
1303
  ["why", entry.explanation ? clip(entry.explanation.replace(/\s+/g, " "), 600) : undefined],
@@ -1239,6 +1307,32 @@ export const explain = {
1239
1307
  };
1240
1308
  },
1241
1309
  };
1310
+ const SATISFIED = /^(set|ok|configured|confirmed|satisfied|complete|ready|bound)$/i;
1311
+ function missingSecrets(blockers) {
1312
+ const names = new Set();
1313
+ for (const check of blockers) {
1314
+ const items = Array.isArray(check.items) ? check.items : [];
1315
+ for (const item of items) {
1316
+ if (!/secret/i.test(item.kind ?? "") || item.confirmed === true || SATISFIED.test(item.status ?? ""))
1317
+ continue;
1318
+ const name = (item.key ?? "").replace(/^secrets?[:./]/i, "") || (item.label ?? "").replace(/^secret\s+/i, "");
1319
+ if (name)
1320
+ names.add(name);
1321
+ }
1322
+ if (items.length)
1323
+ continue;
1324
+ for (const match of `${check.label ?? ""} ${check.detail ?? check.message ?? ""}`.matchAll(/\bSecret ([A-Za-z0-9_.-]+)/g))
1325
+ names.add(match[1]);
1326
+ }
1327
+ return [...names];
1328
+ }
1329
+ function missingSecretsLine(names, may) {
1330
+ const which = `Secret${names.length === 1 ? "" : "s"} ${names.join(", ")} ${names.length === 1 ? "is" : "are"} not set`;
1331
+ const commands = names.map((n) => secretSetCommand(n)).join("; ");
1332
+ if (may === false)
1333
+ return `${which}, and this token's role cannot set secrets. ${SECRET_SETTER}: ${commands}`;
1334
+ return `${which}: a person sets ${names.length === 1 ? "it" : "each"} (never the agent): ${commands}`;
1335
+ }
1242
1336
  const count = (value) => (typeof value === "number" ? value : null);
1243
1337
  export async function solutionState(ctx, ref) {
1244
1338
  let harness;
@@ -1265,6 +1359,12 @@ export async function solutionState(ctx, ref) {
1265
1359
  });
1266
1360
  state.ready_to_activate = typeof readiness.ready_to_activate === "boolean" ? readiness.ready_to_activate : null;
1267
1361
  state.blockers = (readiness.blockers ?? []).map((b) => clip(String(b.label ?? b.key ?? b.detail ?? "?"), 80));
1362
+ const secrets = missingSecrets(readiness.blockers ?? []);
1363
+ const principal = await principalOf(await ctx.client());
1364
+ if (secrets.length)
1365
+ state.missing_secrets = { names: secrets, may_set: maySetSecrets(principal) };
1366
+ if (harness.status !== "active")
1367
+ state.may_activate = mayActivate(accessOf(principal));
1268
1368
  if ("latest_test_run" in readiness) {
1269
1369
  const run = readiness.latest_test_run;
1270
1370
  const summary = run?.summary ?? {};
@@ -1297,9 +1397,11 @@ export function solutionStateLines(state) {
1297
1397
  ? `not ready to activate${state.blockers?.length ? ` (${list(state.blockers, 3)})` : ""}`
1298
1398
  : undefined;
1299
1399
  const lines = [["state", [state.harness.status, ready].filter(Boolean).join(", ")]];
1400
+ if (state.missing_secrets)
1401
+ lines.push(["secrets", missingSecretsLine(state.missing_secrets.names, state.missing_secrets.may_set)]);
1300
1402
  const route = state.default_route;
1301
1403
  if (route)
1302
- lines.push(["default route", defaultRouteText(state.harness, route)]);
1404
+ lines.push(["default route", defaultRouteText(state.harness, route, state.may_activate ?? null)]);
1303
1405
  const run = state.latest_test_run;
1304
1406
  if (run === null)
1305
1407
  lines.push(["last test run", "none yet (`cavelon test run`)"]);
@@ -1313,12 +1415,14 @@ export function solutionStateLines(state) {
1313
1415
  lines.push(["state error", state.unavailable]);
1314
1416
  return lines;
1315
1417
  }
1316
- function defaultRouteText(harness, route) {
1418
+ function defaultRouteText(harness, route, may) {
1317
1419
  if (route.is_default === null)
1318
1420
  return "unknown (this instance does not say which solution is the default)";
1319
1421
  if (route.is_default)
1320
1422
  return "yes: the tenant's chat and widget answer with it where a conversation names no solution";
1321
1423
  const now = route.current ? named(route.current) : "no solution";
1424
+ if (harness.status !== "active" && may === false)
1425
+ return `no: ${now} answers the tenant's chat and widget; only an active solution can be the default, and to activate it ${ACTIVATOR}`;
1322
1426
  const how = harness.status === "active" ? cavelonCommand("harness", "default", harness.slug) : cavelonCommand("activate", "--harness", harness.slug, "--make-default");
1323
1427
  return `no: ${now} answers the tenant's chat and widget; preview a change with ${how}`;
1324
1428
  }
@@ -1344,7 +1448,7 @@ function readinessText(checks, warnings) {
1344
1448
  ...(warnings.length ? ["Warnings:", ...warnings.map((w) => ` - ${w}`)] : []),
1345
1449
  ];
1346
1450
  }
1347
- async function defaultRouteAfterActivation(ctx, harness, input) {
1451
+ async function defaultRouteAfterActivation(ctx, harness, input, defaultConfirmed = false) {
1348
1452
  const make = boolOption(input, "make-default");
1349
1453
  let route;
1350
1454
  try {
@@ -1358,8 +1462,8 @@ async function defaultRouteAfterActivation(ctx, harness, input) {
1358
1462
  if (route.current?.id === harness.id)
1359
1463
  return { data: { default_route: { is_default: true, current } }, lines: [`${named(harness)} is the tenant's default route.`] };
1360
1464
  const commands = defaultCommands(harness.slug);
1361
- const gate = make ? await confirmation(ctx, input, "activate", { harness: harness.id, from: current?.id ?? null }) : undefined;
1362
- if (gate?.confirmed) {
1465
+ const gate = make && !defaultConfirmed ? await confirmation(ctx, input, "activate", { harness: harness.id, from: current?.id ?? null }) : undefined;
1466
+ if (gate?.confirmed || (make && defaultConfirmed)) {
1363
1467
  try {
1364
1468
  await setDefaultRoute(ctx, harness.id);
1365
1469
  }
@@ -1384,7 +1488,7 @@ async function defaultRouteAfterActivation(ctx, harness, input) {
1384
1488
  const confirm = cavelonCommand("activate", "--harness", harness.slug, "--make-default", "--confirm");
1385
1489
  return {
1386
1490
  data: { default_route: { is_default: false, known: route.known, current, preview: commands.preview, confirm: gate.confirm(confirm), ...gate.fields } },
1387
- lines: [defaultChangeLine(harness, route), ...(gate.mismatch ? [gate.mismatch] : []), `Show this to a person; with their yes: ${gate.confirm(confirm)}`],
1491
+ lines: [defaultChangeLine(harness, route), gate.where, ...(gate.mismatch ? [gate.mismatch] : []), `Show this to a person; with their yes: ${gate.confirm(confirm)}`],
1388
1492
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
1389
1493
  };
1390
1494
  }
@@ -1394,11 +1498,40 @@ async function defaultRouteAfterActivation(ctx, harness, input) {
1394
1498
  ];
1395
1499
  return { data: { default_route: { is_default: false, known: route.known, current, preview: commands.preview, confirm: commands.confirm } }, lines };
1396
1500
  }
1501
+ async function reachOf(ctx, harness) {
1502
+ const channels = typeof harness.channel_count === "number" ? harness.channel_count : null;
1503
+ const triggers = await callStable(ctx, "GET", "/api/v1/triggers", "listing triggers", { params: { harness_id: [harness.id] } })
1504
+ .then((list) => list.filter((t) => t.harness_id === harness.id && t.is_active).map((t) => ({ id: t.id, slug: t.slug, name: t.name, type: t.trigger_type })))
1505
+ .catch(() => null);
1506
+ return { channels, triggers };
1507
+ }
1508
+ function reachText(harness, reach) {
1509
+ const parts = [];
1510
+ if (reach.channels)
1511
+ parts.push(`${reach.channels} channel${reach.channels === 1 ? "" : "s"}`);
1512
+ if (reach.triggers?.length)
1513
+ parts.push(`the active trigger${reach.triggers.length === 1 ? "" : "s"} ${reach.triggers.map((t) => `${t.slug} (${t.type})`).join(", ")}`);
1514
+ const unknown = [
1515
+ ...(reach.channels === null ? ["whether a channel reaches it (no channel_count)"] : []),
1516
+ ...(reach.triggers === null ? ["which triggers start its runs (the trigger list could not be read)"] : []),
1517
+ ];
1518
+ const lines = [
1519
+ parts.length
1520
+ ? `Activating ${named(harness)} puts it live for what reaches it: ${parts.join("; ")}. From then on it answers them.`
1521
+ : `Activating ${named(harness)} puts it live.`,
1522
+ ];
1523
+ if (unknown.length)
1524
+ lines.push(`This instance does not say ${unknown.join(", or ")}, so the activation waits for a confirm.`);
1525
+ return lines.join("\n");
1526
+ }
1397
1527
  export const activate = {
1398
1528
  name: "activate",
1399
1529
  summary: "Activate a solution through the readiness gate (never by force); says whether it is the tenant's default route.",
1400
1530
  description: "Only when every readiness check passes, and with a personal access token only when it was created with \"may activate\".\n" +
1401
1531
  "Activating without the evidence stays a person's decision in the Admin.\n" +
1532
+ "A solution that a channel or an active trigger reaches goes live for them at once, so its activation previews first\n" +
1533
+ "and only --confirm activates it; so does one on an instance that does not say what reaches it. Show the preview to a\n" +
1534
+ "person and confirm only with their yes. A draft that nothing reaches activates without --confirm.\n" +
1402
1535
  "Afterwards it says whether the solution is the tenant's default route (the one the tenant's chat and widget answer with\n" +
1403
1536
  "where no solution is named). --make-default previews making it the default; with --confirm as well, it changes it. That\n" +
1404
1537
  "changes live traffic: show the preview to a person and confirm only with their yes. `cavelon harness default` does the\n" +
@@ -1406,26 +1539,35 @@ export const activate = {
1406
1539
  readOnly: false,
1407
1540
  idempotent: true,
1408
1541
  mcpTool: "activate",
1542
+ operations: ["POST /api/v1/harnesses/{harness_id}/activate"],
1409
1543
  options: {
1410
1544
  harness: HARNESS_OPTION,
1411
1545
  env: ENV_OPTION,
1412
1546
  "make-default": { type: "boolean", description: "Also make it the tenant's default route: previews the change; with --confirm, makes it." },
1413
- confirm: { type: "boolean", mcpToken: true, description: "With --make-default: change the default route (after a person saw the preview)." },
1547
+ confirm: {
1548
+ type: "boolean",
1549
+ mcpToken: true,
1550
+ description: "With --make-default: change the default route; for a solution a channel or trigger reaches: activate it (after a person saw the preview).",
1551
+ },
1414
1552
  },
1415
- examples: ["cavelon activate", "cavelon activate --make-default", "cavelon activate --make-default --confirm", "cavelon activate --make-default --confirm <token>"],
1553
+ examples: [
1554
+ "cavelon activate",
1555
+ "cavelon activate --confirm",
1556
+ "cavelon activate --make-default",
1557
+ "cavelon activate --make-default --confirm",
1558
+ "cavelon activate --make-default --confirm <token>",
1559
+ ],
1416
1560
  async run(ctx, input) {
1417
1561
  const session = await ctx.session();
1418
1562
  const { ref, source } = harnessRef(session, input);
1419
1563
  if (!ref)
1420
1564
  throw usageError("Which solution?", "Pass --harness <name or slug> (`cavelon harness list` shows them), or set harness in cavelon.yaml or the env file.");
1421
- if (confirmGiven(input) && !boolOption(input, "make-default")) {
1422
- throw usageError("--confirm only applies to --make-default.", "Activation itself needs no confirmation; the default route does.");
1423
- }
1565
+ const make = boolOption(input, "make-default");
1424
1566
  if (ctx.mode === "mcp" && input.options.confirm === true)
1425
1567
  throw confirmTokenRequired("activate");
1426
1568
  const driven = drivenByAgent(ctx);
1427
1569
  if (driven?.by === "agent" && input.options.confirm === true) {
1428
- throw shellTokenRequired(cavelonCommand("activate", "--harness", ref, "--make-default"), driven.variable);
1570
+ throw shellTokenRequired(cavelonCommand("activate", "--harness", ref, ...(make ? ["--make-default"] : [])));
1429
1571
  }
1430
1572
  const client = await ctx.client();
1431
1573
  const principal = await readPrincipal(client);
@@ -1453,25 +1595,79 @@ export const activate = {
1453
1595
  if (!readiness.ready_to_activate) {
1454
1596
  const blockers = readiness.blockers ?? [];
1455
1597
  const pair = pairOrderHint(await catalogFor(ctx, false), blockers.flatMap((b) => [b.message ?? undefined, b.detail ?? undefined]));
1598
+ const secrets = missingSecrets(blockers);
1599
+ const maySet = maySetSecrets(principal);
1600
+ const secretsLine = secrets.length ? missingSecretsLine(secrets, maySet) : undefined;
1456
1601
  return {
1457
- data: { activated: false, harness, checks, warnings, readiness, ...(pair ? { hint: pair.hint } : {}) },
1602
+ data: {
1603
+ activated: false,
1604
+ harness,
1605
+ checks,
1606
+ warnings,
1607
+ readiness,
1608
+ ...(pair ? { hint: pair.hint } : {}),
1609
+ ...(secrets.length ? { missing_secrets: { names: secrets, may_set: maySet, next: secretsLine } } : {}),
1610
+ },
1458
1611
  text: [
1459
1612
  `${harness.name} (${harness.slug}) is not ready to activate:`,
1460
1613
  ...blockers.map((b) => ` - ${checkLine(b)}`),
1461
1614
  ...readinessText(checks, warnings),
1462
1615
  ...(pair ? [`hint: ${pair.hint}`] : []),
1616
+ ...(secretsLine ? [secretsLine] : []),
1463
1617
  "Resolve these (often: a passing test run), then activate again. Forcing past the gate is a person's decision in the Admin.",
1464
1618
  ].join("\n"),
1465
1619
  exitCode: ExitCode.validation,
1466
1620
  };
1467
1621
  }
1622
+ const reach = await reachOf(ctx, harness);
1623
+ const live = Boolean(reach.channels) || Boolean(reach.triggers?.length) || reach.channels === null || reach.triggers === null;
1624
+ let defaultConfirmed = false;
1625
+ if (live) {
1626
+ const route = make ? await readDefaultRoute(ctx).catch(() => undefined) : undefined;
1627
+ const change = {
1628
+ harness: harness.id,
1629
+ activate: true,
1630
+ channels: reach.channels,
1631
+ triggers: reach.triggers?.map((t) => t.id) ?? null,
1632
+ ...(make ? { make_default: true, from: route?.current?.id ?? null } : {}),
1633
+ };
1634
+ const gate = await confirmation(ctx, input, "activate", change);
1635
+ if (!gate.confirmed) {
1636
+ const confirm = gate.confirm(cavelonCommand("activate", "--harness", harness.slug, ...(make ? ["--make-default"] : []), "--confirm"));
1637
+ const routeLine = make && route && route.current?.id !== harness.id ? [defaultChangeLine(harness, route)] : [];
1638
+ return {
1639
+ data: {
1640
+ activated: false,
1641
+ would: "activate",
1642
+ harness,
1643
+ reach: { channels: reach.channels, triggers: reach.triggers },
1644
+ checks,
1645
+ warnings,
1646
+ readiness,
1647
+ ...(make ? { default_route: { current: route?.current ? { id: route.current.id, slug: route.current.slug, name: route.current.name } : null, known: route?.known ?? false } } : {}),
1648
+ confirm,
1649
+ ...gate.fields,
1650
+ },
1651
+ text: [
1652
+ reachText(harness, reach),
1653
+ ...routeLine,
1654
+ ...readinessText(checks, warnings),
1655
+ gate.where,
1656
+ ...(gate.mismatch ? [gate.mismatch] : []),
1657
+ `Nothing was activated. Show this to a person; with their yes: ${confirm}`,
1658
+ ].join("\n"),
1659
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
1660
+ };
1661
+ }
1662
+ defaultConfirmed = make;
1663
+ }
1468
1664
  const activated = await callStable(ctx, "POST", "/api/v1/harnesses/{harness_id}/activate", "activating solutions", {
1469
1665
  params: { harness_id: [harness.id] },
1470
1666
  body: { force: false },
1471
1667
  });
1472
- const route = await defaultRouteAfterActivation(ctx, activated, input);
1668
+ const route = await defaultRouteAfterActivation(ctx, activated, input, defaultConfirmed);
1473
1669
  return {
1474
- data: { activated: true, harness: activated, checks, warnings, readiness, ...route.data },
1670
+ data: { activated: true, harness: activated, ...(live ? { reach } : {}), checks, warnings, readiness, ...route.data },
1475
1671
  text: [`Activated ${activated.name} (${activated.slug}); status ${activated.status}.`, ...readinessText(checks, warnings), ...route.lines].join("\n"),
1476
1672
  ...(route.failed ? { exitCode: ExitCode.failure } : route.exitCode ? { exitCode: route.exitCode } : {}),
1477
1673
  };