@cavelon/cli 0.1.13 → 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
  },
@@ -33,18 +33,24 @@ export function schemaKnowsQueries(schema) {
33
33
  const properties = toolSchema(schema)?.properties;
34
34
  return isObject(properties) && QUERY_FIELD in properties;
35
35
  }
36
- function parameterSchema(schema) {
36
+ export function querySchema(schema) {
37
37
  const field = toolSchema(schema)?.properties?.[QUERY_FIELD];
38
38
  const branches = isObject(field) && Array.isArray(field.anyOf) ? field.anyOf : [field];
39
39
  for (const branch of branches) {
40
40
  const query = resolveRef(schema, branch);
41
- const parameters = query?.properties?.parameters;
42
- const items = isObject(parameters) ? resolveRef(schema, parameters.items) : undefined;
43
- if (items)
44
- return items;
41
+ if (isObject(query?.properties))
42
+ return query;
45
43
  }
46
44
  return undefined;
47
45
  }
46
+ export function parameterSchema(schema) {
47
+ const parameters = querySchema(schema)?.properties?.parameters;
48
+ return isObject(parameters) ? resolveRef(schema, parameters.items) : undefined;
49
+ }
50
+ export function schemaKnowsWrites(schema) {
51
+ const kind = querySchema(schema)?.properties?.kind;
52
+ return Array.isArray(kind?.enum) && kind.enum.includes("write");
53
+ }
48
54
  export function queryTools(pkg) {
49
55
  const tools = pkg[TOOLS_SECTION];
50
56
  if (!Array.isArray(tools))
@@ -351,7 +357,7 @@ export function queryChanges(pkg, schema, baseline) {
351
357
  }
352
358
  return out;
353
359
  }
354
- export function checkQueryTools(disk, schema, baseline) {
360
+ export function checkQueryTools(disk, schema, baseline, connections) {
355
361
  if (!schemaKnowsQueries(schema))
356
362
  return [];
357
363
  const findings = [];
@@ -368,7 +374,8 @@ export function checkQueryTools(disk, schema, baseline) {
368
374
  });
369
375
  }
370
376
  const dialect = isObject(query.connection) && typeof query.connection.dialect === "string" ? query.connection.dialect : undefined;
371
- const call = typeof query.sql_text === "string" ? procedureCallProblem(query.sql_text, dialect) : undefined;
377
+ const write = schemaKnowsWrites(schema) && query.kind === "write";
378
+ const call = !write && typeof query.sql_text === "string" ? procedureCallProblem(query.sql_text, dialect) : undefined;
372
379
  if (call) {
373
380
  findings.push({
374
381
  code: call.code,
@@ -377,6 +384,14 @@ export function checkQueryTools(disk, schema, baseline) {
377
384
  message: `Query tool "${slug}": ${call.message}`,
378
385
  });
379
386
  }
387
+ const connection = isObject(query.connection) ? query.connection : undefined;
388
+ if (write && connections?.some(c => c.name === connection?.name && c.dialect === dialect && c.allows_writes === false)) {
389
+ findings.push({
390
+ code: "writes_not_allowed", severity: "warning",
391
+ ...locate(disk, `/${TOOLS_SECTION}/${index}/${QUERY_FIELD}/connection`),
392
+ message: `Write query tool "${slug}" names a connection that explicitly disallows writes: its calls and dry-run tests answer writes_not_allowed. A tenant Owner or Admin enables writes on the connection in the Admin; this flag never travels in a package.`,
393
+ });
394
+ }
380
395
  }
381
396
  if (!baseline)
382
397
  return findings;
@@ -389,8 +404,8 @@ export function checkQueryTools(disk, schema, baseline) {
389
404
  code: QUERY_CHANGED_CODE,
390
405
  severity: "warning",
391
406
  ...locate(disk, `/${TOOLS_SECTION}/${change.index}`),
392
- message: `Query tool "${change.slug}" ${what} needs a superadmin in the Admin, and the import preview of a personal access token ` +
393
- `blocks it (${NEEDS_SUPERADMIN_CODE}). An agent's or skill's override of the tool's name, description or max_calls is no query change.`,
407
+ message: `Query tool "${change.slug}" ${what} needs database_connectors.manage (the tenant Owner or a superadmin in Tenant mode) and the person's approval. ` +
408
+ `The import preview blocks a credential without that permission (${NEEDS_SUPERADMIN_CODE}). An agent's or skill's override of the tool's name, description or max_calls is no query change.`,
394
409
  });
395
410
  }
396
411
  for (const { slug, index, tool } of queryTools(disk.package)) {
@@ -443,7 +458,7 @@ export function applyQueryNotes(pkg, changes, offer) {
443
458
  }
444
459
  }
445
460
  const slugs = changes.map((c) => c.slug);
