@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
@@ -18,6 +18,19 @@ 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%
21
34
  function isNumericStr(s) {
22
35
  const t = s.trim();
23
36
  return t !== '' && !Number.isNaN(Number(t));
@@ -80,22 +93,102 @@ export function auditColumns(table, columns, rowCount) {
80
93
  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
94
  }
82
95
  }
96
+ // ── Affinity trap: a string sentinel hiding in a NUMERIC column ──
97
+ // The inverse of the case above. When a column is mostly numeric, the CSV
98
+ // connector types it `numeric` and coerces non-numeric cells (e.g. "Undrafted")
99
+ // to NULL — so the auditor can't see them in samples/topValues. But that
100
+ // coercion is exactly what silently voids `WHERE col = 'Undrafted'` (it matches
101
+ // ZERO rows), producing a wrong count with no error. The connector reports the
102
+ // dominant coerced token; a RECURRING one (≥ COERCED_SENTINEL_MIN, so a lone
103
+ // typo doesn't trip) is a genuine sentinel, not noise.
104
+ if (col.type === 'numeric' && col.coercedNonNumeric && col.coercedNonNumeric.count >= COERCED_SENTINEL_MIN) {
105
+ const { token, count } = col.coercedNonNumeric;
106
+ 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}.`);
107
+ }
108
+ // ── Numbers stored as TEXT — thousands separators, a currency symbol, or a
109
+ // percent suffix ("1,200", "$12,500", "45%") ──
110
+ // dolex typed these categorical because the symbol defeats numeric parsing.
111
+ // SQLite then silently coerces them (SUM("$1,200")→0, "1,200"→1, "45%"→45 for
112
+ // AVG but lexicographic for ORDER BY/MAX), so totals/averages/ranking are wrong.
113
+ if ((col.type === 'categorical' || col.type === 'text') && typeProbe.length >= 2) {
114
+ const nt = classifyNumericText(typeProbe);
115
+ if (nt) {
116
+ 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))}.`);
117
+ }
118
+ }
119
+ // ── Same category split by case/whitespace ("Billing" vs "billing" vs "Billing ") ──
120
+ // Fragments GROUP BY so the true top category is undercounted and can lose.
121
+ // GUARD: only fire on a plausible GROUPING DIMENSION, not FREE TEXT. The
122
+ // discriminator is VALUE LENGTH, not cardinality (verified on real data: nba
123
+ // COMMENT has 5348 distinct values but avg ~22 chars and IS a real reason-code
124
+ // category whose case/pad split understates the top reason 35% → keep; ecommerce
125
+ // review_comment_message avg ~62 chars is free-text prose → skip). Cardinality is
126
+ // a red herring — a bounded code scheme can have thousands of distinct values.
127
+ // Use sampleValues (variety-picked, representative); topValues skew to short
128
+ // frequent tokens and would mask a free-text column's true length.
129
+ const catPool = [...new Set([...(col.topValues?.map((t) => String(t.value)) ?? []), ...samples])];
130
+ const lenPool = samples.length ? samples : catPool;
131
+ const avgValLen = lenPool.length ? lenPool.reduce((s, v) => s + v.length, 0) / lenPool.length : 0;
132
+ const looksFreeText = avgValLen > 45;
133
+ if ((col.type === 'categorical' || col.type === 'text') && (col.topValues?.length ?? 0) >= 2 && !looksFreeText) {
134
+ const seen = new Map();
135
+ let collision;
136
+ for (const raw of catPool) {
137
+ const key = raw.trim().toLowerCase();
138
+ if (key === '')
139
+ continue;
140
+ const prev = seen.get(key);
141
+ if (prev !== undefined && prev !== raw) {
142
+ collision = [prev, raw];
143
+ break;
144
+ }
145
+ if (prev === undefined)
146
+ seen.set(key, raw);
147
+ }
148
+ if (collision) {
149
+ // Keep the TRIM(LOWER) remedy (correct for case/whitespace dirt), but when the
150
+ // column is high-cardinality, ADD a caveat that it won't canonicalize
151
+ // model-specific fragments (body: 87 distinct, "granturismo convertible") —
152
+ // REPLACING the remedy would strip it from legit high-card columns (cities).
153
+ // validated in experiments/013-dirty-categories-fragmentation (variant B).
154
+ const frag = (col.uniqueCount ?? 0) > 25
155
+ ? ` Note ${col.uniqueCount} distinct values — if many are sub-types/model-specific, TRIM(LOWER) won't canonicalize them; map to a controlled vocabulary.`
156
+ : '';
157
+ 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}`);
158
+ }
159
+ }
83
160
  // ── Missing-value sentinels hiding in categorical data ──
84
161
  const valuePool = (col.topValues?.map((t) => String(t.value)) ?? []).concat(samples);
85
162
  const sentinel = valuePool.find((v) => SENTINELS.has(v.trim().toLowerCase()));
86
163
  if (sentinel !== undefined && col.type !== 'numeric') {
87
164
  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
165
  }
89
- // ── Numeric outliers (advisory) ──
166
+ // ── Numeric outliers + sentinel magic-numbers (the silent-wrong class) ──
167
+ // A magic number (−999, 9999999, …) is treated as a sentinel ONLY when it is
168
+ // also a genuine FAR outlier (beyond the 3×IQR fence) — NOT merely beyond
169
+ // p25/p75 (every min/max is, so that gate was a no-op and would flag a real
170
+ // top value like 99999). Both tails are checked, so a column poisoned at both
171
+ // ends reports both.
90
172
  if (col.type === 'numeric' && col.stats) {
91
173
  const { min, max, p25, p75 } = col.stats;
92
174
  const iqr = p75 - p25;
175
+ const extremes = [];
93
176
  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
- }
177
+ if (min < p25 - 3 * iqr)
178
+ extremes.push(min);
179
+ if (max > p75 + 3 * iqr)
180
+ extremes.push(max);
181
+ }
182
+ const sentinels = extremes.filter(isSentinelNumber);
183
+ for (const s of sentinels) {
184
+ 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)}).`,
185
+ // Scope the exclusion: it poisons statistics OF this column, but the row
186
+ // still exists — over-excluding it from total counts gives 99,999 not
187
+ // 100,000. Only filter it when computing this column's own aggregates.
188
+ `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.`);
189
+ }
190
+ if (sentinels.length === 0 && extremes.length > 0) {
191
+ 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
192
  }
