@outsidedata/dolex 8.0.2 → 9.0.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 (84) hide show
  1. package/README.md +33 -7
  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/planner.d.ts +2 -1
  7. package/dist/src/analysis/planner.js +2 -2
  8. package/dist/src/analysis/quality.d.ts +23 -0
  9. package/dist/src/analysis/quality.js +386 -11
  10. package/dist/src/analysis/rules.d.ts +22 -2
  11. package/dist/src/analysis/rules.js +100 -18
  12. package/dist/src/cleaning/author.d.ts +30 -0
  13. package/dist/src/cleaning/author.js +7 -0
  14. package/dist/src/cleaning/exec.d.ts +29 -0
  15. package/dist/src/cleaning/exec.js +161 -0
  16. package/dist/src/cleaning/handlers.d.ts +16 -0
  17. package/dist/src/cleaning/handlers.js +82 -0
  18. package/dist/src/cleaning/index.d.ts +4 -0
  19. package/dist/src/cleaning/index.js +9 -0
  20. package/dist/src/cleaning/manifest.d.ts +35 -0
  21. package/dist/src/cleaning/manifest.js +95 -0
  22. package/dist/src/cleaning/replay.d.ts +34 -0
  23. package/dist/src/cleaning/replay.js +58 -0
  24. package/dist/src/cli/commands/analyze.js +13 -1
  25. package/dist/src/cli/commands/check.js +2 -89
  26. package/dist/src/cli/commands/clean.d.ts +1 -0
  27. package/dist/src/cli/commands/clean.js +127 -0
  28. package/dist/src/cli/commands/deps.d.ts +1 -0
  29. package/dist/src/cli/commands/deps.js +41 -0
  30. package/dist/src/cli/commands/help.js +3 -1
  31. package/dist/src/cli/commands/query.js +4 -1
  32. package/dist/src/cli/commands/sources.d.ts +2 -2
  33. package/dist/src/cli/commands/sources.js +138 -12
  34. package/dist/src/cli/commands/transform.js +19 -4
  35. package/dist/src/cli/commands/visualize.js +2 -0
  36. package/dist/src/cli/index.js +5 -0
  37. package/dist/src/connectors/csv.js +110 -8
  38. package/dist/src/connectors/index.d.ts +2 -0
  39. package/dist/src/connectors/index.js +2 -0
  40. package/dist/src/connectors/manager.d.ts +49 -1
  41. package/dist/src/connectors/manager.js +200 -14
  42. package/dist/src/connectors/mongo/index.d.ts +13 -0
  43. package/dist/src/connectors/mongo/index.js +323 -0
  44. package/dist/src/connectors/pg/index.d.ts +2 -0
  45. package/dist/src/connectors/pg/index.js +248 -0
  46. package/dist/src/connectors/source-factory.d.ts +38 -0
  47. package/dist/src/connectors/source-factory.js +80 -0
  48. package/dist/src/connectors/sql-safety.d.ts +68 -0
  49. package/dist/src/connectors/sql-safety.js +167 -0
  50. package/dist/src/connectors/types.d.ts +51 -0
  51. package/dist/src/connectors/types.js +11 -1
  52. package/dist/src/mcp/index.d.ts +1 -1
  53. package/dist/src/mcp/index.js +29 -10
  54. package/dist/src/mcp/tools/analyze.js +11 -1
  55. package/dist/src/mcp/tools/capabilities.d.ts +1 -0
  56. package/dist/src/mcp/tools/capabilities.js +14 -0
  57. package/dist/src/mcp/tools/clean-column.d.ts +5 -0
  58. package/dist/src/mcp/tools/clean-column.js +47 -0
  59. package/dist/src/mcp/tools/clean-schemas.d.ts +23 -0
  60. package/dist/src/mcp/tools/clean-schemas.js +9 -0
  61. package/dist/src/mcp/tools/drop-columns.js +2 -0
  62. package/dist/src/mcp/tools/list-transforms.js +22 -0
  63. package/dist/src/mcp/tools/promote-columns.js +2 -0
  64. package/dist/src/mcp/tools/query-source.d.ts +2 -2
  65. package/dist/src/mcp/tools/query-source.js +2 -1
  66. package/dist/src/mcp/tools/refine-cli.d.ts +4 -4
  67. package/dist/src/mcp/tools/refine.d.ts +4 -4
  68. package/dist/src/mcp/tools/shared.d.ts +6 -0
  69. package/dist/src/mcp/tools/shared.js +12 -5
  70. package/dist/src/mcp/tools/sources.d.ts +46 -3
  71. package/dist/src/mcp/tools/sources.js +44 -4
  72. package/dist/src/mcp/tools/transform-data.js +22 -0
  73. package/dist/src/mcp/tools/visualize-cli.d.ts +2 -2
  74. package/dist/src/mcp/tools/visualize.d.ts +3 -2
  75. package/dist/src/mcp/tools/visualize.js +1 -0
  76. package/dist/src/transforms/evaluator.js +58 -3
  77. package/dist/src/transforms/tokenizer.js +20 -2
  78. package/dist/src/transforms/types.d.ts +6 -6
  79. package/dist/src/types.d.ts +39 -2
  80. package/dist/src/utils/capabilities.d.ts +28 -0
  81. package/dist/src/utils/capabilities.js +58 -0
  82. package/dist/src/utils/optional-deps.d.ts +8 -0
  83. package/dist/src/utils/optional-deps.js +8 -0
  84. package/package.json +9 -3
