@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.
@@ -1,15 +1,27 @@
1
1
  import { CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption } from "../command.js";
2
2
  import { CavelonError, ExitCode, usageError } from "../errors.js";
3
- import { connectorOffer } from "../database-queries.js";
3
+ import { connectorOffer, isProcedureCall } from "../database-queries.js";
4
4
  import { requireFeature } from "../features.js";
5
5
  import { clip, keyValues, moreHint, table } from "../format.js";
6
6
  import { callStable } from "../invoke.js";
7
7
  import { cavelonCommand, fill } from "../printed.js";
8
8
  import { isUuid } from "../session.js";
9
+ import { accessFor, requirePersonForIdentityChoice } from "../access.js";
10
+ function reported(value) {
11
+ if (value === undefined)
12
+ return undefined;
13
+ if (value === null)
14
+ return "unknown";
15
+ if (typeof value === "boolean")
16
+ return value ? "yes" : "no";
17
+ return typeof value === "string" || typeof value === "number" ? value : undefined;
18
+ }
19
+ const WRITE_EVIDENCE = ["kind", "dry_run", "rolled_back", "affected_rows", "committed"];
20
+ const NO_WRITE_RETRY = "Do not retry an ambiguous write outcome. Check the database for the change before anyone repeats it.";
9
21
  const FEATURE = "database_connector_enabled";
10
22
  const DOCS_PAGE = "administration/database-connectors";
