@outsidedata/dolex 8.0.2 → 8.1.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.
Files changed (47) hide show
  1. package/README.md +3 -0
  2. package/dist/src/analysis/clean-exec.d.ts +23 -0
  3. package/dist/src/analysis/clean-exec.js +87 -0
  4. package/dist/src/analysis/data-context.d.ts +140 -0
  5. package/dist/src/analysis/data-context.js +96 -0
  6. package/dist/src/analysis/quality.d.ts +23 -0
  7. package/dist/src/analysis/quality.js +290 -6
  8. package/dist/src/analysis/rules.js +41 -0
  9. package/dist/src/cleaning/author.d.ts +30 -0
  10. package/dist/src/cleaning/author.js +7 -0
  11. package/dist/src/cleaning/exec.d.ts +29 -0
  12. package/dist/src/cleaning/exec.js +161 -0
  13. package/dist/src/cleaning/handlers.d.ts +16 -0
  14. package/dist/src/cleaning/handlers.js +82 -0
  15. package/dist/src/cleaning/index.d.ts +8 -0
  16. package/dist/src/cleaning/index.js +4 -0
  17. package/dist/src/cleaning/manifest.d.ts +35 -0
  18. package/dist/src/cleaning/manifest.js +95 -0
  19. package/dist/src/cli/commands/check.js +2 -89
  20. package/dist/src/cli/commands/clean.d.ts +1 -0
  21. package/dist/src/cli/commands/clean.js +115 -0
  22. package/dist/src/cli/commands/help.js +1 -0
  23. package/dist/src/cli/commands/query.js +4 -1
  24. package/dist/src/cli/commands/visualize.js +2 -0
  25. package/dist/src/cli/index.js +2 -0
  26. package/dist/src/connectors/csv.js +81 -8
  27. package/dist/src/connectors/manager.d.ts +10 -0
  28. package/dist/src/connectors/manager.js +60 -1
  29. package/dist/src/connectors/sql-safety.d.ts +68 -0
  30. package/dist/src/connectors/sql-safety.js +167 -0
  31. package/dist/src/mcp/index.js +9 -1
  32. package/dist/src/mcp/tools/clean-column.d.ts +5 -0
  33. package/dist/src/mcp/tools/clean-column.js +45 -0
  34. package/dist/src/mcp/tools/clean-schemas.d.ts +23 -0
  35. package/dist/src/mcp/tools/clean-schemas.js +9 -0
  36. package/dist/src/mcp/tools/query-source.d.ts +2 -2
  37. package/dist/src/mcp/tools/query-source.js +2 -1
  38. package/dist/src/mcp/tools/shared.d.ts +1 -0
  39. package/dist/src/mcp/tools/shared.js +1 -1
  40. package/dist/src/mcp/tools/visualize-cli.d.ts +2 -2
  41. package/dist/src/mcp/tools/visualize.d.ts +3 -2
  42. package/dist/src/mcp/tools/visualize.js +1 -0
  43. package/dist/src/transforms/evaluator.js +58 -3
  44. package/dist/src/transforms/tokenizer.js +20 -2
  45. package/dist/src/transforms/types.d.ts +6 -6
  46. package/dist/src/types.d.ts +10 -0
  47. package/package.json +5 -2
