@deepsql/mcp 0.14.0 → 0.16.0

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.
@@ -281,6 +281,237 @@ test("indexes list --json emits raw JSON and no human prose", async () => {
281
281
  assert.equal(parsed[0].id, "r1");
282
282
  });
283
283
 
284
+ // ═════════════════════════════════════════════════════════════════════════════
285
+ // Advisor-surface tests (top / show / refresh / apply / dismiss)
286
+ // — absorbed from the deprecated `index-recommendations` namespace in 0.15.0.
287
+ // ═════════════════════════════════════════════════════════════════════════════
288
+
289
+ // Richer stub that captures the full request signature (path, method, query)
290
+ // so the advisor tests can assert on POST vs GET, query strings, etc. Same
291
+ // shape as `loadWithStubs` above but with explicit request-object capture.
292
+ function loadWithRichStubs({ requests = [], responder = () => [] }) {
293
+ for (const k of [
294
+ require.resolve("../api/client"),
295
+ require.resolve("./_session"),
296
+ require.resolve("./_connections"),
297
+ require.resolve("./indexes"),
298
+ ]) {
299
+ delete require.cache[k];
300
+ }
301
+
302
+ const apiKey = require.resolve("../api/client");
303
+ require.cache[apiKey] = {
304
+ id: apiKey,
305
+ filename: apiKey,
306
+ loaded: true,
307
+ exports: {
308
+ ApiError: class ApiError extends Error { constructor(m, s) { super(m); this.status = s; } },
309
+ async request(baseUrl, path, opts = {}) {
310
+ const captured = { path, method: opts.method || "GET", query: opts.query || null };
311
+ requests.push(captured);
312
+ return responder(captured);
313
+ },
314
+ },
315
+ };
316
+
317
+ const sessKey = require.resolve("./_session");
318
+ require.cache[sessKey] = {
319
+ id: sessKey, filename: sessKey, loaded: true,
320
+ exports: { resolveSession: () => ({ baseUrl: "http://test", token: "t", defaultConnection: null }) },
321
+ };
322
+
323
+ const connKey = require.resolve("./_connections");
324
+ require.cache[connKey] = {
325
+ id: connKey, filename: connKey, loaded: true,
326
+ exports: {
327
+ resolveConnectionId: async () => "conn-abc",
328
+ listConnections: async () => [],
329
+ },
330
+ };
331
+
332
+ return require("./indexes");
333
+ }
334
+
335
+ function captureStreams() {
336
+ let out = "";
337
+ let err = "";
338
+ return {
339
+ stdout: { write: (s) => { out += s; } },
340
+ stderr: { write: (s) => { err += s; } },
341
+ out: () => out,
342
+ err: () => err,
343
+ };
344
+ }
345
+
346
+ // ─── top ───────────────────────────────────────────────────────────────────
347
+
348
+ test("indexes top renders workload-weighted summary with net-benefit + evidence", async () => {
349
+ const indexes = loadWithRichStubs({
350
+ responder: ({ path }) => {
351
+ assert.match(path, /\/index-recommendations\/conn-abc\/top$/);
352
+ return [{
353
+ id: "rec-1",
354
+ tableName: "orders",
355
+ columnNames: "customer_id,status",
356
+ kind: "CREATE_INDEX",
357
+ priority: "HIGH",
358
+ occurrenceCount: 4,
359
+ netBenefitMs: 4823000,
360
+ evidenceCount: 3,
361
+ reason: "Workload-weighted composite.",
362
+ hypopgBeforeCost: 1000,
363
+ hypopgAfterCost: 250,
364
+ hypopgReductionPct: 75,
365
+ topEvidence: [
366
+ { calls: 4500, meanExecTimeMs: 850, totalExecTimeMs: 3825000, role: "WHERE_EQ" },
367
+ ],
368
+ }];
369
+ },
370
+ });
371
+ const s = captureStreams();
372
+ await indexes.run(opts(["top", "--connection", "mylocalpg"]), s);
373
+ assert.match(s.out(), /\[CREATE\] orders\(customer_id,status\)/);
374
+ assert.match(s.out(), /seen 4×/);
375
+ assert.match(s.out(), /net=1\.3h saved/);
376
+ assert.match(s.out(), /HypoPG cost: 1000 → 250 \(−75\.0%\)/);
377
+ assert.match(s.out(), /id: rec-1/);
378
+ assert.match(s.out(), /top evidence: 4500 calls/);
379
+ });
380
+
381
+ test("indexes top renders an empty-state message", async () => {
382
+ const indexes = loadWithRichStubs({ responder: () => [] });
383
+ const s = captureStreams();
384
+ await indexes.run(opts(["top", "--connection", "c1"]), s);
385
+ assert.match(s.out(), /No pending index recommendations/);
386
+ assert.match(s.out(), /indexes refresh/); // points at the consolidated namespace, not the deprecated one
387
+ });
388
+
389
+ test("indexes top --limit clamps to [1, 50]", async () => {
390
+ const requests = [];
391
+ const indexes = loadWithRichStubs({ requests, responder: () => [] });
392
+ const s = captureStreams();
393
+ await indexes.run(opts(["top", "--connection", "c1", "--limit", "999"]), s);
394
+ await indexes.run(opts(["top", "--connection", "c1", "--limit", "0"]), s);
395
+ await indexes.run(opts(["top", "--connection", "c1", "--limit", "10"]), s);
396
+ assert.equal(requests[0].query.limit, 50);
397
+ assert.equal(requests[1].query.limit, 1);
398
+ assert.equal(requests[2].query.limit, 10);
399
+ });
400
+
401
+ test("indexes top --json passes the raw payload through", async () => {
402
+ const indexes = loadWithRichStubs({
403
+ responder: () => [{ id: "rec-1", tableName: "orders" }],
404
+ });
405
+ const s = captureStreams();
406
+ await indexes.run(opts(["top", "--connection", "c1", "--json"]), s);
407
+ const parsed = JSON.parse(s.out());
408
+ assert.equal(parsed[0].id, "rec-1");
409
+ });
410
+
411
+ // ─── apply (the one mutation) ──────────────────────────────────────────────
412
+
413
+ test("indexes apply --mode apply without --confirm refuses up-front (no API call)", async () => {
414
+ const requests = [];
415
+ const indexes = loadWithRichStubs({ requests, responder: () => ({}) });
416
+ const s = captureStreams();
417
+ await assert.rejects(
418
+ () => indexes.run(opts(["apply", "rec-1", "--mode", "apply"]), s),
419
+ /Re-run with --confirm/,
420
+ );
421
+ assert.equal(requests.length, 0, "API should not be hit without --confirm");
422
+ });
423
+
424
+ test("indexes apply --mode dry-run defaults concurrent=true and surfaces planner-cost delta", async () => {
425
+ const requests = [];
426
+ const indexes = loadWithRichStubs({
427
+ requests,
428
+ responder: ({ path, method, query }) => {
429
+ assert.equal(path, "/index-recommendations/rec-1/apply");
430
+ assert.equal(method, "POST");
431
+ assert.deepEqual(query, { mode: "DRY_RUN", confirm: false, concurrent: true });
432
+ return {
433
+ recommendationId: "rec-1",
434
+ executedDdl: "CREATE INDEX idx_o_status ON orders (status);",
435
+ mode: "DRY_RUN",
436
+ status: "OK",
437
+ beforeCost: 1000,
438
+ afterCost: 250,
439
+ costReductionPct: 75,
440
+ samples: [{ fingerprint: "abc123def456", beforeCost: 1000, afterCost: 250 }],
441
+ message: "DRY_RUN complete — planner cost −75.0% (1000 → 250)",
442
+ };
443
+ },
444
+ });
445
+ const s = captureStreams();
446
+ await indexes.run(opts(["apply", "rec-1", "--mode", "dry-run"]), s);
447
+ assert.match(s.out(), /\[DRY_RUN\] OK/);
448
+ assert.match(s.out(), /planner cost: 1000 → 250 \(−75\.0%\)/);
449
+ assert.match(s.out(), /fp=abc123def456 cost 1000 → 250/);
450
+ });
451
+
452
+ test("indexes apply --no-concurrent passes concurrent=false to the backend", async () => {
453
+ const requests = [];
454
+ const indexes = loadWithRichStubs({
455
+ requests,
456
+ responder: () => ({ mode: "APPLY", status: "OK", executedDdl: "CREATE INDEX …" }),
457
+ });
458
+ const s = captureStreams();
459
+ await indexes.run(
460
+ opts(["apply", "rec-1", "--mode", "apply", "--confirm", "--no-concurrent"]),
461
+ s,
462
+ );
463
+ assert.deepEqual(requests[0].query, {
464
+ mode: "APPLY",
465
+ confirm: true,
466
+ concurrent: false,
467
+ });
468
+ });
469
+
470
+ test("indexes apply rejects unknown modes early (no API call)", async () => {
471
+ const requests = [];
472
+ const indexes = loadWithRichStubs({ requests, responder: () => ({}) });
473
+ const s = captureStreams();
474
+ await assert.rejects(
475
+ () => indexes.run(opts(["apply", "rec-1", "--mode", "bogus"]), s),
476
+ /Unknown mode/,
477
+ );
478
+ assert.equal(requests.length, 0);
479
+ });
480
+
481
+ // ─── refresh / dismiss / show ──────────────────────────────────────────────
482
+
483
+ test("indexes refresh POSTs to /generate and surfaces the count", async () => {
484
+ const indexes = loadWithRichStubs({
485
+ responder: ({ path, method }) => {
486
+ assert.equal(path, "/index-recommendations/generate/conn-abc");
487
+ assert.equal(method, "POST");
488
+ return { success: true, count: 12, message: "Generated 12 index recommendations" };
489
+ },
490
+ });
491
+ const s = captureStreams();
492
+ await indexes.run(opts(["refresh", "--connection", "mylocalpg"]), s);
493
+ assert.match(s.out(), /Refresh complete: 12 candidate/);
494
+ });
495
+
496
+ test("indexes dismiss issues PUT /{id}/dismiss", async () => {
497
+ const requests = [];
498
+ const indexes = loadWithRichStubs({ requests, responder: () => ({}) });
499
+ const s = captureStreams();
500
+ await indexes.run(opts(["dismiss", "rec-9"]), s);
501
+ assert.equal(requests[0].path, "/index-recommendations/rec-9/dismiss");
502
+ assert.equal(requests[0].method, "PUT");
503
+ assert.match(s.out(), /Dismissed recommendation rec-9/);
504
+ });
505
+
506
+ test("indexes show <id> requires --connection", async () => {
507
+ const indexes = loadWithRichStubs({});
508
+ const s = captureStreams();
509
+ await assert.rejects(
510
+ () => indexes.run(opts(["show", "rec-1"]), s),
511
+ /needs --connection/,
512
+ );
513
+ });
514
+
284
515
  // Keep the suite hermetic — flush the stubs back so later test files that