100
193
  // Zeros where a measurement should be positive (e.g. diamonds x/y/z = 0).
101
194
  if (min === 0 && /(^|_)(x|y|z|width|height|depth|length|weight|price|diameter|size)(_|$)/i.test(col.name)) {
@@ -132,3 +225,194 @@ function fmt(n) {
132
225
  return String(n);
133
226
  return Number.isInteger(n) ? String(n) : n.toFixed(2);
134
227
  }
228
+ /** True for magic numbers that are almost always "missing" — the curated set
229
+ * PLUS any repunit-9 of length ≥3 (999, 9999, …, 9999999, and negatives), so a
230
+ * fixed list can't be evaded by simply using more 9s. */
231
+ function isSentinelNumber(v) {
232
+ if (!Number.isFinite(v))
233
+ return false;
234
+ return NUMERIC_SENTINELS.has(v) || /^9{3,}$/.test(String(Math.abs(v)));
235
+ }
236
+ /** Classify a categorical column whose values are really numbers wearing a text
237
+ * costume: thousands separators, a currency symbol, or a percent suffix. Returns
238
+ * the dominant kind (≥60% of probe values) with a tailored, NON-destructive fix,
239
+ * or null. Order matters: currency/percent before bare separators. */
240
+ function classifyNumericText(probe) {
241
+ const vals = probe.map((v) => v.trim()).filter((v) => v !== '');
242
+ if (vals.length < 2)
243
+ return null;
244
+ const frac = (xs) => xs.length / vals.length;
245
+ const currency = vals.filter((v) => CURRENCY_NUM.test(v));
246
+ if (frac(currency) >= 0.6) {
247
+ // Tailor the fix to the ACTUAL symbol present → a 2-REPLACE expression the
248
+ // model can reproduce reliably (a blanket 4-deep nest gets its parens garbled).
249
+ const sym = (currency[0].match(/[$€£¥]/) ?? ['$'])[0];
250
+ return {
251
+ issue: 'numeric-text-symbol', label: 'currency amounts', examples: currency.slice(0, 2),
252
+ harm: `SQLite reads "${sym}1,200" as 0 — SUM/AVG/ORDER BY are silently wrong.`,
253
+ fix: (c) => `CAST(REPLACE(REPLACE(${c}, '${sym}', ''), ',', '') AS REAL)`,
254
+ };
255
+ }
256
+ const percent = vals.filter((v) => PERCENT_NUM.test(v));
257
+ if (frac(percent) >= 0.6)
258
+ return {
259
+ issue: 'numeric-text-symbol', label: 'percentages', examples: percent.slice(0, 2),
260
+ harm: 'The "%" makes the value text — ORDER BY/MAX are lexicographic, and it is not a usable number.',
261
+ fix: (c) => `CAST(REPLACE(${c}, '%', '') AS REAL)`,
262
+ };
263
+ const sep = vals.filter((v) => THOUSANDS_NUM.test(v));
264
+ if (sep.length >= 2 && frac(sep) >= 0.6)
265
+ return {
266
+ issue: 'numeric-text-separators', label: 'numbers with thousands separators', examples: sep.slice(0, 2),
267
+ harm: 'SQLite reads "1,200" as 1 — SUM/AVG/ORDER BY are silently wrong.',
268
+ fix: (c) => `CAST(REPLACE(${c}, ',', '') AS REAL)`,
269
+ };
270
+ return null;
271
+ }
272
+ const MAX_DUP_ROWS_SCAN = 500_000; // skip the full-table distinct scan above this
273
+ const MAX_IDENTICAL_PAIRS = 80; // bound the pairwise identical-column comparison
274
+ function esc(name) {
275
+ return `"${name.replace(/"/g, '""')}"`;
276
+ }
277
+ function pct(n, total) {
278
+ return total > 0 ? `${((n / total) * 100).toFixed(1)}%` : '0%';
279
+ }
280
+ export async function tableLevelChecks(t, query) {
281
+ const out = [];
282
+ // Duplicate rows (skip very large tables to bound cost).
283
+ if (t.rowCount > 0 && t.rowCount <= MAX_DUP_ROWS_SCAN) {
284
+ const res = await query(`SELECT (SELECT COUNT(*) FROM ${esc(t.name)}) - (SELECT COUNT(*) FROM (SELECT DISTINCT * FROM ${esc(t.name)})) AS dups`);
285
+ const dups = res.ok && res.rows && res.rows[0] ? Number(res.rows[0].dups) : NaN;
286
+ if (!res.ok || !Number.isFinite(dups)) {
287
+ out.push({
288
+ severity: 'high', table: t.name, issue: 'check-incomplete',
289
+ detail: `Duplicate-row check could not complete${res.ok ? '' : `: ${res.error}`}.`,
290
+ suggestion: 'The audit is incomplete — do not trust a clean result; re-run.',
291
+ });
292
+ }
293
+ else if (dups > 0) {
294
+ out.push({
295
+ severity: 'medium', table: t.name, issue: 'duplicate-rows',
296
+ detail: `${dups} fully-duplicate row${dups === 1 ? '' : 's'} (${pct(dups, t.rowCount)} of the table).`,
297
+ suggestion: 'Verify these are real repeats, not a double-load or join fan-out. COUNT(*) over-counts; use COUNT(DISTINCT …) or SELECT DISTINCT.',
298
+ });
299
+ }
300
+ }
301
+ // Identical (redundant/leaked) columns: only compare columns that already share
302
+ // type + cardinality + null count, so the pairwise scan stays cheap.
303
+ const groups = new Map();
304
+ for (const c of t.columns) {
305
+ const key = `${c.type}|${c.uniqueCount}|${c.nullCount}`;
306
+ const arr = groups.get(key);
307
+ if (arr)
308
+ arr.push(c);
309
+ else
310
+ groups.set(key, [c]);
311
+ }
312
+ let comparisons = 0;
313
+ for (const group of groups.values()) {
314
+ if (group.length < 2)
315
+ continue;
316
+ for (let i = 0; i < group.length; i++) {
317
+ for (let j = i + 1; j < group.length; j++) {
318
+ if (comparisons++ >= MAX_IDENTICAL_PAIRS)
319
+ break;
320
+ const a = group[i].name;
321
+ const b = group[j].name;
322
+ const res = await query(`SELECT COUNT(*) AS diff FROM ${esc(t.name)} WHERE ${esc(a)} IS NOT ${esc(b)}`);
323
+ const diff = res.ok && res.rows && res.rows[0] ? Number(res.rows[0].diff) : NaN;
324
+ if (!res.ok || !Number.isFinite(diff)) {
325
+ out.push({
326
+ severity: 'high', table: t.name, column: `${a} vs ${b}`, issue: 'check-incomplete',
327
+ detail: `Could not compare columns "${a}" and "${b}"${res.ok ? '' : `: ${res.error}`}.`,
328
+ suggestion: 'The audit is incomplete — do not trust a clean result; re-run.',
329
+ });
330
+ }
331
+ else if (diff === 0) {
332
+ out.push({
333
+ severity: 'high', table: t.name, column: `${a} = ${b}`, issue: 'identical-columns',
334
+ detail: `Columns "${a}" and "${b}" are identical on every row.`,
335
+ suggestion: 'Redundant or leaked feature — a model/analysis "predicting" one just reads the other. Drop one.',
336
+ });
337
+ }
338
+ }
339
+ }
340
+ }
341
+ return out;
342
+ }
343
+ /** The full audit: profile checks + table-level checks, over every table. The ONE
344
+ * entry point both the CLI `check` command and the analysis loop call. */
345
+ export async function auditDataset(tables, query) {
346
+ const findings = [];
347
+ for (const t of tables) {
348
+ findings.push(...auditColumns(t.name, t.columns, t.rowCount));
349
+ findings.push(...(await tableLevelChecks(t, query)));
350
+ }
351
+ return findings;
352
+ }
353
+ const SEV_RANK = { high: 0, medium: 1, low: 2 };
354
+ // Only ACTION-GUIDING issues go into the LLM prompt — the ones that silently
355
+ // corrupt a number and have a concrete SQL fix. Advisory findings (mostly-null,
356
+ // non-iso-date, constant, outliers, id-like, …) are real and stay in the full
357
+ // audit / `dolex check`, but injecting them just bloats the prompt and DISTRACTS
358
+ // the model on unrelated questions (measured: f1's 21 mostly-null + 12 non-iso
359
+ // findings dragged a clean "most wins" query off its correct answer). Keep this
360
+ // list tight — every line added is a line that competes with the user's question.
361
+ const PROMPT_WORTHY_ISSUES = new Set([
362
+ 'numeric-text-symbol', 'numeric-text-separators', 'mixed-type', // type traps
363
+ 'sentinel-value', // missing-value markers that poison aggregates
364
+ 'dirty-categories', // case/space splits that change the GROUP BY winner
365
+ 'duplicate-rows', // inflate counts
366
+ 'identical-columns', // leaked/redundant column
367
+ 'check-incomplete', // a check could not run — never hide that
368
+ ]);
369
+ /** Compact, ACTION-GUIDING summary for injection into an LLM system prompt. Filters
370
+ * to the silent-wrong-number issues (PROMPT_WORTHY_ISSUES), collapses repeats of
371
+ * the same issue into ONE line (13 "NULL" sentinel columns → one line, not 13),
372
+ * and caps tightly. '' if nothing actionable. The full audit still lives in
373
+ * `session.audit` / `dolex check`. */
374
+ export function formatAuditForPrompt(findings, maxLines = 5) {
375
+ const worthy = findings
376
+ .filter((f) => f.severity !== 'low' && PROMPT_WORTHY_ISSUES.has(f.issue))
377
+ .sort((a, b) => SEV_RANK[a.severity] - SEV_RANK[b.severity]);
378
+ if (worthy.length === 0)
379
+ return '';
380
+ // Group by issue, preserving severity-sorted order, to collapse repeats.
381
+ const byIssue = new Map();
382
+ for (const f of worthy) {
383
+ const arr = byIssue.get(f.issue);
384
+ if (arr)
385
+ arr.push(f);
386
+ else
387
+ byIssue.set(f.issue, [f]);
388
+ }
389
+ const lines = [];
390
+ for (const [, group] of byIssue) {
391
+ if (lines.length >= maxLines)
392
+ break;
393
+ const f = group[0];
394
+ const sev = `[${f.severity.toUpperCase()}]`;
395
+ if (group.length === 1) {
396
+ lines.push(`• ${sev} ${f.column ? f.column + ': ' : ''}${f.detail}${f.suggestion ? ' → ' + f.suggestion : ''}`);
397
+ }
398
+ else {
399
+ // Collapse: one line for the shared issue + the shared fix. Count and noun
400
+ // are driven by the COLUMN-BEARING findings (a column-less finding like
401
+ // duplicate-rows must not be counted as a "column" or padded into "+N more").
402
+ const ids = group.map((g) => g.column).filter((c) => Boolean(c));
403
+ const suffix = f.suggestion ? ' → ' + f.suggestion : '';
404
+ if (ids.length > 0) {
405
+ const more = ids.length > 6 ? `, +${ids.length - 6} more` : '';
406
+ lines.push(`• ${sev} ${ids.length} columns with ${f.issue} (${ids.slice(0, 6).join(', ')}${more})${suffix}`);
407
+ }
408
+ else {
409
+ lines.push(`• ${sev} ${group.length} ${f.issue} findings${suffix}`);
410
+ }
411
+ }
412
+ }
413
+ const shown = lines.length;
414
+ const issuesTotal = byIssue.size;
415
+ if (issuesTotal > shown)
416
+ lines.push(`• …and ${issuesTotal - shown} more issue type(s).`);
417
+ return lines.join('\n');
418
+ }
@@ -173,10 +173,51 @@ const composition = (columns, table) => {
173
173
  }
174
174
  return null;
175
175
  };
