@cavelon/cli 0.1.12 → 0.1.14

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.
@@ -12,12 +12,12 @@ import { readTextFile, writeFileAtomic } from "../fsutil.js";
12
12
  import { uncommitted } from "../git.js";
13
13
  import { callStable, workflowOperation } from "../invoke.js";
14
14
  import { deref, jsonBodySchema } from "../openapi.js";
15
- import { harnessNotFoundError, lookupHarness, SLUG } from "../harness-ref.js";
15
+ import { harnessNotFoundError, listHarnesses, lookupHarness, SLUG } from "../harness-ref.js";
16
16
  import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefaultRoute } from "../default-route.js";
17
17
  import { ceilingHint, LIMIT_ABOVE_CEILING, parseLimits, readLimits } from "../limits.js";
18
18
  import { digest, fileDigest, fileDigests, listPreviews, loadPreview, previewExpiry, readItemFiles, readPulledFiles, rememberAppliedFiles, retiredPreview, retirePreviews, savePreview, writePulledFiles, writeState, } from "../local-state.js";
19
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";
20
+ import { applyQueryNotes, connectorOffer, importWritesQueries, NEEDS_SUPERADMIN_CODE, queryBlockedHint, queryChanges, queryTools, readQueryBaseline, rememberQueries, schemaKnowsWrites } from "../database-queries.js";
21
21
  import { cliFix, similarCodes } from "../code-hints.js";
22
22
  import { KIT_ERROR_CODES } from "../kit-codes.js";
23
23
  import { confirmationPointer } from "../change-confirmation.js";