285
516
  // require these modules don't pick up our fakes.
286
517
  test.after(() => {
@@ -1,426 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * `deepsql index-recommendations` — surface DeepSQL's DBA-grade index
5
- * advisor from the terminal. Mirrors the MCP tools (`get_index_recommendations`
6
- * + `apply_index_recommendation`) so an on-call DBA gets the same workflow
7
- * an AI coding agent does, without needing the IDE plumbing.
8
- *
9
- * Subcommands:
10
- * deepsql index-recommendations top --connection <name> [--limit N] [--json]
11
- * deepsql index-recommendations list --connection <name> [--json]
12
- * deepsql index-recommendations show <id> [--json]
13
- * deepsql index-recommendations refresh --connection <name> [--json]
14
- * deepsql index-recommendations apply <id> [--mode dry-run|apply|apply-and-measure]
15
- * [--confirm] [--concurrent|--no-concurrent]
16
- * [--json]
17
- * deepsql index-recommendations dismiss <id> [--json]
18
- *
19
- * Default output is a compact terminal-friendly table. `--json` passes the
20
- * raw backend payload through, which is what callers from scripts / CI
21
- * pipelines want.
22
- *
23
- * Apply is the one mutation. The contract matches the MCP tool: default
24
- * mode is `dry-run` (HypoPG-based, no writes); the two write modes
25
- * (`apply`, `apply-and-measure`) require `--confirm`. `--no-concurrent`
26
- * opts out of CREATE INDEX CONCURRENTLY when the brief ACCESS EXCLUSIVE
27
- * lock is acceptable (small dev tables, or after the DBA has drained the
28
- * connection pool).
29
- */
30
-
31
- const { ApiError, request } = require("../api/client");
32
- const { resolveSession } = require("./_session");
33
- const { resolveConnectionId } = require("./_connections");
34
-
35
- const SUBCOMMANDS = {
36
- top: cmdTop,
37
- list: cmdList,
38
- show: cmdShow,
39
- refresh: cmdRefresh,
40
- apply: cmdApply,
41
- dismiss: cmdDismiss,
42
- };
43
-
44
- async function run(opts, io = {}) {
45
- const sub = opts.positional[0];
46
- if (!sub) {
47
- throw new Error(
48
- "Usage: deepsql index-recommendations <top|list|show|refresh|apply|dismiss> …"
49
- );
50
- }
51
- const handler = SUBCOMMANDS[sub];
52
- if (!handler) {
53
- throw new Error(`Unknown index-recommendations subcommand: ${sub}.`);
54
- }
55
- return wrap(handler)(
56
- { ...opts, positional: opts.positional.slice(1) },
57
- io
58
- );
59
- }
60
-
61
- function wrap(handler) {
62
- return async (opts, io) => {
63
- try {
64
- return await handler(opts, io);
65
- } catch (err) {
66
- if (err instanceof ApiError && err.status === 403) {
67
- throw new Error(
68
- "Access denied — index-recommendation operations require permissions on this connection."
69
- );
70
- }
71
- if (err instanceof ApiError && err.status === 404) {
72
- throw new Error(err.message || "Recommendation not found.");
73
- }
74
- throw err;
75
- }
76
- };
77
- }
78
-
79
- // ─── top ───────────────────────────────────────────────────────────────────
80
-
81
- async function cmdTop(opts, { stdout = process.stdout } = {}) {
82
- const session = resolveSession(opts);
83
- const connectionId = await resolveConnectionId(session, opts.connection);
84
- const limit = clampLimit(opts.limit, 5);
85
- const result = await request(
86
- session.baseUrl,
87
- `/index-recommendations/${encodeURIComponent(connectionId)}/top`,
88
- { token: session.token, query: { limit } }
89
- );
90
-
91
- if (opts.json) {
92
- stdout.write(`${JSON.stringify(result, null, 2)}\n`);
93
- return;
94
- }
95
-
96
- const list = Array.isArray(result) ? result : [];
97
- if (list.length === 0) {
98
- stdout.write(
99
- "No pending index recommendations. The 6-hour refresh scheduler may not have run yet, " +
100
- "or the workload has none worth flagging. Try `deepsql index-recommendations refresh` " +
101
- "to force a fresh accumulation cycle.\n"
102
- );
103
- return;
104
- }
105
-
106
- stdout.write(`Top ${list.length} pending index recommendation(s):\n\n`);
107
- list.forEach((r, idx) => {
108
- const action = r.kind === "DROP_INDEX" ? "DROP" : "CREATE";
109
- const target =
110
- r.kind === "DROP_INDEX"
111
- ? `${r.tableName}.${r.indexName} (unused)`
112
- : `${r.tableName}(${r.columnNames})`;
113
-
114
- const meta = [
115
- r.priority,
116
- r.occurrenceCount != null ? `seen ${r.occurrenceCount}×` : null,
117
- formatNet(r),
118
- r.evidenceCount > 0 ? `${r.evidenceCount} ev` : null,
119
- ]
120
- .filter(Boolean)
121
- .join(", ");
122
-
123
- stdout.write(`${idx + 1}. [${action}] ${target} — ${meta}\n`);
124
- stdout.write(` id: ${r.id}\n`);
125
- if (r.hypopgReductionPct != null) {
126
- stdout.write(
127
- ` HypoPG cost: ${formatCost(r.hypopgBeforeCost)} → ${formatCost(r.hypopgAfterCost)} ` +
128
- `(${signedPct(r.hypopgReductionPct)})\n`
129
- );
130
- }
131
- if (r.reason) {
132
- stdout.write(` ${truncate(r.reason, 200)}\n`);
133
- }
134
- if (Array.isArray(r.topEvidence) && r.topEvidence.length) {
135
- const ev = r.topEvidence[0];
136
- stdout.write(
137
- ` top evidence: ${ev.calls} calls × ${formatMs(ev.meanExecTimeMs)}` +
138
- ` mean = ${formatMs(ev.totalExecTimeMs)} total (${ev.role})\n`
139
- );
140
- }
141
- stdout.write("\n");
142
- });
143
- }
144
-
145
- // ─── list / show ───────────────────────────────────────────────────────────
146
-
147
- async function cmdList(opts, { stdout = process.stdout } = {}) {
148
- const session = resolveSession(opts);
149
- const connectionId = await resolveConnectionId(session, opts.connection);
150
- const result = await request(
151
- session.baseUrl,
152
- `/index-recommendations/pending/${encodeURIComponent(connectionId)}`,
153
- { token: session.token }
154
- );
155
- if (opts.json) {
156
- stdout.write(`${JSON.stringify(result, null, 2)}\n`);
157
- return;
158
- }
159
- const list = Array.isArray(result) ? result : [];
160
- if (list.length === 0) {
161
- stdout.write("No pending index recommendations.\n");
162
- return;
163
- }
164
- stdout.write(`${list.length} pending recommendation(s):\n\n`);
165
- list.forEach((r, idx) => {
166
- const action = r.kind === "DROP_INDEX" ? "DROP" : "CREATE";
167
- stdout.write(
168
- `${idx + 1}. [${action}] ${r.tableName}(${r.columnNames || r.indexName}) — ${r.priority}, occ=${r.occurrenceCount}, id=${r.id}\n`
169
- );
170
- });
171
- }
172
-
173
- async function cmdShow(opts, { stdout = process.stdout } = {}) {
174
- const id = opts.positional[0];
175
- if (!id) throw new Error("Usage: deepsql index-recommendations show <id>");
176
- const session = resolveSession(opts);
177
- // No direct GET by id endpoint — use the connection's top with a wide
178
- // limit and filter client-side. Cheap enough for inspection use.
179
- const connectionId = opts.connection
180
- ? await resolveConnectionId(session, opts.connection)
181
- : null;
182
- if (!connectionId) {
183
- throw new Error(
184
- "`show` needs --connection <name> to look up the recommendation (or pin one with `deepsql connections use`)."
185
- );
186
- }
187
- const list = await request(
188
- session.baseUrl,
189
- `/index-recommendations/${encodeURIComponent(connectionId)}/top`,
190
- { token: session.token, query: { limit: 50 } }
191
- );
192
- const found = (list || []).find((r) => r.id === id);
193
- if (!found) {
194
- throw new Error(`Recommendation ${id} not in the top-50 for this connection.`);
195
- }
196
- if (opts.json) {
197
- stdout.write(`${JSON.stringify(found, null, 2)}\n`);
198
- return;
199
- }
200
- renderRecommendationDetail(stdout, found);
201
- }
202
-
203
- // ─── refresh ───────────────────────────────────────────────────────────────
204
-
205
- async function cmdRefresh(opts, { stdout = process.stdout, stderr = process.stderr } = {}) {
206
- const session = resolveSession(opts);
207
- const connectionId = await resolveConnectionId(session, opts.connection);
208
- stderr.write(`Refreshing index recommendations on ${opts.connection || connectionId}…\n`);
209
- const result = await request(
210
- session.baseUrl,
211
- `/index-recommendations/generate/${encodeURIComponent(connectionId)}`,
212
- { method: "POST", token: session.token, timeoutMs: 600000 }
213
- );
214
- if (opts.json) {
215
- stdout.write(`${JSON.stringify(result, null, 2)}\n`);
216
- return;
217
- }
218
- if (result && result.success) {
219
- stdout.write(
220
- `Refresh complete: ${result.count} candidate(s) merged. ` +
221
- `Use \`deepsql index-recommendations top\` to see the top-N.\n`
222
- );
223
- } else {
224
- stdout.write(`Refresh response: ${JSON.stringify(result)}\n`);
225
- }
226
- }
227
-
228
- // ─── apply ─────────────────────────────────────────────────────────────────
229
-
230
- async function cmdApply(opts, { stdout = process.stdout, stderr = process.stderr } = {}) {
231
- const id = opts.positional[0];
232
- if (!id) {
233
- throw new Error(
234
- "Usage: deepsql index-recommendations apply <id> [--mode dry-run|apply|apply-and-measure] [--confirm] [--no-concurrent]"
235
- );
236
- }
237
-
238
- const mode = normalizeMode(opts.mode);
239
- const isWriteMode = mode === "APPLY" || mode === "APPLY_AND_MEASURE";
240
- if (isWriteMode && !opts.confirm) {
241
- throw new Error(
242
- `Mode ${mode} mutates the target database. Re-run with --confirm to proceed.`
243
- );
244
- }
245
- // --concurrent defaults to true; --no-concurrent flips it off (parser
246
- // surfaces noConcurrent boolean).
247
- const concurrent = !opts.noConcurrent;
248
-
249
- const session = resolveSession(opts);
250
- if (isWriteMode) {
251
- stderr.write(`Running ${mode} on recommendation ${id}…\n`);
252
- }
253
-
254
- const result = await request(
255
- session.baseUrl,
256
- `/index-recommendations/${encodeURIComponent(id)}/apply`,
257
- {
258
- method: "POST",
259
- token: session.token,
260
- timeoutMs: 600000,
261
- query: { mode, confirm: opts.confirm === true, concurrent },
262
- }
263
- );
264
-
265
- if (opts.json) {
266
- stdout.write(`${JSON.stringify(result, null, 2)}\n`);
267
- return;
268
- }
269
- renderApplyResult(stdout, result);
270
- }
271
-
272
- // ─── dismiss ───────────────────────────────────────────────────────────────
273
-
274
- async function cmdDismiss(opts, { stdout = process.stdout } = {}) {
275
- const id = opts.positional[0];
276
- if (!id) throw new Error("Usage: deepsql index-recommendations dismiss <id>");
277
- const session = resolveSession(opts);
278
- const result = await request(
279
- session.baseUrl,
280
- `/index-recommendations/${encodeURIComponent(id)}/dismiss`,
281
- { method: "PUT", token: session.token }
282
- );
283
- if (opts.json) {
284
- stdout.write(`${JSON.stringify(result, null, 2)}\n`);
285
- return;
286
- }
287
- stdout.write(`Dismissed recommendation ${id}.\n`);
288
- }
289
-
290
- // ─── formatting helpers ────────────────────────────────────────────────────
291
-
292
- function renderRecommendationDetail(stdout, r) {
293
- const action = r.kind === "DROP_INDEX" ? "DROP" : "CREATE";
294
- stdout.write(`[${action}] ${r.tableName}(${r.columnNames || r.indexName})\n`);
295
- stdout.write(` id : ${r.id}\n`);
296
- stdout.write(` priority : ${r.priority}\n`);
297
- stdout.write(` status : ${r.status || "PENDING"}\n`);
298
- stdout.write(` occurrenceCnt : ${r.occurrenceCount}\n`);
299
- stdout.write(` workloadScore : ${formatMs(r.workloadScoreMs)}\n`);
300
- stdout.write(` writeCost : ${formatMs(r.writeCostScore)}\n`);
301
- stdout.write(` netBenefit : ${formatMs(r.netBenefitMs)}\n`);
302
- if (r.hypopgReductionPct != null) {
303
- stdout.write(
304
- ` HypoPG : ${formatCost(r.hypopgBeforeCost)} → ${formatCost(r.hypopgAfterCost)} ` +
305
- `(${signedPct(r.hypopgReductionPct)})\n`
306
- );
307
- }
308
- stdout.write(` DDL : ${r.createStatement}\n`);
309
- if (r.reason) stdout.write(` reason : ${r.reason}\n`);
310
- if (Array.isArray(r.topEvidence) && r.topEvidence.length) {
311
- stdout.write(` contributing queries (${r.topEvidence.length}):\n`);
312
- for (const ev of r.topEvidence) {
313
- stdout.write(
314
- ` - fp=${(ev.fingerprint || "?").slice(0, 12)} calls=${ev.calls} mean=${formatMs(ev.meanExecTimeMs)} total=${formatMs(ev.totalExecTimeMs)} role=${ev.role}\n`
315
- );
316
- if (ev.exampleSql) {
317
- stdout.write(` ${truncate(ev.exampleSql, 200)}\n`);
318
- }
319
- }
320
- }
321
- }
322
-
323
- function renderApplyResult(stdout, r) {
324
- if (!r || typeof r !== "object") {
325
- stdout.write("Apply returned no body.\n");
326
- return;
327
- }
328
- const status = r.status || "?";
329
- if (status === "BLOCKED_NEEDS_CONFIRMATION") {
330
- stdout.write(`[${r.mode}] blocked — pass --confirm to mutate the database.\n`);
331
- return;
332
- }
333
- if (status === "NOT_FOUND") {
334
- stdout.write(`[${r.mode}] recommendation not found: ${r.recommendationId}\n`);
335
- return;
336
- }
337
- if (status === "NO_USABLE_SAMPLES") {
338
- stdout.write(
339
- `[${r.mode}] no literal-bearing contributing queries available; cannot measure.\n`
340
- );
341
- return;
342
- }
343
- if (status === "FAILED") {
344
- stdout.write(`[${r.mode}] failed: ${r.message || "(no message)"}\n`);
345
- return;
346
- }
347
-
348
- stdout.write(`[${r.mode}] ${status}\n`);
349
- stdout.write(` DDL: ${r.executedDdl}\n`);
350
- if (r.beforeCost != null && r.afterCost != null) {
351
- stdout.write(
352
- ` planner cost: ${formatCost(r.beforeCost)} → ${formatCost(r.afterCost)} ` +
353
- `(${signedPct(r.costReductionPct)})\n`
354
- );
355
- }
356
- if (r.beforeWallTimeMs != null && r.afterWallTimeMs != null) {
357
- stdout.write(
358
- ` wall time: ${formatMs(r.beforeWallTimeMs)} → ${formatMs(r.afterWallTimeMs)} ` +
359
- `(${signedPct(r.wallTimeImprovementPct)})\n`
360
- );
361
- }
362
- if (Array.isArray(r.samples) && r.samples.length) {
363
- stdout.write(` ${r.samples.length} contributing query sample(s):\n`);
364
- for (const s of r.samples.slice(0, 5)) {
365
- stdout.write(
366
- ` fp=${(s.fingerprint || "?").slice(0, 12)} cost ${formatCost(s.beforeCost)} → ${formatCost(s.afterCost)}` +
367
- (s.error ? ` (error: ${s.error})` : "") +
368
- "\n"
369
- );
370
- }
371
- }
372
- if (r.message) stdout.write(` ${r.message}\n`);
373
- }
374
-
375
- function clampLimit(raw, fallback) {
376
- const n = Number.parseInt(raw, 10);
377
- if (!Number.isFinite(n)) return fallback;
378
- return Math.min(50, Math.max(1, n));
379
- }
380
-
381
- function normalizeMode(raw) {
382
- if (!raw) return "DRY_RUN";
383
- // Accept dash-form (CLI convention) and underscore-form (API enum).
384
- const m = String(raw).toUpperCase().replace(/-/g, "_");
385
- if (!["DRY_RUN", "APPLY", "APPLY_AND_MEASURE"].includes(m)) {
386
- throw new Error(`Unknown mode: ${raw}. Expected dry-run, apply, or apply-and-measure.`);
387
- }
388
- return m;
389
- }
390
-
391
- function formatMs(ms) {
392
- if (ms == null || !Number.isFinite(Number(ms))) return "—";
393
- const n = Number(ms);
394
- if (n <= 0) return "0ms";
395
- if (n >= 86_400_000) return `${(n / 86_400_000).toFixed(1)}d`;
396
- if (n >= 3_600_000) return `${(n / 3_600_000).toFixed(1)}h`;
397
- if (n >= 60_000) return `${(n / 60_000).toFixed(1)}m`;
398
- if (n >= 1_000) return `${(n / 1_000).toFixed(1)}s`;
399
- return `${n.toFixed(n >= 10 ? 0 : 1)}ms`;
400
- }
401
-
402
- function formatCost(c) {
403
- if (c == null || !Number.isFinite(Number(c))) return "—";
404
- return Number(c).toFixed(0);
405
- }
406
-
407
- function signedPct(pct) {
408
- if (pct == null || !Number.isFinite(Number(pct))) return "—";
409
- const sign = pct >= 0 ? "−" : "+";
410
- return `${sign}${Math.abs(pct).toFixed(1)}%`;
411
- }
412
-
413
- function formatNet(r) {
414
- if (r.netBenefitMs != null && r.netBenefitMs > 0) {
415
- return `net=${formatMs(r.netBenefitMs)} saved`;
416
- }
417
- if (r.estimatedImpact != null) return `impact ${r.estimatedImpact}`;
418
- return null;
419
- }
420
-
421
- function truncate(s, max) {
422
- if (!s) return s;
423
- return s.length <= max ? s : `${s.slice(0, max)}…`;
424
- }
425
-
426
- module.exports = { run };