176
+ // Period-over-period growth: the change and % change of a measure vs the previous
177
+ // time bucket (WoW/MoM/YoY depending on the bucket). Uses LAG; the % change is
178
+ // guarded with NULLIF (div-by-zero) and 100.0 (real division) — the SQL-safety
179
+ // traps this engine warns about, avoided at the source.
180
+ const periodOverPeriod = (columns, table) => {
181
+ const timeCol = first(columns, 'time');
182
+ const measureCol = first(columns, 'measure');
183
+ if (!timeCol || !measureCol)
184
+ return null;
185
+ const tb = timeBucketing(timeCol);
186
+ if (!tb)
187
+ return null;
188
+ const { label: bucket, expr: bucketExpr } = tb;
189
+ const period = q(`${timeCol.name}_${bucket}`);
190
+ const total = q(sumAlias(measureCol.name));
191
+ const sql = `WITH t AS (SELECT ${bucketExpr} AS ${period}, SUM(${q(measureCol.name)}) AS ${total} FROM ${q(table)} GROUP BY 1) ` +
192
+ `SELECT ${period}, ${total}, ${total} - LAG(${total}) OVER (ORDER BY ${period}) AS change, ` +
193
+ `ROUND(100.0 * (${total} - LAG(${total}) OVER (ORDER BY ${period})) / NULLIF(LAG(${total}) OVER (ORDER BY ${period}), 0), 1) AS pct_change ` +
194
+ `FROM t ORDER BY ${period} ASC`;
195
+ return makeStep('trend', `${capitalize(measureCol.name)} Growth (period over period)`, `How fast is ${capitalize(measureCol.name)} growing from one ${bucket} to the next?`, `Show ${bucket}-over-${bucket} change and % change in ${measureCol.name}`, `Time column "${timeCol.name}" + measure "${measureCol.name}" supports period-over-period growth (${bucket}). % change is NULLIF-guarded against a zero base.`, sql, table, ['bar', 'line', 'waterfall']);
196
+ };
197
+ // Seasonality: average a measure by month-of-year ACROSS years, isolating the
198
+ // recurring seasonal shape from the long-run trend. Only meaningful with sub-year
199
+ // (ISO date) resolution — skipped for year-only columns.
200
+ const seasonality = (columns, table) => {
201
+ const timeCol = first(columns, 'time');
202
+ const measureCol = first(columns, 'measure');
203
+ if (!timeCol || !measureCol)
204
+ return null;
205
+ if (isYearColumn(timeCol))
206
+ return null; // year-only → no within-year season
207
+ const vals = (timeCol.topValues ?? []).map((t) => String(t.value));
208
+ if (vals.length > 0 && !isIsoDateColumn(timeCol))
209
+ return null; // non-ISO date → strftime would NULL
210
+ const c = q(timeCol.name);
211
+ const sql = `SELECT strftime('%m', ${c}) AS month, AVG(${q(measureCol.name)}) AS ${q(`avg_${measureCol.name}`)} ` +
212
+ `FROM ${q(table)} WHERE strftime('%m', ${c}) IS NOT NULL GROUP BY 1 ORDER BY 1 ASC`;
213
+ return makeStep('trend', `${capitalize(measureCol.name)} Seasonality (by month)`, `Does ${capitalize(measureCol.name)} follow a recurring monthly/seasonal pattern?`, `Show average ${measureCol.name} by month of year across all years`, `ISO date "${timeCol.name}" + measure "${measureCol.name}" lets us average by month-of-year to separate seasonality from trend.`, sql, table, ['bar', 'line', 'radar']);
214
+ };
176
215
  // --- All Rules --------------------------------------------------------------
