@cavelon/cli 0.2.3 → 0.2.4

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.
package/README.md CHANGED
@@ -177,7 +177,8 @@ Every command takes `--json` (one JSON document on stdout, errors included),
177
177
  | `db instance` | read-only | The dialects the instance runs and the addresses it connects to databases from, which a database's firewall lets in. |
178
178
  | `db connections` / `db queries [<query>] [--connection]` / `db runs <query>` | read-only | The tenant's database connections (with their CA certificates' expiry), saved queries (one in full with its SQL and parameters) and a query's runs (no values, no rows). |
179
179
  | `db test <connection>` | changing | The tenant Owner tests a connection step by step; exit 3 when a step fails. |
180
- | `db test-run <query> [--value name=value…]` | changing | The tenant Owner runs a saved query once, identity parameters included, and sees what the model would; exit 3 when it fails. |
180
+ | `db test-run <query> [--draft] [--value name=value…]` | changing | Test a saved query or validate and test edited package SQL before apply. Writes dry-run and report rollback evidence; exit 3 when it fails. Drafts need the Owner's managing PAT. |
181
+ | `db queries delete\|enable\|disable\|rename <query> [<new-slug>] [--confirm]` | changing | Preview a saved-query change, then obtain the person's approval. Delete reports removed assignments; pull follows the change. |
181
182
  | `loop start <trigger> [--input <json>] [--wait] [--confirm]` | changing | Start a loop through its trigger, as you; without `--confirm`, shows the trigger, its solution and the payload; with it, returns the run and operation ids. |
182
183
  | `loop cancel <run> [--confirm]` | changing (destructive) | Stop a trigger run and its loops; without `--confirm`, shows what would stop. |
183
184
  | `loop watch <run> [--loop] [--timeout 10m]` | read-only | One line per decided iteration and per state change, then the loop's outcome; returns when it ends or pauses. |
package/dist/access.js CHANGED
@@ -31,6 +31,7 @@ export const OPERATION_PERMISSIONS = {
31
31
  "GET /api/v1/database-connectors/connections/{connection_id}/login-script": ["database_connectors.view"],
32
32
  "POST /api/v1/database-connectors/queries/{query_id}/test-run": [["database_connectors.test", "database_connectors.manage"]],
33
33
  "POST /api/v1/database-connectors/queries": ["database_connectors.manage"],
34
+ "POST /api/v1/database-connectors/queries/test-run": ["database_connectors.manage"],
34
35
  "PATCH /api/v1/database-connectors/queries/{query_id}": ["database_connectors.manage"],
35
36
  "DELETE /api/v1/database-connectors/queries/{query_id}": ["database_connectors.manage"],
36
37
  "PUT /api/v1/variables/{name}": [SETTINGS_VALUES],
@@ -0,0 +1,120 @@
1
+ export const CITUS_ADMIN_FUNCTIONS = new Set([
2
+ "alter_distributed_table",
3
+ "alter_old_partitions_set_access_method",
4
+ "alter_role_if_exists",
5
+ "alter_table_set_access_method",
6
+ "assign_distributed_transaction_id",
7
+ "broadcast_intermediate_result",
8
+ "check_distributed_deadlocks",
9
+ "citus_activate_node",
10
+ "citus_add_inactive_node",
11
+ "citus_add_local_table_to_metadata",
12
+ "citus_add_node",
13
+ "citus_add_rebalance_strategy",
14
+ "citus_add_secondary_node",
15
+ "citus_cleanup_orphaned_resources",
16
+ "citus_cleanup_orphaned_shards",
17
+ "citus_copy_shard_placement",
18
+ "citus_create_restore_point",
19
+ "citus_disable_node",
20
+ "citus_drain_node",
21
+ "citus_drop_all_shards",
22
+ "citus_finalize_upgrade_to_citus11",
23
+ "citus_finish_citus_upgrade",
24
+ "citus_finish_pg_upgrade",
25
+ "citus_job_cancel",
26
+ "citus_job_wait",
27
+ "citus_move_shard_placement",
28
+ "citus_pause_node_within_txn",
29
+ "citus_prepare_pg_upgrade",
30
+ "citus_rebalance_start",
31
+ "citus_rebalance_stop",
32
+ "citus_rebalance_wait",
33
+ "citus_remove_node",
34
+ "citus_run_local_command",
35
+ "citus_schema_distribute",
36
+ "citus_schema_move",
37
+ "citus_schema_undistribute",
38
+ "citus_set_coordinator_host",
39
+ "citus_set_default_rebalance_strategy",
40
+ "citus_set_node_property",
41
+ "citus_split_shard_by_split_points",
42
+ "citus_stat_statements_reset",
43
+ "citus_stat_tenants_local_reset",
44
+ "citus_stat_tenants_reset",
45
+ "citus_task_wait",
46
+ "citus_unmark_object_distributed",
47
+ "citus_update_node",
48
+ "citus_update_shard_statistics",
49
+ "citus_update_table_statistics",
50
+ "citus_validate_rebalance_strategy_functions",
51
+ "create_distributed_function",
52
+ "create_distributed_table",
53
+ "create_distributed_table_concurrently",
54
+ "create_intermediate_result",
55
+ "create_reference_table",
56
+ "create_time_partitions",
57
+ "drop_old_time_partitions",
58
+ "fetch_intermediate_results",
59
+ "fix_all_partition_shard_index_names",
60
+ "fix_partition_shard_index_names",
61
+ "fix_pre_citus10_partitioned_table_constraint_names",
62
+ "isolate_tenant_to_new_shard",
63
+ "lock_relation_if_exists",
64
+ "lock_shard_metadata",
65
+ "lock_shard_resources",
66
+ "master_activate_node",
67
+ "master_add_inactive_node",
68
+ "master_add_node",
69
+ "master_add_secondary_node",
70
+ "master_copy_shard_placement",
71
+ "master_create_empty_shard",
72
+ "master_disable_node",
73
+ "master_drain_node",
74
+ "master_get_new_placementid",
75
+ "master_get_new_shardid",
76
+ "master_move_shard_placement",
77
+ "master_remove_distributed_table_metadata_from_workers",
78
+ "master_remove_node",
79
+ "master_remove_partition_metadata",
80
+ "master_run_on_worker",
81
+ "master_set_node_property",
82
+ "master_unmark_object_distributed",
83
+ "master_update_node",
84
+ "master_update_shard_statistics",
85
+ "master_update_table_statistics",
86
+ "notify_constraint_dropped",
87
+ "rebalance_table_shards",
88
+ "recover_prepared_transactions",
89
+ "remove_local_tables_from_metadata",
90
+ "replicate_reference_tables",
91
+ "replicate_table_shards",
92
+ "start_metadata_sync_to_all_nodes",
93
+ "start_metadata_sync_to_node",
94
+ "stop_metadata_sync_to_node",
95
+ "truncate_local_data_after_distributing_table",
96
+ "undistribute_table",
97
+ "update_distributed_table_colocation",
98
+ "worker_adjust_identity_column_seq_ranges",
99
+ "worker_apply_inter_shard_ddl_command",
100
+ "worker_apply_sequence_command",
101
+ "worker_apply_shard_ddl_command",
102
+ "worker_change_sequence_dependency",
103
+ "worker_copy_table_to_node",
104
+ "worker_create_or_alter_role",
105
+ "worker_create_or_replace_object",
106
+ "worker_create_truncate_trigger",
107
+ "worker_drop_all_shell_tables",
108
+ "worker_drop_distributed_table",
109
+ "worker_drop_sequence_dependency",
110
+ "worker_drop_shell_table",
111
+ "worker_fix_partition_shard_index_names",
112
+ "worker_fix_pre_citus10_partitioned_table_constraint_names",
113
+ "worker_nextval",
114
+ "worker_partition_query_result",
115
+ "worker_record_sequence_dependency",
116
+ "worker_save_query_explain_analyze",
117
+ "worker_split_copy",
118
+ "worker_split_shard_release_dsm",
119
+ "worker_split_shard_replication_setup",
120
+ ]);
@@ -12,7 +12,7 @@ import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
12
12
  import { CONFIRM_TOKEN, confirmInTerminal, confirmThroughClient, confirmToken, confirmTokenRequired, personApproves, personRoute } from "../confirm-token.js";
13
13
  import { actingTarget, targetLine } from "../acting.js";
14
14
  import { accessFor, operationAccess } from "../access.js";
15
- import { cavelonCommand, fill, personCommand } from "../printed.js";
15
+ import { cavelonCommand, personCommand } from "../printed.js";
16
16
  import { apiApproval } from "../api-approval-policy.js";
17
17
  import { yoloAllows } from "../automation-policy.js";
18
18
  export const JSON_BODY_DEPRECATED = "`--json <body>` as the request body is deprecated and will be removed in a later release; pass the body with --body. " +
@@ -154,13 +154,13 @@ function secretsIn(doc, op, args) {
154
154
  }
155
155
  return [...found];
156
156
  }