446
- if (slugs.length && offer.may_write_queries === false) {
461
+ if (slugs.length && offer.enabled !== false && offer.may_write_queries === false) {
447
462
  warnings.push(`This apply would ${changes.every((c) => c.created) ? "create" : "create or change"} the database quer${slugs.length === 1 ? "y" : "ies"} ${named(slugs)}, ` +
448
463
  `which this credential may not do (may_write_queries is false): the preview blocks ${slugs.length === 1 ? "it" : "them"}, and one blocked query stops the whole import. ` +
449
464
  (offer.queries_written_by ? `${offer.queries_written_by} ` : "") +
@@ -463,7 +478,11 @@ export function applyQueryNotes(pkg, changes, offer) {
463
478
  export function queryBlockedHint(files) {
464
479
  const where = files.length ? ` in ${files.join(", ")}` : "";
465
480
  return ("A database query the import would create or change stops the whole import: nothing is applied while one blocks. " +
466
- "A superadmin applies it in the Admin (the blocker's hint names where); after that, apply passes while the queries match. " +
481
+ "The blocker's hint names who this instance permits and where they apply it (with the manage gate, the tenant Owner may use a personal access token holding database_connectors.manage); after that, apply passes while the queries match. " +
467
482
  `To apply the other changes first, leave each blocked query as the instance holds it${where}: restore the tool's entry as the last pull wrote it, ` +
468
483
  "or remove its database_query block (the tool then keeps the instance's query, name and description), and apply again.");
469
484
  }
485
+ export function importWritesQueries(preview) {
486
+ const report = preview.database_queries;
487
+ return isObject(report) && Array.isArray(report.would_write) && report.would_write.length > 0;
488
+ }
package/dist/http.js CHANGED
@@ -30,6 +30,7 @@ export class ApiClient {
30
30
  target;
31
31
  env;
32
32
  tokensOff;
33
+ genericForbiddenHint;
33
34
  revalidateTenant;
34
35
  confirmer;
35
36
  constructor(target, env = {}) {
@@ -172,6 +173,12 @@ export class ApiClient {
172
173
  const kind = this.target.token.startsWith("cbp_") ? "api_key" : this.target.token.startsWith("cvpat_") ? "personal_access_token" : undefined;
173
174
  const access = await accessFor(this).catch(() => undefined);
174
175
  sent = { ...sent, credential: { kind, access, method: sent.method, path: sent.path } };
176
+ if (forbiddenHint("", sent.credential).details.needs_a_person === true) {
177
+ this.genericForbiddenHint ??= this.get("/api/v1/meta/error-catalog", { allow: [400, 401, 403, 404, 405], timeoutMs: 10_000 })
178
+ .then((response) => response.data?.api_error_codes?.find((entry) => entry.code === "forbidden")?.hint ?? undefined)
179
+ .catch(() => undefined);
180
+ sent.genericForbiddenHint = await this.genericForbiddenHint;
181
+ }
175
182
  }
176
183
  return errorFromResponse(status, body, what, headers, sent);
177
184
  }
@@ -340,6 +347,14 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
340
347
  if (status === 400 && !hint && message && /select a tenant|tenant context|X-Tenant-Id/i.test(message)) {
341
348
  hint = `Choose a tenant with \`${cavelonCommand("use")}\` (it lists your tenants), --tenant or CAVELON_TENANT.`;
342
349
  }
350
+ if (status === 403 && sent.credential) {
351
+ const forbidden = forbiddenHint(message ?? "", sent.credential);
352
+ if (forbidden.details.needs_a_person === true) {
353
+ hint = !hint || hint === sent.genericForbiddenHint || hint === forbidden.hint ? forbidden.hint : `${forbidden.hint} ${hint}`;
354
+ if (details === undefined)
355
+ details = forbidden.details;
356
+ }
357
+ }
343
358
  if ((status === 401 || status === 403) && !hint) {
344
359
  hint =
345
360
  status === 401
package/dist/kit-codes.js CHANGED
@@ -22,6 +22,7 @@ export const KIT_ERROR_CODES = [
22
22
  { code: "unexpected_redirect", area: "cli", message: "The instance redirected a request elsewhere.", hint: "Check the instance URL (https, host, path)." },
23
23
  { code: "internal_error", area: "cli", message: "cavelon failed in an unexpected way.", hint: "Run the command again; if it repeats, report it with the command and its output." },
24
24
  { code: "operation_unavailable", area: "cli", message: "This instance does not offer what the command needs (the route or a field is not in its OpenAPI).", hint: "The instance may be older than the feature; `cavelon status` shows its version." },
25
+ { code: "chat_user_reader_forbidden", area: "cli", message: "This credential cannot read as a selected Chat User; nothing was sent.", hint: "Chat needs a personal access token; chat and test runs need knowledge_bases.view and end_users.read. `cavelon whoami` shows the acting tenant and credential's permissions. Choose a current reader with `cavelon api list_chat_users -p tenant_id=<tenant_id>`; check email_verified for email-bound queries." },
25
26
  { code: "openapi_unavailable", area: "cli", message: "The instance does not serve its OpenAPI.", hint: "`cavelon api` needs it; ask the instance's operator to route it." },
26
27
  { code: "error_catalog_unavailable", area: "cli", message: "The instance does not publish its error catalog.", hint: "Try `cavelon docs search <code>`." },
27
28
  { code: "docs_unavailable", area: "cli", message: "The instance does not serve its docs to agents (no /llms.txt).", hint: "Read the docs in the Admin until the instance is updated." },
@@ -53,6 +54,7 @@ export const KIT_ERROR_CODES = [
53
54
  { code: "path_outside_solution", area: "cli", message: "A tool reads and writes files only inside the solution folder.", hint: "Name a file inside the solution folder, or ask the person to run the command in their terminal." },
54
55
  { code: "path_in_kit_directory", area: "cli", message: "The file is in cavelon's own directory (login and cache); no tool reads or writes there.", hint: "Name a file in the solution folder." },
55
56
  { code: "skills_missing", area: "cli", message: "This cavelon has no skills to install; its package is incomplete.", hint: "Reinstall @cavelon/cli." },
57
+ { code: "import_needs_a_person", area: "cli", message: "The instance keeps package imports from this credential; nothing was imported.", hint: "A person imports in the Admin or with their own personal access token. The API key can still preview with `cavelon apply`." },
56
58
  { code: "preview_unknown", area: "cli", message: "No open preview with that id in this solution.", hint: "Run `cavelon apply` for a new preview and confirm its id; `cavelon status` lists the open ones." },
57
59
  { code: "preview_other_instance", area: "cli", message: "The preview was made on another instance.", hint: "Confirm it with the instance it was made on, or preview again here." },
58
60
  { code: "preview_other_tenant", area: "cli", message: "The preview was made for another tenant than this command acts in.", hint: "Run the confirm command the preview printed (it names --env and --tenant), or preview again here." },
package/dist/mcp.js CHANGED
@@ -52,9 +52,12 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
52
52
  "instance allows this tenant (upload sizes and types, run and tool limits, timeouts, quotas) and who changes each. " +
53
53
  "Never change a limit on your own: propose the old and new value (limits_set for a limit a tenant admin changes, " +
54
54
  "models_set_limit for an endpoint's max_concurrent_requests) and let the person decide; an operator's limit goes to the operator. " +
55
- "db_connections, db_queries and db_runs read the database connections, saved queries and their runs behind database query " +
56
- "tools; only a superadmin in the Admin creates or changes a connection or a query, so an apply that changes a query is " +
57
- "blocked for any token: tell the person, and apply the rest with the query left as the instance holds it. " +
55
+ "db_connections, db_queries and db_runs read database connections, saved queries and their runs. Connection commands " +
56
+ "and query-writing apply follow the permissions and needs_a_person the instance publishes: use whoami, including " +
57
+ "database_connectors.manage, instead of assuming every token is blocked. An authorized personal access token may " +
58
+ "manage definitions. Query changes need the person's approval even on a draft; after approval cavelon sends the " +
59
+ "instance's confirmation for the exact change where required. Passwords, privilege acknowledgment and enabling writes " +
60
+ "stay with a person in the Admin; never accept or pass the database password or set allows_writes through a tool. " +
58
61
  "variables_list/variables_get/variables_set handle plain-text {{var:…}} values; setting one needs a role that may manage " +
59
62
  "the tenant's settings, as a secret does (a Builder's may not): where whoami says the credential may not, tell the person " +
60
63
  "who sets it instead of calling variables_set. secrets_list shows which {{secret:…}} " +
@@ -134,9 +137,13 @@ export function notForThisCredential(spec, access) {
134
137
  export function toolFor(spec, commands = [], access) {
135
138
  const marked = spec.mcpEffect ?? (spec.readOnly ? "Read-only." : spec.destructive ? "Changes the instance; may delete or overwrite." : "Changes the instance.");
136
139
  const refused = notForThisCredential(spec, access);
140
+ const conditional = (spec.operations ?? []).flatMap(operation => {
141
+ const reason = operationAccess(access, operation).personWhen;
142
+ return reason === undefined ? [] : [`Needs a person only when (${operation}): ${reason}. Ordinary requests remain usable; the instance decides every request.`];
143
+ });
137
144
  return {
138
145
  name: toolName(spec),
139
- description: mcpSpelling([refused, spec.summary, spec.description, marked].filter(Boolean).join("\n"), spec, commands),
146
+ description: mcpSpelling([refused, spec.summary, spec.description, ...conditional, marked].filter(Boolean).join("\n"), spec, commands),
140
147
  inputSchema: inputSchema(spec, commands),
141
148
  annotations: {
142
149
  title: spec.summary,