11
- const connectorOn = (ctx) => requireFeature(ctx, FEATURE, "database_connector_disabled", "the database connector");
12
- function withPermissionHint(error, hint) {
23
+ export const connectorOn = (ctx) => requireFeature(ctx, FEATURE, "database_connector_disabled", "the database connector");
24
+ export function withPermissionHint(error, hint) {
13
25
  if (!(error instanceof CavelonError) || error.status !== 403)
14
26
  return error;
15
27
  return new CavelonError(error.exitCode, {
@@ -18,11 +30,12 @@ function withPermissionHint(error, hint) {
18
30
  message: error.message,
19
31
  hint: `${hint} \`${cavelonCommand("whoami")}\` shows the token's role.`,
20
32
  docs: error.docs,
33
+ details: error.details,
21
34
  });
22
35
  }
23
36
  const ownerOnly = (error, what) => withPermissionHint(error, `${what} needs the tenant Owner's permission (database_connectors.test), or a superadmin in the Admin; the roles that read the connections do not hold it.`);
24
- const viewerOnly = (error) => withPermissionHint(error, "Reading the database connector needs database_connectors.view, which the tenant roles that see tools hold, and a superadmin in Tenant mode.");
25
- async function read(ctx, path, what, query) {
37
+ export const viewerOnly = (error) => withPermissionHint(error, "Reading the database connector needs database_connectors.view, which the tenant roles that see tools hold, and a superadmin in Tenant mode.");
38
+ export async function read(ctx, path, what, query) {
26
39
  await connectorOn(ctx);
27
40
  try {
28
41
  return await callStable(ctx, "GET", path, what, { query });
@@ -33,7 +46,7 @@ async function read(ctx, path, what, query) {
33
46
  }
34
47
  const listConnections = (ctx) => read(ctx, "/api/v1/database-connectors/connections", "database connections");
35
48
  const listQueries = (ctx, connectionId) => read(ctx, "/api/v1/database-connectors/queries", "database queries", { connection_id: connectionId });
36
- async function resolveConnection(ctx, ref) {
49
+ export async function resolveConnection(ctx, ref) {
37
50
  const all = await listConnections(ctx);
38
51
  const hit = all.find((c) => c.id === ref.toLowerCase()) ?? all.find((c) => c.name === ref) ?? all.find((c) => c.name.toLowerCase() === ref.toLowerCase());
39
52
  if (hit)
@@ -41,7 +54,7 @@ async function resolveConnection(ctx, ref) {
41
54
  throw new CavelonError(ExitCode.failure, {
42
55
  code: "database_connection_not_found",
43
56
  message: `No database connection "${ref}" in this tenant.`,
44
- hint: `\`${cavelonCommand("db", "connections")}\` lists them${all.length ? ` (${all.map((c) => c.name).slice(0, 10).join(", ")})` : "; a superadmin creates one in the Admin"}.`,
57
+ hint: `\`${cavelonCommand("db", "connections")}\` lists them${all.length ? ` (${all.map((c) => c.name).slice(0, 10).join(", ")})` : "; the tenant Owner creates one with db connections create or in the Admin"}.`,
45
58
  });
46
59
  }
47
60
  async function resolveQuery(ctx, ref) {
@@ -65,8 +78,8 @@ async function resolveQuery(ctx, ref) {
65
78
  hint: `\`${cavelonCommand("db", "queries")}\` lists them by the slug of their tool${all.length ? ` (${all.map((q) => q.slug).slice(0, 10).join(", ")})` : ""}.`,
66
79
  });
67
80
  }
68
- function connectionView(c) {
69
- const { ca_certificate_pem: pem, ...rest } = c;
81
+ export function connectionView(c) {
82
+ const { ca_certificate_pem: pem, password: _password, ...rest } = c;
70
83
  return { ...rest, ca_certificate_set: Boolean(pem) };
71
84
  }
72
85
  const DAY_MS = 86_400_000;
@@ -86,7 +99,7 @@ function expiryWarnings(connections, now) {
86
99
  ? `expired on ${day(cert.not_after)}`
87
100
  : `expires on ${day(cert.not_after)} (in ${days === 0 ? "less than a day" : `${days} day${days === 1 ? "" : "s"}`})`;
88
101
  warnings.push(`The CA certificate "${cert.subject}" of the database connection "${c.name}" ${when}: from then its TLS check fails, and with it the connection's queries. ` +
89
- `A superadmin uploads the renewed CA in the Admin; then the tenant Owner tests the connection again: ${cavelonCommand("db", "test", c.name)}`);
102
+ `The tenant Owner uploads the renewed public CA with db connections ca or in the Admin, then tests the connection again: ${cavelonCommand("db", "test", c.name)}`);
90
103
  }
91
104
  }
92
105
  return warnings;
@@ -130,6 +143,7 @@ function explainLine(codes) {
130
143
  return "";
131
144
  return `\n\nWhat a code means: ${cavelonCommand("explain", fill("code"))} (${distinct.slice(0, 8).join(", ")})`;
132
145
  }
146
+ const refusalOf = (name, refusal) => `${name} (${refusal.code}${refusal.message ? `: ${clip(refusal.message, 200)}` : ""})`;
133
147
  function firewallSentence(offer) {
134
148
  const { egress_ips: ips, connections_per_process: perProcess } = offer.network;
135
149
  const pool = `Each process of the instance that runs agents opens at most ${perProcess} connection${perProcess === 1 ? "" : "s"} per database connection.`;
@@ -142,7 +156,7 @@ function firewallSentence(offer) {
142
156
  }
143
157
  export const dbInstance = {
144
158
  name: "db instance",
145
- summary: "What this instance offers for database connections: the dialects it runs, and the addresses a database's firewall lets in.",
159
+ summary: "What this instance offers for database connections: dialects, firewall addresses and write-query support where published.",
146
160
  description: "Read it before a database connection is set up: a connection of a dialect the instance does not run can be saved, but\n" +
147
161
  "its test and queries answer unavailable, and the customer's database must let the instance's egress addresses in. An\n" +
148
162
  "instance older than this route says only its dialects, in its capabilities.",
@@ -174,6 +188,8 @@ export const dbInstance = {
174
188
  ["dialects", offer.runnable_dialects.join(", ") || "none"],
175
189
  ["egress_ips", offer.network.egress_ips.join(", ") || "none named"],
176
190
  ["connections_per_process", offer.network.connections_per_process],
191
+ ["write_queries", reported(offer.write_queries)],
192
+ ["max_affected_rows_limit", reported(offer.max_affected_rows_limit)],
177
193
  ]),
178
194
  "",
179
195
  firewall,
@@ -185,7 +201,8 @@ export const dbInstance = {
185
201
  export const dbConnections = {
186
202
  name: "db connections",
187
203
  summary: "The tenant's database connections: dialect, target, TLS mode, CA certificates, last test and query count; never a password.",
188
- description: "A superadmin creates and changes connections in the Admin; a token reads them. A package names a query's connection by\n" +
204
+ description: "A token holding database_connectors.manage creates and changes connections; a person sets the password in the Admin.\n" +
205
+ "allows_writes, when published, is read-only here: enabling writes remains a dashboard action. A package names a connection by\n" +
189
206
  "name and dialect, so the same name serves in every tenant and environment. A query tool is ready for agents only while\n" +
190
207
  "its connection is enabled and its last test passed; the tenant Owner runs the test with `cavelon db test <connection>`.\n" +
191
208
  `It warns of a CA certificate that has expired or expires within ${EXPIRY_WARNING_DAYS} days.`,
@@ -208,33 +225,39 @@ export const dbConnections = {
208
225
  target: `${conn.host}:${conn.port}/${conn.database_name}`,
209
226
  tls: conn.tls_mode,
210
227
  enabled: conn.is_enabled ? "yes" : "no",
228
+ ...(typeof conn.allows_writes === "boolean" ? { allows_writes: conn.allows_writes ? "yes" : "no" } : {}),
211
229
  last_test: lastTest(conn),
212
230
  queries: conn.query_count ?? null,
213
231
  id: conn.id,
214
232
  };
215
233
  });
216
234
  const untested = page.items.filter((c) => c.last_test_outcome !== "ok").map((c) => String(c.name));
217
- const refused = page.items.filter((c) => c.query_enable_refusal?.code);
235
+ const connections = page.items;
236
+ const refused = connections.filter((c) => c.query_enable_refusal?.code);
237
+ const procedureRefused = connections.filter((c) => c.procedure_call_refusal?.code);
218
238
  return {
219
239
  data: page,
220
- text: (table(rows, ["name", "dialect", "target", "tls", "enabled", "last_test", "queries", "id"]) ||
221
- `No database connections. A superadmin creates one in the Admin (\`${cavelonCommand("docs", "get", DOCS_PAGE)}\` says who does what).`) +
222
- caLines(page.items).join("\n") +
240
+ text: (table(rows, ["name", "dialect", "target", "tls", "enabled", ...(rows.some(c => "allows_writes" in c) ? ["allows_writes"] : []), "last_test", "queries", "id"]) ||
241
+ `No database connections. The tenant Owner creates one with db connections create or in the Admin (\`${cavelonCommand("docs", "get", DOCS_PAGE)}\` says who does what).`) +
242
+ caLines(connections).join("\n") +
223
243
  moreHint(page.next_cursor, cavelonCommand("db", "connections")) +
224
244
  (untested.length ? `\n\nNot tested successfully: ${untested.join(", ")}; its queries are not ready for agents. The Owner tests one with: ${cavelonCommand("db", "test", fill("connection"))}` : "") +
225
- (refused.length
226
- ? `\n\nQueries cannot be enabled on: ${refused.map((c) => `${c.name} (${c.query_enable_refusal.code}${c.query_enable_refusal.message ? `: ${clip(c.query_enable_refusal.message, 200)}` : ""})`).join("; ")}` +
227
- explainLine(refused.map((c) => c.query_enable_refusal.code))
228
- : ""),
245
+ (refused.length ? `\n\nQueries cannot be enabled on: ${refused.map((c) => refusalOf(c.name, c.query_enable_refusal)).join("; ")}` : "") +
246
+ (procedureRefused.length
247
+ ? `\n\nStored-procedure queries (EXEC) cannot be saved or run on: ${procedureRefused.map((c) => refusalOf(c.name, c.procedure_call_refusal)).join("; ")}`
248
+ : "") +
249
+ explainLine([...refused.map((c) => c.query_enable_refusal.code), ...procedureRefused.map((c) => c.procedure_call_refusal.code)]),
229
250
  };
230
251
  },
231
252
  };
232
253
  export const dbQueries = {
233
254
  name: "db queries",
234
255
  summary: "The tenant's saved database queries by tool slug; with a query, its SQL, parameters and limits.",
235
- description: "Each saved query is one agent tool (tool_type database_query). A superadmin writes it in the Admin; `cavelon pull` writes\n" +
236
- "its definition into the package's tools. A parameter filled by end_user.* comes from the signed-in visitor, never from\n" +
237
- "the model. Without a query: one line per query. With one (its tool's slug or the query's id): the whole query.",
256
+ description: "Each saved query is one agent tool (tool_type database_query). The tenant Owner or a superadmin in Tenant mode writes\n" +
257
+ "it with database_connectors.manage: in the Admin or through apply with a personal access token and the person's approval.\n" +
258
+ "`cavelon pull` writes its definition into the package's tools. A parameter filled by end_user.* comes from the signed-in visitor, never from\n" +
259
+ "the model. Where published, kind is read or write; write settings are max_affected_rows, requires_confirmation and max_calls.\n" +
260
+ "Without a query: one line per query. With one (its tool's slug or the query's id): the whole query.",
238
261
  readOnly: true,
239
262
  idempotent: true,
240
263
  mcpTool: "db_queries",
@@ -249,12 +272,18 @@ export const dbQueries = {
249
272
  const ref = positional(input, "query");
250
273
  if (ref) {
251
274
  const q = await resolveQuery(ctx, ref);
275
+ const connection = (await listConnections(ctx)).find((c) => c.id === q.connection_id);
276
+ const procedure = q.kind !== "write" && isProcedureCall(q.sql_text, connection?.dialect);
277
+ const refusal = procedure ? connection?.procedure_call_refusal : undefined;
252
278
  const text = [
253
279
  keyValues([
254
280
  ["query", `${q.slug} (${q.name})`],
255
281
  ["connection", q.connection_name],
256
282
  ["description", q.description ? clip(q.description, 300) : undefined],
257
- ["limits", `max_rows ${q.max_rows}, max_result_chars ${q.max_result_chars}`],
283
+ ["kind", reported(q.kind)],
284
+ ["limits", `max_rows ${q.max_rows}, max_result_chars ${q.max_result_chars}${typeof q.max_affected_rows === "number" ? `, max_affected_rows ${q.max_affected_rows}` : ""}`],
285
+ ["requires_confirmation", reported(q.requires_confirmation)],
286
+ ["max_calls", reported(q.max_calls)],
258
287
  ["anonymous", q.allows_anonymous ? "visitors may call it without signing in" : "a signed-in visitor only"],
259
288
  ["enabled", q.is_enabled ? "yes" : "no"],
260
289
  ["version", q.version],
@@ -264,11 +293,19 @@ export const dbQueries = {
264
293
  "SQL:",
265
294
  q.sql_text,
266
295
  "",
296
+ ...(procedure
297
+ ? [
298
+ "It calls a stored procedure: the model gets its first result set. It runs only while the connection's last test found no write privileges,",
299
+ "and the instance reads the procedure's definition at every save, enable and test run and refuses one that writes.",
300
+ ...(refusal?.code ? [`Not now on ${connection.name}: ${refusal.code}${refusal.message ? ` (${clip(refusal.message, 200)})` : ""}`] : []),
301
+ "",
302
+ ]
303
+ : []),
267
304
  q.parameters.length ? table(parameterRows(q.parameters), ["name", "filled_by", "type", "required", "constraints", "description"]) : "No parameters.",
268
305
  "",
269
306
  `Its runs (no values, no rows): ${cavelonCommand("db", "runs", q.slug)}`,
270
307
  ].join("\n");
271
- return { data: q, text };
308
+ return { data: q, text: text + explainLine([refusal?.code]) };
272
309
  }
273
310
  const connectionRef = stringOption(input, "connection");
274
311
  const connection = connectionRef ? await resolveConnection(ctx, connectionRef) : undefined;
@@ -279,6 +316,7 @@ export const dbQueries = {
279
316
  slug: q.slug,
280
317
  name: q.name,
281
318
  connection: q.connection_name,
319
+ kind: q.kind ?? null,
282
320
  parameters: q.parameters.map((p) => (filledBy(p) === "model" ? p.name : `${p.name} (${filledBy(p)})`)).join(", ") || null,
283
321
  max_rows: q.max_rows,
284
322
  anonymous: q.allows_anonymous ? "yes" : "no",
@@ -287,7 +325,7 @@ export const dbQueries = {
287
325
  }));
288
326
  return {
289
327
  data: page,
290
- text: (table(rows, ["slug", "name", "connection", "parameters", "max_rows", "anonymous", "enabled", "version"], 60) || "No database queries.") +
328
+ text: (table(rows, ["slug", "name", "connection", ...(page.items.some(q => q.kind !== undefined) ? ["kind"] : []), "parameters", "max_rows", "anonymous", "enabled", "version"], 60) || "No database queries.") +
291
329
  moreHint(page.next_cursor, cavelonCommand("db", "queries")) +
292
330
  (rows.length ? `\n\nOne query in full: ${cavelonCommand("db", "queries", fill("slug"))}` : ""),
293
331
  };
@@ -295,7 +333,7 @@ export const dbQueries = {
295
333
  };
296
334
  export const dbRuns = {
297
335
  name: "db runs",
298
- summary: "A saved query's runs, newest first: source, outcome, error code, duration and row count; never values or rows.",
336
+ summary: "A saved query's runs: outcome, counts and published write evidence (kind, affected_rows, committed, dry_run); never values or rows.",
299
337
  description: "Every run leaves this evidence, an agent's call and a test run alike; the instance keeps no parameter value, row or SQL.\n" +
300
338
  "`cavelon explain <code>` says what an error code means and how to fix it.",
301
339
  readOnly: true,
@@ -331,12 +369,14 @@ export const dbRuns = {
331
369
  rows: r.row_count ?? null,
332
370
  truncated: r.truncated ? "yes" : null,
333
371
  version: r.query_version,
372
+ ...Object.fromEntries(WRITE_EVIDENCE.filter(k => k !== "rolled_back").map(k => [k, reported(r[k]) ?? null])),
334
373
  }));
335
374
  return {
336
375
  data: { query: { id: q.id, slug: q.slug, version: q.version }, items, next_cursor: next },
337
- text: (table(rows, ["at", "source", "outcome", "error_code", "duration_ms", "rows", "truncated", "version"]) || `No runs of ${q.slug} yet.`) +
376
+ text: (table(rows, ["at", "source", "outcome", "error_code", "duration_ms", "rows", ...WRITE_EVIDENCE.filter(k => k !== "rolled_back" && items.some(r => r[k] !== undefined)), "truncated", "version"]) || `No runs of ${q.slug} yet.`) +
338
377
  moreHint(next, cavelonCommand("db", "runs", q.slug)) +
339
- explainLine(items.map((r) => r.error_code)),
378
+ explainLine(items.map((r) => r.error_code)) +
379
+ (items.some(r => r.error_code === "write_outcome_unknown") ? `\n\n${NO_WRITE_RETRY}` : ""),
340
380
  };
341
381
  },
342
382
  };
@@ -348,7 +388,10 @@ export const dbTest = {
348
388
  "step names its code; `cavelon explain <code>` says how to fix it. A finding under write_privileges means the database user\n" +
349
389
  "can write: ask the database administrator for a read-only user. On SQL Server, which has no read-only transaction, the\n" +
350
390
  "connection's queries then do not run (write_privileges_unacknowledged) until its login may only read or a superadmin\n" +
351
- "acknowledges the write privileges in the Admin.",
391
+ "acknowledges the write privileges in the Admin; a stored-procedure query (EXEC) runs only on a login the test found\n" +
392
+ "without write privileges, acknowledged or not. A passing test on SQL Server also reads again the procedure each\n" +
393
+ "stored-procedure query calls, and lists those that no longer pass the instance's check (procedure_findings); they stay\n" +
394
+ "as they are, and their next save or enable is refused until the procedure only reads again.",
352
395
  readOnly: false,
353
396
  idempotent: true,
354
397
  mcpEffect: "Runs the connection test on the instance and stores its outcome as the connection's last test; changes no setting.",
@@ -370,19 +413,51 @@ export const dbTest = {
370
413
  }
371
414
  const ok = result.outcome === "ok";
372
415
  const steps = (result.steps ?? []).map((s) => ({ step: s.name, status: s.status, code: s.code ?? null, message: s.driver_message ? clip(s.driver_message, 160) : null }));
416
+ const findings = (Array.isArray(result.procedure_findings) ? result.procedure_findings : []).map((f) => ({
417
+ query: f.slug ?? f.query_id ?? "?",
418
+ code: f.code ?? null,
419
+ message: f.message ? clip(f.message, 200) : null,
420
+ }));
421
+ if (findings.length) {
422
+ ctx.warn(`The test passed, but the procedure of ${findings.length === 1 ? "one stored-procedure query" : `${findings.length} stored-procedure queries`} ` +
423
+ `(${findings.map((f) => f.query).join(", ")}) no longer passes the instance's check: ${findings.length === 1 ? "it stays" : "they stay"} as ${findings.length === 1 ? "it is" : "they are"}, ` +
424
+ "and a save or enable is refused until the procedure only reads again.");
425
+ }
373
426
  const text = [
374
427
  `Connection "${connection.name}" (${connection.dialect}): ${ok ? "test passed" : `test failed (${result.outcome})`}, ${result.duration_ms} ms.`,
375
428
  table(steps, ["step", "status", "code", ...(steps.some((s) => s.message) ? ["message"] : [])], 80),
376
429
  ...(result.server_version ? [`server: ${result.server_version}`] : []),
377
430
  ...(result.write_privileges ? [`write privileges: ${clip(JSON.stringify(result.write_privileges), 300)}`] : []),
431
+ ...(findings.length
432
+ ? ["", "Stored-procedure queries whose procedure no longer passes (they stay as they are; a save or enable is refused):", table(findings, ["query", "code", "message"], 80)]
433
+ : []),
378
434
  ].join("\n");
379
435
  return {
380
436
  data: { connection: { id: connection.id, name: connection.name, dialect: connection.dialect }, ...result },
381
- text: text + explainLine(steps.filter((s) => s.code && s.status !== "ok").map((s) => s.code)),
437
+ text: text + explainLine([...steps.filter((s) => s.code && s.status !== "ok").map((s) => s.code), ...findings.map((f) => f.code)]),
382
438
  exitCode: ok ? ExitCode.ok : ExitCode.validation,
383
439
  };
384
440
  },
385
441
  };
442
+ const RUN_REFUSAL_STEPS = {
443
+ database_connection_untested: (q) => `The tenant Owner tests the connection first: ${cavelonCommand("db", "test", q.connection_name)}`,
444
+ write_privileges_block_procedure: (q) => `The connection's login needs to lose its write privileges (a database administrator's change), then the tenant Owner tests it again: ${cavelonCommand("db", "test", q.connection_name)}`,
445
+ procedure_definition_unreadable: () => "The connection's login needs VIEW DEFINITION on the procedure, and the procedure must not be created WITH ENCRYPTION.",
446
+ procedure_definition_writes: () => "The procedure must only read (temporary tables and table variables are fine), or a superadmin writes the query as a SELECT.",
447
+ };
448
+ function refusedRun(error, query) {
449
+ if (!(error instanceof CavelonError) || error.status !== 409)
450
+ return error;
451
+ const step = RUN_REFUSAL_STEPS[error.code];
452
+ return new CavelonError(error.exitCode, {
453
+ code: error.code,
454
+ status: error.status,
455
+ message: error.message,
456
+ hint: [error.hint, step?.(query), `\`${cavelonCommand("explain", error.code)}\` says more.`].filter(Boolean).join(" "),
457
+ docs: error.docs,
458
+ details: error.details,
459
+ });
460
+ }
386
461
  function typed(parameter, raw) {
387
462
  const type = parameter?.type ?? "string";
388
463
  if (type === "integer" || type === "number") {
@@ -421,10 +496,19 @@ export const dbTestRun = {
421
496
  description: "Needs the tenant Owner's permission (database_connectors.test); it reads the customer's own data. Give each parameter\n" +
422
497
  "with --value name=value, those the platform fills from the signed-in visitor (end_user.*) too: that is how an\n" +
423
498
  "identity-scoped query is checked for one customer. The instance records the run (counts only) and audits it with your\n" +
424
- "name; the rows come back once and are never stored. A failed run names its code; `cavelon explain <code>` says more.",
499
+ "name. Where the instance publishes the matching needs_a_person_when restriction, the kit refuses an API key on an\n" +
500
+ "end_user.* query before sending (exit 5): a person tests it in the Admin or with their personal access token. Ordinary queries\n" +
501
+ "remain usable with an API key. On an older instance that omits the restriction, the server decides.\n" +
502
+ "The rows come back once and are never stored. A failed run names its code; `cavelon explain <code>` says more.\n" +
503
+ "A write query's test is a dry run that rolls back; it still needs the connection to allow writes. The result reports\n" +
504
+ "kind, dry_run, rolled_back, affected_rows and committed only where published; an omitted value stays unknown. Never\n" +
505
+ "retry an ambiguous write outcome. A read stored-procedure query (SQL Server) shows the procedure's first result set; the instance refuses its run (exit 4)\n" +
506
+ "while the connection's last test found write privileges or the procedure's definition writes or cannot be read, and\n" +
507
+ "a run whose procedure ended the connector's transaction comes back with a notice saying so and whether the query was\n" +
508
+ "switched off.",
425
509
  readOnly: false,
426
510
  idempotent: true,
427
- mcpEffect: "Runs the saved query once on the instance; it leaves a run record (counts only) and an audit entry, and changes no setting.",
511
+ mcpEffect: "Tests the saved query once on the instance; writes are dry runs that roll back. Leaves a run record and audit entry, and changes no setting. Never retry an ambiguous write outcome.",
428
512
  mcpTool: "db_test_run",
429
513
  operations: ["POST /api/v1/database-connectors/queries/{query_id}/test-run"],
430
514
  positionals: [{ name: "query", description: "The query's tool slug or id.", required: true }],
@@ -435,6 +519,9 @@ export const dbTestRun = {
435
519
  examples: ["cavelon db test-run order_status --value order_no=A-10023 --value email=ada@example.com", "cavelon db test-run stock --value sku=4711 --json"],
436
520
  async run(ctx, input) {
437
521
  const query = await resolveQuery(ctx, positional(input, "query"));
522
+ if (query.parameters.some(p => p.source?.startsWith("end_user."))) {
523
+ requirePersonForIdentityChoice(await accessFor(await ctx.client()), "POST /api/v1/database-connectors/queries/{query_id}/test-run", "test a query with end_user.* parameters");
524
+ }
438
525
  const values = runValues(query, listOption(input, "value"));
439
526
  const shown = intOption(input, "rows", { min: 0, max: 500, fallback: ROWS_SHOWN });
440
527
  let result;
@@ -446,7 +533,10 @@ export const dbTestRun = {
446
533
  });
447
534
  }
448
535
  catch (error) {
449
- throw ownerOnly(error, "A test run");
536
+ if (query.kind === "write" && error instanceof CavelonError && (error.code === "network_error" || error.code === "request_timeout")) {
537
+ throw new CavelonError(error.exitCode, { code: error.code, status: error.status, message: error.message, hint: NO_WRITE_RETRY, docs: error.docs, details: error.details });
538
+ }
539
+ throw refusedRun(ownerOnly(error, "A test run"), query);
450
540
  }
451
541
  const ok = result.outcome === "ok" && !result.error_code;
452
542
  const columns = result.columns ?? [];
@@ -458,6 +548,8 @@ export const dbTestRun = {
458
548
  ["outcome", result.error_code ? `${result.outcome} (${result.error_code}${result.sqlstate ? `, SQLSTATE ${result.sqlstate}` : ""})` : result.outcome],
459
549
  ["rows", ok ? `${result.returned_rows ?? rows.length} returned of ${result.row_count ?? "?"}${result.truncated ? ", truncated for the model" : ""}` : undefined],
460
550
  ["duration_ms", result.duration_ms],
551
+ ["notice", result.notice || undefined],
552
+ ...WRITE_EVIDENCE.map(k => [k, reported(result[k])]),
461
553
  ]),
462
554
  "",
463
555
  "What the model sees:",
@@ -467,7 +559,7 @@ export const dbTestRun = {
467
559
  ].join("\n");
468
560
  return {
469
561
  data: { query: { id: query.id, slug: query.slug, version: query.version }, ...result },
470
- text: text + explainLine([result.error_code]),
562
+ text: text + explainLine([result.error_code]) + (result.error_code === "write_outcome_unknown" ? `\n\n${NO_WRITE_RETRY}` : ""),
471
563
  exitCode: ok ? ExitCode.ok : ExitCode.validation,
472
564
  };
473
565
  },
@@ -15,6 +15,7 @@ import { schema } from "./schema.js";
15
15
  import { harnessClone, harnessDefault, harnessList, harnessNew, tenantCreate, tenantList } from "./tenants.js";
16
16
  import { kbUpload, testRun, trace } from "./work.js";
17
17
  import { dbConnections, dbInstance, dbQueries, dbRuns, dbTest, dbTestRun } from "./db.js";
18
+ import { dbConnectionCa, dbConnectionCreate, dbConnectionDelete, dbConnectionUpdate, dbLoginScript, dbSchema } from "./db-connections.js";
18
19
  import { secretsDelete, secretsList, secretsSet, variablesDelete, variablesGet, variablesList, variablesSet } from "./values.js";
19
20
  import { loopCancel, loopIterations, loopPause, loopResume, loopStart, loopWatch, triggerIdentity } from "./loops.js";
20
21
  import { artifactsExport, sandboxActivity, sandboxCat, sandboxFiles, sandboxList, sandboxLogs, sandboxReceipt, sandboxRefresh, sandboxSeed, sandboxValidate, } from "./sandboxes.js";
@@ -105,6 +106,12 @@ export const COMMANDS = [
105
106
  trace,
106
107
  dbInstance,
107
108
  dbConnections,
109
+ dbConnectionCreate,
110
+ dbConnectionUpdate,
111
+ dbConnectionDelete,
112
+ dbConnectionCa,
113
+ dbLoginScript,
114
+ dbSchema,
108
115
  dbQueries,
109
116
  dbRuns,
110
117
  dbTest,
@@ -316,6 +316,7 @@ function reachText(reach) {
316
316
  export const whoami = {
317
317
  name: "whoami",
318
318
  summary: "Show who the token acts as, in which tenant, and where the token came from.",
319
+ description: "Shows needs_a_person and the optional needs_a_person_when separately. Conditional identity guidance leaves ordinary requests usable; an omitted list stays unknown.",
319
320
  readOnly: true,
320
321
  idempotent: true,
321
322
  mcpTool: "whoami",
@@ -393,6 +394,7 @@ export const whoami = {
393
394
  scopes: principal?.api_key?.scopes ?? null,
394
395
  permissions: access?.permissions ?? null,
395
396
  needs_a_person: access?.complete ? access.needsAPerson : null,
397
+ needs_a_person_when: access?.needsAPersonWhen ?? null,
396
398
  published: Boolean(principal),
397
399
  },
398
400
  owner: me
@@ -442,6 +444,7 @@ export const whoami = {
442
444
  ["scopes", data.credential.scopes ? data.credential.scopes.join(", ") || "none" : undefined],
443
445
  ["permissions", permissionsText(access)],
444
446
  ["needs a person", needsAPersonText(access)],
447
+ ["needs a person when", needsAPersonWhenText(access)],
445
448
  ["platform mode", typeof principal?.token?.platform_mode_allowed === "boolean" ? platformModeText(principal.token) : undefined],
446
449
  ["reaches", reach ? reachText(reach) : undefined],
447
450
  ["version", data.instance.version ? `${data.instance.version}${versionCachedAt ? ` (cached at ${versionCachedAt})` : ""}` : undefined],
@@ -482,6 +485,13 @@ function needsAPersonText(access) {
482
485
  const shown = all.slice(0, LISTED).map((o) => `\n ${o.method} ${o.path}${o.reason ? ` (${clip(o.reason, 80)})` : ""}`);
483
486
  return `${all.length} operation${all.length === 1 ? "" : "s"} a person runs, not this credential:${shown.join("")}${all.length > LISTED ? `\n … ${all.length - LISTED} more (--json)` : ""}`;
484
487
  }
488
+ function needsAPersonWhenText(access) {
489
+ const all = access?.needsAPersonWhen;
490
+ if (!all?.length)
491
+ return undefined;
492
+ const shown = all.slice(0, LISTED).map(o => `\n ${o.method} ${o.path}: ${clip(o.reason, 160)}`);
493
+ return `Only in these cases; ordinary requests remain usable:${shown.join("")}${all.length > LISTED ? `\n … ${all.length - LISTED} more (--json)` : ""}`;
494
+ }
485
495
  function secretsText(may, inAdmin) {
486
496
  if (may === null)
487
497
  return undefined;
@@ -622,6 +632,7 @@ function limitsLine(state, near) {
622
632
  export const status = {
623
633
  name: "status",
624
634
  summary: "Show the instance, tenant, solution, running operations and quotas close to full for this directory.",
635
+ description: "For the folder's solution, shows readiness and whether activation would take the default chat and widget route. An omitted route flag is unknown. Readiness reserves no route state; activation reports the actual effect.",
625
636
  readOnly: true,
626
637
  idempotent: true,
627
638
  mcpTool: "status",
@@ -401,8 +401,9 @@ export const setup = {
401
401
  tenantless: true,
402
402
  summary: "Set up your coding agents for Cavelon and log in, in one guided step.",
403
403
  description: "Finds Claude Code, Codex, Cursor, VS Code with GitHub Copilot, Gemini CLI and Kiro, shows what it will change for each, asks once\n" +
404
- "and does it: Claude Code and Codex get the Cavelon plugin through their own plugin command; the others get the `cavelon` MCP\n" +
405
- "server in their user MCP configuration and the skills in their user skills folder. It touches nothing else in those files and\n" +
404
+ "and does it: Claude Code and Codex get the Cavelon plugin through their own plugin command, Gemini CLI the extension of this\n" +
405
+ "release (or the files, when the release has none); the others get the `cavelon` MCP server in their user MCP configuration\n" +
406
+ "and the skills in their user skills folder. It touches nothing else in those files and\n" +
406
407
  "records what it did, so --remove undoes exactly that. Then it logs in if needed, choosing the tenant by name as `login` does.\n" +
407
408
  "The server starts as `cavelon mcp` when cavelon is installed, otherwise through npx. --check reports what is set up and\n" +
408
409
  "working: each agent's entry, the MCP server starting, and the login. An agent found but never set up for Cavelon is\n" +