157
- function secretRefusal(op, fields, driven) {
157
+ function secretRefusal(op, fields) {
158
158
  const named = fields.map((f) => `"${f}"`).join(", ");
159
159
  return new CavelonError(ExitCode.needsAction, {
160
160
  code: "secret_field_for_a_person",
161
161
  message: `The request to ${op.alias} sets ${named}, which the instance marks as a secret value (x-cavelon-secret); ` +
162
- `a person enters secret values, so ${notSentBy(driven)}`,
163
- hint: `A person sets a secret value in their own terminal with \`${cavelonCommand("secrets", "set", fill("name"))}\`, or enters it in the Admin. Leave the field out to send the rest.`,
162
+ "cavelon api never sends secret fields, including from a person's terminal.",
163
+ hint: "Enter database passwords, private keys and keytabs in the Admin under Settings › Security & access › Databases. For other secrets, use the Admin or the dedicated secrets command where the instance allows it. Leave the field out to send the rest.",
164
164
  details: { fields },
165
165
  });
166
166
  }
@@ -209,7 +209,8 @@ export const api = {
209
209
  "Other changes still need the person's yes: the MCP client asks them, or they send it from their own terminal.\n" +
210
210
  "A changed request needs a new preview; confirm: true is refused. Instance confirmation requirements always win.\n" +
211
211
  "Run by an agent, one the instance marks for a person only (x-cavelon-person-only) is refused, as is a body that\n" +
212
- "sets a field the instance marks as a secret value (x-cavelon-secret) and a file outside the solution folder. On an\n" +
212
+ "sends a file outside the solution folder. Secret body fields (x-cavelon-secret) are refused in every mode, including\n" +
213
+ "a person's terminal; enter passwords, keys and keytabs in the Admin. On an\n" +
213
214
  "instance that marks no operation, one that changes a secret, creates or revokes a credential or decides an\n" +
214
215
  "approval is refused. A person's own terminal sends at once.\n" +
215
216
  "In a solution folder, the persona operations (get_bot_persona, upsert_bot_persona, …) get the folder's solution as\n" +
@@ -273,10 +274,10 @@ export const api = {
273
274
  details: { source: kept.source, ...(kept.reason ? { reason: kept.reason } : {}) },
274
275
  });
275
276
  }
276
- const secrets = secretsIn(doc, op, args);
277
- if (secrets.length)
278
- throw secretRefusal(op, secrets, driven);
279
277
  }