@@ -18,6 +18,30 @@ const SENTINELS = new Set([
18
18
  '#value!', '#ref!', '#div/0!', '#name?', '#num!',
19
19
  '-999', '-9999',
20
20
  ]);
21
+ // Magic NUMBERS that are almost always "missing", not real data. Only flagged
22
+ // when they also sit outside the column's own distribution (see the numeric
23
+ // branch), so a column where one of these is a legitimate value won't trip.
24
+ const NUMERIC_SENTINELS = new Set([-999, -9999, -99999, -9998, -8888, 9999, 99999, 999999]);
25
+ // How often a non-numeric token must recur in a numeric column before it's a
26
+ // string sentinel (coerced to NULL by affinity) rather than a one-off typo.
27
+ const COERCED_SENTINEL_MIN = 10;
28
+ // Numbers stored as TEXT that SQLite silently coerces wrong. US grouping only —
29
+ // "1.200,50" (European) is intentionally NOT matched here (stripping its comma
30
+ // would corrupt it); locale-aware parsing is a separate, larger concern.
31
+ const THOUSANDS_NUM = /^-?\d{1,3}(,\d{3})+(\.\d+)?$/; // 1,200 / 12,500.50 / -3,000
32
+ const CURRENCY_NUM = /^[-+]?[$€£¥]\s?\d[\d,]*(\.\d+)?$/; // $1,200 / €980 / £12,500.50
33
+ const PERCENT_NUM = /^[-+]?\d[\d,]*(\.\d+)?\s*%$/; // 45% / 12.5% / 1,200%
34
+ const ACCOUNTING_NUM = /^\(\s?[$€£¥]?\s?\d[\d,]*(\.\d+)?\s?\)$/; // (1,234) / ($1,234.50) — parens = negative
35
+ // Boolean columns written inconsistently (Yes/Y/1/true vs No/N/0/false).
36
+ const BOOL_TRUE = new Set(['true', 't', 'yes', 'y', '1']);
37
+ const BOOL_FALSE = new Set(['false', 'f', 'no', 'n', '0']);
38
+ const canonBool = (v) => {
39
+ const k = v.trim().toLowerCase();
40
+ return BOOL_TRUE.has(k) ? 'true' : BOOL_FALSE.has(k) ? 'false' : null;
41
+ };
42
+ // Invisible dirt: leading/trailing whitespace, non-breaking/zero-width spaces,
43
+ // smart quotes, BOM — splits otherwise-identical values.
44
+ const DIRTY_WS = /^\s|\s$|[\u00A0\u200B\u2018\u2019\u201C\u201D\uFEFF]/; // NBSP, ZWSP, smart quotes, BOM
21
45
  function isNumericStr(s) {
22
46
  const t = s.trim();
23
47
  return t !== '' && !Number.isNaN(Number(t));
@@ -34,6 +58,29 @@ function looksLikeYear(col) {
34
58
  function isDatePartName(name) {
35
59
  return /(^|_)(month|months|hour|hours|minute|minutes|second|seconds|day|days|week|weeks|time|date)(_|$)/i.test(name);
36
60
  }
61
+ function classifyDateFmt(v) {
62
+ const s = v.trim();
63
+ if (/^\d{4}-\d{2}-\d{2}/.test(s))
64
+ return 'iso';
65
+ if (/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(s))
66
+ return 'us';
67
+ if (/^\d{1,2}\.\d{1,2}\.\d{4}$/.test(s))
68
+ return 'eu';
69
+ if (/^\d{1,2}\s+[A-Za-z]{3,}\s+\d{4}$/.test(s))
70
+ return 'text';
71
+ if (/^[A-Za-z]{3,}\s+\d{1,2},?\s+\d{4}$/.test(s))
72
+ return 'text';
73
+ return null;
74
+ }
75
+ function detectDateFormats(values) {
76
+ const found = new Set();
77
+ for (const v of values) {
78
+ const f = classifyDateFmt(v);
79
+ if (f)
80
+ found.add(f);
81
+ }
82
+ return found;
83
+ }
37
84
  /** Profile-based data-quality checks for one table's columns. */
38
85
  export function auditColumns(table, columns, rowCount) {
39
86
  const findings = [];
@@ -80,22 +127,128 @@ export function auditColumns(table, columns, rowCount) {
80
127
  add('low', col.name, 'numeric-text', `All-numeric values stored as text, with leading zeros (e.g. ${lz.join(', ')}).`, 'Fine for zero-padded codes (zip/SKU); just note numeric sort/compare on it is lexicographic.');
81
128
  }
82
129
  }
130
+ // ── Affinity trap: a string sentinel hiding in a NUMERIC column ──
131
+ // The inverse of the case above. When a column is mostly numeric, the CSV
132
+ // connector types it `numeric` and coerces non-numeric cells (e.g. "Undrafted")
133
+ // to NULL — so the auditor can't see them in samples/topValues. But that
134
+ // coercion is exactly what silently voids `WHERE col = 'Undrafted'` (it matches
135
+ // ZERO rows), producing a wrong count with no error. The connector reports the
136
+ // dominant coerced token; a RECURRING one (≥ COERCED_SENTINEL_MIN, so a lone
137
+ // typo doesn't trip) is a genuine sentinel, not noise.
138
+ if (col.type === 'numeric' && col.coercedNonNumeric && col.coercedNonNumeric.count >= COERCED_SENTINEL_MIN) {
139
+ const { token, count } = col.coercedNonNumeric;
140
+ add('high', col.name, 'mixed-type', `${count} cells hold a non-numeric value "${token}" that was coerced to NULL because the column is numeric.`, `It is a string sentinel, not a number. \`WHERE ${esc(col.name)} = '${token}'\` matches NOTHING (the value is gone) — count its rows on a TEXT column instead, e.g. another draft_* field, and treat it as missing when aggregating ${col.name}.`);
141
+ }
142
+ // ── Numbers stored as TEXT — thousands separators, a currency symbol, or a
143
+ // percent suffix ("1,200", "$12,500", "45%") ──
144
+ // dolex typed these categorical because the symbol defeats numeric parsing.
145
+ // SQLite then silently coerces them (SUM("$1,200")→0, "1,200"→1, "45%"→45 for
146
+ // AVG but lexicographic for ORDER BY/MAX), so totals/averages/ranking are wrong.
147
+ if ((col.type === 'categorical' || col.type === 'text') && typeProbe.length >= 2) {
148
+ const nt = classifyNumericText(typeProbe);
149
+ if (nt) {
150
+ add('high', col.name, nt.issue, `Values are ${nt.label} stored as text (e.g. ${nt.examples.join(', ')}).`, `${nt.harm} Convert before aggregating: ${nt.fix(esc(col.name))}.`);
151
+ }
152
+ }
153
+ // ── Same category split by case/whitespace ("Billing" vs "billing" vs "Billing ") ──
154
+ // Fragments GROUP BY so the true top category is undercounted and can lose.
155
+ // GUARD: only fire on a plausible GROUPING DIMENSION, not FREE TEXT. The
156
+ // discriminator is VALUE LENGTH, not cardinality (verified on real data: nba
157
+ // COMMENT has 5348 distinct values but avg ~22 chars and IS a real reason-code
158
+ // category whose case/pad split understates the top reason 35% → keep; ecommerce
159
+ // review_comment_message avg ~62 chars is free-text prose → skip). Cardinality is
160
+ // a red herring — a bounded code scheme can have thousands of distinct values.
161
+ // Use sampleValues (variety-picked, representative); topValues skew to short
162
+ // frequent tokens and would mask a free-text column's true length.
163
+ const catPool = [...new Set([...(col.topValues?.map((t) => String(t.value)) ?? []), ...samples])];
164
+ const lenPool = samples.length ? samples : catPool;
165
+ const avgValLen = lenPool.length ? lenPool.reduce((s, v) => s + v.length, 0) / lenPool.length : 0;
166
+ const looksFreeText = avgValLen > 45;
167
+ let dirtyCatFired = false;
168
+ if ((col.type === 'categorical' || col.type === 'text') && (col.topValues?.length ?? 0) >= 2 && !looksFreeText) {
169
+ const seen = new Map();
170
+ let collision;
171
+ for (const raw of catPool) {
172
+ const key = raw.trim().toLowerCase();
173
+ if (key === '')
174
+ continue;
175
+ const prev = seen.get(key);
176
+ if (prev !== undefined && prev !== raw) {
177
+ collision = [prev, raw];
178
+ break;
179
+ }
180
+ if (prev === undefined)
181
+ seen.set(key, raw);
182
+ }
183
+ if (collision) {
184
+ dirtyCatFired = true;
185
+ // Keep the TRIM(LOWER) remedy (correct for case/whitespace dirt), but when the
186
+ // column is high-cardinality, ADD a caveat that it won't canonicalize
187
+ // model-specific fragments (body: 87 distinct, "granturismo convertible") —
188
+ // REPLACING the remedy would strip it from legit high-card columns (cities).
189
+ // validated in experiments/013-dirty-categories-fragmentation (variant B).
190
+ const frag = (col.uniqueCount ?? 0) > 25
191
+ ? ` Note ${col.uniqueCount} distinct values — if many are sub-types/model-specific, TRIM(LOWER) won't canonicalize them; map to a controlled vocabulary.`
192
+ : '';
193
+ add('medium', col.name, 'dirty-categories', `Values differ only by case/whitespace and are counted as separate categories (e.g. "${collision[0]}" vs "${collision[1]}").`, `They split one logical category across rows, distorting counts and the top category. Normalize: GROUP BY TRIM(LOWER(${esc(col.name)})).${frag}`);
194
+ }
195
+ }
196
+ // ── Boolean column written inconsistently (Yes/Y/1 vs No/N/0/true/false) ──
197
+ // Same true/false data in mixed encodings splits filters and groupings. Gate
198
+ // on an ALPHABETIC form present so a pure numeric 1/0 column isn't swept in.
199
+ if ((col.type === 'categorical' || col.type === 'text')) {
200
+ const boolForms = [...new Set(catPool.map((v) => v.trim()).filter((v) => v !== ''))];
201
+ if (boolForms.length >= 2 && boolForms.length <= 8) {
202
+ const canon = boolForms.map(canonBool);
203
+ const allBool = canon.every((c) => c !== null);
204
+ const hasAlpha = boolForms.some((v) => /[a-z]/i.test(v));
205
+ const distinctCanon = new Set(canon).size;
206
+ if (allBool && hasAlpha && boolForms.length > distinctCanon) {
207
+ add('low', col.name, 'boolean-variants', `Boolean column with inconsistent encodings (e.g. ${boolForms.slice(0, 3).map((v) => `"${v}"`).join(', ')}).`, 'These are the same true/false values written differently — they split filters and GROUP BY. Canonicalize to one form.');
208
+ }
209
+ }
210
+ }
211
+ // ── Invisible dirt: whitespace / non-standard unicode in string values ──
212
+ // Skipped when dirty-categories already fired (its TRIM(LOWER) remedy covers
213
+ // the same column, and the two fixes would otherwise conflict).
214
+ if ((col.type === 'categorical' || col.type === 'text') && !dirtyCatFired) {
215
+ const dirty = catPool.find((v) => v !== '' && DIRTY_WS.test(v));
216
+ if (dirty !== undefined) {
217
+ add('low', col.name, 'dirty-whitespace', `Values carry leading/trailing whitespace or non-standard characters (e.g. ${JSON.stringify(dirty)}).`, 'Invisible differences split otherwise-identical values; TRIM and normalize unicode (NBSP, zero-width, smart quotes).');
218
+ }
219
+ }
83
220
  // ── Missing-value sentinels hiding in categorical data ──
84
221
  const valuePool = (col.topValues?.map((t) => String(t.value)) ?? []).concat(samples);
85
222
  const sentinel = valuePool.find((v) => SENTINELS.has(v.trim().toLowerCase()));
86
223
  if (sentinel !== undefined && col.type !== 'numeric') {
87
224
  add('medium', col.name, 'sentinel-value', `Contains a likely missing-value sentinel: "${sentinel}".`, 'These read as real categories — they inflate counts and skew group analysis. Treat as null.');
88
225
  }
89
- // ── Numeric outliers (advisory) ──
226
+ // ── Numeric outliers + sentinel magic-numbers (the silent-wrong class) ──
227
+ // A magic number (−999, 9999999, …) is treated as a sentinel ONLY when it is
228
+ // also a genuine FAR outlier (beyond the 3×IQR fence) — NOT merely beyond
229
+ // p25/p75 (every min/max is, so that gate was a no-op and would flag a real
230
+ // top value like 99999). Both tails are checked, so a column poisoned at both
231
+ // ends reports both.
90
232
  if (col.type === 'numeric' && col.stats) {
91
233
  const { min, max, p25, p75 } = col.stats;
92
234
  const iqr = p75 - p25;
235
+ const extremes = [];
93
236
  if (iqr > 0) {
94
- const upper = p75 + 3 * iqr;
95
- const lower = p25 - 3 * iqr;
96
- if (max > upper || min < lower) {
97
- add('low', col.name, 'outliers', `Extreme values beyond 3×IQR (range ${fmt(min)}…${fmt(max)}, p25–p75 ${fmt(p25)}…${fmt(p75)}).`, 'Verify they are genuine, not data-entry errors or missing-as-extreme.');
98
- }
237
+ if (min < p25 - 3 * iqr)
238
+ extremes.push(min);
239
+ if (max > p75 + 3 * iqr)
240
+ extremes.push(max);
241
+ }
242
+ const sentinels = extremes.filter(isSentinelNumber);
243
+ for (const s of sentinels) {
244
+ add('high', col.name, 'sentinel-value', `Extreme value ${fmt(s)} is a classic missing-value sentinel, not real data (a far outlier vs p25–p75 ${fmt(p25)}…${fmt(p75)}).`,
245
+ // Scope the exclusion: it poisons statistics OF this column, but the row
246
+ // still exists — over-excluding it from total counts gives 99,999 not
247
+ // 100,000. Only filter it when computing this column's own aggregates.
248
+ `When computing a statistic OF ${col.name} (its AVG/SUM/MIN/MAX/MEDIAN), exclude it: WHERE ${esc(col.name)} <> ${s}. It is still a real row — do NOT drop it from total row COUNTs or other columns' analysis.`);
249
+ }
250
+ if (sentinels.length === 0 && extremes.length > 0) {
251
+ add('low', col.name, 'outliers', `Extreme values beyond 3×IQR (range ${fmt(min)}…${fmt(max)}, p25–p75 ${fmt(p25)}…${fmt(p75)}).`, 'Verify they are genuine, not data-entry errors or missing-as-extreme.');
99
252
  }
100
253
  // Zeros where a measurement should be positive (e.g. diamonds x/y/z = 0).
101
254
  if (min === 0 && /(^|_)(x|y|z|width|height|depth|length|weight|price|diameter|size)(_|$)/i.test(col.name)) {
@@ -116,12 +269,33 @@ export function auditColumns(table, columns, rowCount) {
116
269
  if (col.type === 'date' && looksLikeYear(col)) {
117
270
  add('low', col.name, 'year-column', `Holds 4-digit years, not full dates.`, 'Group by it directly — do not apply month/day date math (strftime) to it.');
118
271
  }
119
- // ── Non-ISO date columns (time-series footgun) ──
272
+ // ── Non-ISO / mixed date formats (time-series footgun) ──
273
+ // Use topValues (frequency-ranked) NOT sampleValues — the first N rows of a CSV
274
+ // are often format-homogeneous (e.g. all ISO), so sampleValues misses the tail.
120
275
  if (col.type === 'date' && !looksLikeYear(col)) {
121
- const dvals = samples;
122
- const nonIso = dvals.filter((v) => !/^\d{4}-\d{2}-\d{2}/.test(v));
123
- if (dvals.length >= 3 && nonIso.length > 0) {
124
- add('medium', col.name, 'non-iso-date', `Looks like dates but not ISO YYYY-MM-DD (e.g. ${nonIso.slice(0, 2).join(', ')}).`, 'Time bucketing (strftime) only parses ISO — non-ISO dates collapse to NULL, so analyze skips the trend. Reformat to YYYY-MM-DD for time-series analysis.');
276
+ const topVals = (col.topValues ?? []).map((t) => String(t.value)).filter(Boolean);
277
+ const dateProbe = [...new Set([...samples, ...topVals])].filter(Boolean);
278
+ if (dateProbe.length >= 3) {
279
+ const formats = detectDateFormats(dateProbe);
280
+ if (formats.size >= 2) {
281
+ // Multiple incompatible formats in the same column — HIGH, and prompt-worthy.
282
+ // strftime + BETWEEN silently discard non-ISO rows; the model must normalize first.
283
+ const examples = [];
284
+ for (const fmt of formats) {
285
+ const ex = dateProbe.find((v) => classifyDateFmt(v) === fmt);
286
+ if (ex)
287
+ examples.push(`"${ex}" (${fmt})`);
288
+ }
289
+ add('high', col.name, 'mixed-date-format', `Column has ${formats.size} incompatible date formats: ${examples.join(', ')}.`, `strftime/BETWEEN silently ignore non-ISO rows — ISO rows only are counted. Normalize to YYYY-MM-DD with a clean() function before filtering or aggregating by date.`);
290
+ }
291
+ else {
292
+ // Single non-ISO format — keep existing MEDIUM advisory (not prompt-worthy,
293
+ // but surfaced in `dolex check` for awareness).
294
+ const nonIso = dateProbe.filter((v) => !/^\d{4}-\d{2}-\d{2}/.test(v));
295
+ if (nonIso.length > 0) {
296
+ add('medium', col.name, 'non-iso-date', `Looks like dates but not ISO YYYY-MM-DD (e.g. ${nonIso.slice(0, 2).join(', ')}).`, 'Time bucketing (strftime) only parses ISO — non-ISO dates collapse to NULL, so analyze skips the trend. Reformat to YYYY-MM-DD for time-series analysis.');
297
+ }
298
+ }
125
299
  }
126
300
  }
127
301
  }
@@ -132,3 +306,204 @@ function fmt(n) {
132
306
  return String(n);
133
307
  return Number.isInteger(n) ? String(n) : n.toFixed(2);
134
308
  }
309
+ /** True for magic numbers that are almost always "missing" — the curated set
310
+ * PLUS any repunit-9 of length ≥3 (999, 9999, …, 9999999, and negatives), so a
311
+ * fixed list can't be evaded by simply using more 9s. */
312
+ function isSentinelNumber(v) {
313
+ if (!Number.isFinite(v))
314
+ return false;
315
+ return NUMERIC_SENTINELS.has(v) || /^9{3,}$/.test(String(Math.abs(v)));
316
+ }
317
+ /** Classify a categorical column whose values are really numbers wearing a text
318
+ * costume: thousands separators, a currency symbol, or a percent suffix. Returns
319
+ * the dominant kind (≥60% of probe values) with a tailored, NON-destructive fix,
320
+ * or null. Order matters: currency/percent before bare separators. */
321
+ function classifyNumericText(probe) {
322
+ const vals = probe.map((v) => v.trim()).filter((v) => v !== '');
323
+ if (vals.length < 2)
324
+ return null;
325
+ const frac = (xs) => xs.length / vals.length;
326
+ // Accounting negatives first — "(1,234)" matches neither currency nor sep, but
327
+ // it IS a number (a negative one), and missing it loses the sign silently.
328
+ const accounting = vals.filter((v) => ACCOUNTING_NUM.test(v));
329
+ if (frac(accounting) >= 0.6)
330
+ return {
331
+ issue: 'numeric-text-parens', label: 'accounting-style negatives', examples: accounting.slice(0, 2),
332
+ harm: 'SQLite reads "(1,234)" as 0 and loses the negative sign — SUM/AVG/ORDER BY are silently wrong.',
333
+ fix: (c) => `CASE WHEN ${c} LIKE '(%' THEN -CAST(REPLACE(REPLACE(REPLACE(${c}, '(', ''), ')', ''), ',', '') AS REAL) ELSE CAST(REPLACE(${c}, ',', '') AS REAL) END`,
334
+ };
335
+ const currency = vals.filter((v) => CURRENCY_NUM.test(v));
336
+ if (frac(currency) >= 0.6) {
337
+ // Tailor the fix to the ACTUAL symbol present → a 2-REPLACE expression the
338
+ // model can reproduce reliably (a blanket 4-deep nest gets its parens garbled).
339
+ const sym = (currency[0].match(/[$€£¥]/) ?? ['$'])[0];
340
+ return {
341
+ issue: 'numeric-text-symbol', label: 'currency amounts', examples: currency.slice(0, 2),
342
+ harm: `SQLite reads "${sym}1,200" as 0 — SUM/AVG/ORDER BY are silently wrong.`,
343
+ fix: (c) => `CAST(REPLACE(REPLACE(${c}, '${sym}', ''), ',', '') AS REAL)`,
344
+ };
345
+ }
346
+ const percent = vals.filter((v) => PERCENT_NUM.test(v));
347
+ if (frac(percent) >= 0.6)
348
+ return {
349
+ issue: 'numeric-text-symbol', label: 'percentages', examples: percent.slice(0, 2),
350
+ harm: 'The "%" makes the value text — ORDER BY/MAX are lexicographic, and it is not a usable number.',
351
+ fix: (c) => `CAST(REPLACE(${c}, '%', '') AS REAL)`,
352
+ };
353
+ const sep = vals.filter((v) => THOUSANDS_NUM.test(v));
354
+ if (sep.length >= 2 && frac(sep) >= 0.6)
355
+ return {
356
+ issue: 'numeric-text-separators', label: 'numbers with thousands separators', examples: sep.slice(0, 2),
357
+ harm: 'SQLite reads "1,200" as 1 — SUM/AVG/ORDER BY are silently wrong.',
358
+ fix: (c) => `CAST(REPLACE(${c}, ',', '') AS REAL)`,
359
+ };
360
+ return null;
361
+ }
362
+ const MAX_DUP_ROWS_SCAN = 500_000; // skip the full-table distinct scan above this
363
+ const MAX_IDENTICAL_PAIRS = 80; // bound the pairwise identical-column comparison
364
+ function esc(name) {
365
+ return `"${name.replace(/"/g, '""')}"`;
366
+ }
367
+ function pct(n, total) {
368
+ return total > 0 ? `${((n / total) * 100).toFixed(1)}%` : '0%';
369
+ }
370
+ export async function tableLevelChecks(t, query) {
371
+ const out = [];
372
+ // Duplicate rows (skip very large tables to bound cost).
373
+ if (t.rowCount > 0 && t.rowCount <= MAX_DUP_ROWS_SCAN) {
374
+ const res = await query(`SELECT (SELECT COUNT(*) FROM ${esc(t.name)}) - (SELECT COUNT(*) FROM (SELECT DISTINCT * FROM ${esc(t.name)})) AS dups`);
375
+ const dups = res.ok && res.rows && res.rows[0] ? Number(res.rows[0].dups) : NaN;
376
+ if (!res.ok || !Number.isFinite(dups)) {
377
+ out.push({
378
+ severity: 'high', table: t.name, issue: 'check-incomplete',
379
+ detail: `Duplicate-row check could not complete${res.ok ? '' : `: ${res.error}`}.`,
380
+ suggestion: 'The audit is incomplete — do not trust a clean result; re-run.',
381
+ });
382
+ }
383
+ else if (dups > 0) {
384
+ out.push({
385
+ severity: 'medium', table: t.name, issue: 'duplicate-rows',
386
+ detail: `${dups} fully-duplicate row${dups === 1 ? '' : 's'} (${pct(dups, t.rowCount)} of the table).`,
387
+ suggestion: 'Verify these are real repeats, not a double-load or join fan-out. COUNT(*) over-counts; use COUNT(DISTINCT …) or SELECT DISTINCT.',
388
+ });
389
+ }
390
+ }
391
+ // Identical (redundant/leaked) columns: only compare columns that already share
392
+ // type + cardinality + null count, so the pairwise scan stays cheap.
393
+ const groups = new Map();
394
+ for (const c of t.columns) {
395
+ const key = `${c.type}|${c.uniqueCount}|${c.nullCount}`;
396
+ const arr = groups.get(key);
397
+ if (arr)
398
+ arr.push(c);
399
+ else
400
+ groups.set(key, [c]);
401
+ }
402
+ let comparisons = 0;
403
+ for (const group of groups.values()) {
404
+ if (group.length < 2)
405
+ continue;
406
+ for (let i = 0; i < group.length; i++) {
407
+ for (let j = i + 1; j < group.length; j++) {
408
+ if (comparisons++ >= MAX_IDENTICAL_PAIRS)
409
+ break;
410
+ const a = group[i].name;
411
+ const b = group[j].name;
412
+ const res = await query(`SELECT COUNT(*) AS diff FROM ${esc(t.name)} WHERE ${esc(a)} IS NOT ${esc(b)}`);
413
+ const diff = res.ok && res.rows && res.rows[0] ? Number(res.rows[0].diff) : NaN;
414
+ if (!res.ok || !Number.isFinite(diff)) {
415
+ out.push({
416
+ severity: 'high', table: t.name, column: `${a} vs ${b}`, issue: 'check-incomplete',
417
+ detail: `Could not compare columns "${a}" and "${b}"${res.ok ? '' : `: ${res.error}`}.`,
418
+ suggestion: 'The audit is incomplete — do not trust a clean result; re-run.',
419
+ });
420
+ }
421
+ else if (diff === 0) {
422
+ out.push({
423
+ severity: 'high', table: t.name, column: `${a} = ${b}`, issue: 'identical-columns',
424
+ detail: `Columns "${a}" and "${b}" are identical on every row.`,
425
+ suggestion: 'Redundant or leaked feature — a model/analysis "predicting" one just reads the other. Drop one.',
426
+ });
427
+ }
428
+ }
429
+ }
430
+ }
431
+ return out;
432
+ }
433
+ /** The full audit: profile checks + table-level checks, over every table. The ONE
434
+ * entry point both the CLI `check` command and the analysis loop call. */
435
+ export async function auditDataset(tables, query) {
436
+ const findings = [];
437
+ for (const t of tables) {
438
+ findings.push(...auditColumns(t.name, t.columns, t.rowCount));
439
+ findings.push(...(await tableLevelChecks(t, query)));
440
+ }
441
+ return findings;
442
+ }
443
+ const SEV_RANK = { high: 0, medium: 1, low: 2 };
444
+ // Only ACTION-GUIDING issues go into the LLM prompt — the ones that silently
445
+ // corrupt a number and have a concrete SQL fix. Advisory findings (mostly-null,
446
+ // non-iso-date, constant, outliers, id-like, …) are real and stay in the full
447
+ // audit / `dolex check`, but injecting them just bloats the prompt and DISTRACTS
448
+ // the model on unrelated questions (measured: f1's 21 mostly-null + 12 non-iso
449
+ // findings dragged a clean "most wins" query off its correct answer). Keep this
450
+ // list tight — every line added is a line that competes with the user's question.
451
+ const PROMPT_WORTHY_ISSUES = new Set([
452
+ 'numeric-text-symbol', 'numeric-text-separators', 'mixed-type', // type traps
453
+ 'mixed-date-format', // ≥2 incompatible date formats — strftime silently drops non-ISO rows
454
+ 'sentinel-value', // missing-value markers that poison aggregates
455
+ 'dirty-categories', // case/space splits that change the GROUP BY winner
456
+ 'duplicate-rows', // inflate counts
457
+ 'identical-columns', // leaked/redundant column
458
+ 'check-incomplete', // a check could not run — never hide that
459
+ ]);
460
+ /** Compact, ACTION-GUIDING summary for injection into an LLM system prompt. Filters
461
+ * to the silent-wrong-number issues (PROMPT_WORTHY_ISSUES), collapses repeats of
462
+ * the same issue into ONE line (13 "NULL" sentinel columns → one line, not 13),
463
+ * and caps tightly. '' if nothing actionable. The full audit still lives in
464
+ * `session.audit` / `dolex check`. */
465
+ export function formatAuditForPrompt(findings, maxLines = 5) {
466
+ const worthy = findings
467
+ .filter((f) => f.severity !== 'low' && PROMPT_WORTHY_ISSUES.has(f.issue))
468
+ .sort((a, b) => SEV_RANK[a.severity] - SEV_RANK[b.severity]);
469
+ if (worthy.length === 0)
470
+ return '';
471
+ // Group by issue, preserving severity-sorted order, to collapse repeats.
472
+ const byIssue = new Map();
473
+ for (const f of worthy) {
474
+ const arr = byIssue.get(f.issue);
475
+ if (arr)
476
+ arr.push(f);
477
+ else
478
+ byIssue.set(f.issue, [f]);
479
+ }
480
+ const lines = [];
481
+ for (const [, group] of byIssue) {
482
+ if (lines.length >= maxLines)
483
+ break;
484
+ const f = group[0];
485
+ const sev = `[${f.severity.toUpperCase()}]`;
486
+ if (group.length === 1) {
487
+ lines.push(`• ${sev} ${f.column ? f.column + ': ' : ''}${f.detail}${f.suggestion ? ' → ' + f.suggestion : ''}`);
488
+ }
489
+ else {
490
+ // Collapse: one line for the shared issue + the shared fix. Count and noun
491
+ // are driven by the COLUMN-BEARING findings (a column-less finding like
492
+ // duplicate-rows must not be counted as a "column" or padded into "+N more").
493
+ const ids = group.map((g) => g.column).filter((c) => Boolean(c));
494
+ const suffix = f.suggestion ? ' → ' + f.suggestion : '';
495
+ if (ids.length > 0) {
496
+ const more = ids.length > 6 ? `, +${ids.length - 6} more` : '';
497
+ lines.push(`• ${sev} ${ids.length} columns with ${f.issue} (${ids.slice(0, 6).join(', ')}${more})${suffix}`);
498
+ }
499
+ else {
500
+ lines.push(`• ${sev} ${group.length} ${f.issue} findings${suffix}`);
501
+ }
502
+ }
503
+ }
504
+ const shown = lines.length;
505
+ const issuesTotal = byIssue.size;
506
+ if (issuesTotal > shown)
507
+ lines.push(`• …and ${issuesTotal - shown} more issue type(s).`);
508
+ return lines.join('\n');
509
+ }
@@ -21,8 +21,28 @@ export declare function isIsoDateColumn(col: ClassifiedColumn): boolean;
21
21
  * date column — we'd rather skip the trend than ship strftime SQL that silently
22
22
  * produces a single NULL bucket summing the whole table.
23
23
  */
24
- export declare function timeBucketing(col: ClassifiedColumn): {
24
+ /** SQL flavor for planner-generated date/time SQL. */
25
+ export type PlannerDialect = 'sqlite' | 'postgres';
26
+ /**
27
+ * Raised when analysis-plan generation is asked to run against a source whose
28
+ * query paradigm the planner can't emit. The planner produces SELECT SQL, so a
29
+ * document store (mongodb → aggregation pipeline) is REFUSED here rather than
30
+ * silently handed SQLite SQL — the caller surfaces `message` as a clean error.
31
+ */
32
+ export declare class PlannerUnsupportedSourceError extends Error {
33
+ readonly sourceType: string;
34
+ constructor(sourceType: string, message: string);
35
+ }
36
+ /**
37
+ * Resolve a registered source's `type` to the SQL flavor the planner emits.
38
+ * The ONE place source-type → planner-dialect is decided, so no call site
39
+ * re-derives it with a `type === 'postgres' ? …` ternary that silently maps an
40
+ * unrecognized (e.g. mongodb) source to SQLite. csv/undefined → sqlite,
41
+ * postgres → postgres; a pipeline source (mongodb) or unknown type THROWS.
42
+ */
43
+ export declare function plannerDialectForSource(type: string | undefined): PlannerDialect;
44
+ export declare function timeBucketing(col: ClassifiedColumn, dialect?: PlannerDialect): {
25
45
  label: string;
26
46
  expr: string;
27
47
  } | null;
28
- export declare function generateCandidates(columns: ClassifiedColumn[], table: string): AnalysisStep[];
48
+ export declare function generateCandidates(columns: ClassifiedColumn[], table: string, dialect?: PlannerDialect): AnalysisStep[];