@@ -124,7 +124,7 @@ async function limitsFor(ctx, offline) {
124
124
  async function acceptedVersions(ctx, offline) {
125
125
  return (await capabilitiesFor(ctx, offline))?.contracts?.package_versions?.accepted;
126
126
  }
127
- const BLOCKING_WARNINGS = new Set([REFERENCE_UNKNOWN_CODE, MODEL_UNKNOWN_CODE]);
127
+ const BLOCKING_WARNINGS = new Set([REFERENCE_UNKNOWN_CODE, MODEL_UNKNOWN_CODE, "tool_call_database_query_missing"]);
128
128
  function findingLine(f) {
129
129
  const where = f.file ? `${f.file}${f.line ? `:${f.line}` : ""}` : "";
130
130
  const at = f.path ? ` ${f.path}` : "";
@@ -312,9 +312,9 @@ export const pull = {
312
312
  return { data: { ...record, inventory, ...(pulledShared ? { tenant_wide_pulled: pulledShared } : {}) }, text: lines.join("\n") };
313
313
  },
314
314
  };
315
- async function inventoryFor(ctx, project, disk, offline) {
315
+ async function inventoryFor(ctx, project, disk, offline, schema) {
316
316
  let inventory = await readInventory(project.root);
317
- const missing = missingInventory(disk, inventory);
317
+ const missing = missingInventory(disk, inventory, schema);
318
318
  let failed = missing;
319
319
  if (missing.length && !offline) {
320
320
  failed = await readInventoryKinds(ctx, project.root, missing, ctx.io.now());
@@ -342,7 +342,16 @@ async function validatePackage(ctx, project, offline) {
342
342
  : "The instance does not publish its package schema (/api/v1/meta/package-schema).",
343
343
  });
344
344
  }
345
- const { inventory, skipped } = await inventoryFor(ctx, project, disk, offline);
345
+ const { inventory, skipped } = await inventoryFor(ctx, project, disk, offline, schema);
346
+ let queryConnections;
347
+ if (!offline && schemaKnowsWrites(schema) && queryTools(disk.package).some(t => t.tool.database_query?.kind === "write")) {
348
+ try {
349
+ queryConnections = await callStable(ctx, "GET", "/api/v1/database-connectors/connections", "checking write-query connections");
350
+ }
351
+ catch {
352
+ ctx.warn("The write-query connection check was skipped: the instance's connections could not be read, so allows_writes is unknown.");
353
+ }
354
+ }
346
355
  const findings = checkPackage(disk, {
347
356
  schema,
348
357
  catalog: await catalogFor(ctx, offline),
@@ -351,6 +360,7 @@ async function validatePackage(ctx, project, offline) {
351
360
  inventory,
352
361
  solution: project.harness,
353
362
  queryBaseline: await readQueryBaseline(project.root),
363
+ queryConnections,
354
364
  });
355
365
  return { disk, findings, schema, schemaVersion: schema["x-package-version"] ?? version ?? null, used, skipped };
356
366
  }
@@ -380,6 +390,8 @@ export const validate = {
380
390
  "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" +
381
391
  "on the instance before the import; the import preview blocks it otherwise, so validate does not say \"Valid\" then, and\n" +
382
392
  "--strict fails on every warning (exit 3).\n" +
393
+ "For write queries, reads connections now unless --offline and warns only on explicit allows_writes: false; an\n" +
394
+ "omitted flag or unreadable list stays unknown. Warns when a direct query node requires confirmation it cannot collect.\n" +
383
395
  "Each finding carries a code: `cavelon explain <code>` says more. The import preview checks everything again on the server.\n\n" +
384
396
  "With --json, `warnings` is always a list of `{code, message}` objects: the warning findings (at most --limit), then the\n" +
385
397
  "warnings about the run, such as a stale copy of the schema, with code null. `warning_count` counts them all and\n" +
@@ -517,6 +529,8 @@ function sectionsChanging(p, sections) {
517
529
  return found.length ? found : undefined;
518
530
  }
519
531
  function changesNothing(p) {
532
+ if (importWritesQueries(p))
533
+ return false;
520
534
  const s = p.summary;
521
535
  if (!s || typeof s !== "object")
522
536
  return false;
@@ -701,6 +715,17 @@ async function instanceHolds(ctx, project, stored) {
701
715
  function personApplyCommand(stored) {
702
716
  return personCommand("apply", ...(stored.env ? ["--env", stored.env] : []), "--confirm", stored.preview_id);
703
717
  }
718
+ function importNeedsAPerson(access) {
719
+ const { person } = operationAccess(access, "POST /api/v1/agent-graph/import");
720
+ if (!person)
721
+ return undefined;
722
+ return new CavelonError(ExitCode.needsAction, {
723
+ code: "import_needs_a_person",
724
+ message: "This credential cannot import the package here; nothing was imported.",
725
+ hint: `A person imports it in the Admin or with their own personal access token. The instance says: ${person}.`,
726
+ details: { credential: access?.kind ?? null, needs_a_person: true, reason: person },
727
+ });
728
+ }
704
729
  async function confirmPreview(ctx, project, previewId, allowStale) {
705
730
  const stored = await loadPreview(project.root, previewId);
706
731
  const session = await ctx.session();
@@ -739,11 +764,15 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
739
764
  }
740
765
  if (stored.tenant_id && session.tokenKind !== "api_key")
741
766
  client.target.tenantId = stored.tenant_id;
767
+ const refusal = importNeedsAPerson(await accessFor(client));
768
+ if (refusal)
769
+ throw refusal;
742
770
  const driven = drivenByAgent(ctx);
743
- const guarded = stored.request[INCLUDE_TENANT_WIDE] === true || stored.request.package.manifest?.scope === "full_config";
744
- if (driven && stored.person_reason !== null) {
771
+ const queries = importWritesQueries(stored.preview);
772
+ const guarded = queries || stored.request[INCLUDE_TENANT_WIDE] === true || stored.request.package.manifest?.scope === "full_config";
773
+ if (driven && (queries || stored.person_reason !== null)) {
745
774
  const into = stored.harness ? `solution ${stored.harness.slug}` : "the tenant";
746
- const reason = stored.person_reason ?? "was stored by an older cavelon, which did not record whether it needs a person";
775
+ const reason = stored.person_reason ?? (queries ? QUERY_IMPORT_REASON : "was stored by an older cavelon, which did not record whether it needs a person");
747
776
  await personApproves(ctx, driven, { tool: "apply", what: `Import preview ${stored.preview_id} into ${into}: it ${reason}.`, command: personApplyCommand(stored), guarded });
748
777
  }
749
778
  else if (!driven)
@@ -898,6 +927,7 @@ function packageHarnessName(pkg, slug) {
898
927
  const name = typeof entry?.name === "string" ? entry.name.trim() : "";
899
928
  return name ? name.slice(0, 255) : undefined;
900
929
  }
930
+ const QUERY_IMPORT_REASON = "creates or changes database queries, whose SQL can read or change rows in the tenant's database";
901
931
  function personReason(preview, harness, mode, env, shared = [], sharedReaches = []) {
902
932
  if (shared.length) {
903
933
  const reaching = sharedReaches.length ? `, reaching the active solution${sharedReaches.length === 1 ? "" : "s"} ${list(sharedReaches, 5)}` : "";
@@ -914,6 +944,8 @@ function personReason(preview, harness, mode, env, shared = [], sharedReaches =
914
944
  return "deletes";
915
945
  if (env === "prod")
916
946
  return "goes to env/prod";
947
+ if (importWritesQueries(preview))
948
+ return QUERY_IMPORT_REASON;
917
949
  return undefined;
918
950
  }
919
951
  export const apply = {
@@ -924,9 +956,11 @@ export const apply = {
924
956
  "budgets and ignored sections, and is stored in .cavelon/. A preview never creates the solution: one the env file names\n" +
925
957
  "that is not on the instance yet gets the `cavelon harness new` command that creates it as a draft. A person sets the\n" +
926
958
  "secrets (`cavelon secrets set <name>`, or in the Admin where the instance lets no token set one), never the agent.\n" +
959
+ "Where the instance says this credential cannot import (needs_a_person), it still previews but prints no confirm\n" +
960
+ "command: a person imports in the Admin or with their own personal access token. --confirm refuses before sending (exit 5).\n" +
927
961
  "Show a preview that reaches an active solution or env/prod to a person before confirming. Such a preview (show_to_person:\n" +
928
- "tenant-wide sections, an active solution, deletions, env/prod) a coding agent cannot confirm: over MCP the client asks\n" +
929
- "the person, and from an agent's shell the person runs the confirm in their own terminal. A stale preview exits 4 and\n" +
962
+ "tenant-wide sections, an active solution, deletions, env/prod, or database query writes) a coding agent cannot confirm.\n" +
963
+ "Over MCP the client asks the person; from an agent's shell the person runs the confirm in their own terminal. A stale preview exits 4 and\n" +
930
964
  "imports nothing: one whose target changed on the instance since, one whose package files changed since (what they\n" +
931
965
  "hold, not their formatting; --allow-stale imports what the preview showed anyway), and one older than a day. So does\n" +
932
966
  "an import its own check refuses when it applies, naming each blocker. --discard <id|all> forgets stored previews;\n" +
@@ -1028,8 +1062,10 @@ export const apply = {
1028
1062
  const target = harness ? { id: harness.id, slug: harness.slug } : null;
1029
1063
  const acting = await actingTarget(ctx);
1030
1064
  const data = { previewed: true, ...preview, env: envFile?.name ?? null, harness: target, target: acting };
1031
- if (queries.data)
1032
- data.database_queries = queries.data;
1065
+ if (queries.data) {
1066
+ const reported = preview.database_queries;
1067
+ data.database_queries = { ...queries.data, ...(reported && typeof reported === "object" && !Array.isArray(reported) ? reported : {}) };
1068
+ }
1033
1069
  const reported = solutionImport ? tenantWideReport(preview.tenant_wide) : undefined;
1034
1070
  const sections = reported?.sections ?? shared;
1035
1071
  const applied = reported ? reported.applied : tenantWide || !takes;
@@ -1066,6 +1102,9 @@ export const apply = {
1066
1102
  ? `tenant-wide: ${sharedLeftOut.join(", ")} left out (\`${cavelonCommand("apply", "--include-tenant-wide")}\` imports them, for every solution of the tenant${reachText ? `; they would reach ${reachText}` : ""})`
1067
1103
  : undefined;
1068
1104
  const access = await accessFor(await ctx.client());
1105
+ const refusal = importNeedsAPerson(access);
1106
+ if (refusal)
1107
+ data.import_access = { allowed: false, needs_a_person: refusal.details.reason, hint: refusal.hint };
1069
1108
  const commands = setCommands(preview, undefined, secretsInAdminOnly(access?.principal) === true);
1070
1109
  if (commands.secrets.length || commands.variables.length)
1071
1110
  data.set_commands = commands;
@@ -1097,6 +1136,7 @@ export const apply = {
1097
1136
  ...(pair ? [`hint: ${pair.hint}`] : []),
1098
1137
  ...(sharedHint ? [`hint: ${sharedHint}`] : []),
1099
1138
  ...(queryHint ? [`hint: ${queryHint}`] : []),
1139
+ ...(refusal ? [refusal.hint] : []),
1100
1140
  `The preview has blockers; fix them and run \`${cavelonCommand("apply")}\` again.`,
1101
1141
  ].join("\n"),
1102
1142
  exitCode: ExitCode.validation,
@@ -1139,12 +1179,12 @@ export const apply = {
1139
1179
  const expired = (await listPreviews(project.root, ctx.io.now())).filter((old) => old.expired);
1140
1180
  await retirePreviews(project.root, expired.map((old) => ({ preview_id: old.preview_id, reason: "expired", at })));
1141
1181
  }
1142
- data.show_to_person = Boolean(reason);
1182
+ data.show_to_person = Boolean(reason || refusal);
1143
1183
  const driven = drivenByAgent(ctx);
1144
- const route = driven && reason && preview.preview_id ? personRoute(ctx, driven) : undefined;
1184
+ const route = !refusal && driven && reason && preview.preview_id ? personRoute(ctx, driven) : undefined;
1145
1185
  if (route)
1146
1186
  data.needs_person = route;
1147
- const confirmLine = !preview.preview_id
1187
+ const confirmLine = refusal || !preview.preview_id
1148
1188
  ? undefined
1149
1189
  : route === "terminal"
1150
1190
  ? confirmInTerminal(personApplyCommand({ preview_id: preview.preview_id, env: envFile?.name ?? null }))
@@ -1160,6 +1200,7 @@ export const apply = {
1160
1200
  ...(preview.preview_id ? [`preview id: ${preview.preview_id}`] : []),
1161
1201
  ...(reason ? [`This ${reason}: show this preview to a person before confirming.`] : []),
1162
1202
  ...(confirmLine ? [`Import exactly this: ${confirmLine}`] : []),
1203
+ ...(refusal ? [refusal.hint] : []),
1163
1204
  ].join("\n");
1164
1205
  return { data, text };
1165
1206
  },
@@ -1367,6 +1408,39 @@ function missingSecretsLine(names, may, inAdmin) {
1367
1408
  }
1368
1409
  return `${which}: a person sets ${names.length === 1 ? "it" : "each"} (never the agent): ${commands}`;
1369
1410
  }
1411
+ function previewRouteEffect(readiness) {
1412
+ return {
1413
+ takes_default_route: typeof readiness.takes_default_route === "boolean" ? readiness.takes_default_route : null,
1414
+ takes_default_route_from: readiness.takes_default_route_from ?? null,
1415
+ takes_default_route_from_name: readiness.takes_default_route_from_name ?? null,
1416
+ };
1417
+ }
1418
+ function actualRouteEffect(activated) {
1419
+ return {
1420
+ took_default_route: typeof activated.took_default_route === "boolean" ? activated.took_default_route : null,
1421
+ took_default_route_from: activated.took_default_route_from ?? null,
1422
+ took_default_route_from_name: activated.took_default_route_from_name ?? null,
1423
+ };
1424
+ }
1425
+ function activationRouteText(harness, effect, from, fromName, actual = false) {
1426
+ if (effect === null)
1427
+ return actual
1428
+ ? "This instance does not report whether activation changed the tenant's default chat and widget route."
1429
+ : "This instance does not say whether activation takes the tenant's default chat and widget route, so a person must confirm.";
1430
+ if (!effect)
1431
+ return actual
1432
+ ? "Activation did not change the tenant's default chat and widget route."
1433
+ : "Activation would not change the tenant's default chat and widget route.";
1434
+ const previous = from ? named({ slug: from, name: fromName ?? from }) : null;
1435
+ const action = previous
1436
+ ? `${actual ? "replaced" : "would replace"} ${previous} with ${named(harness)} as the tenant's default route`
1437
+ : `${actual ? "assigned" : "would assign"} the tenant's unassigned default route to ${named(harness)}`;
1438
+ return `Activation ${action}. ${actual ? "The" : "This changes live traffic: the"} tenant's chat and widget answer with it where a conversation names no solution.`;
1439
+ }
1440
+ function previewRouteText(harness, effect) {
1441
+ return `${activationRouteText(harness, effect.takes_default_route, effect.takes_default_route_from, effect.takes_default_route_from_name)}\n` +
1442
+ "This preview reserves no route state; activation reports the actual effect.";
1443
+ }
1370
1444
  const count = (value) => (typeof value === "number" ? value : null);
1371
1445
  export async function solutionState(ctx, ref) {
1372
1446
  let harness;
@@ -1392,6 +1466,7 @@ export async function solutionState(ctx, ref) {
1392
1466
  params: { harness_id: [harness.id] },
1393
1467
  });
1394
1468
  state.ready_to_activate = typeof readiness.ready_to_activate === "boolean" ? readiness.ready_to_activate : null;
1469
+ Object.assign(state, previewRouteEffect(readiness));
1395
1470
  state.blockers = (readiness.blockers ?? []).map((b) => clip(String(b.label ?? b.key ?? b.detail ?? "?"), 80));
1396
1471
  const secrets = missingSecrets(readiness.blockers ?? []);
1397
1472
  const principal = await principalOf(await ctx.client());
@@ -1431,6 +1506,12 @@ export function solutionStateLines(state) {
1431
1506
  ? `not ready to activate${state.blockers?.length ? ` (${list(state.blockers, 3)})` : ""}`
1432
1507
  : undefined;
1433
1508
  const lines = [["state", [state.harness.status, ready].filter(Boolean).join(", ")]];
1509
+ if (!active && "takes_default_route" in state)
1510
+ lines.push(["activation route", previewRouteText(state.harness, {
1511
+ takes_default_route: state.takes_default_route ?? null,
1512
+ takes_default_route_from: state.takes_default_route_from ?? null,
1513
+ takes_default_route_from_name: state.takes_default_route_from_name ?? null,
1514
+ })]);
1434
1515
  if (state.missing_secrets)
1435
1516
  lines.push(["secrets", missingSecretsLine(state.missing_secrets.names, state.missing_secrets.may_set, state.missing_secrets.set_in_admin ?? null)]);
1436
1517
  const route = state.default_route;
@@ -1537,7 +1618,11 @@ async function defaultRouteAfterActivation(ctx, harness, input, defaultConfirmed
1537
1618
  return { data: { default_route: { is_default: false, known: route.known, current, preview: commands.preview, confirm: commands.confirm } }, lines };
1538
1619
  }
1539
1620
  async function reachOf(ctx, harness) {
1540
- const channels = typeof harness.channel_count === "number" ? harness.channel_count : null;
1621
+ let channels = typeof harness.channel_count === "number" ? harness.channel_count : null;
1622
+ if (channels === null) {
1623
+ const row = await listHarnesses(ctx).then((list) => list.find((h) => h.id === harness.id)).catch(() => undefined);
1624
+ channels = typeof row?.channel_count === "number" ? row.channel_count : null;
1625
+ }
1541
1626
  const triggers = await callStable(ctx, "GET", "/api/v1/triggers", "listing triggers", { params: { harness_id: [harness.id] } })
1542
1627
  .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 })))
1543
1628
  .catch(() => null);
@@ -1568,8 +1653,10 @@ export const activate = {
1568
1653
  description: "Only when every readiness check passes, and with a personal access token only when it was created with \"may activate\".\n" +
1569
1654
  "Activating without the evidence stays a person's decision in the Admin.\n" +
1570
1655
  "A solution that a channel or an active trigger reaches goes live for them at once, so its activation previews first\n" +
1571
- "and only --confirm activates it; so does one on an instance that does not say what reaches it. Show the preview to a\n" +
1572
- "person and confirm only with their yes. A draft that nothing reaches activates without --confirm.\n" +
1656
+ "and only the person's --confirm activates it. Activation that takes the default chat and widget route also needs their\n" +
1657
+ "yes, including assigning an unassigned route. Unknown reach or route effects need their confirmation too. A solution\n" +
1658
+ "nothing reaches activates without --confirm only when readiness explicitly says takes_default_route=false.\n" +
1659
+ "Readiness previews the route effect without reserving state; the activation result reports what actually happened.\n" +
1573
1660
  "Afterwards it says whether the solution is the tenant's default route (the one the tenant's chat and widget answer with\n" +
1574
1661
  "where no solution is named). --make-default previews making it the default; with --confirm as well, it changes it. That\n" +
1575
1662
  "changes live traffic: show the preview to a person and confirm only with their yes. `cavelon harness default` does the\n" +
@@ -1586,7 +1673,7 @@ export const activate = {
1586
1673
  confirm: {
1587
1674
  type: "boolean",
1588
1675
  mcpToken: true,
1589
- description: "With --make-default: change the default route; for a solution a channel or trigger reaches: activate it (after a person saw the preview).",
1676
+ description: "With --make-default: the person's yes to change the default route; otherwise, to activate when reach or the activation's route effect is true or unknown.",
1590
1677
  },
1591
1678
  },
1592
1679
  examples: [
@@ -1631,6 +1718,7 @@ export const activate = {
1631
1718
  });
1632
1719
  const checks = readinessChecks(readiness);
1633
1720
  const warnings = (readiness.warnings ?? []).map(checkLine);
1721
+ const routeEffect = previewRouteEffect(readiness);
1634
1722
  if (!readiness.ready_to_activate) {
1635
1723
  const blockers = readiness.blockers ?? [];
1636
1724
  const pair = pairOrderHint(await catalogFor(ctx, false), blockers.flatMap((b) => [b.message ?? undefined, b.detail ?? undefined]));
@@ -1644,6 +1732,7 @@ export const activate = {
1644
1732
  checks,
1645
1733
  warnings,
1646
1734
  readiness,
1735
+ ...routeEffect,
1647
1736
  ...(pair ? { hint: pair.hint } : {}),
1648
1737
  ...(secrets.length ? { missing_secrets: { names: secrets, may_set: maySet, next: secretsLine } } : {}),
1649
1738
  },
@@ -1651,6 +1740,7 @@ export const activate = {
1651
1740
  `${harness.name} (${harness.slug}) is not ready to activate:`,
1652
1741
  ...blockers.map((b) => ` - ${checkLine(b)}`),
1653
1742
  ...readinessText(checks, warnings),
1743
+ previewRouteText(harness, routeEffect),
1654
1744
  ...(pair ? [`hint: ${pair.hint}`] : []),
1655
1745
  ...(secretsLine ? [secretsLine] : []),
1656
1746
  "Resolve these (often: a passing test run), then activate again. Forcing past the gate is a person's decision in the Admin.",
@@ -1659,21 +1749,22 @@ export const activate = {
1659
1749
  };
1660
1750
  }
1661
1751
  const reach = await reachOf(ctx, harness);
1662
- const live = Boolean(reach.channels) || Boolean(reach.triggers?.length) || reach.channels === null || reach.triggers === null;
1752
+ const needsPerson = Boolean(reach.channels) || Boolean(reach.triggers?.length) || reach.channels === null || reach.triggers === null || routeEffect.takes_default_route !== false;
1663
1753
  let defaultConfirmed = false;
1664
- if (live) {
1754
+ if (needsPerson) {
1665
1755
  const route = make ? await readDefaultRoute(ctx).catch(() => undefined) : undefined;
1666
1756
  const change = {
1667
1757
  harness: harness.id,
1668
1758
  activate: true,
1669
1759
  channels: reach.channels,
1670
1760
  triggers: reach.triggers?.map((t) => t.id) ?? null,
1761
+ ...routeEffect,
1671
1762
  ...(make ? { make_default: true, from: route?.current?.id ?? null } : {}),
1672
1763
  };
1673
1764
  const words = ["activate", "--harness", harness.slug, ...(make ? ["--make-default"] : []), "--confirm"];
1674
1765
  const gate = await confirmation(ctx, input, "activate", change, {
1675
1766
  person: {
1676
- what: [reachText(harness, reach), ...(make && route && route.current?.id !== harness.id ? [defaultChangeLine(harness, route)] : [])].join("\n"),
1767
+ what: [reachText(harness, reach), previewRouteText(harness, routeEffect), ...(make && route && route.current?.id !== harness.id ? [defaultChangeLine(harness, route)] : [])].join("\n"),
1677
1768
  words,
1678
1769
  },
1679
1770
  });
@@ -1689,12 +1780,14 @@ export const activate = {
1689
1780
  checks,
1690
1781
  warnings,
1691
1782
  readiness,
1783
+ ...routeEffect,
1692
1784
  ...(make ? { default_route: { current: route?.current ? { id: route.current.id, slug: route.current.slug, name: route.current.name } : null, known: route?.known ?? false } } : {}),
1693
1785
  confirm,
1694
1786
  ...gate.fields,
1695
1787
  },
1696
1788
  text: [
1697
1789
  reachText(harness, reach),
1790
+ previewRouteText(harness, routeEffect),
1698
1791
  ...routeLine,
1699
1792
  ...readinessText(checks, warnings),
1700
1793
  gate.where,
@@ -1711,9 +1804,10 @@ export const activate = {
1711
1804
  body: { force: false },
1712
1805
  });
1713
1806
  const route = await defaultRouteAfterActivation(ctx, activated, input, defaultConfirmed);
1807
+ const actualEffect = actualRouteEffect(activated);
1714
1808
  return {
1715
- data: { activated: true, harness: activated, ...(live ? { reach } : {}), checks, warnings, readiness, ...route.data },
1716
- text: [`Activated ${activated.name} (${activated.slug}); status ${activated.status}.`, ...readinessText(checks, warnings), ...route.lines].join("\n"),
1809
+ data: { activated: true, harness: activated, reach, checks, warnings, readiness, ...routeEffect, ...actualEffect, ...route.data },
1810
+ text: [`Activated ${activated.name} (${activated.slug}); status ${activated.status}.`, activationRouteText(activated, actualEffect.took_default_route, actualEffect.took_default_route_from, actualEffect.took_default_route_from_name, true), ...readinessText(checks, warnings), ...route.lines].join("\n"),
1717
1811
  ...(route.failed ? { exitCode: ExitCode.failure } : route.exitCode ? { exitCode: route.exitCode } : {}),
1718
1812
  };
1719
1813
  },
@@ -16,6 +16,7 @@ import { caseCounts, caseLabel, countsText, failedCase, caseKnowledgeOutcomes, N
16
16
  import { isUuid } from "../session.js";
17
17
  import { cavelonCommand } from "../printed.js";
18
18
  import { readZipSummary, ZipError } from "../zip.js";
19
+ import { AS_CHAT_USER_OPTION, chatUserReader, chatUserReaderError } from "../chat-reader.js";
19
20
  import { TIMEOUT_OPTION, timeoutMs, waitAndReport } from "./async.js";
20
21
  import { stageErrors, stageErrorText } from "./loops.js";
21
22
  import { resolveHarnessId } from "../harness-ref.js";
@@ -652,13 +653,20 @@ export const testRun = {
652
653
  summary: "Start test-suite runs; returns operation ids.",
653
654
  description: "Without --suite, runs every suite of the solution (--harness, or cavelon.yaml's harness).\n" +
654
655
  "With --wait, exits 1 when a case failed or a run measured nothing comparable (cases not run, technical errors),\n" +
655
- "5 when answers wait for a manual verdict or a value a case needs.",
656
+ "5 when answers wait for a manual verdict or a value a case needs.\n" +
657
+ "--as-chat-user chooses a Chat User reader for these runs only, for knowledge and identity-bound database queries;\n" +
658
+ "it never edits a saved suite. Without the option, uses each suite's saved reader. Choose an id with\n" +
659
+ "`cavelon api list_chat_users -p tenant_id=<tenant_id>`; check email_verified for email-bound queries.\n" +
660
+ "Where the instance publishes the matching needs_a_person_when restriction, an API key cannot choose this reader\n" +
661
+ "(exit 5, nothing sent): a person chooses it in the Admin or with their personal access token. A key can still run a\n" +
662
+ "suite whose reader a person saved. Older instances that omit the restriction leave the decision to the server.",
656
663
  readOnly: false,
657
664
  mcpTool: "test_run",
658
665
  operations: ["POST /api/v1/test-suites/{suite_id}/runs"],
659
666
  options: {
660
667
  suite: { type: "string", multiple: true, value: "<suite>", description: "Suite name or id." },
661
668
  harness: { type: "string", value: "<harness>", description: "The solution to run against: its name, slug or id." },
669
+ "as-chat-user": AS_CHAT_USER_OPTION,
662
670
  wait: WAIT_OPTION,
663
671
  timeout: TIMEOUT_OPTION,
664
672
  "idempotency-key": { type: "string", value: "<key>", description: "Send an Idempotency-Key with each start." },
@@ -666,6 +674,7 @@ export const testRun = {
666
674
  examples: ["cavelon test run --suite smoke --wait --timeout 10m", "cavelon test run --harness support --json"],
667
675
  async run(ctx, input) {
668
676
  const session = await ctx.session();
677
+ const reader = await chatUserReader(ctx, input, "/api/v1/test-suites/{suite_id}/runs");
669
678
  const harnessRef = stringOption(input, "harness") ?? session.project?.harness;
670
679
  const harnessId = harnessRef ? await resolveHarnessId(ctx, harnessRef) : undefined;
671
680
  const suites = await callStable(ctx, "GET", "/api/v1/test-suites", "test suites", {
@@ -700,14 +709,14 @@ export const testRun = {
700
709
  const key = stringOption(input, "idempotency-key");
701
710
  const runs = [];
702
711
  for (const suite of chosen) {
703
- const body = {};
712
+ const body = { ...reader };
704
713
  if (harnessId)
705
714
  body.harness_id = harnessId;
706
715
  runs.push(await callStable(ctx, "POST", "/api/v1/test-suites/{suite_id}/runs", "test runs", {
707
716
  params: { suite_id: [suite.id] },
708
717
  body,
709
718
  headers: key ? { "Idempotency-Key": `${key}:${suite.id}` } : undefined,
710
- }));
719
+ }).catch((error) => { throw chatUserReaderError(error, reader); }));
711
720
  }
712
721
  const operationIds = runs.map((r) => r.operation_id).filter((id) => Boolean(id));
713
722
  const started = runs.map((r) => ({ run_id: r.id, suite: r.suite_name ?? r.suite_id, status: r.status, operation_id: r.operation_id ?? null }));
@@ -738,11 +747,12 @@ export const testRun = {
738
747
  ...results.map((r) => `${r.suite}: ${r.status} ${summaryText(r.summary)}`),
739
748
  ...(resume ? ["", `${waited.why} after the timeout; the runs go on. Resume: ${resume}`] : []),
740
749
  ].join("\n");
741
- return { data: { runs: results, failed_cases: failedCases, ...waited.data, ...(resume ? { resume } : {}) }, text, exitCode };
750
+ return { data: { runs: results, failed_cases: failedCases, ...waited.data, ...reader, ...(resume ? { resume } : {}) }, text: reader ? `Reading as Chat User ${reader.reader_chat_user_id} for these runs only.\n${text}` : text, exitCode };
742
751
  }
743
752
  return {
744
- data: { runs: started, operation_ids: operationIds },
745
- text: table(started, ["suite", "run_id", "status", "operation_id"]) +
753
+ data: { runs: started, operation_ids: operationIds, ...reader },
754
+ text: (reader ? `Reading as Chat User ${reader.reader_chat_user_id} for these runs only.\n` : "") +
755
+ table(started, ["suite", "run_id", "status", "operation_id"]) +
746
756
  (operationIds.length ? `\n\nWait with: ${cavelonCommand("wait", ...operationIds)}` : ""),
747
757
  };
748
758
  },