@@ -93,6 +93,19 @@ function toTableName(filename) {
93
93
  */
94
94
  function registerCustomAggregates(db) {
95
95
  const sortedNums = (values) => values.filter(v => v != null && !isNaN(v)).sort((a, b) => a - b);
96
+ // Accumulate ONLY real numeric values. SQLite NULL arrives as JS null and empty
97
+ // cells as '' — both coerce to 0 via Number(), which would silently count missing
98
+ // values as zero and corrupt median/stddev/cv/mad/percentiles (and disagree with
99
+ // native AVG/COUNT, which ignore NULLs). Skip them BEFORE coercion. Non-numeric
100
+ // strings → NaN → also skipped. (Regression: __tests__/connectors/aggregates.test.ts)
101
+ const pushNum = (acc, val) => {
102
+ if (val === null || val === undefined || val === '')
103
+ return acc;
104
+ const n = Number(val);
105
+ if (Number.isFinite(n))
106
+ acc.push(n);
107
+ return acc;
108
+ };
96
109
  const computePercentile = (sorted, p) => {
97
110
  if (sorted.length === 0)
98
111
  return null;
@@ -107,12 +120,12 @@ function registerCustomAggregates(db) {
107
120
  };
108
121
  db.aggregate('median', {
109
122
  start: () => [],
110
- step: (acc, val) => { acc.push(Number(val)); return acc; },
123
+ step: (acc, val) => pushNum(acc, val),
111
124
  result: (acc) => computePercentile(sortedNums(acc), 0.5),
112
125
  });
113
126
  db.aggregate('stddev', {
114
127
  start: () => [],
115
- step: (acc, val) => { acc.push(Number(val)); return acc; },
128
+ step: (acc, val) => pushNum(acc, val),
116
129
  result: (acc) => {
117
130
  const nums = sortedNums(acc);
118
131
  if (nums.length === 0)
@@ -124,24 +137,63 @@ function registerCustomAggregates(db) {
124
137
  });
125
138
  db.aggregate('p25', {
126
139
  start: () => [],
127
- step: (acc, val) => { acc.push(Number(val)); return acc; },
140
+ step: (acc, val) => pushNum(acc, val),
128
141
  result: (acc) => computePercentile(sortedNums(acc), 0.25),
129
142
  });
130
143
  db.aggregate('p75', {
131
144
  start: () => [],
132
- step: (acc, val) => { acc.push(Number(val)); return acc; },
145
+ step: (acc, val) => pushNum(acc, val),
133
146
  result: (acc) => computePercentile(sortedNums(acc), 0.75),
134
147
  });
135
148
  db.aggregate('p10', {
136
149
  start: () => [],
137
- step: (acc, val) => { acc.push(Number(val)); return acc; },
150
+ step: (acc, val) => pushNum(acc, val),
138
151
  result: (acc) => computePercentile(sortedNums(acc), 0.10),
139
152
  });
140
153
  db.aggregate('p90', {
141
154
  start: () => [],
142
- step: (acc, val) => { acc.push(Number(val)); return acc; },
155
+ step: (acc, val) => pushNum(acc, val),
143
156
  result: (acc) => computePercentile(sortedNums(acc), 0.90),
144
157
  });
158
+ // Extended tail percentiles (floor/ceiling extremes) — same shape as p10..p90.
159
+ for (const [name, p] of [['p1', 0.01], ['p5', 0.05], ['p95', 0.95], ['p99', 0.99]]) {
160
+ db.aggregate(name, {
161
+ start: () => [],
162
+ step: (acc, val) => pushNum(acc, val),
163
+ result: (acc) => computePercentile(sortedNums(acc), p),
164
+ });
165
+ }
166
+ // Coefficient of variation — stddev/mean (population). Scale-free dispersion, for
167
+ // comparing variability across different-magnitude metrics. NULL when mean is 0
168
+ // (the ratio is undefined) or there are no values.
169
+ db.aggregate('cv', {
170
+ start: () => [],
171
+ step: (acc, val) => pushNum(acc, val),
172
+ result: (acc) => {
173
+ const nums = sortedNums(acc);
174
+ if (nums.length === 0)
175
+ return null;
176
+ const mean = nums.reduce((a, b) => a + b, 0) / nums.length;
177
+ if (mean === 0)
178
+ return null;
179
+ const variance = nums.reduce((sum, v) => sum + (v - mean) ** 2, 0) / nums.length;
180
+ return Math.sqrt(variance) / mean;
181
+ },
182
+ });
183
+ // Median absolute deviation — median(|x - median(x)|). A robust (outlier-resistant)
184
+ // dispersion measure; pairs with median better than stddev does for skewed data.
185
+ db.aggregate('mad', {
186
+ start: () => [],
187
+ step: (acc, val) => pushNum(acc, val),
188
+ result: (acc) => {
189
+ const nums = sortedNums(acc);
190
+ if (nums.length === 0)
191
+ return null;
192
+ const med = computePercentile(nums, 0.5);
193
+ const devs = sortedNums(nums.map((v) => Math.abs(v - med)));
194
+ return computePercentile(devs, 0.5);
195
+ },
196
+ });
145
197
  }
146
198
  /**
147
199
  * Load CSV files into an in-memory SQLite database and build schema metadata.
@@ -183,6 +235,10 @@ function loadCsvs(csvPaths) {
183
235
  let nullCount = 0; // undefined/null/\N
184
236
  let emptyCount = 0; // ''
185
237
  let nonNumericCount = 0; // non-empty values that are not numbers
238
+ // Tally the NON-EMPTY non-numeric tokens (e.g. "Undrafted") so a recurring
239
+ // string sentinel hiding in a numeric column can be surfaced to the auditor —
240
+ // NUMERIC affinity coerces it to NULL, erasing it from the stored data.
241
+ const nonNumericTokens = new Map();
186
242
  for (const row of rows) {
187
243
  const v = row[col];
188
244
  if (v === undefined || v === null || v === '\\N') {
@@ -200,8 +256,10 @@ function loadCsvs(csvPaths) {
200
256
  }
201
257
  if (isNumericStr(v))
202
258
  numericDistinct.add(v);
203
- else
259
+ else {
204
260
  nonNumericCount++;
261
+ nonNumericTokens.set(v, (nonNumericTokens.get(v) ?? 0) + 1);
262
+ }
205
263
  }
206
264
  const type = inferColumnType(col, samples, distinct.size, rows.length);
207
265
  // Zero-padded codes (zip '00501', '007') look numeric but must stay TEXT
@@ -213,7 +271,21 @@ function loadCsvs(csvPaths) {
213
271
  // ORDER BY (SQLite ranks text above all numbers). Counts reflect that.
214
272
  const finalNullCount = numericAffinity ? nullCount + emptyCount + nonNumericCount : nullCount;
215
273
  const finalUnique = numericAffinity ? numericDistinct.size : distinct.size;
216
- return { col, type, samples, distinctCount: finalUnique, nullCount: finalNullCount, numericAffinity };
274
+ // The dominant non-empty token coerced to NULL (numeric columns only) — the
275
+ // fingerprint of a string-sentinel affinity trap. Empty strings don't count;
276
+ // they're plain missing values the auditor reports via the null ratio.
277
+ let coercedNonNumeric;
278
+ if (numericAffinity && nonNumericTokens.size > 0) {
279
+ let token = '';
280
+ let count = 0;
281
+ for (const [tok, c] of nonNumericTokens)
282
+ if (c > count) {
283
+ token = tok;
284
+ count = c;
285
+ }
286
+ coercedNonNumeric = { token, count };
287
+ }
288
+ return { col, type, samples, distinctCount: finalUnique, nullCount: finalNullCount, numericAffinity, coercedNonNumeric };
217
289
  });
218
290
  const numericCols = new Set(colMeta.filter((m) => m.numericAffinity).map((m) => m.col));
219
291
  // Create table with NUMERIC affinity for numeric columns, TEXT otherwise.
@@ -307,6 +379,7 @@ function loadCsvs(csvPaths) {
307
379
  totalCount: rows.length,
308
380
  stats: columnStats,
309
381
  topValues,
382
+ coercedNonNumeric: meta.coercedNonNumeric,
310
383
  };
311
384
  columns.push(column);
312
385
  allColumns.push({ table: tableName, col: column });
@@ -17,6 +17,10 @@ export interface SqlQueryResult {
17
17
  totalRows?: number;
18
18
  truncated?: boolean;
19
19
  error?: string;
20
+ /** Advisory SQL-safety diagnostics (e.g. integer-division truncation). The
21
+ * query still ran; these signal silent-wrong-answer traps so the caller can
22
+ * re-issue a corrected query. The engine never rewrites the SQL itself. */
23
+ warnings?: string[];
20
24
  }
21
25
  export declare class SourceManager {
22
26
  private registry;
@@ -78,6 +82,12 @@ export declare class SourceManager {
78
82
  * Error messages are enriched with available table/column names.
79
83
  */
80
84
  querySql(idOrName: string, sql: string, maxRows?: number): Promise<SqlQueryResult>;
85
+ /**
86
+ * Advisory SQL-safety pass over a successful query. Best-effort: any failure
87
+ * yields no warnings (never blocks or breaks the query). Gated on a cheap
88
+ * syntactic pre-filter so the type probes only run when a risky term exists.
89
+ */
90
+ private analyzeSqlSafety;
81
91
  /**
82
92
  * Enrich SQLite error messages with available table/column info.
83
93
  */
@@ -11,6 +11,7 @@
11
11
  import * as fs from 'fs';
12
12
  import * as crypto from 'crypto';
13
13
  import { csvConnector } from './csv.js';
14
+ import { riskyDivisionTerms, detectSqlFootguns, divisionDenominators, detectDivByZero, detectBareAggregate } from './sql-safety.js';
14
15
  const MAX_RESULT_ROWS = 10000;
15
16
  // ─── SQL Safety ───────────────────────────────────────────────────────────
16
17
  function isReadOnlySelect(sql) {
@@ -299,12 +300,14 @@ export class SourceManager {
299
300
  // Only mark as truncated if we hit our limit AND the user didn't have an explicit LIMIT
300
301
  const userHasLimit = /\bLIMIT\s+\d+/i.test(sql);
301
302
  const hitOurLimit = result.rows.length >= Math.min(maxRows, MAX_RESULT_ROWS);
303
+ const warnings = await this.analyzeSqlSafety(resolved.source, sql);
302
304
  return {
303
305
  ok: true,
304
306
  rows: result.rows,
305
307
  columns: result.columns,
306
308
  totalRows: result.rows.length,
307
309
  truncated: hitOurLimit && !userHasLimit,
310
+ ...(warnings.length ? { warnings } : {}),
308
311
  };
309
312
  }
310
313
  catch (err) {
@@ -312,6 +315,62 @@ export class SourceManager {
312
315
  return { ok: false, error: `SQL query failed: ${enriched}` };
313
316
  }
314
317
  }
318
+ /**
319
+ * Advisory SQL-safety pass over a successful query. Best-effort: any failure
320
+ * yields no warnings (never blocks or breaks the query). Gated on a cheap
321
+ * syntactic pre-filter so the type probes only run when a risky term exists.
322
+ */
323
+ async analyzeSqlSafety(source, sql) {
324
+ try {
325
+ const hasDivision = riskyDivisionTerms(sql).length > 0;
326
+ const denoms = divisionDenominators(sql);
327
+ const maybeBareAgg = /\b(?:SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\(/i.test(sql) && !/\bGROUP\s+BY\b/i.test(sql);
328
+ if (!hasDivision && denoms.length === 0 && !maybeBareAgg)
329
+ return [];
330
+ const schema = await source.getSchema();
331
+ const colToTable = new Map();
332
+ for (const t of schema.tables)
333
+ for (const c of t.columns)
334
+ if (!colToTable.has(c.name))
335
+ colToTable.set(c.name, t.name);
336
+ const typeCache = new Map();
337
+ const columnType = async (col) => {
338
+ if (typeCache.has(col))
339
+ return typeCache.get(col);
340
+ let type;
341
+ const table = colToTable.get(col);
342
+ if (table) {
343
+ const r = await source.executeQuery(`SELECT typeof("${col}") AS t FROM "${table}" WHERE "${col}" IS NOT NULL LIMIT 1`);
344
+ const v = r.rows?.[0]?.t;
345
+ type = typeof v === 'string' ? v : undefined;
346
+ }
347
+ typeCache.set(col, type);
348
+ return type;
349
+ };
350
+ const zeroCache = new Map();
351
+ const columnHasZero = async (col) => {
352
+ if (zeroCache.has(col))
353
+ return zeroCache.get(col);
354
+ let zero = false;
355
+ const table = colToTable.get(col);
356
+ if (table) {
357
+ const r = await source.executeQuery(`SELECT 1 AS z FROM "${table}" WHERE "${col}" = 0 LIMIT 1`);
358
+ zero = (r.rows?.length ?? 0) > 0;
359
+ }
360
+ zeroCache.set(col, zero);
361
+ return zero;
362
+ };
363
+ const warnings = [
364
+ ...(await detectSqlFootguns(sql, columnType)),
365
+ ...(await detectDivByZero(sql, columnHasZero)),
366
+ ...detectBareAggregate(sql, (col) => colToTable.has(col)),
367
+ ];
368
+ return warnings.map((w) => w.message);
369
+ }
370
+ catch {
371
+ return [];
372
+ }
373
+ }
315
374
  /**
316
375
  * Enrich SQLite error messages with available table/column info.
317
376
  */
@@ -331,7 +390,7 @@ export class SourceManager {
331
390
  return `${errorMsg}. Available tables: ${tables.join(', ')}`;
332
391
  }
333
392
  if (/no such function/i.test(errorMsg)) {
334
- return `${errorMsg}. Available aggregate functions: SUM, AVG, MIN, MAX, COUNT, MEDIAN, STDDEV, P25, P75, P10, P90. Window functions: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, etc.`;
393
+ return `${errorMsg}. Available aggregate functions: SUM, AVG, MIN, MAX, COUNT, MEDIAN, STDDEV, CV, MAD, P1, P5, P10, P25, P75, P90, P95, P99. Window functions: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, etc.`;
335
394
  }
336
395
  }
337
396
  catch {
@@ -0,0 +1,68 @@
1
+ /**
2
+ * SQL safety pass — advisory footgun detection for model/human-authored SELECTs.
3
+ *
4
+ * The engine NEVER rewrites the caller's SQL (that would be "hidden SQL" — the
5
+ * analyst must stay in control). Instead it DETECTS silent-wrong-answer traps and
6
+ * SIGNALS them back as warnings, so the caller re-issues a corrected query. This
7
+ * mirrors the evaluator-gate principle at the query layer.
8
+ *
9
+ * Design validated head-to-head in
10
+ * `local-orchestration/experiments/017-sql-integer-division.ts`: an auto-rewrite
11
+ * variant corrupted `/` inside string literals and comments; a type-blind detector
12
+ * cried wolf on legitimate real-typed division. The promoted approach is
13
+ * term-aware + TYPE-aware detection with no mutation.
14
+ *
15
+ * Currently detects: integer-division truncation (`int / int` → SQLite floors to 0).
16
+ * Add further checks (div-by-zero, bare GROUP BY, COUNT DISTINCT nulls, anti-join
17
+ * NULL trap) here as new functions invoked by detectSqlFootguns.
18
+ */
19
+ export interface SqlSafetyWarning {
20
+ code: 'integer-division' | 'division-by-zero' | 'bare-aggregate';
21
+ message: string;
22
+ }
23
+ /** Resolve a base column's SQLite storage type ('integer' | 'real' | ...), or
24
+ * undefined when the operand is not a resolvable base column (alias/expr). */
25
+ export type ColumnTypeResolver = (column: string) => Promise<string | undefined>;
26
+ /** Multiplicative terms containing a `/` that are NOT already float-safe (no float
27
+ * literal, no CAST-to-real), with their candidate column identifiers. Pure syntax
28
+ * — cheap enough to use as a pre-filter before any type probing. */
29
+ export declare function riskyDivisionTerms(sql: string): {
30
+ term: string;
31
+ columns: string[];
32
+ }[];
33
+ /** Division denominators (the operand right of each `/`) with their candidate
34
+ * column identifiers. A `NULLIF(...)`-wrapped denominator is already guarded and
35
+ * skipped. Applies to ALL division (float `x/0` also yields NULL in SQLite), so
36
+ * it is independent of the integer-truncation check above. */
37
+ export declare function divisionDenominators(sql: string): {
38
+ denom: string;
39
+ columns: string[];
40
+ }[];
41
+ /**
42
+ * Detect division whose denominator column actually CONTAINS a zero — `x / 0`
43
+ * silently yields NULL in SQLite (no error), which then vanishes from downstream
44
+ * aggregates. Data-gated on purpose: it warns ONLY when a real zero is present, so
45
+ * it never cries wolf on a zero-free denominator (no overbearing blanket warning).
46
+ */
47
+ export declare function detectDivByZero(sql: string, columnHasZero: (column: string) => Promise<boolean>): Promise<SqlSafetyWarning[]>;
48
+ /**
49
+ * Detect a bare (non-aggregated, non-grouped) column selected ALONGSIDE an
50
+ * aggregate with NO GROUP BY — e.g. `SELECT name, SUM(score) FROM t`. SQLite does
51
+ * not error; it pairs an ARBITRARY row's `name` with a whole-table aggregate (a
52
+ * meaningless pairing the caller rarely intends).
53
+ *
54
+ * Deliberately CONSERVATIVE — built to avoid false positives:
55
+ * - skips anything with a GROUP BY (verifying GROUP BY membership syntactically is
56
+ * too false-positive-prone);
57
+ * - skips a LONE MIN()/MAX(): SQLite has a documented special case where bare
58
+ * columns then take values from the extremal row, so that is actually correct;
59
+ * - only flags identifiers that are real base columns.
60
+ */
61
+ export declare function detectBareAggregate(sql: string, isBaseColumn: (col: string) => boolean): SqlSafetyWarning[];
62
+ /**
63
+ * Detect silent-wrong-answer footguns in a SELECT. Type-aware: a division term is
64
+ * flagged only when EVERY resolvable operand column is integer-typed (a single
65
+ * real operand means SQLite promotes to real → no truncation). Unknown operands
66
+ * are treated conservatively as non-integer (no flag) to avoid crying wolf.
67
+ */
68
+ export declare function detectSqlFootguns(sql: string, columnType: ColumnTypeResolver): Promise<SqlSafetyWarning[]>;
@@ -0,0 +1,167 @@
1
+ /**
2
+ * SQL safety pass — advisory footgun detection for model/human-authored SELECTs.
3
+ *
4
+ * The engine NEVER rewrites the caller's SQL (that would be "hidden SQL" — the
5
+ * analyst must stay in control). Instead it DETECTS silent-wrong-answer traps and
6
+ * SIGNALS them back as warnings, so the caller re-issues a corrected query. This
7
+ * mirrors the evaluator-gate principle at the query layer.
8
+ *
9
+ * Design validated head-to-head in
10
+ * `local-orchestration/experiments/017-sql-integer-division.ts`: an auto-rewrite
11
+ * variant corrupted `/` inside string literals and comments; a type-blind detector
12
+ * cried wolf on legitimate real-typed division. The promoted approach is
13
+ * term-aware + TYPE-aware detection with no mutation.
14
+ *
15
+ * Currently detects: integer-division truncation (`int / int` → SQLite floors to 0).
16
+ * Add further checks (div-by-zero, bare GROUP BY, COUNT DISTINCT nulls, anti-join
17
+ * NULL trap) here as new functions invoked by detectSqlFootguns.
18
+ */
19
+ // Strip string literals + comments before any text analysis, so a `/` inside
20
+ // quoted content or a comment is never mistaken for a division operator.
21
+ // (Mirrors the literal/comment stripping already used by isReadOnlySelect.)
22
+ function strip(sql) {
23
+ return sql
24
+ .replace(/'[^']*'/g, "''")
25
+ .replace(/"[^"]*"/g, '""')
26
+ .replace(/--.*$/gm, '')
27
+ .replace(/\/\*[\s\S]*?\*\//g, '');
28
+ }
29
+ // A maximal multiplicative term: operand ([*/] operand)+. operand = number |
30
+ // func(one paren level) | identifier. One level covers SUM(wins), AVG(x)/COUNT(*).
31
+ const OPERAND = String.raw `(?:\w+\s*\([^()]*\)|\w+(?:\.\w+)?|\d+(?:\.\d+)?)`;
32
+ const TERM = new RegExp(`${OPERAND}(?:\\s*[*/]\\s*${OPERAND})+`, 'g');
33
+ const FLOAT_LIT = /\d+\.\d+/;
34
+ const CAST_REAL = /CAST\s*\([^()]*AS\s+(?:REAL|FLOAT|DOUBLE)/i;
35
+ const TERM_FUNCS = new Set(['sum', 'avg', 'count', 'min', 'max', 'cast', 'as', 'real', 'float', 'double', 'total', 'abs', 'round']);
36
+ /** Multiplicative terms containing a `/` that are NOT already float-safe (no float
37
+ * literal, no CAST-to-real), with their candidate column identifiers. Pure syntax
38
+ * — cheap enough to use as a pre-filter before any type probing. */
39
+ export function riskyDivisionTerms(sql) {
40
+ const s = strip(sql);
41
+ const out = [];
42
+ for (const m of s.matchAll(TERM)) {
43
+ const term = m[0];
44
+ if (!term.includes('/'))
45
+ continue; // pure multiplication can't truncate
46
+ if (FLOAT_LIT.test(term) || CAST_REAL.test(term))
47
+ continue; // float context → safe
48
+ const columns = [...term.matchAll(/[a-z_]\w*/gi)].map((x) => x[0]).filter((id) => !TERM_FUNCS.has(id.toLowerCase()));
49
+ out.push({ term, columns });
50
+ }
51
+ return out;
52
+ }
53
+ /** Division denominators (the operand right of each `/`) with their candidate
54
+ * column identifiers. A `NULLIF(...)`-wrapped denominator is already guarded and
55
+ * skipped. Applies to ALL division (float `x/0` also yields NULL in SQLite), so
56
+ * it is independent of the integer-truncation check above. */
57
+ export function divisionDenominators(sql) {
58
+ const s = strip(sql);
59
+ const re = new RegExp(`/\\s*(${OPERAND})`, 'g');
60
+ const out = [];
61
+ for (const m of s.matchAll(re)) {
62
+ const denom = m[1].trim();
63
+ if (/^NULLIF\s*\(/i.test(denom))
64
+ continue; // already guarded
65
+ const columns = [...denom.matchAll(/[a-z_]\w*/gi)].map((x) => x[0]).filter((id) => !TERM_FUNCS.has(id.toLowerCase()) && id.toLowerCase() !== 'nullif');
66
+ if (columns.length)
67
+ out.push({ denom, columns });
68
+ }
69
+ return out;
70
+ }
71
+ /**
72
+ * Detect division whose denominator column actually CONTAINS a zero — `x / 0`
73
+ * silently yields NULL in SQLite (no error), which then vanishes from downstream
74
+ * aggregates. Data-gated on purpose: it warns ONLY when a real zero is present, so
75
+ * it never cries wolf on a zero-free denominator (no overbearing blanket warning).
76
+ */
77
+ export async function detectDivByZero(sql, columnHasZero) {
78
+ const warnings = [];
79
+ for (const { denom, columns } of divisionDenominators(sql)) {
80
+ let zero = false;
81
+ for (const col of columns) {
82
+ if (await columnHasZero(col)) {
83
+ zero = true;
84
+ break;
85
+ }
86
+ }
87
+ if (zero) {
88
+ warnings.push({
89
+ code: 'division-by-zero',
90
+ message: `Denominator "${denom}" contains zero values — SQLite returns NULL for x/0 (no error), and those rows silently drop out of aggregates. ` +
91
+ `Guard it: <numerator> / NULLIF(${denom}, 0), or filter the zeros out.`,
92
+ });
93
+ }
94
+ }
95
+ return warnings;
96
+ }
97
+ const AGG = /\b(?:SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\(/i;
98
+ /** The top-level SELECT projection list (between the first SELECT and its FROM). */
99
+ function selectList(stripped) {
100
+ const m = stripped.match(/\bSELECT\b([\s\S]*?)\bFROM\b/i);
101
+ return m ? m[1] : undefined;
102
+ }
103
+ /**
104
+ * Detect a bare (non-aggregated, non-grouped) column selected ALONGSIDE an
105
+ * aggregate with NO GROUP BY — e.g. `SELECT name, SUM(score) FROM t`. SQLite does
106
+ * not error; it pairs an ARBITRARY row's `name` with a whole-table aggregate (a
107
+ * meaningless pairing the caller rarely intends).
108
+ *
109
+ * Deliberately CONSERVATIVE — built to avoid false positives:
110
+ * - skips anything with a GROUP BY (verifying GROUP BY membership syntactically is
111
+ * too false-positive-prone);
112
+ * - skips a LONE MIN()/MAX(): SQLite has a documented special case where bare
113
+ * columns then take values from the extremal row, so that is actually correct;
114
+ * - only flags identifiers that are real base columns.
115
+ */
116
+ export function detectBareAggregate(sql, isBaseColumn) {
117
+ const s = strip(sql);
118
+ if (/\bGROUP\s+BY\b/i.test(s))
119
+ return []; // grouped → out of scope (conservative)
120
+ const list = selectList(s);
121
+ if (!list || !AGG.test(list))
122
+ return [];
123
+ // Lone MIN()/MAX() → SQLite fills bare columns from the extremal row (correct).
124
+ const aggs = [...list.matchAll(/\b(SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\(/gi)].map((m) => m[1].toUpperCase());
125
+ if (aggs.length === 1 && (aggs[0] === 'MIN' || aggs[0] === 'MAX'))
126
+ return [];
127
+ // Drop aggregate call expressions, then look for surviving base-column identifiers.
128
+ const bare = list.replace(/\b(?:SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\([^()]*\)/gi, ' ');
129
+ const cols = [...bare.matchAll(/[a-z_]\w*/gi)].map((m) => m[0]).filter((id) => !TERM_FUNCS.has(id.toLowerCase()) && isBaseColumn(id));
130
+ if (cols.length === 0)
131
+ return [];
132
+ const uniq = [...new Set(cols)];
133
+ return [{
134
+ code: 'bare-aggregate',
135
+ message: `Column${uniq.length > 1 ? 's' : ''} "${uniq.join('", "')}" ${uniq.length > 1 ? 'are' : 'is'} selected next to an aggregate with no GROUP BY — ` +
136
+ `SQLite pairs an ARBITRARY row's value with a whole-table aggregate here. ` +
137
+ `For the label of the top row use ORDER BY … LIMIT 1 (or a subquery); for per-group rows add GROUP BY.`,
138
+ }];
139
+ }
140
+ /**
141
+ * Detect silent-wrong-answer footguns in a SELECT. Type-aware: a division term is
142
+ * flagged only when EVERY resolvable operand column is integer-typed (a single
143
+ * real operand means SQLite promotes to real → no truncation). Unknown operands
144
+ * are treated conservatively as non-integer (no flag) to avoid crying wolf.
145
+ */
146
+ export async function detectSqlFootguns(sql, columnType) {
147
+ const warnings = [];
148
+ for (const { term, columns } of riskyDivisionTerms(sql)) {
149
+ if (columns.length === 0)
150
+ continue;
151
+ let allInteger = true;
152
+ for (const col of columns) {
153
+ if ((await columnType(col)) !== 'integer') {
154
+ allInteger = false;
155
+ break;
156
+ }
157
+ }
158
+ if (allInteger) {
159
+ warnings.push({
160
+ code: 'integer-division',
161
+ message: `Integer division in "${term.trim()}" will truncate toward zero (SQLite floors int/int — e.g. 16/32 → 0, not 0.5). ` +
162
+ `Wrap the numerator: CAST(<numerator> AS REAL) / <denominator>.`,
163
+ });
164
+ }
165
+ }
166
+ return warnings;
167
+ }
@@ -45,6 +45,8 @@ import { handleTransformData } from './tools/transform-data.js';
45
45
  import { handlePromoteColumns } from './tools/promote-columns.js';
46
46
  import { handleListTransforms } from './tools/list-transforms.js';
47
47
  import { handleDropColumns } from './tools/drop-columns.js';
48
+ import { cleanColumnSchema } from './tools/clean-schemas.js';
49
+ import { handleCleanColumn } from './tools/clean-column.js';
48
50
  import { specStore } from './spec-store.js';
49
51
  import { mkdirSync, readFileSync } from 'fs';
50
52
  import { join } from 'path';
@@ -96,6 +98,7 @@ const server = new McpServer({
96
98
  '• describe_data: Full column stats, top values, sample rows. Call only when you need deep exploration.',
97
99
  '• analyze_data: Auto-generate analysis plan with ready SQL queries. Execute each step with visualize; present results one at a time.',
98
100
  '• query_data: Run SQL query, get rows. Returns resultId for visualize().',
101
+ '• clean_column: Clean one column with a Python clean(value) you write — parse messy dates, null sentinels, canonicalize categories. Preview first, then apply:true writes a non-destructive <column>_clean. (Requires python3.)',
99
102
  '• visualize: Chart data. Pass inline data array, resultId from query_data, or sourceId + sql for server-side query. Matches a chart to the shape of the data. Set title/subtitle here to avoid a refine round-trip.',
100
103
  '• refine_visualization: Tweak a chart — sort, limit, filter, palette, highlight, flip, title, format. Each call returns a new specId.',
101
104
  '• list_patterns: Browse available chart types. Only needed when the user asks what charts are available or you need a pattern ID.',
@@ -170,7 +173,7 @@ server.registerTool('analyze_data', {
170
173
  }, handleAnalyzeSource({ sourceManager }));
171
174
  server.registerTool('query_data', {
172
175
  title: 'Query Data',
173
- description: 'Run a SQL query on a loaded dataset. JOINs, GROUP BY, window functions, CTEs.\nCustom aggregates: MEDIAN, STDDEV, P25, P75, P10, P90.\nReturns resultId for visualize().',
176
+ description: 'Run a SQL query on a loaded dataset. JOINs, GROUP BY, window functions, CTEs.\nCustom aggregates: MEDIAN, STDDEV, CV, MAD, P1/P5/P10/P25/P75/P90/P95/P99.\nReturns resultId for visualize().',
174
177
  inputSchema: querySourceInputSchema,
175
178
  }, handleQuerySource({ sourceManager }));
176
179
  // Derived data layer tools
@@ -194,6 +197,11 @@ server.registerTool('drop_columns', {
194
197
  description: 'Drop derived or working columns. For derived columns, validates no other columns depend on it. For working columns shadowing a derived column, restores the derived values.\n\nUse ["*"] with layer to drop all columns in a layer.',
195
198
  inputSchema: dropColumnsSchema.shape,
196
199
  }, handleDropColumns({ sourceManager }));
200
+ server.registerTool('clean_column', {
201
+ title: 'Clean Column',
202
+ description: 'Clean one column by writing a Python `def clean(value):` function (you author it, the server runs it — the Python sibling of query_data). PREVIEW first (apply omitted/false): validates the fix and returns before→after stats + a sample WITHOUT writing. Then call again with apply:true to write a NEW column (<column>_clean) — NON-DESTRUCTIVE, the original column is kept.\n\nWHEN TO USE: after describe_data or the data-quality audit flags a column (a sentinel value, a mixed-type column, messy categories). Use it for fixes the SQL expression language can\'t do: parse a non-ISO date (datetime.strptime → ISO), null a sentinel (return None for "None"/"Undrafted"/999999), canonicalize a messy category (value.strip().lower()). NOTE: value arrives as a string (or None) — cast before numeric work.\n\nRequires python3 on PATH. Executes the Python you provide — same trust model as the SQL you pass to query_data.',
203
+ inputSchema: cleanColumnSchema.shape,
204
+ }, handleCleanColumn({ sourceManager }));
197
205
  // Privacy / cache management tools
198
206
  const privacyDeps = { sourceManager, serverStartTime };
199
207
  server.registerTool('server_status', {
@@ -0,0 +1,5 @@
1
+ import type { z } from 'zod';
2
+ import type { cleanColumnSchema } from './clean-schemas.js';
3
+ export declare function handleCleanColumn(deps: {
4
+ sourceManager: any;
5
+ }): (args: z.infer<typeof cleanColumnSchema>) => Promise<import("./shared.js").McpResponse>;
@@ -0,0 +1,45 @@
1
+ import { connectAndValidateTable, isTransformError, errorResponse, jsonResponse } from './shared.js';
2
+ import { pythonAvailable, runPythonClean, cleanStats, safetyVerdict, previewSample, applyCleanColumn } from '../../cleaning/exec.js';
3
+ const q = (s) => `"${s.replace(/"/g, '""')}"`;
4
+ export function handleCleanColumn(deps) {
5
+ return async (args) => {
6
+ const ctx = await connectAndValidateTable(deps, args.sourceId, args.table);
7
+ if (isTransformError(ctx))
8
+ return ctx;
9
+ const colNames = ctx.table.columns.map((c) => c.name);
10
+ if (!colNames.includes(args.column))
11
+ return errorResponse(`Column '${args.column}' not found. Available: [${colNames.join(', ')}]`);
12
+ const newColumn = args.newColumn ?? `${args.column}_clean`;
13
+ if (colNames.includes(newColumn))
14
+ return errorResponse(`Column '${newColumn}' already exists. Pass a different newColumn or drop it first.`);
15
+ if (!pythonAvailable())
16
+ return errorResponse('clean_column requires python3 on PATH (not found). Install Python 3 to use this tool.');
17
+ const rows = ctx.db.prepare(`SELECT rowid AS __rid, ${q(args.column)} AS v FROM ${q(args.table)}`).all();
18
+ const rowids = rows.map((r) => r.__rid);
19
+ // Canonicalize blanks to null on the way IN: the CSV connector stores an empty cell as ''
20
+ // but treats '' as missing everywhere else, so clean(value) sees None for an empty cell.
21
+ const raw = rows.map((r) => (r.v === null || r.v === '' ? null : String(r.v)));
22
+ let cleaned;
23
+ let errors;
24
+ try {
25
+ ({ cleaned, errors } = runPythonClean(args.code, raw));
26
+ }
27
+ catch (e) {
28
+ return errorResponse(`clean() failed to run: ${e?.message ?? String(e)}`);
29
+ }
30
+ // Canonicalize blanks to null on the way OUT too, so stats/preview report exactly what
31
+ // applyCleanColumn writes (it stores '' as NULL). One canonical form across the pipeline.
32
+ cleaned = cleaned.map((v) => (v === '' ? null : v));
33
+ const stats = { ...cleanStats(raw, cleaned), errors };
34
+ const safety = safetyVerdict(raw, cleaned, errors);
35
+ const sample = previewSample(raw, cleaned, 20);
36
+ if (!safety.ok)
37
+ return errorResponse(`clean() rejected: ${safety.reason}. (nothing was applied)`);
38
+ if (!args.apply) {
39
+ return jsonResponse({ preview: true, column: args.column, newColumn, stats, sample, note: 'Preview only — pass apply:true to write the cleaned column (non-destructive; original kept).' });
40
+ }
41
+ applyCleanColumn(ctx.db, args.table, newColumn, rowids, cleaned);
42
+ ctx.source.invalidateSchema?.();
43
+ return jsonResponse({ applied: true, column: args.column, newColumn, stats, sample });
44
+ };
45
+ }
@@ -0,0 +1,23 @@
1
+ import { z } from 'zod';
2
+ export declare const cleanColumnSchema: z.ZodObject<{
3
+ sourceId: z.ZodString;
4
+ table: z.ZodString;
5
+ column: z.ZodString;
6
+ code: z.ZodString;
7
+ newColumn: z.ZodOptional<z.ZodString>;
8
+ apply: z.ZodOptional<z.ZodBoolean>;
9
+ }, "strip", z.ZodTypeAny, {
10
+ table: string;
11
+ code: string;
12
+ column: string;
13
+ sourceId: string;
14
+ newColumn?: string | undefined;
15
+ apply?: boolean | undefined;
16
+ }, {
17
+ table: string;
18
+ code: string;
19
+ column: string;
20
+ sourceId: string;
21
+ newColumn?: string | undefined;
22
+ apply?: boolean | undefined;
23
+ }>;
@@ -0,0 +1,9 @@
1
+ import { z } from 'zod';
2
+ export const cleanColumnSchema = z.object({
3
+ sourceId: z.string().describe('Dataset ID returned by load_csv'),
4
+ table: z.string().describe('Table name within the source'),
5
+ column: z.string().describe('The column to clean'),
6
+ code: z.string().describe('A Python 3 function `def clean(value):` taking ONE raw cell value — ALWAYS a string, or None (cast it yourself with int()/float() before any numeric work) — and returning the cleaned value (None for missing/sentinel). May import stdlib (datetime, re). No I/O.'),
7
+ newColumn: z.string().optional().describe('Name for the cleaned column (default: <column>_clean). Non-destructive — the original column is kept.'),
8
+ apply: z.boolean().optional().describe('false (default) = PREVIEW (validate + show before→after, no write). true = write the cleaned column.'),
9
+ });
@@ -8,12 +8,12 @@ export declare const querySourceInputSchema: z.ZodObject<{
8
8
  sql: z.ZodString;
9
9
  maxRows: z.ZodOptional<z.ZodNumber>;
10
10
  }, "strip", z.ZodTypeAny, {
11
- sourceId: string;
12
11
  sql: string;
12
+ sourceId: string;
13
13
  maxRows?: number | undefined;
14
14
  }, {
15
- sourceId: string;
16
15
  sql: string;
16
+ sourceId: string;
17
17
  maxRows?: number | undefined;
18
18
  }>;
19
19
  export declare function handleQuerySource(deps: {