177
216
  const ALL_RULES = [
178
217
  timeTrend,
179
218
  trendByGroup,
219
+ periodOverPeriod,
220
+ seasonality,
180
221
  comparison,
181
222
  distribution,
182
223
  relationship,
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Authoring prompt + constrained-output schema — the SHARED knowledge of HOW to
3
+ * ask a model to write a Python clean(). The core never calls a model; a caller
4
+ * (orchestrator's local model, or any agent) does the transport and passes the
5
+ * resulting code in as a CleanAuthor.
6
+ */
7
+ export interface AuthorRequest {
8
+ column: string;
9
+ issue: string;
10
+ task: string;
11
+ samples: string[];
12
+ feedback?: string;
13
+ }
14
+ export type CleanAuthor = (req: AuthorRequest) => Promise<string>;
15
+ export declare const PY_SCHEMA: {
16
+ type: string;
17
+ properties: {
18
+ code: {
19
+ type: string;
20
+ };
21
+ note: {
22
+ type: string;
23
+ };
24
+ };
25
+ required: string[];
26
+ };
27
+ export declare function buildAuthorPrompt(req: AuthorRequest): {
28
+ system: string;
29
+ user: string;
30
+ };
@@ -0,0 +1,7 @@
1
+ export const PY_SCHEMA = { type: 'object', properties: { code: { type: 'string' }, note: { type: 'string' } }, required: ['code', 'note'] };
2
+ export function buildAuthorPrompt(req) {
3
+ const system = 'Write a Python 3 function `def clean(value):` taking ONE raw cell value (string) and returning the CLEANED value (None for missing/sentinel). May import stdlib (datetime, re). Output JSON {code, note}: code = the COMPLETE function plus any imports. No I/O.';
4
+ const user = `Column "${req.column}". Detected issue: ${req.issue}. Sample values: ${req.samples.map((s) => JSON.stringify(s)).join(', ')}.\nTASK: ${req.task}` +
5
+ (req.feedback ? `\n\nYour PREVIOUS attempt FAILED validation: ${req.feedback}. Write a corrected function.` : '');
6
+ return { system, user };
7
+ }
@@ -0,0 +1,29 @@
1
+ /** Thrown when the static screen rejects model code (banned import/call/dunder) or the
2
+ * code defines no clean(). Callers (MCP/CLI) surface the message; the autonomous author
3
+ * loop turns it into validation feedback so the model retries with safe code. */
4
+ export declare class CleanRejected extends Error {
5
+ constructor(reason: string);
6
+ }
7
+ export declare function pythonAvailable(): boolean;
8
+ export declare function runPythonClean(code: string, values: (string | null)[]): {
9
+ cleaned: (string | null)[];
10
+ errors: number;
11
+ };
12
+ export interface CleanStats {
13
+ rows: number;
14
+ errors: number;
15
+ changed: number;
16
+ nulledFromValue: number;
17
+ distinctBefore: number;
18
+ distinctAfter: number;
19
+ }
20
+ export declare function cleanStats(raw: (string | null)[], cleaned: (string | null)[]): CleanStats;
21
+ export declare function safetyVerdict(raw: (string | null)[], cleaned: (string | null)[], errors: number): {
22
+ ok: boolean;
23
+ reason?: string;
24
+ };
25
+ export declare function previewSample(raw: (string | null)[], cleaned: (string | null)[], n: number): {
26
+ before: string | null;
27
+ after: string | null;
28
+ }[];
29
+ export declare function applyCleanColumn(db: any, table: string, newColumn: string, rowids: number[], cleaned: (string | null)[]): void;
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Data-cleaning execution core (no MCP, no SourceManager) — runs a model-authored
3
+ * Python clean(value) over a column's values and applies the result non-destructively.
4
+ *
5
+ * SECURITY (Tier 1): the author of this code is an LLM whose prompt embeds raw CSV cell
6
+ * values, so a malicious cell can steer it into writing exfiltration/RCE (proven: see
7
+ * local-orchestration/experiments/016-prompt-injection-author.ts — the default clean
8
+ * model emitted `eval(open('~/.config/...'))` on a disguised payload). Before ANY model
9
+ * code runs, the harness STATICALLY screens it (import allowlist + banned-name/dunder
10
+ * deny) and runs it under POSIX resource limits (CPU/AS/FSIZE — enforced on Linux; macOS
11
+ * honors a subset). Rejected code throws CleanRejected; the executor is NEVER reached.
12
+ * This is a hardened deny-list, not a true jail — a hosted/multi-tenant deployment must
13
+ * STILL run the whole engine in a network-denied, read-only container (see CLAUDE.md).
14
+ */
15
+ import { execFileSync } from 'child_process';
16
+ import { mkdtempSync, writeFileSync, rmSync } from 'fs';
17
+ import { tmpdir } from 'os';
18
+ import { join } from 'path';
19
+ /** Thrown when the static screen rejects model code (banned import/call/dunder) or the
20
+ * code defines no clean(). Callers (MCP/CLI) surface the message; the autonomous author
21
+ * loop turns it into validation feedback so the model retries with safe code. */
22
+ export class CleanRejected extends Error {
23
+ constructor(reason) { super(reason); this.name = 'CleanRejected'; }
24
+ }
25
+ export function pythonAvailable() {
26
+ try {
27
+ execFileSync('python3', ['--version'], { stdio: 'ignore' });
28
+ return true;
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ // The trusted runner: screens the model code (argv[1]) with `ast` BEFORE compiling/exec'ing
35
+ // it, sets resource limits, then runs clean() over the values (argv[2]). The model code is
36
+ // loaded from a FILE (never interpolated into this string) so it cannot break out of the
37
+ // harness. Allowlist imports (the prompt only needs datetime/re); deny dangerous builtins by
38
+ // NAME (rebind-proof: `e = eval; e(...)` is caught) and all dunder attribute access (closes
39
+ // the `().__class__.__bases__[0].__subclasses__()` escape).
40
+ const RUNNER = String.raw `
41
+ import ast, sys, json, resource
42
+ ALLOWED_IMPORTS = {"datetime","time","re","math","json","string","decimal","fractions",
43
+ "unicodedata","collections","itertools","calendar","statistics","numbers"}
44
+ BANNED_NAMES = {"eval","exec","compile","open","input","breakpoint","__import__","__builtins__",
45
+ "globals","locals","vars","getattr","setattr","delattr","memoryview","exit","quit"}
46
+ def screen(src):
47
+ tree = ast.parse(src)
48
+ for n in ast.walk(tree):
49
+ if isinstance(n, ast.Import):
50
+ for a in n.names:
51
+ if a.name.split('.')[0] not in ALLOWED_IMPORTS: raise ValueError("import not allowed: " + a.name)
52
+ elif isinstance(n, ast.ImportFrom):
53
+ mod = (n.module or "").split('.')[0]
54
+ if mod not in ALLOWED_IMPORTS: raise ValueError("import not allowed: " + str(n.module))
55
+ elif isinstance(n, ast.Name) and n.id in BANNED_NAMES:
56
+ raise ValueError("name not allowed: " + n.id)
57
+ elif isinstance(n, ast.Attribute) and n.attr.startswith("__") and n.attr.endswith("__"):
58
+ raise ValueError("dunder attribute not allowed: " + n.attr)
59
+ return tree
60
+ def limits():
61
+ GB = 1024*1024*1024
62
+ for res, lim in ((resource.RLIMIT_CPU, (10, 10)), (resource.RLIMIT_AS, (GB, GB)),
63
+ (resource.RLIMIT_FSIZE, (16*1024*1024, 16*1024*1024))):
64
+ try: resource.setrlimit(res, lim)
65
+ except Exception: pass
66
+ src = open(sys.argv[1]).read()
67
+ try:
68
+ tree = screen(src)
69
+ except (ValueError, SyntaxError) as e:
70
+ print(json.dumps({"rejected": str(e)})); sys.exit(0)
71
+ limits()
72
+ ns = {}
73
+ try:
74
+ exec(compile(tree, "<clean>", "exec"), ns)
75
+ except Exception as e:
76
+ print(json.dumps({"rejected": "module-level error: " + str(e)})); sys.exit(0)
77
+ clean = ns.get("clean")
78
+ if not callable(clean):
79
+ print(json.dumps({"rejected": "no clean(value) function defined"})); sys.exit(0)
80
+ vals = json.load(open(sys.argv[2]))
81
+ out = []; err = 0
82
+ for v in vals:
83
+ try:
84
+ r = clean(v); out.append(None if r is None else str(r))
85
+ except Exception:
86
+ err += 1; out.append(None)
87
+ print(json.dumps({"cleaned": out, "errors": err}))
88
+ `;
89
+ // NOTE (scale): runs python3 synchronously and JSON.parses the result in one shot (maxBuffer 512MB,
90
+ // overflow ⇒ a graceful execFileSync error). Fine for the local single-user model; a hosted/multi-client
91
+ // deployment would stream + parse off the event loop. Out of scope here — see the security note above.
92
+ export function runPythonClean(code, values) {
93
+ const dir = mkdtempSync(join(tmpdir(), 'dolex-clean-'));
94
+ try {
95
+ const cf = join(dir, 'clean_src.py');
96
+ writeFileSync(cf, code); // model code — read, never interpolated
97
+ const vf = join(dir, 'v.json');
98
+ writeFileSync(vf, JSON.stringify(values));
99
+ const rf = join(dir, 'runner.py');
100
+ writeFileSync(rf, RUNNER); // trusted harness
101
+ const raw = execFileSync('python3', [rf, cf, vf], { timeout: 60000, encoding: 'utf8', maxBuffer: 512 * 1024 * 1024 });
102
+ // Parse ONLY the final non-empty line: model-authored clean() (or imported modules)
103
+ // may print debug output, which would otherwise poison JSON.parse. The protocol line
104
+ // is always the last thing we print.
105
+ const lines = raw.trimEnd().split('\n');
106
+ const parsed = JSON.parse(lines[lines.length - 1]);
107
+ if (parsed.rejected)
108
+ throw new CleanRejected(parsed.rejected); // screen/exec/shape rejection
109
+ return { cleaned: parsed.cleaned, errors: parsed.errors };
110
+ }
111
+ finally {
112
+ rmSync(dir, { recursive: true, force: true });
113
+ }
114
+ }
115
+ const isBlank = (x) => x === null || x === '' || x === undefined;
116
+ export function cleanStats(raw, cleaned) {
117
+ let changed = 0, nulledFromValue = 0;
118
+ for (let i = 0; i < raw.length; i++) {
119
+ if (String(raw[i] ?? '') !== String(cleaned[i] ?? ''))
120
+ changed++;
121
+ if (!isBlank(raw[i]) && isBlank(cleaned[i]))
122
+ nulledFromValue++;
123
+ }
124
+ return {
125
+ rows: raw.length, errors: 0, changed, nulledFromValue,
126
+ distinctBefore: new Set(raw.filter((v) => !isBlank(v))).size,
127
+ distinctAfter: new Set(cleaned.filter((v) => !isBlank(v))).size,
128
+ };
129
+ }
130
+ export function safetyVerdict(raw, cleaned, errors) {
131
+ const rows = raw.length;
132
+ if (rows === 0)
133
+ return { ok: false, reason: 'no rows to clean' };
134
+ if (errors > rows * 0.5)
135
+ return { ok: false, reason: `the function errored on ${errors}/${rows} rows` };
136
+ const nonBlankBefore = raw.filter((v) => !isBlank(v)).length;
137
+ const nonBlankAfter = cleaned.filter((v) => !isBlank(v)).length;
138
+ if (nonBlankBefore > 0 && nonBlankAfter === 0)
139
+ return { ok: false, reason: 'every value became blank/null — the function likely destroyed the column' };
140
+ return { ok: true };
141
+ }
142
+ export function previewSample(raw, cleaned, n) {
143
+ const out = [];
144
+ for (let i = 0; i < raw.length && out.length < n; i++) {
145
+ if (String(raw[i] ?? '') !== String(cleaned[i] ?? ''))
146
+ out.push({ before: raw[i], after: cleaned[i] });
147
+ }
148
+ return out;
149
+ }
150
+ const q = (s) => `"${s.replace(/"/g, '""')}"`;
151
+ export function applyCleanColumn(db, table, newColumn, rowids, cleaned) {
152
+ db.exec(`ALTER TABLE ${q(table)} ADD COLUMN ${q(newColumn)}`);
153
+ const upd = db.prepare(`UPDATE ${q(table)} SET ${q(newColumn)} = ? WHERE rowid = ?`);
154
+ const tx = db.transaction((pairs) => {
155
+ // '' = missing — match the connector's "empty string is null" convention so the
156
+ // stored value agrees with stats/safety (which treat '' as blank). [second-look fix]
157
+ for (const [val, rid] of pairs)
158
+ upd.run(val === '' ? null : val, rid);
159
+ });
160
+ tx(cleaned.map((v, i) => [v, rowids[i]]));
161
+ }
@@ -0,0 +1,16 @@
1
+ import type { QualityFinding } from '../analysis/quality.js';
2
+ export interface AcceptResult {
3
+ ok: boolean;
4
+ summary: string;
5
+ fail?: string;
6
+ }
7
+ interface Handler {
8
+ task: (f: QualityFinding) => string | null;
9
+ accept: (pairs: [string, any][], f: QualityFinding) => AcceptResult;
10
+ }
11
+ export declare const HANDLERS: Record<string, Handler>;
12
+ /** Run the model-authored code over the sample values and apply the issue's
13
+ * acceptance test. Uses the shared exec (string|null normalized) — the same
14
+ * executor the MCP tool uses, so there is exactly ONE python runner. */
15
+ export declare function validateFix(finding: QualityFinding, code: string, sampleVals: string[]): AcceptResult;
16
+ export {};