278
+ const secrets = secretsIn(doc, op, args);
279
+ if (secrets.length)
280
+ throw secretRefusal(op, secrets);
280
281
  if (driven && !op.readOnly) {
281
282
  const words = [
282
283
  "api",
@@ -508,7 +509,7 @@ export const apiDescribe = {
508
509
  : `For a person: it ${kept.reason}, and this instance marks no operation, so an agent does not send it. ${kept.hint}`);
509
510
  }
510
511
  if (secrets.length)
511
- lines.push(`Secret values (x-cavelon-secret): ${secrets.join(", ")}. A person enters them; an agent leaves them out.`);
512
+ lines.push(`Secret values (x-cavelon-secret): ${secrets.join(", ")}. Enter them in the Admin; cavelon api never sends them.`);
512
513
  if (op.confirmation) {
513
514
  lines.push(`Bound confirmation required (x-cavelon-confirmation)${op.confirmationWhen ? `: ${op.confirmationWhen}` : "."} cavelon asks the instance for the ` +
514
515
  "confirmation once the person approved the call: in their own terminal, or in the MCP client's dialog. The instance binds the id to the token, tenant and exact request; it does not verify the person's answer.");
@@ -13,15 +13,15 @@ import { connectionView, connectorOn, read, resolveConnection, viewerOnly, withP
13
13
  const CONNECTIONS = "/api/v1/database-connectors/connections";
14
14
  const CONNECTION = `${CONNECTIONS}/{connection_id}`;
15
15
  const manageHint = "This needs database_connectors.manage in Tenant mode: the tenant Owner (legacy Admin) or a superadmin, using a personal access token or the dashboard. A tenant API key cannot manage connections.";
16
- async function managementPreflight(ctx, method, route) {
16
+ export async function managementPreflight(ctx, method, route) {
17
17
  await connectorOn(ctx);
18
- const { op } = await workflowOperation(ctx, method, route, "database connection management");
18
+ const { doc, op } = await workflowOperation(ctx, method, route, "database connection and query management");
19
19
  const access = operationAccess(await accessFor(await ctx.client()), `${method} ${route}`);
20
20
  if (op.personOnly?.marked || access.person) {
21
21
  const reason = op.personOnly?.marked ? op.personOnly.reason : access.person;
22
22
  throw new CavelonError(ExitCode.needsAction, {
23
23
  code: "operation_for_a_person", message: `This instance keeps ${method} ${route} for a person${reason ? ` (${reason})` : ""}.`,
24
- hint: "A person manages the connection in the Admin under Settings › Security & access › Databases. This instance may be older than connection management with a personal access token.",
24
+ hint: "A person manages database connections and queries in the Admin under Settings › Security & access › Databases. This instance may be older than management with a personal access token.",
25
25
  });
26
26
  }
27
27
  if (access.allowed === false)
@@ -29,6 +29,7 @@ async function managementPreflight(ctx, method, route) {
29
29
  code: "permission_missing", status: 403, message: `This credential lacks ${allOf(access.missing)} for ${method} ${route}.`,
30
30
  hint: manageHint, details: { permissions: access.missing, sent: false },
31
31
  });
32
+ return { doc, op };
32
33
  }
33
34
  async function manage(ctx, method, route, body, id) {
34
35
  try {
@@ -38,7 +39,7 @@ async function manage(ctx, method, route, body, id) {
38
39
  catch (error) {
39
40
  if (error instanceof CavelonError && error.code === "credential_required_for_target_change") {
40
41
  throw new CavelonError(error.exitCode, { code: error.code, status: error.status, message: error.message, details: error.details,
41
- hint: "A person changes host, port or dialect of a password-bearing connection in the Admin under Settings › Security & access › Databases, with the new server's password. The kit never takes a password." });
42
+ hint: "A person changes a credential-bearing connection's target, SSH tunnel or Kerberos login in the Admin under Settings › Security & access › Databases, supplying its password, SSH key or keytab again. The kit never takes those credentials." });
42
43
  }
43
44
  throw withPermissionHint(error, manageHint);
44
45
  }
@@ -53,6 +54,17 @@ const connectionOptions = {
53
54
  "tls-mode": textOption("TLS mode, checked against the published schema; omitted on create uses the instance's default.", "<mode>"),
54
55
  "statement-timeout-ms": textOption("Statement timeout in milliseconds, within the instance's bounds.", "<ms>"),
55
56
  enabled: textOption("Enable or disable the connection (true or false); omitted leaves the instance's default or current value.", "<true|false>"),
57
+ "follows-redirects": textOption("Follow checked listener redirects (Oracle or SQL Server); cannot combine with an SSH tunnel.", "<true|false>"),
58
+ "auth-method": textOption("Sign-in method from the published schema (password or kerberos); credentials stay in the Admin.", "<method>"),
59
+ "kerberos-realm": textOption("Kerberos realm, for example CORP.EXAMPLE.COM.", "<realm>"),
60
+ "kerberos-principal": textOption("Kerberos account name without the realm.", "<principal>"),
61
+ "kerberos-kdc": { type: "string", multiple: true, value: "<host>", description: "KDC host on port 88; repeat for multiple KDCs. Use --kerberos-kdcs for explicit ports." },
62
+ "kerberos-kdcs": textOption('Public KDC JSON array, for example [{"host":"kdc.example.com","port":88}]; null clears it.', "<json>"),
63
+ "ssh-host": textOption("SSH bastion host. Also give --ssh-username and --ssh-host-key-fingerprint.", "<host>"),
64
+ "ssh-port": textOption("Bastion port (default 22); the instance checks private target permissions.", "<port>"),
65
+ "ssh-username": textOption("SSH forwarding account; a person enters its private key in the Admin.", "<username>"),
66
+ "ssh-host-key-fingerprint": textOption("Required SHA256 bastion host-key fingerprint; no trust on first use.", "<SHA256:...>"),
67
+ "remove-ssh-tunnel": { type: "boolean", description: "Remove the SSH tunnel; a credential-bearing connection may require the Admin." },
56
68
  };
57
69
  function booleanText(input, name) {
58
70
  const value = stringOption(input, name);
@@ -66,7 +78,7 @@ function connectionBody(input, name) {
66
78
  const body = {};
67
79
  if (name !== undefined)
68
80
  body.name = name;
69
- for (const [option, field] of Object.entries({ name: "name", dialect: "dialect", host: "host", "database-name": "database_name", username: "username", "tls-mode": "tls_mode" })) {
81
+ for (const [option, field] of Object.entries({ name: "name", dialect: "dialect", host: "host", "database-name": "database_name", username: "username", "tls-mode": "tls_mode", "auth-method": "auth_method", "kerberos-realm": "kerberos_realm", "kerberos-principal": "kerberos_principal" })) {
70
82
  const value = stringOption(input, option);
71
83
  if (value !== undefined)
72
84
  body[field] = value;
@@ -79,17 +91,58 @@ function connectionBody(input, name) {
79
91
  const enabled = booleanText(input, "enabled");
80
92
  if (enabled !== undefined)
81
93
  body.is_enabled = enabled;
94
+ const redirects = booleanText(input, "follows-redirects");
95
+ if (redirects !== undefined)
96
+ body.follows_redirects = redirects;
97
+ const kdcs = listOption(input, "kerberos-kdc");
98
+ const rawKdcs = stringOption(input, "kerberos-kdcs");
99
+ if (kdcs.length && rawKdcs !== undefined)
100
+ throw usageError("Use --kerberos-kdc or --kerberos-kdcs, not both.");
101
+ if (kdcs.length)
102
+ body.kerberos_kdcs = kdcs.map(host => ({ host, port: 88 }));
103
+ if (rawKdcs !== undefined) {
104
+ try {
105
+ body.kerberos_kdcs = JSON.parse(rawKdcs);
106
+ }
107
+ catch {
108
+ throw usageError("--kerberos-kdcs needs a JSON array of public host/port objects, or null.");
109
+ }
110
+ }
111
+ const ssh = { host: stringOption(input, "ssh-host"), port: intOption(input, "ssh-port"), username: stringOption(input, "ssh-username"), host_key_fingerprint: stringOption(input, "ssh-host-key-fingerprint") };
112
+ const hasSsh = Object.values(ssh).some(v => v !== undefined);
113
+ if (input.options["remove-ssh-tunnel"] && hasSsh)
114
+ throw usageError("Do not combine --remove-ssh-tunnel with SSH settings.");
115
+ if (hasSsh) {
116
+ if (!ssh.host || !ssh.username || !ssh.host_key_fingerprint)
117
+ throw usageError("An SSH tunnel needs --ssh-host, --ssh-username and --ssh-host-key-fingerprint together.");
118
+ body.ssh_tunnel = { ...ssh, port: ssh.port ?? 22 };
119
+ }
120
+ if (input.options["remove-ssh-tunnel"])
121
+ body.ssh_tunnel = null;
122
+ if (body.ssh_tunnel && redirects === true)
123
+ throw usageError("An SSH tunnel cannot follow listener redirects.");
82
124
  return body;
83
125
  }
84
126
  async function savedResult(ctx, connection, verb) {
85
127
  const principal = await principalOf(await ctx.client());
86
- const person = principal?.needs_a_person?.find(o => o.method === "PUT" && o.path === `${CONNECTION}/password`) ?? null;
87
- const next = connection.password_set ? `Test the connection: ${cavelonCommand("db", "test", connection.name)}` :
128
+ const credential = connection.auth_method === "kerberos" ? "kerberos-keytab" : "password";
129
+ const person = principal?.needs_a_person?.find(o => o.method === "PUT" && o.path === `${CONNECTION}/${credential}`) ?? null;
130
+ const pending = [];
131
+ if (connection.auth_method === "kerberos" && !connection.kerberos_keytab_set && !connection.password_set)
132
+ pending.push("a person sets the Kerberos keytab or password in the Admin under Settings › Security & access › Databases");
133
+ if (connection.auth_method !== "kerberos" && !connection.password_set)
134
+ pending.push("a person sets the database password in the Admin under Settings › Security & access › Databases");
135
+ if (connection.ssh_tunnel && !connection.ssh_tunnel.private_key_set)
136
+ pending.push("a person sets the SSH private key in the Admin under Settings › Security & access › Databases");
137
+ const next = pending.length ? `${pending.join("; ")}; then run ${cavelonCommand("db", "test", connection.name)}.` : connection.password_set || connection.kerberos_keytab_set ? `Test the connection: ${cavelonCommand("db", "test", connection.name)}` :
88
138
  `${person?.reason ? `${person.reason}: ` : ""}a person sets the password in the Admin under Settings › Security & access › Databases, then runs ${cavelonCommand("db", "test", connection.name)}. The password never goes through the kit.`;
89
139
  return { data: { connection: connectionView(connection), needs_a_person: person, next_step: next }, text: `${verb} connection ${connection.name} (${connection.id}).\n${keyValues([
90
140
  ["dialect", connection.dialect], ["target", `${connection.host}:${connection.port}/${connection.database_name}`], ["username", connection.username],
91
141
  ["tls_mode", connection.tls_mode], ["password_set", connection.password_set], ["allows_writes", connection.allows_writes],
92
142
  ["ca_certificates", connection.ca_certificates], ["ca_certificate_sha256", connection.ca_certificate_sha256],
143
+ ["auth_method", connection.auth_method], ["kerberos_realm", connection.kerberos_realm], ["kerberos_principal", connection.kerberos_principal],
144
+ ["kerberos_keytab_set", connection.kerberos_keytab_set], ["follows_redirects", connection.follows_redirects],
145
+ ["ssh_bastion", connection.ssh_tunnel?.host], ["authorized_keys_entry", connection.ssh_tunnel?.authorized_keys_entry],
93
146
  ])}\n${next}` };
94
147
  }
95
148
  export const dbConnectionCreate = {
@@ -123,6 +176,11 @@ export const dbConnectionUpdate = {
123
176
  if (!Object.keys(body).length)
124
177
  throw usageError("Give at least one connection field to change.");
125
178
  const connection = await resolveConnection(ctx, positional(input, "connection"));
179
+ const access = operationAccess(await accessFor(await ctx.client()), `PATCH ${CONNECTION}`);
180
+ const modes = ["disable", "require", "verify_ca", "verify_full"];
181
+ if (access.personWhen && typeof body.tls_mode === "string" && modes.includes(connection.tls_mode) && modes.includes(body.tls_mode) && modes.indexOf(body.tls_mode) < modes.indexOf(connection.tls_mode)) {
182
+ throw personConnectionChange("weaken TLS");
183
+ }
126
184
  return savedResult(ctx, await manage(ctx, "PATCH", CONNECTION, body, connection.id), "Updated");
127
185
  },
128
186
  };
@@ -173,14 +231,19 @@ function publicCertificates(pem) {
173
231
  return pem;
174
232
  }
175
233
  export const dbConnectionCa = {
176
- name: "db connections ca", summary: "Upload a public CA certificate bundle (database_connectors.manage); refuse private keys before sending.",
177
- description: "The file must contain only valid PEM CERTIFICATE blocks. It is bounded by the instance's published CA limit.\n" +
234
+ name: "db connections ca", summary: "Show the person-only Admin CA step where published; older instances may accept a public certificate upload.",
235
+ description: "A current instance keeps every CA change for a person in the Admin; the kit refuses before reading the file.\n" +
236
+ "On an older instance without that published restriction, the file must contain only valid PEM CERTIFICATE blocks.\n" +
237
+ "It is bounded by the instance's published CA limit.\n" +
178
238
  "The output keeps certificate metadata and fingerprints, never the PEM. Test the connection again after uploading it.",
179
239
  readOnly: false, idempotent: true, mcpTool: "db_connection_ca", operations: [`PATCH ${CONNECTION}`],
180
240
  positionals: [{ name: "connection", required: true, description: "Connection name or id." }, { name: "file", required: true, description: "Public PEM certificate file, never a private key." }],
181
241
  examples: ["cavelon db connections ca shop-db ./public-ca.pem"],
182
242
  async run(ctx, input) {
183
243
  await connectorOn(ctx);
244
+ const access = operationAccess(await accessFor(await ctx.client()), `PATCH ${CONNECTION}`);
245
+ if (access.personWhen || access.person)
246
+ throw personConnectionChange("change the CA certificate");
184
247
  const { doc, op } = await workflowOperation(ctx, "PATCH", CONNECTION, "public CA certificate upload");
185
248
  const body = doc ? deref(doc, op.requestBody?.content["application/json"]?.schema) : undefined;
186
249
  const ca = body?.properties?.ca_certificate_pem;
@@ -209,6 +272,13 @@ export const dbConnectionCa = {
209
272
  return savedResult(ctx, await manage(ctx, "PATCH", CONNECTION, { ca_certificate_pem: pem }, connection.id), "Updated CA of");
210
273
  },
211
274
  };
275
+ function personConnectionChange(change) {
276
+ return new CavelonError(ExitCode.needsAction, {
277
+ code: "operation_for_a_person", message: `A token cannot ${change}. Nothing was sent.`,
278
+ hint: "A person uses the Admin under Settings › Security & access › Databases › the connection › CA certificate or TLS settings.",
279
+ details: { sent: false },
280
+ });
281
+ }
212
282
  export const dbLoginScript = {
213
283
  name: "db login-script", summary: "Print the instance's published read-only login SQL for a dialect or saved connection; no database is contacted.",
214
284
  description: "Needs database_connectors.view. The DBA replaces the script's password placeholder locally, outside the kit.\n" +
@@ -0,0 +1,66 @@
1
+ import { confirmation, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
2
+ import { createHash } from "node:crypto";
3
+ import { positional } from "../command.js";
4
+ import { CavelonError, ExitCode, usageError } from "../errors.js";
5
+ import { clip, keyValues } from "../format.js";
6
+ import { callStable, previewRequest } from "../invoke.js";
7
+ import { cavelonCommand } from "../printed.js";
8
+ import { resolveQuery } from "./db.js";
9
+ import { managementPreflight } from "./db-connections.js";
10
+ const ROUTE = "/api/v1/database-connectors/queries/{query_id}";
11
+ const evidenceFor = (query) => ({ id: query.id, slug: query.slug, version: query.version, kind: query.kind, is_enabled: query.is_enabled,
12
+ sql_sha256: createHash("sha256").update(query.sql_text).digest("hex") });
13
+ function queryChange(change) {
14
+ const method = change === "delete" ? "DELETE" : "PATCH";
15
+ const tool = `db_query_${change}`;
16
+ return {
17
+ name: `db queries ${change}`,
18
+ summary: `${change[0].toUpperCase()}${change.slice(1)} a saved database query; preview first, then the person confirms.`,
19
+ description: "Needs database_connectors.manage. Each preview is bound to this query's version and the exact change.\n" +
20
+ "Rechecks the query after approval; a changed query needs a fresh preview.\n" +
21
+ "Deleting also removes its agent and skill assignments; the result lists what the instance removed.\n" +
22
+ "Run cavelon pull afterwards so the package follows the saved query.\n" + PERSON_CONFIRMS_HELP,
23
+ readOnly: false, destructive: change === "delete", mcpTool: tool, operations: [`${method} ${ROUTE}`],
24
+ positionals: [{ name: "query", required: true, description: "Saved query's slug or id." },
25
+ ...(change === "rename" ? [{ name: "new-slug", required: true, description: "New tool slug, checked against the instance's schema." }] : [])],
26
+ options: { confirm: { type: "boolean", mcpToken: true, description: "Send the exact previewed change after the person's approval." } },
27
+ examples: [`cavelon db queries ${change} order_status${change === "rename" ? " order_lookup" : ""}`],
28
+ async run(ctx, input) {
29
+ const { doc, op } = await managementPreflight(ctx, method, ROUTE);
30
+ const query = await resolveQuery(ctx, positional(input, "query"));
31
+ const slug = positional(input, "new-slug");
32
+ if (change === "rename" && !slug?.trim())
33
+ throw usageError("Give the new query slug.");
34
+ const body = change === "delete" ? undefined : change === "rename" ? { slug } : { is_enabled: change === "enable" };
35
+ previewRequest(doc, op, { params: { query_id: [query.id] }, body });
36
+ const words = ["db", "queries", change, query.id, ...(slug ? [slug] : []), "--confirm"];
37
+ const evidence = evidenceFor(query);
38
+ const gate = await confirmation(ctx, input, tool, { query: evidence, method, body }, {
39
+ person: { what: `${change} saved ${query.kind ?? "unknown-kind"} database query ${query.slug} (version ${query.version}, SQL SHA-256 ${evidence.sql_sha256})${slug ? ` to ${slug}` : ""}${change === "delete" ? " and remove its agent and skill assignments" : ""}.`, words },
40
+ });
41
+ if (!gate.confirmed)
42
+ return {
43
+ data: { sent: false, query: evidence, change, body: body ?? null,
44
+ confirm: gate.confirm(cavelonCommand(...words)), ...gate.fields },
45
+ text: `${keyValues([["query", query.slug], ["version", query.version], ["kind", query.kind], ["sql_sha256", evidence.sql_sha256], ["change", change], ["new_slug", slug]])}\n${gate.where}\n${gate.mismatch ?? "Nothing was changed."}\n${gate.confirm(cavelonCommand(...words))}`,
46
+ exitCode: gate.exitCode,
47
+ };
48
+ await managementPreflight(ctx, method, ROUTE);
49
+ if (JSON.stringify(evidenceFor(await resolveQuery(ctx, query.id))) !== JSON.stringify(evidence)) {
50
+ ctx.approved = undefined;
51
+ throw new CavelonError(ExitCode.conflict, {
52
+ code: "token_mismatch", message: "The saved query changed while approval was pending. Nothing was changed by this command.",
53
+ hint: "Request a fresh preview and approve the query as it is now.", details: { sent: false },
54
+ });
55
+ }
56
+ const result = await callStable(ctx, method, ROUTE, "saved database query management", { params: { query_id: [query.id] }, body });
57
+ const next = `Run ${cavelonCommand("pull")} so package/ follows this change.`;
58
+ return { data: { sent: true, change, ...result, next_step: next },
59
+ text: `${change} completed for ${query.slug}.${change === "delete" ? `\nRemoved assignments: ${clip(JSON.stringify(result.removed_references ?? {}), 3000)}` : ""}\n${next}` };
60
+ },
61
+ };
62
+ }
63
+ export const dbQueryDelete = queryChange("delete");
64
+ export const dbQueryEnable = queryChange("enable");
65
+ export const dbQueryDisable = queryChange("disable");
66
+ export const dbQueryRename = queryChange("rename");
@@ -1,6 +1,7 @@
1
- import { CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption } from "../command.js";
2
- import { CavelonError, ExitCode, usageError } from "../errors.js";
3
- import { connectorOffer, isProcedureCall } from "../database-queries.js";
1
+ import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption } from "../command.js";
2
+ import { CavelonError, ExitCode, usageError, validationError } from "../errors.js";
3
+ import { connectorOffer, isProcedureCall, queryTools } from "../database-queries.js";
4
+ import { requireSolution, validatePackage } from "./solution.js";
4
5
  import { requireFeature } from "../features.js";
5
6
  import { clip, keyValues, moreHint, table } from "../format.js";
6
7
  import { callStable } from "../invoke.js";
@@ -17,7 +18,7 @@ function reported(value) {
17
18
  return value ? "yes" : "no";
18
19
  return typeof value === "string" || typeof value === "number" ? value : undefined;
19
20
  }
20
- const WRITE_EVIDENCE = ["kind", "dry_run", "rolled_back", "affected_rows", "committed"];
21
+ const WRITE_EVIDENCE = ["kind", "dry_run", "rolled_back", "affected_rows", "committed", "surface", "redirect_hops", "redirect_target_class"];
21
22
  const NO_WRITE_RETRY = "Do not retry an ambiguous write outcome. Check the database for the change before anyone repeats it.";
22
23
  const FEATURE = "database_connector_enabled";
23
24
  const DOCS_PAGE = "administration/database-connectors";
@@ -58,7 +59,7 @@ export async function resolveConnection(ctx, ref) {
58
59
  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"}.`,
59
60
  });
60
61
  }
61
- async function resolveQuery(ctx, ref) {
62
+ export async function resolveQuery(ctx, ref) {
62
63
  await connectorOn(ctx);
63
64
  if (isUuid(ref)) {
64
65
  try {
@@ -100,7 +101,7 @@ function expiryWarnings(connections, now) {
100
101
  ? `expired on ${day(cert.not_after)}`
101
102
  : `expires on ${day(cert.not_after)} (in ${days === 0 ? "less than a day" : `${days} day${days === 1 ? "" : "s"}`})`;
102
103
  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. ` +
103
- `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)}`);
104
+ `A person replaces the CA certificate in the Admin under Settings › Security & access › Databases, then tests the connection again: ${cavelonCommand("db", "test", c.name)}`);
104
105
  }
105
106
  }
106
107
  return warnings;
@@ -194,10 +195,13 @@ export const dbInstance = {
194
195
  ["connections_per_process", offer.network.connections_per_process],
195
196
  ["write_queries", reported(offer.write_queries)],
196
197
  ["max_affected_rows_limit", reported(offer.max_affected_rows_limit)],
198
+ ["kerberos_dialects", offer.kerberos_dialects?.join(", ")],
199
+ ["ssh_tunnels", reported(offer.ssh_tunnels)],
197
200
  ]),
198
201
  "",
199
202
  firewall,
200
203
  ...(counts.length ? ["", databaseLimitsText(counts)] : []),
204
+ ...(offer.network.private_targets ? ["", "Private targets (managed by a platform operator in the Admin):", table(offer.network.private_targets, ["cidr", "ports", "source", "usable"]) || "none"] : []),
201
205
  ...(offer.runnable_dialects.length ? [] : ["", "This instance runs no database dialect: a connection can be saved, but its test and queries answer unavailable."]),
202
206
  ].join("\n"),
203
207
  };
@@ -244,6 +248,7 @@ export const dbConnections = {
244
248
  data: page,
245
249
  text: (table(rows, ["name", "dialect", "target", "tls", "enabled", ...(rows.some(c => "allows_writes" in c) ? ["allows_writes"] : []), "last_test", "queries", "id"]) ||
246
250
  `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).`) +
251
+ connections.filter(c => c.ssh_tunnel).map(c => `\n\n${c.name}: SSH bastion ${c.ssh_tunnel.username}@${c.ssh_tunnel.host}:${c.ssh_tunnel.port}${c.ssh_tunnel.authorized_keys_entry ? `\nInstall this exact authorized_keys entry on the bastion:\n${c.ssh_tunnel.authorized_keys_entry}` : "\nA person sets its SSH key in the Admin."}`).join("") +
247
252
  caLines(connections).join("\n") +
248
253
  moreHint(page.next_cursor, cavelonCommand("db", "connections")) +
249
254
  (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"))}` : "") +
@@ -417,7 +422,10 @@ export const dbTest = {
417
422
  throw ownerOnly(error, "A connection test");
418
423
  }
419
424
  const ok = result.outcome === "ok";
420
- 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 }));
425
+ const steps = (result.steps ?? []).map((s) => ({ step: s.name, status: s.status, code: s.code ?? null,
426
+ engine: s.detail?.engine ?? null, private_target_id: s.detail?.private_target_id ?? null,
427
+ redirects: s.detail?.redirects === undefined ? null : clip(JSON.stringify(s.detail.redirects), 300),
428
+ message: s.driver_message ? clip(s.driver_message, 160) : null }));
421
429
  const findings = (Array.isArray(result.procedure_findings) ? result.procedure_findings : []).map((f) => ({
422
430
  query: f.slug ?? f.query_id ?? "?",
423
431
  code: f.code ?? null,
@@ -430,7 +438,7 @@ export const dbTest = {
430
438
  }
431
439
  const text = [
432
440
  `Connection "${connection.name}" (${connection.dialect}): ${ok ? "test passed" : `test failed (${result.outcome})`}, ${result.duration_ms} ms.`,
433
- table(steps, ["step", "status", "code", ...(steps.some((s) => s.message) ? ["message"] : [])], 80),
441
+ table(steps, ["step", "status", "code", ...["engine", "private_target_id", "redirects"].filter(k => steps.some(s => s[k] !== null)), ...(steps.some((s) => s.message) ? ["message"] : [])], 80),
434
442
  ...(result.server_version ? [`server: ${result.server_version}`] : []),
435
443
  ...(result.write_privileges ? [`write privileges: ${clip(JSON.stringify(result.write_privileges), 300)}`] : []),
436
444
  ...(findings.length
@@ -522,8 +530,10 @@ function runValues(query, given) {
522
530
  const ROWS_SHOWN = 20;
523
531
  export const dbTestRun = {
524
532
  name: "db test-run",
525
- summary: "Run a saved query once with the values given, identity parameters included; show what the model would see and the rows.",
526
- description: "Needs the tenant Owner's permission (database_connectors.test); it reads the customer's own data. Give each parameter\n" +
533
+ summary: "Test a saved query, or validate and test unsaved package SQL with --draft; show model output and rows.",
534
+ description: "With --draft, reads the tool slug from package/, validates first and tests without saving or applying. Needs\n" +
535
+ "database_connectors.manage with the Owner's personal access token or the Admin; an API key cannot run a draft.\n" +
536
+ "Needs the tenant Owner's permission (database_connectors.test); it reads the customer's own data. Give each parameter\n" +
527
537
  "with --value name=value, those the platform fills from the signed-in visitor (end_user.*) too: that is how an\n" +
528
538
  "identity-scoped query is checked for one customer. A list parameter takes a JSON array (--value 'skus=[\"X-1\",\"X-2\"]'),\n" +
529
539
  "one to max_items items of its type; the instance checks each item and names a refused one by position, never its value.\n" +
@@ -540,31 +550,37 @@ export const dbTestRun = {
540
550
  "switched off.",
541
551
  readOnly: false,
542
552
  idempotent: true,
543
- 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.",
553
+ mcpEffect: "Tests a saved query or unsaved package definition once on the instance; writes are dry runs that roll back. The instance keeps audit evidence and changes no setting or saved query. Never retry an ambiguous write outcome.",
544
554
  mcpTool: "db_test_run",
545
- operations: ["POST /api/v1/database-connectors/queries/{query_id}/test-run"],
555
+ operations: ["POST /api/v1/database-connectors/queries/{query_id}/test-run", "POST /api/v1/database-connectors/queries/test-run"],
556
+ operationsAreAlternatives: true,
546
557
  positionals: [{ name: "query", description: "The query's tool slug or id.", required: true }],
547
558
  options: {
559
+ draft: { type: "boolean", description: "Validate package/ and test its unsaved query definition before apply (database_connectors.manage)." },
548
560
  value: { type: "string", multiple: true, value: "<name=value>", description: "One parameter's value, typed as the parameter's type; a list parameter's is a JSON array." },
549
561
  rows: { type: "string", value: "<n>", description: `Show at most n rows in the text (default ${ROWS_SHOWN}); --json carries what the instance returned.` },
550
562
  },
551
563
  examples: [
564
+ "cavelon db test-run order_status --draft --value order_no=A-10023 --value email=ada@example.com",
552
565
  "cavelon db test-run order_status --value order_no=A-10023 --value email=ada@example.com",
553
566
  "cavelon db test-run stock --value sku=4711 --json",
554
567
  `cavelon db test-run stock_of_skus --value 'skus=["X-1","X-2"]'`,
555
568
  ],
556
569
  async run(ctx, input) {
557
- const query = await resolveQuery(ctx, positional(input, "query"));
558
- if (query.parameters.some(p => p.source?.startsWith("end_user."))) {
570
+ const draft = boolOption(input, "draft");
571
+ const ref = positional(input, "query");
572
+ const local = draft ? await draftQuery(ctx, ref) : undefined;
573
+ const query = local?.query ?? await resolveQuery(ctx, ref);
574
+ if (!draft && query.parameters.some(p => p.source?.startsWith("end_user."))) {
559
575
  requirePersonForIdentityChoice(await accessFor(await ctx.client()), "POST /api/v1/database-connectors/queries/{query_id}/test-run", "test a query with end_user.* parameters");
560
576
  }
561
577
  const values = runValues(query, listOption(input, "value"));
562
578
  const shown = intOption(input, "rows", { min: 0, max: 500, fallback: ROWS_SHOWN });
563
579
  let result;
564
580
  try {
565
- result = await callStable(ctx, "POST", "/api/v1/database-connectors/queries/{query_id}/test-run", "test runs of database queries", {
566
- params: { query_id: [query.id] },
567
- body: { values },
581
+ result = await callStable(ctx, "POST", draft ? "/api/v1/database-connectors/queries/test-run" : "/api/v1/database-connectors/queries/{query_id}/test-run", "test runs of database queries", {
582
+ params: draft ? undefined : { query_id: [query.id] },
583
+ body: { ...local?.body, values },
568
584
  timeoutMs: 90_000,
569
585
  });
570
586
  }
@@ -572,7 +588,7 @@ export const dbTestRun = {
572
588
  if (query.kind === "write" && error instanceof CavelonError && (error.code === "network_error" || error.code === "request_timeout")) {
573
589
  throw new CavelonError(error.exitCode, { code: error.code, status: error.status, message: error.message, hint: NO_WRITE_RETRY, docs: error.docs, details: error.details });
574
590
  }
575
- throw refusedRun(ownerOnly(error, "A test run"), query);
591
+ throw refusedRun(draft ? withPermissionHint(error, "A draft query test needs database_connectors.manage with the tenant Owner's personal access token or the Admin; an API key cannot run it.") : ownerOnly(error, "A test run"), query);
576
592
  }
577
593
  const ok = result.outcome === "ok" && !result.error_code;
578
594
  const columns = result.columns ?? [];
@@ -580,7 +596,7 @@ export const dbTestRun = {
580
596
  const more = (result.rows?.length ?? 0) - rows.length;
581
597
  const text = [
582
598
  keyValues([
583
- ["query", `${query.slug} (version ${query.version})`],
599
+ ["query", `${query.slug} (${draft ? "unsaved draft" : `version ${query.version}`})`],
584
600
  ["outcome", result.error_code ? `${result.outcome} (${result.error_code}${result.sqlstate ? `, SQLSTATE ${result.sqlstate}` : ""})` : result.outcome],
585
601
  ["rows", ok ? `${result.returned_rows ?? rows.length} returned of ${result.row_count ?? "?"}${result.truncated ? ", truncated for the model" : ""}` : undefined],
586
602
  ["duration_ms", result.duration_ms],
@@ -594,9 +610,39 @@ export const dbTestRun = {
594
610
  ...(more > 0 ? [`… ${more} more rows (--rows, or --json).`] : []),
595
611
  ].join("\n");
596
612
  return {
597
- data: { query: { id: query.id, slug: query.slug, version: query.version }, ...result },
613
+ data: { query: { ...(draft ? { draft: true } : { id: query.id, version: query.version }), slug: query.slug }, ...result },
598
614
  text: text + explainLine([result.error_code]) + (result.error_code === "write_outcome_unknown" ? `\n\n${NO_WRITE_RETRY}` : ""),
599
615
  exitCode: ok ? ExitCode.ok : ExitCode.validation,
600
616
  };
601
617
  },
602
618
  };
619
+ async function draftQuery(ctx, ref) {
620
+ await connectorOn(ctx);
621
+ const access = await accessFor(await ctx.client());
622
+ if (access?.kind === "api_key")
623
+ throw new CavelonError(ExitCode.needsAction, {
624
+ code: "key_needs_a_person", message: "An API key cannot test an unsaved database query. Nothing was sent.",
625
+ hint: "Use the tenant Owner's personal access token with database_connectors.manage, or test the draft in the Admin.",
626
+ });
627
+ const project = requireSolution(await ctx.session());
628
+ const { disk, findings } = await validatePackage(ctx, project, false);
629
+ const errors = findings.filter(f => f.severity === "error");
630
+ if (errors.length)
631
+ throw validationError("The package has validation errors; the draft was not run.", { findings: errors }, "Run cavelon validate and fix the named fields first.");
632
+ for (const finding of findings.filter(f => f.severity === "warning"))
633
+ ctx.warn(`${finding.code}: ${finding.message}`);
634
+ const tool = queryTools(disk.package).find(t => t.slug === ref);
635
+ if (!tool)
636
+ throw usageError(`No database query tool "${ref}" in package/.`, "--draft takes the package tool's slug, not a saved query id.");
637
+ const definition = tool.tool.database_query;
638
+ const target = definition.connection;
639
+ const connection = await resolveConnection(ctx, target.name);
640
+ if (connection.dialect !== target.dialect)
641
+ throw validationError(`Connection "${target.name}" uses ${connection.dialect}, but the draft names ${target.dialect}.`);
642
+ const body = { connection_id: connection.id, slug: tool.slug };
643
+ for (const field of ["sql_text", "parameters", "max_rows", "max_result_chars", "kind", "max_affected_rows"]) {
644
+ if (definition[field] !== undefined)
645
+ body[field] = definition[field];
646
+ }
647
+ return { query: { slug: tool.slug, connection_name: connection.name, parameters: (definition.parameters ?? []), kind: definition.kind }, body };
648
+ }
@@ -16,6 +16,7 @@ import { harnessClone, harnessDefault, harnessList, harnessNew, tenantCreate, te
16
16
  import { kbUpload, testRun, trace } from "./work.js";
17
17
  import { dbConnections, dbInstance, dbQueries, dbRuns, dbTest, dbTestRun } from "./db.js";
18
18
  import { dbConnectionCa, dbConnectionCreate, dbConnectionDelete, dbConnectionUpdate, dbLoginScript, dbSchema } from "./db-connections.js";
19
+ import { dbQueryDelete, dbQueryEnable, dbQueryDisable, dbQueryRename } from "./db-query-management.js";
19
20
  import { secretsDelete, secretsList, secretsSet, variablesDelete, variablesGet, variablesList, variablesSet } from "./values.js";
20
21
  import { loopCancel, loopIterations, loopPause, loopResume, loopStart, loopWatch, triggerIdentity } from "./loops.js";
21
22
  import { artifactsExport, sandboxActivity, sandboxCat, sandboxFiles, sandboxList, sandboxLogs, sandboxReceipt, sandboxRefresh, sandboxSeed, sandboxValidate, } from "./sandboxes.js";
@@ -116,6 +117,10 @@ export const COMMANDS = [
116
117
  dbLoginScript,
117
118
  dbSchema,
118
119
  dbQueries,
120
+ dbQueryDelete,
121
+ dbQueryEnable,
122
+ dbQueryDisable,
123
+ dbQueryRename,
119
124
  dbRuns,
120
125
  dbTest,
121
126
  dbTestRun,
@@ -17,6 +17,7 @@ import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefault
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 { WRITE_PATH_HINT } from "../database-write-paths.js";
20
21
  import { applyQueryNotes, connectorOffer, importWritesQueries, NEEDS_SUPERADMIN_CODE, queryBlockedHint, queryChanges, queryTools, readQueryBaseline, rememberQueries, schemaKnowsWrites } from "../database-queries.js";
21
22
  import { yoloAllows } from "../automation-policy.js";
22
23
  import { cliFix, similarCodes } from "../code-hints.js";
@@ -330,7 +331,7 @@ async function inventoryFor(ctx, project, disk, offline, schema) {
330
331
  }));
331
332
  return { inventory, skipped };
332
333
  }
333
- async function validatePackage(ctx, project, offline) {
334
+ export async function validatePackage(ctx, project, offline) {
334
335
  const disk = await readPackage(project.root, project.layout);
335
336
  const version = packageVersionOf(disk.package) ?? project.packageVersion;
336
337
  const { schema, used } = await schemaFor(ctx, version, offline);
@@ -1362,8 +1363,9 @@ export const explain = {
1362
1363
  const read = capacity ? (await listedPages(ctx, pages)).map((page) => ({ page, command: cavelonCommand("docs", "get", page) })) : [];
1363
1364
  const fix = cliFix(entry);
1364
1365
  const cli = entry.kind === "cli" || !fix ? undefined : spoken(fix);
1365
- const hint = entry.hint ? spoken(entry.hint) : entry.hint;
1366
- const data = { ...entry, hint, ...(entry.area === KNOWLEDGE_OUTCOME_AREA ? { kind: "knowledge_outcome" } : {}), docs, ...(cli ? { cli_fix: cli } : {}), ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
1366
+ const writeAdvice = entry.code === "confirmation_unavailable" && catalog?.api_error_codes?.some(e => e.code === "write_needs_confirmation");
1367
+ const hint = writeAdvice ? WRITE_PATH_HINT : entry.hint ? spoken(entry.hint) : entry.hint;
1368
+ const data = { ...entry, hint, ...(writeAdvice ? { instance_hint: entry.hint } : {}), ...(entry.area === KNOWLEDGE_OUTCOME_AREA ? { kind: "knowledge_outcome" } : {}), docs, ...(cli ? { cli_fix: cli } : {}), ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
1367
1369
  return {
1368
1370
  data,
1369
1371
  text: keyValues([
@@ -2,6 +2,7 @@ import { readJsonFile } from "./fsutil.js";
2
2
  import { statePath, writeState } from "./local-state.js";
3
3
  import { locate } from "./package-files.js";
4
4
  import { canonical, settledForm } from "./package-format.js";
5
+ import { CITUS_ADMIN_FUNCTIONS } from "./citus-functions.js";
5
6
  export const QUERY_TOOL_TYPE = "database_query";
6
7
  const QUERY_FIELD = "database_query";
7
8
  const TOOLS_SECTION = "tools";
@@ -443,6 +444,50 @@ export function oracleQueryProblem(sql, dialect, write) {
443
444
  }
444
445
  return undefined;
445
446
  }
447
+ export function citusQueryProblem(sql, dialect, write) {
448
+ if (dialect !== "postgresql")
449
+ return undefined;
450
+ const tokens = sqlTokens(sql, dialect);
451
+ if (!tokens)
452
+ return undefined;
453
+ const code = tokens.filter(t => t.kind !== "comment");
454
+ if (code.some((t, i) => t.kind === "semicolon" && i !== code.length - 1))
455
+ return undefined;
456
+ if (write ? !isWord(code[0], "INSERT", "UPDATE", "DELETE") : !isWord(code.find(t => !isSymbol(t, "(")), "SELECT", "WITH") || commonReadRefusal(code))
457
+ return undefined;
458
+ const nameOf = (t) => t?.kind === "word" ? t.text.toLowerCase() : t?.kind === "identifier" && t.text.startsWith('"') ? t.text.slice(1, -1).replaceAll('""', '"').toLowerCase() : undefined;
459
+ for (let i = 0; i < code.length - 1; i++) {
460
+ const name = nameOf(code[i]);
461
+ if (!name || !isSymbol(code[i + 1], "("))
462
+ continue;
463
+ let before = i - 1;
464
+ let schema;
465
+ if (isSymbol(code[before], ".")) {
466
+ schema = nameOf(code[before - 1]);
467
+ before -= 2;
468
+ }
469
+ if (schema !== undefined && schema !== "pg_catalog" && schema !== "citus_internal")
470
+ continue;
471
+ if (isWord(code[before], "INTO", "AS"))
472
+ continue;
473
+ let depth = 0;
474
+ let after = i + 1;
475
+ for (; after < code.length; after++) {
476
+ if (isSymbol(code[after], "("))
477
+ depth++;
478
+ if (isSymbol(code[after], ")") && --depth === 0) {
479
+ after++;
480
+ break;
481
+ }
482
+ }
483
+ if (isWord(code[after], "AS") && (isSymbol(code[after + 1], "(") || isWord(code[after + 1], "MATERIALIZED", "NOT")))
484
+ continue;
485
+ if (schema === "citus_internal" || name.startsWith("run_command_on_") || name.startsWith("citus_internal_") || CITUS_ADMIN_FUNCTIONS.has(name)) {
486
+ return problem(write ? "write_statement_refused" : "forbidden_keyword", `The SQL may not call ${name}: Citus' administrative functions run commands on other nodes or change the cluster.`, "sql_text");
487
+ }
488
+ }
489
+ return undefined;
490
+ }
446
491
  export function listOutsideIn(sql, dialect, listNames) {
447
492
  if (!listNames.length)
448
493
  return undefined;
@@ -544,7 +589,7 @@ export function checkQueryTools(disk, schema, baseline, connections) {
544
589
  message: `Query tool "${slug}": ${call.message}`,
545
590
  });
546
591
  }
547
- const oracle = typeof query.sql_text === "string" ? oracleQueryProblem(query.sql_text, dialect, write) : undefined;
592
+ const oracle = typeof query.sql_text === "string" ? oracleQueryProblem(query.sql_text, dialect, write) ?? citusQueryProblem(query.sql_text, dialect, write) : undefined;
548
593
  if (oracle) {
549
594
  findings.push({
550
595
  code: oracle.code,
@@ -0,0 +1,98 @@
1
+ import { queryTools, schemaKnowsWrites } from "./database-queries.js";
2
+ import { locate } from "./package-files.js";
3
+ const object = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : undefined;
4
+ const rows = (v) => Array.isArray(v) ? v.filter(x => object(x)) : [];
5
+ const active = (v) => v.is_active !== false;
6
+ const scope = (v, harness) => v.harness_slug === undefined || v.harness_slug === harness;
7
+ const CODE = "write_needs_confirmation";
8
+ export const WRITE_PATH_HINT = "Keep requires_confirmation on for chat. A direct Tool Call without it needs the latest Approval decision to be approved and no later agent stage; alternatively use a schedule, a webhook whose secret header is checked, or Run now. The instance checks the actual run and decision.";
9
+ export function checkWritePaths(disk, schema, catalog, baseline) {
10
+ if (!schemaKnowsWrites(schema) || !catalog?.api_error_codes?.some(e => e.code === CODE))
11
+ return [];
12
+ const queries = new Map();
13
+ for (const [slug, tool] of Object.entries(baseline?.tools ?? {})) {
14
+ const query = object(tool.database_query);
15
+ if (query)
16
+ queries.set(slug, query);
17
+ }
18
+ for (const { slug, tool } of queryTools(disk.package)) {
19
+ const query = object(tool.database_query);
20
+ if (query)
21
+ queries.set(slug, query);
22
+ }
23
+ for (const tool of rows(disk.package.tools))
24
+ if (tool.tool_type !== "database_query" && typeof tool.slug === "string")
25
+ queries.delete(tool.slug);
26
+ const unconfirmed = (slug) => typeof slug === "string" && queries.get(slug)?.kind === "write" && queries.get(slug)?.requires_confirmation === false;
27
+ const registry = object(disk.package.registry_entities);
28
+ const nodes = rows(registry?.orchestration_nodes);
29
+ const agents = rows(disk.package.agents);
30
+ const edges = rows(registry?.graph_edges);
31
+ const triggers = rows(registry?.triggers);
32
+ const skills = rows(disk.package.skills);
33
+ const findings = new Map();
34
+ const warn = (pointer, message) => findings.set(pointer, { code: CODE, severity: "warning", ...locate(disk, pointer), message, hint: WRITE_PATH_HINT });
35
+ const outsider = (trigger) => trigger.trigger_type !== "schedule" && !(trigger.trigger_type === "webhook" && object(trigger.config)?.auth_mode === "secret_header");
36
+ const harnesses = new Set([...nodes, ...agents, ...triggers].map(x => x.harness_slug));
37
+ for (const harness of harnesses) {
38
+ const localNodes = nodes.filter(n => active(n) && scope(n, harness));
39
+ const localAgents = agents.filter(a => active(a) && scope(a, harness));
40
+ const localEdges = edges.filter(e => active(e) && scope(e, harness));
41
+ const localTriggers = triggers.filter(t => active(t) && scope(t, harness));
42
+ const pending = [];
43
+ const add = (kind, slug, approved = false) => { if (typeof slug === "string")
44
+ pending.push({ kind, slug, approved }); };
45
+ for (const node of localNodes) {
46
+ if (node.node_type === "chat_start")
47
+ add("orchestration", node.slug);
48
+ if (node.node_type === "trigger_start") {
49
+ const trigger = localTriggers.find(t => t.slug === object(node.config)?.trigger_slug);
50
+ if (trigger && outsider(trigger))
51
+ add("orchestration", node.slug);
52
+ }
53
+ }
54
+ for (const trigger of localTriggers.filter(outsider))
55
+ add("agent", trigger.entrypoint_agent_slug);
56
+ if (!localNodes.some(n => n.node_type === "chat_start")) {
57
+ for (const agent of localAgents.filter(a => a.is_entrypoint === true))
58
+ add("agent", agent.slug);
59
+ }
60
+ const seen = new Set();
61
+ while (pending.length) {
62
+ const current = pending.pop();
63
+ const key = JSON.stringify(current);
64
+ if (seen.has(key))
65
+ continue;
66
+ seen.add(key);
67
+ const node = current.kind === "orchestration" ? localNodes.find(n => n.slug === current.slug) : undefined;
68
+ const agent = current.kind === "agent" ? localAgents.find(a => a.slug === current.slug) : undefined;
69
+ if (current.kind === "orchestration" && !node || current.kind === "agent" && !agent)
70
+ continue;
71
+ let approved = current.approved;
72
+ if (agent) {
73
+ approved = false;
74
+ const assignments = [...rows(agent.tool_assignments), ...rows(agent.skill_assignments).filter(active).flatMap(a => rows(skills.find(s => s.slug === a.skill_slug)?.tool_assignments))].filter(active);
75
+ for (const assignment of assignments.filter(a => unconfirmed(a.tool_slug))) {
76
+ warn(`/agents/${agents.indexOf(agent)}/tool_assignments`, `Agent "${current.slug}" can call write query "${String(assignment.tool_slug)}" without confirmation on an outsider-started path; an agent cannot use the Approval-node exception, so the instance refuses it with ${CODE}.`);
77
+ }
78
+ for (const handoff of rows(agent.handoffs).filter(active))
79
+ add("agent", handoff.to_agent_slug, false);
80
+ }
81
+ if (node?.node_type === "approval")
82
+ approved = true;
83
+ if (node?.node_type === "tool_call" && unconfirmed(object(node.config)?.tool_slug) && !approved) {
84
+ warn(`/registry_entities/orchestration_nodes/${nodes.indexOf(node)}/config/tool_slug`, `Tool Call node "${current.slug}" calls write query "${String(object(node.config)?.tool_slug)}" on an outsider-started path without an Approval node after the last agent stage; the instance refuses it with ${CODE}.`);
85
+ }
86
+ for (const edge of localEdges) {
87
+ const from = object(edge.from_node_ref);
88
+ const to = object(edge.to_node_ref);
89
+ if (from?.kind !== current.kind || from.slug !== current.slug || typeof to?.kind !== "string")
90
+ continue;
91
+ const condition = object(object(edge.config)?.condition);
92
+ const rejected = node?.node_type === "approval" && (object(edge.config)?.default === true || condition?.path === "approval.approved" && condition.operator === "equals" && condition.value === false);
93
+ add(to.kind, to.slug, rejected ? false : approved);
94
+ }
95
+ }
96
+ }
97
+ return [...findings.values()];
98
+ }
package/dist/mcp.js CHANGED
@@ -127,6 +127,8 @@ export function inputSchema(spec, commands = []) {
127
127
  export function notForThisCredential(spec, access) {
128
128
  if (!access)
129
129
  return undefined;
130
+ if (spec.operationsAreAlternatives && spec.operations?.some(operation => operationAccess(access, operation).allowed !== false))
131
+ return undefined;
130
132
  for (const operation of spec.operations ?? []) {
131
133
  const refused = operationAccess(access, operation);
132
134
  if (refused.allowed !== false)
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "format": 1,
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "entries": {
5
5
  "omp": [
6
6
  "omp-extension.mjs"
@@ -5,6 +5,7 @@ import { locate, schemaSections, tenantWideSections } from "./package-files.js";
5
5
  import { MANIFEST_SECTION, PERSONA_SECTION, sectionFields } from "./package-format.js";
6
6
  import { kitErrorEntry } from "./kit-codes.js";
7
7
  import { checkWorkflowQueries } from "./workflow-queries.js";
8
+ import { checkWritePaths } from "./database-write-paths.js";
8
9
  import { cavelonCommand, fill, folderCommand } from "./printed.js";
9
10
  import { branches, checkModels, checkReferences, checkUnknownFields, closest, DUPLICATE_CODE, FIELD_UNKNOWN_CODE, MODEL_UNKNOWN_CODE, REFERENCE_MISSING_CODE, REFERENCE_UNKNOWN_CODE, KNOWLEDGE_TOOL_KEYS, } from "./package-references.js";
10
11
  export const SCHEMA_CODE = "package_schema_invalid";
@@ -33,6 +34,12 @@ const ASSERTION_UNCHECKED_CODE = "test_assertion_unchecked";
33
34
  const TESTING_DOCS = "/docs/concepts/regression-testing";
34
35
  const DATABASE_DOCS = "/docs/administration/database-connectors";
35
36
  export const KIT_CODES = [
37
+ {
38
+ code: "private_target_refused", area: "database_connector",
39
+ message: "The instance refused a platform operator's private database target.",
40
+ hint: "Read detail.reason: invalid_range means an invalid CIDR; too_wide means a range above the allowed size; contains_local_interface means the range includes the instance's own interface; platform_network or platform_service means it reaches platform infrastructure; overlaps_another_tenant means another tenant owns an overlapping range. A Platform Owner reviews the range in the Admin in Platform mode. A tenant token never adds or removes these targets.",
41
+ docs: DATABASE_DOCS,
42
+ },
36
43
  {
37
44
  code: SCHEMA_CODE,
38
45
  area: "package",
@@ -342,6 +349,7 @@ export function checkPackage(disk, options) {
342
349
  findings.push(...checkTenantWide(disk, options.schema, options.solution));
343
350
  findings.push(...checkQueryTools(disk, options.schema, options.queryBaseline, options.queryConnections));
344
351
  findings.push(...checkWorkflowQueries(disk, options.schema, options.inventory, options.queryBaseline));
352
+ findings.push(...checkWritePaths(disk, options.schema, options.catalog, options.queryBaseline));
345
353
  noteTenantWide(findings, options.schema, options.solution);
346
354
  for (const finding of findings) {
347
355
  const entry = findingEntry(options.catalog, finding.code);
@@ -328,6 +328,22 @@ schema has them: `cavelon validate` reports an unknown section):
328
328
 
329
329
  ## Database query tools
330
330
 
331
+ Before applying edited SQL, run `cavelon db test-run <slug> --draft --value
332
+ <name>=<value>`: it validates package/ and tests the unsaved query without
333
+ saving it. Draft tests need `database_connectors.manage` with the Owner's PAT
334
+ or the Admin, never an API key. Saved query delete, enable, disable and rename
335
+ use `cavelon db queries <action>`; preview first and obtain the person's yes,
336
+ then pull so the package follows. YOLO does not approve those changes.
337
+
338
+ Connection settings stay outside packages. The CLI accepts public SSH tunnel,
339
+ Kerberos and listener-redirect settings, but passwords, SSH private keys,
340
+ keytabs, any CA change and weaker TLS stay with a person in the Admin.
341
+ `db instance` publishes runnable and Kerberos dialects, SSH support and the
342
+ tenant's admitted private targets; never infer support from a dialect name.
343
+ Db2 requires verified TLS and the instance's explicit offer. PostgreSQL
344
+ compatible engines use `postgresql`, MySQL compatible engines use `mysql`;
345
+ TiDB is refused. `validate` warns on Citus administrative function calls.
346
+
331
347
  A database query tool lets an agent answer from a customer's live database. A
332
348
  saved query of explicit `kind: read` or `kind: write` is one tool (`tool_type: database_query` in
333
349
  `package/tools.yaml`); the model only calls it and fills the parameters it is
@@ -552,8 +568,14 @@ graph_edges:
552
568
  in such a run.
553
569
  - **Write confirmation and budget.** Every direct Tool Call node refuses a
554
570
  write with `requires_confirmation: true` (`confirmation_unavailable`),
555
- because it cannot wait for the person's click; `validate` warns. Turn it
556
- off only for an intended unattended write. The shared workflow cap
571
+ because it cannot wait for the person's click; `validate` warns. Without
572
+ query confirmation, use a schedule, a webhook whose secret header is checked,
573
+ or Run now. On an outsider-started path, only a direct Tool Call after the
574
+ latest approved Approval decision with no later agent stage may write;
575
+ a later rejection revokes it. An agent cannot use that exception. Other
576
+ paths answer `write_needs_confirmation`; keep confirmation on for chat.
577
+ `validate` warns about statically visible unsafe paths; it cannot attest
578
+ an actual runtime decision. The shared workflow cap
557
579
  counts the query's saved `max_calls` across a workflow run's Tool Call
558
580
  nodes, Agent stages, `for_each` iterations and concurrent branches, and
559
581
  persists on resume. The next call is refused with `tool_call_limit_reached`
@@ -105,11 +105,17 @@ use it when you parse the result.
105
105
  URL if you do not know it.
106
106
 
107
107
  - **Connect a database, leaving the password with a person.** A database query tool
108
- needs a connection of the name and dialect its package names, tested
108
+ can be edited and tested before apply with `db test-run <slug> --draft`;
109
+ validate, test the unsaved query, then preview apply and obtain the person's
110
+ approval. Draft tests need the Owner's PAT with `database_connectors.manage`.
111
+ SSH keys, Kerberos keytabs, CA changes and weaker TLS are Admin steps too.
112
+ The query needs a connection of the name and dialect its package names, tested
109
113
  successfully, in every tenant it is applied to. A personal access token
110
114
  holding `database_connectors.manage` (the tenant Owner, legacy Admin, or a
111
115
  superadmin in Tenant mode) may run `cavelon db connections create|update|delete`
112
- and upload a public CA with `cavelon db connections ca <connection> <file>`.
116
+ using public settings. A person changes the CA or weakens TLS in the Admin;
117
+ `db connections ca` retains public-file uploads only on older instances
118
+ that do not publish the restriction.
113
119
  Create sends no password and prints the Admin step from `needs_a_person`;
114
120
  a person enters it in Settings › Security & access › Databases. Never take
115
121
  a password as an argument, environment value, stdin, file or tool input.
@@ -135,6 +135,14 @@ The case's own reason (which knowledge base, which value) is in the output of
135
135
 
136
136
  ## Database query tools
137
137
 
138
+ Test edited package SQL before apply with `cavelon db test-run <slug> --draft
139
+ --value <name>=<value>` (MCP `db_test_run` with `draft: true`). It runs local
140
+ validation, resolves the connection in this tenant and saves no query.
141
+ It needs the Owner's PAT with `database_connectors.manage` or the Admin;
142
+ an API key is refused. Use `db instance` and the connection test's published
143
+ SSH, engine, private-target and redirect evidence to check the actual setup.
144
+ Passwords, keytabs, SSH keys and CA/TLS decisions stay in the Admin.
145
+
138
146
  Test a solution with database query tools against a test database, never the
139
147
  customer's live one: the test tenant (`--env test`) has a connection of the
140
148
  same name pointing at a test database with known rows, set up by a person in
@@ -202,9 +210,16 @@ the Admin. Then:
202
210
  checks the database before any repetition. Query-definition approval and
203
211
  `requires_confirmation` before executing a chat write are separate.
204
212
  - A direct workflow Tool Call write with confirmation enabled answers
205
- `confirmation_unavailable`. For an intended unattended write only, turn
206
- that query setting off and retain model-only arguments and trigger
207
- identity checks. The shared `max_calls` budget counts across direct nodes,
213
+ `confirmation_unavailable`. Keep confirmation on for chat. A query without
214
+ it writes only from a schedule, a webhook with a checked secret header, or
215
+ Run now, or from a direct Tool Call after the latest approved Approval
216
+ decision with no later agent stage. A later rejection revokes approval;
217
+ an agent never uses that exception. Test rejected, bypass and intervening-agent
218
+ paths for `write_needs_confirmation` and zero writes. Operator test surfaces
219
+ (Playground/voice, suites, debug runs and dashboard/PAT chat) always dry-run
220
+ writes; check `surface`, rollback and commit evidence, never infer it from
221
+ missing fields. Retain model-only arguments and trigger identity checks.
222
+ The shared `max_calls` budget counts across direct nodes,
208
223
  Agent stages, `for_each`, concurrent branches and resume; expect
209
224
  `tool_call_limit_reached` on the next call and `refused` run evidence.
210
225
  A direct node fails with that code; an Agent receives the tool's refusal.
@@ -153,7 +153,7 @@ export function checkWorkflowQueries(disk, schema, inventory, baseline) {
153
153
  continue;
154
154
  const confirmation = object(object(querySchema(schema)?.properties)?.requires_confirmation);
155
155
  if (schemaKnowsWrites(schema) && query.kind === "write" && confirmation && (query.requires_confirmation ?? confirmation.default) === true) {
156
- findings.push({ code: "confirmation_unavailable", severity: "warning", ...locate(disk, at), message: `Tool Call node "${String(node.slug ?? index)}" calls write query "${slug}" with requires_confirmation: the node cannot wait for a person's click, so the instance refuses it with confirmation_unavailable.`, hint: "Call the query from an agent in a signed-in person's chat, or have the tenant's query manager turn confirmation off for an intended unattended write." });
156
+ findings.push({ code: "confirmation_unavailable", severity: "warning", ...locate(disk, at), message: `Tool Call node "${String(node.slug ?? index)}" calls write query "${slug}" with requires_confirmation: the node cannot wait for a person's click, so the instance refuses it with confirmation_unavailable.`, hint: "Keep confirmation on for an agent's chat use. For a direct Tool Call, put an Approval node immediately before it with no intervening agent stage, or start the run from a schedule, a webhook with a checked secret header, or Run now; only those intended paths may use a query without confirmation." });
157
157
  }
158
158
  const parameters = rows(query.parameters);
159
159
  const model = new Set(parameters.filter((parameter) => (parameter.source ?? source) === source).map((parameter) => parameter.name));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cavelon/cli",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "The cavelon binary: CLI and local MCP server for building Cavelon solutions with a coding agent.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/goodguys-gmbh/cavelon-dev-kit",