@outsidedata/dolex 8.0.1 → 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.
- package/README.md +6 -4
- package/dist/src/analysis/clean-exec.d.ts +23 -0
- package/dist/src/analysis/clean-exec.js +87 -0
- package/dist/src/analysis/data-context.d.ts +140 -0
- package/dist/src/analysis/data-context.js +96 -0
- package/dist/src/analysis/quality.d.ts +23 -0
- package/dist/src/analysis/quality.js +290 -6
- package/dist/src/analysis/rules.js +41 -0
- package/dist/src/cleaning/author.d.ts +30 -0
- package/dist/src/cleaning/author.js +7 -0
- package/dist/src/cleaning/exec.d.ts +29 -0
- package/dist/src/cleaning/exec.js +161 -0
- package/dist/src/cleaning/handlers.d.ts +16 -0
- package/dist/src/cleaning/handlers.js +82 -0
- package/dist/src/cleaning/index.d.ts +8 -0
- package/dist/src/cleaning/index.js +4 -0
- package/dist/src/cleaning/manifest.d.ts +35 -0
- package/dist/src/cleaning/manifest.js +95 -0
- package/dist/src/cli/commands/check.js +2 -89
- package/dist/src/cli/commands/clean.d.ts +1 -0
- package/dist/src/cli/commands/clean.js +115 -0
- package/dist/src/cli/commands/help.js +1 -0
- package/dist/src/cli/commands/query.js +4 -1
- package/dist/src/cli/commands/visualize.js +2 -0
- package/dist/src/cli/index.js +2 -0
- package/dist/src/connectors/csv.js +81 -8
- package/dist/src/connectors/manager.d.ts +10 -0
- package/dist/src/connectors/manager.js +60 -1
- package/dist/src/connectors/sql-safety.d.ts +68 -0
- package/dist/src/connectors/sql-safety.js +167 -0
- package/dist/src/mcp/index.js +9 -1
- package/dist/src/mcp/tools/clean-column.d.ts +5 -0
- package/dist/src/mcp/tools/clean-column.js +45 -0
- package/dist/src/mcp/tools/clean-schemas.d.ts +23 -0
- package/dist/src/mcp/tools/clean-schemas.js +9 -0
- package/dist/src/mcp/tools/query-source.d.ts +2 -2
- package/dist/src/mcp/tools/query-source.js +2 -1
- package/dist/src/mcp/tools/shared.d.ts +1 -0
- package/dist/src/mcp/tools/shared.js +1 -1
- package/dist/src/mcp/tools/visualize-cli.d.ts +2 -2
- package/dist/src/mcp/tools/visualize.d.ts +3 -2
- package/dist/src/mcp/tools/visualize.js +1 -0
- package/dist/src/transforms/evaluator.js +58 -3
- package/dist/src/transforms/tokenizer.js +20 -2
- package/dist/src/transforms/types.d.ts +6 -6
- package/dist/src/types.d.ts +10 -0
- package/package.json +5 -2
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-issue cleaning handlers + the acceptance-test validator (the autonomous
|
|
3
|
+
* guardrail: trust the validated output, never the generator). Model-free.
|
|
4
|
+
*
|
|
5
|
+
* Ported verbatim from local-orchestration/src/clean.ts (the proven reviewer-bench
|
|
6
|
+
* handlers) — the python runner is now the shared exec, so there is exactly ONE.
|
|
7
|
+
*/
|
|
8
|
+
import { runPythonClean } from './exec.js';
|
|
9
|
+
const blank = (x) => x === null || x === '' || x === undefined;
|
|
10
|
+
const isoLike = (s) => /^\d{4}-\d{2}-\d{2}/.test(String(s));
|
|
11
|
+
// Real date STRUCTURE only — D/M/Y, "Mon DD YYYY", or ISO. A bare 4-digit number is NOT a
|
|
12
|
+
// date (else a duration column like *_time(seconds) gets "cleaned" into epoch dates).
|
|
13
|
+
const looksDate = (s) => /(\d{1,2}[\/\-.]\d{1,2}[\/\-.]\d{2,4})|([A-Za-z]{3,}\.?\s+\d{1,2},?\s+\d{4})|(\d{4}-\d{2}-\d{2})/.test(String(s));
|
|
14
|
+
export const HANDLERS = {
|
|
15
|
+
'non-iso-date': {
|
|
16
|
+
task: () => 'The values are dates in a NON-ISO format. Parse each and return it as ISO YYYY-MM-DD (return None if it is not a date).',
|
|
17
|
+
accept: (pairs) => {
|
|
18
|
+
const nonblank = pairs.filter(([o]) => !blank(o));
|
|
19
|
+
const d = nonblank.filter(([o]) => looksDate(o));
|
|
20
|
+
// Only treat this as a date column if MOST values are real dates — guards against
|
|
21
|
+
// cleaning a non-date column that has a few coincidentally date-like values.
|
|
22
|
+
const isDateColumn = nonblank.length > 0 && d.length >= nonblank.length * 0.5;
|
|
23
|
+
const conv = d.filter(([, c]) => isoLike(c));
|
|
24
|
+
const ok = isDateColumn && conv.length >= Math.floor(d.length * 0.9);
|
|
25
|
+
const badEx = d.find(([, c]) => !isoLike(c) && !blank(c));
|
|
26
|
+
const why = !isDateColumn ? `only ${d.length}/${nonblank.length} values are real dates — not a date column` : badEx ? `for ${JSON.stringify(badEx[0])} returned ${JSON.stringify(badEx[1])}, expected ISO YYYY-MM-DD` : undefined;
|
|
27
|
+
return { ok, summary: `${conv.length}/${d.length} date-like → ISO (${d.length}/${nonblank.length} look like dates)`, fail: why };
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
'mixed-type': {
|
|
31
|
+
task: (f) => { const m = f.detail.match(/non-numeric value "([^"]+)"/); return m ? `The value ${JSON.stringify(m[1])} is a missing-value sentinel coerced into a numeric column. Return None for it; return the number (as a float) otherwise.` : null; },
|
|
32
|
+
accept: (pairs, f) => {
|
|
33
|
+
const m = f.detail.match(/non-numeric value "([^"]+)"/);
|
|
34
|
+
const lit = m ? m[1] : '';
|
|
35
|
+
const sent = pairs.filter(([o]) => o === lit);
|
|
36
|
+
const badSent = sent.find(([, c]) => !blank(c));
|
|
37
|
+
const badNum = pairs.filter(([o]) => o !== lit && !blank(o)).find(([o, c]) => !blank(c) && Number(c) !== Number(o));
|
|
38
|
+
const bad = badSent || badNum;
|
|
39
|
+
return { ok: sent.length > 0 && !bad, summary: `${sent.length} ${JSON.stringify(lit)} sentinels → None`, fail: bad ? `for ${JSON.stringify(bad[0])} returned ${JSON.stringify(bad[1])}` : undefined };
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
'sentinel-value': {
|
|
43
|
+
task: (f) => { const m = f.detail.match(/Extreme value ([\d.eE+-]+)/) || f.detail.match(/sentinel:\s*"([^"]+)"/); return m ? `The value ${m[1]} is a missing-value sentinel, not real data. Return None for it; return the value otherwise.` : null; },
|
|
44
|
+
accept: (pairs, f) => {
|
|
45
|
+
const m = f.detail.match(/Extreme value ([\d.eE+-]+)/) || f.detail.match(/sentinel:\s*"([^"]+)"/);
|
|
46
|
+
const lit = m ? m[1] : '';
|
|
47
|
+
const sent = pairs.filter(([o]) => o === lit || Number(o) === Number(lit));
|
|
48
|
+
const bad = sent.find(([, c]) => !blank(c));
|
|
49
|
+
return { ok: sent.length > 0 && !bad, summary: `${sent.length} ${JSON.stringify(lit)} sentinels → None`, fail: bad ? `for ${JSON.stringify(bad[0])} returned ${JSON.stringify(bad[1])}` : undefined };
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
'dirty-categories': {
|
|
53
|
+
task: () => 'Values differ only by case/whitespace and split one category. Canonicalize each value (strip surrounding whitespace and lowercase) so variants collapse.',
|
|
54
|
+
accept: (pairs) => {
|
|
55
|
+
const m = new Map(pairs.map(([o, c]) => [o, c]));
|
|
56
|
+
// find any case/space variant pair in the sample and check they collapse
|
|
57
|
+
const keys = [...m.keys()];
|
|
58
|
+
let merged = false, checked = 0;
|
|
59
|
+
for (const a of keys)
|
|
60
|
+
for (const b of keys) {
|
|
61
|
+
if (a !== b && a.trim().toLowerCase() === b.trim().toLowerCase()) {
|
|
62
|
+
checked++;
|
|
63
|
+
if (m.get(a) === m.get(b) && !blank(m.get(a)))
|
|
64
|
+
merged = true;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const ok = checked === 0 ? pairs.every(([, c]) => typeof c === 'string' && c === c.trim().toLowerCase()) : merged;
|
|
68
|
+
return { ok, summary: checked > 0 ? `${checked} case/space variant pair(s) collapse` : 'all values canonical' };
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
/** Run the model-authored code over the sample values and apply the issue's
|
|
73
|
+
* acceptance test. Uses the shared exec (string|null normalized) — the same
|
|
74
|
+
* executor the MCP tool uses, so there is exactly ONE python runner. */
|
|
75
|
+
export function validateFix(finding, code, sampleVals) {
|
|
76
|
+
const handler = finding.column ? HANDLERS[finding.issue] : undefined;
|
|
77
|
+
if (!handler)
|
|
78
|
+
return { ok: false, summary: `no handler for issue "${finding.issue}"` };
|
|
79
|
+
const { cleaned } = runPythonClean(code, sampleVals);
|
|
80
|
+
const pairs = sampleVals.map((o, i) => [o, cleaned[i]]);
|
|
81
|
+
return handler.accept(pairs, finding);
|
|
82
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { pythonAvailable, runPythonClean, cleanStats, safetyVerdict, previewSample, applyCleanColumn, CleanRejected } from './exec.js';
|
|
2
|
+
export type { CleanStats } from './exec.js';
|
|
3
|
+
export { HANDLERS, validateFix } from './handlers.js';
|
|
4
|
+
export type { AcceptResult } from './handlers.js';
|
|
5
|
+
export { PY_SCHEMA, buildAuthorPrompt } from './author.js';
|
|
6
|
+
export type { AuthorRequest, CleanAuthor } from './author.js';
|
|
7
|
+
export { buildCleanManifest, applyManifest, cleanDataset } from './manifest.js';
|
|
8
|
+
export type { FixRecord, CleanManifest } from './manifest.js';
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { pythonAvailable, runPythonClean, cleanStats, safetyVerdict, previewSample, applyCleanColumn, CleanRejected } from './exec.js';
|
|
2
|
+
export { HANDLERS, validateFix } from './handlers.js';
|
|
3
|
+
export { PY_SCHEMA, buildAuthorPrompt } from './author.js';
|
|
4
|
+
export { buildCleanManifest, applyManifest, cleanDataset } from './manifest.js';
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { CleanAuthor } from './author.js';
|
|
2
|
+
export interface FixRecord {
|
|
3
|
+
column: string;
|
|
4
|
+
issue: string;
|
|
5
|
+
task: string;
|
|
6
|
+
pythonCode: string;
|
|
7
|
+
validated: boolean;
|
|
8
|
+
summary: string;
|
|
9
|
+
}
|
|
10
|
+
export interface CleanManifest {
|
|
11
|
+
dataset: string;
|
|
12
|
+
createdBy: string;
|
|
13
|
+
createdAt: string;
|
|
14
|
+
fixes: FixRecord[];
|
|
15
|
+
}
|
|
16
|
+
export declare function buildCleanManifest(rawPath: string, author: CleanAuthor, opts?: {
|
|
17
|
+
tries?: number;
|
|
18
|
+
onLog?: (s: string) => void;
|
|
19
|
+
createdBy?: string;
|
|
20
|
+
}): Promise<CleanManifest>;
|
|
21
|
+
/** Replay validated fixes over a CSV (NON-destructive: keep <col>_raw). NO model. */
|
|
22
|
+
export declare function applyManifest(rawPath: string, manifest: CleanManifest): {
|
|
23
|
+
rows: Record<string, string>[];
|
|
24
|
+
fields: string[];
|
|
25
|
+
};
|
|
26
|
+
/** Full activation: build manifest (via injected author) → materialize cleaned CSV + persist manifest. */
|
|
27
|
+
export declare function cleanDataset(rawPath: string, author: CleanAuthor, opts?: {
|
|
28
|
+
outDir?: string;
|
|
29
|
+
onLog?: (s: string) => void;
|
|
30
|
+
createdBy?: string;
|
|
31
|
+
}): Promise<{
|
|
32
|
+
cleanedPath: string;
|
|
33
|
+
manifestPath: string;
|
|
34
|
+
manifest: CleanManifest;
|
|
35
|
+
}>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Manifest build (discover → author[injected] → acceptance-test → store) + replay
|
|
3
|
+
* (deterministic, no model). The model-free heart of the cleaning core.
|
|
4
|
+
*
|
|
5
|
+
* Ported from local-orchestration/src/clean.ts with two changes: the model author
|
|
6
|
+
* is INJECTED (CleanAuthor) so the core stays model-free, and the python runner is
|
|
7
|
+
* the shared exec (runPythonClean) so there is exactly ONE executor.
|
|
8
|
+
*/
|
|
9
|
+
import * as fs from 'fs';
|
|
10
|
+
import * as path from 'path';
|
|
11
|
+
import Papa from 'papaparse';
|
|
12
|
+
import { SourceManager } from '../connectors/manager.js';
|
|
13
|
+
import { auditDataset } from '../analysis/quality.js';
|
|
14
|
+
import { runPythonClean } from './exec.js';
|
|
15
|
+
import { HANDLERS, validateFix } from './handlers.js';
|
|
16
|
+
export async function buildCleanManifest(rawPath, author, opts = {}) {
|
|
17
|
+
const log = opts.onLog ?? (() => { });
|
|
18
|
+
const tries = opts.tries ?? 3;
|
|
19
|
+
const rows = Papa.parse(fs.readFileSync(rawPath, 'utf8'), { header: true, skipEmptyLines: true }).data;
|
|
20
|
+
const mgr = new SourceManager();
|
|
21
|
+
const add = await mgr.add('ds', { type: 'csv', path: rawPath });
|
|
22
|
+
const sid = add.entry.id;
|
|
23
|
+
await mgr.connect(sid);
|
|
24
|
+
const tables = (await mgr.getSchema(sid)).schema.tables;
|
|
25
|
+
const findings = await auditDataset(tables, (s) => mgr.querySql(sid, s));
|
|
26
|
+
const manifest = { dataset: path.basename(rawPath), createdBy: opts.createdBy ?? 'injected-author', createdAt: '', fixes: [] };
|
|
27
|
+
for (const f of findings) {
|
|
28
|
+
const handler = f.column ? HANDLERS[f.issue] : undefined;
|
|
29
|
+
if (!handler)
|
|
30
|
+
continue;
|
|
31
|
+
const task = handler.task(f);
|
|
32
|
+
if (!task)
|
|
33
|
+
continue;
|
|
34
|
+
if (manifest.fixes.some((x) => x.column === f.column))
|
|
35
|
+
continue; // one fix per column
|
|
36
|
+
const sampleVals = [...new Set(rows.map((r) => r[f.column]).filter((v) => v !== undefined))].slice(0, 200);
|
|
37
|
+
// the acceptance test must SEE the sentinel/edge value or it can't validate the fix —
|
|
38
|
+
// the first-200-distinct sample may miss a rare sentinel (e.g. odometer 999999).
|
|
39
|
+
const sentinel = (f.detail.match(/non-numeric value "([^"]+)"/) || f.detail.match(/Extreme value ([\d.eE+-]+)/) || f.detail.match(/sentinel:\s*"([^"]+)"/) || [])[1];
|
|
40
|
+
if (sentinel !== undefined && !sampleVals.includes(sentinel))
|
|
41
|
+
sampleVals.push(sentinel);
|
|
42
|
+
const samples = sampleVals.slice(0, 4);
|
|
43
|
+
let feedback, stored = false;
|
|
44
|
+
for (let attempt = 1; attempt <= tries; attempt++) {
|
|
45
|
+
let code;
|
|
46
|
+
try {
|
|
47
|
+
code = await author({ column: f.column, issue: f.issue, task, samples, feedback });
|
|
48
|
+
}
|
|
49
|
+
catch (e) {
|
|
50
|
+
log(` ${f.column} attempt ${attempt}: author error ${e?.message}`);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
let acc;
|
|
54
|
+
try {
|
|
55
|
+
acc = validateFix(f, code, sampleVals);
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
acc = { ok: false, summary: 'python error', fail: String(e?.message || e).slice(0, 80) };
|
|
59
|
+
}
|
|
60
|
+
log(` ${f.column} (${f.issue}) attempt ${attempt}: ${acc.summary} → ${acc.ok ? 'VALID' : 'FAIL ' + (acc.fail ?? '')}`);
|
|
61
|
+
if (acc.ok) {
|
|
62
|
+
manifest.fixes.push({ column: f.column, issue: f.issue, task, pythonCode: code, validated: true, summary: acc.summary });
|
|
63
|
+
stored = true;
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
feedback = acc.fail;
|
|
67
|
+
}
|
|
68
|
+
if (!stored)
|
|
69
|
+
log(` ${f.column}: no valid fix after ${tries} tries — skipped (never store an unvalidated fix)`);
|
|
70
|
+
}
|
|
71
|
+
return manifest;
|
|
72
|
+
}
|
|
73
|
+
/** Replay validated fixes over a CSV (NON-destructive: keep <col>_raw). NO model. */
|
|
74
|
+
export function applyManifest(rawPath, manifest) {
|
|
75
|
+
const parsed = Papa.parse(fs.readFileSync(rawPath, 'utf8'), { header: true, skipEmptyLines: true });
|
|
76
|
+
const rows = parsed.data;
|
|
77
|
+
for (const fix of manifest.fixes) {
|
|
78
|
+
const { cleaned } = runPythonClean(fix.pythonCode, rows.map((r) => r[fix.column] ?? ''));
|
|
79
|
+
rows.forEach((r, i) => { r[`${fix.column}_raw`] = r[fix.column] ?? ''; r[fix.column] = cleaned[i] === null || cleaned[i] === undefined ? '' : String(cleaned[i]); });
|
|
80
|
+
}
|
|
81
|
+
const fields = [...(parsed.meta.fields || []), ...manifest.fixes.map((f) => `${f.column}_raw`)];
|
|
82
|
+
return { rows, fields };
|
|
83
|
+
}
|
|
84
|
+
/** Full activation: build manifest (via injected author) → materialize cleaned CSV + persist manifest. */
|
|
85
|
+
export async function cleanDataset(rawPath, author, opts = {}) {
|
|
86
|
+
const manifest = await buildCleanManifest(rawPath, author, { onLog: opts.onLog, createdBy: opts.createdBy });
|
|
87
|
+
const outDir = opts.outDir ?? path.dirname(rawPath);
|
|
88
|
+
const base = path.basename(rawPath, path.extname(rawPath));
|
|
89
|
+
const manifestPath = path.join(outDir, `${base}.cleanfix.json`);
|
|
90
|
+
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
|
|
91
|
+
const { rows, fields } = applyManifest(rawPath, manifest);
|
|
92
|
+
const cleanedPath = path.join(outDir, `${base}.clean.csv`);
|
|
93
|
+
fs.writeFileSync(cleanedPath, Papa.unparse(rows, { columns: fields }));
|
|
94
|
+
return { cleanedPath, manifestPath, manifest };
|
|
95
|
+
}
|
|
@@ -8,14 +8,9 @@
|
|
|
8
8
|
import { parseArgs, str, bool } from '../args.js';
|
|
9
9
|
import * as o from '../output.js';
|
|
10
10
|
import { openTarget } from '../data-source.js';
|
|
11
|
-
import {
|
|
11
|
+
import { auditDataset } from '../../analysis/quality.js';
|
|
12
12
|
const BOOLEANS = ['json', 'help'];
|
|
13
13
|
const ALIASES = { h: 'help', table: 'from' };
|
|
14
|
-
const MAX_DUP_ROWS_SCAN = 500_000; // skip the full-table distinct scan above this
|
|
15
|
-
const MAX_IDENTICAL_PAIRS = 80; // bound the pairwise identical-column comparison
|
|
16
|
-
function esc(name) {
|
|
17
|
-
return `"${name.replace(/"/g, '""')}"`;
|
|
18
|
-
}
|
|
19
14
|
export async function checkCommand(argv) {
|
|
20
15
|
const args = parseArgs(argv, { booleans: BOOLEANS, aliases: ALIASES });
|
|
21
16
|
if (bool(args, 'help')) {
|
|
@@ -33,11 +28,7 @@ export async function checkCommand(argv) {
|
|
|
33
28
|
const tablesToCheck = explicitTable
|
|
34
29
|
? opened.tables.filter((t) => t.name === opened.defaultTable)
|
|
35
30
|
: opened.tables;
|
|
36
|
-
const findings =
|
|
37
|
-
for (const t of tablesToCheck) {
|
|
38
|
-
findings.push(...auditColumns(t.name, t.columns, t.rowCount));
|
|
39
|
-
findings.push(...(await tableLevelChecks(opened, t)));
|
|
40
|
-
}
|
|
31
|
+
const findings = await auditDataset(tablesToCheck, (sql) => opened.query(sql));
|
|
41
32
|
if (bool(args, 'json')) {
|
|
42
33
|
const counts = countBySeverity(findings);
|
|
43
34
|
o.out(JSON.stringify({ tables: tablesToCheck.map((t) => t.name), counts, findings }, null, 2));
|
|
@@ -49,81 +40,6 @@ export async function checkCommand(argv) {
|
|
|
49
40
|
await opened.close();
|
|
50
41
|
}
|
|
51
42
|
}
|
|
52
|
-
async function tableLevelChecks(opened, t) {
|
|
53
|
-
const out = [];
|
|
54
|
-
// Duplicate rows (skip very large tables to bound cost).
|
|
55
|
-
if (t.rowCount > 0 && t.rowCount <= MAX_DUP_ROWS_SCAN) {
|
|
56
|
-
const res = await opened.query(`SELECT (SELECT COUNT(*) FROM ${esc(t.name)}) - (SELECT COUNT(*) FROM (SELECT DISTINCT * FROM ${esc(t.name)})) AS dups`);
|
|
57
|
-
const dups = res.ok && res.rows && res.rows[0] ? Number(res.rows[0].dups) : NaN;
|
|
58
|
-
if (!res.ok || !Number.isFinite(dups)) {
|
|
59
|
-
// A failed check must be loud — never report clean when we didn't actually look.
|
|
60
|
-
out.push({
|
|
61
|
-
severity: 'high',
|
|
62
|
-
table: t.name,
|
|
63
|
-
issue: 'check-incomplete',
|
|
64
|
-
detail: `Duplicate-row check could not complete${res.ok ? '' : `: ${res.error}`}.`,
|
|
65
|
-
suggestion: 'The audit is incomplete — do not trust a clean result; re-run.',
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
else if (dups > 0) {
|
|
69
|
-
out.push({
|
|
70
|
-
severity: 'medium',
|
|
71
|
-
table: t.name,
|
|
72
|
-
issue: 'duplicate-rows',
|
|
73
|
-
detail: `${dups} fully-duplicate row${dups === 1 ? '' : 's'} (${pct(dups, t.rowCount)} of the table).`,
|
|
74
|
-
suggestion: 'Verify these are real repeats and not an accidental double-load or join fan-out.',
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
// Identical (redundant/leaked) columns: only compare columns that already share
|
|
79
|
-
// type + cardinality + null count, so the pairwise scan stays cheap.
|
|
80
|
-
const groups = new Map();
|
|
81
|
-
for (const c of t.columns) {
|
|
82
|
-
const key = `${c.type}|${c.uniqueCount}|${c.nullCount}`;
|
|
83
|
-
const arr = groups.get(key);
|
|
84
|
-
if (arr)
|
|
85
|
-
arr.push(c);
|
|
86
|
-
else
|
|
87
|
-
groups.set(key, [c]);
|
|
88
|
-
}
|
|
89
|
-
let comparisons = 0;
|
|
90
|
-
for (const group of groups.values()) {
|
|
91
|
-
if (group.length < 2)
|
|
92
|
-
continue;
|
|
93
|
-
for (let i = 0; i < group.length; i++) {
|
|
94
|
-
for (let j = i + 1; j < group.length; j++) {
|
|
95
|
-
if (comparisons++ >= MAX_IDENTICAL_PAIRS)
|
|
96
|
-
break;
|
|
97
|
-
const a = group[i].name;
|
|
98
|
-
const b = group[j].name;
|
|
99
|
-
const res = await opened.query(`SELECT COUNT(*) AS diff FROM ${esc(t.name)} WHERE ${esc(a)} IS NOT ${esc(b)}`);
|
|
100
|
-
const diff = res.ok && res.rows && res.rows[0] ? Number(res.rows[0].diff) : NaN;
|
|
101
|
-
if (!res.ok || !Number.isFinite(diff)) {
|
|
102
|
-
// Don't silently treat a failed comparison as "columns differ".
|
|
103
|
-
out.push({
|
|
104
|
-
severity: 'high',
|
|
105
|
-
table: t.name,
|
|
106
|
-
column: `${a} vs ${b}`,
|
|
107
|
-
issue: 'check-incomplete',
|
|
108
|
-
detail: `Could not compare columns "${a}" and "${b}"${res.ok ? '' : `: ${res.error}`}.`,
|
|
109
|
-
suggestion: 'The audit is incomplete — do not trust a clean result; re-run.',
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
else if (diff === 0) {
|
|
113
|
-
out.push({
|
|
114
|
-
severity: 'high',
|
|
115
|
-
table: t.name,
|
|
116
|
-
column: `${a} = ${b}`,
|
|
117
|
-
issue: 'identical-columns',
|
|
118
|
-
detail: `Columns "${a}" and "${b}" are identical on every row.`,
|
|
119
|
-
suggestion: 'Redundant or leaked feature — a model/analysis "predicting" one just reads the other. Drop one.',
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
return out;
|
|
126
|
-
}
|
|
127
43
|
const ORDER = ['high', 'medium', 'low'];
|
|
128
44
|
const LABEL = { high: 'HIGH', medium: 'MEDIUM', low: 'LOW' };
|
|
129
45
|
function render(name, tableCount, findings) {
|
|
@@ -164,9 +80,6 @@ function countBySeverity(findings) {
|
|
|
164
80
|
low: findings.filter((f) => f.severity === 'low').length,
|
|
165
81
|
};
|
|
166
82
|
}
|
|
167
|
-
function pct(n, total) {
|
|
168
|
-
return total > 0 ? `${((n / total) * 100).toFixed(1)}%` : '0%';
|
|
169
|
-
}
|
|
170
83
|
function printHelp() {
|
|
171
84
|
o.out(`${o.c.bold('dolex check')} — audit data for bad data & analysis footguns
|
|
172
85
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function cleanCommand(argv: string[]): Promise<number>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `dolex clean` — remediate a column with a CALLER-AUTHORED Python clean(value)
|
|
3
|
+
* (the CLI twin of the MCP clean_column tool). Preview by default; --apply
|
|
4
|
+
* materializes a non-destructive cleaned CSV (<col>_raw kept) + a replayable
|
|
5
|
+
* manifest. --apply-manifest replays an existing manifest with no code.
|
|
6
|
+
* Authoring is the caller's job — the command never calls a model.
|
|
7
|
+
*/
|
|
8
|
+
import { readFileSync, writeFileSync } from 'fs';
|
|
9
|
+
import { dirname, basename, join, resolve } from 'path';
|
|
10
|
+
import Papa from 'papaparse';
|
|
11
|
+
import { parseArgs, str, bool } from '../args.js';
|
|
12
|
+
import * as o from '../output.js';
|
|
13
|
+
import { openTarget } from '../data-source.js';
|
|
14
|
+
import { pythonAvailable, runPythonClean, cleanStats, safetyVerdict, previewSample, applyManifest, } from '../../cleaning/index.js';
|
|
15
|
+
const BOOLEANS = ['apply', 'help'];
|
|
16
|
+
const ALIASES = { h: 'help', c: 'column' };
|
|
17
|
+
export async function cleanCommand(argv) {
|
|
18
|
+
const args = parseArgs(argv, { booleans: BOOLEANS, aliases: ALIASES });
|
|
19
|
+
if (bool(args, 'help')) {
|
|
20
|
+
printHelp();
|
|
21
|
+
return 0;
|
|
22
|
+
}
|
|
23
|
+
const target = args._[0];
|
|
24
|
+
if (!target) {
|
|
25
|
+
o.fail('Usage: dolex clean <csv> --column <col> --code-file <fix.py> [--apply]');
|
|
26
|
+
return 1;
|
|
27
|
+
}
|
|
28
|
+
if (!pythonAvailable()) {
|
|
29
|
+
o.fail('dolex clean requires python3 on PATH (not found).');
|
|
30
|
+
return 1;
|
|
31
|
+
}
|
|
32
|
+
const manifestArg = str(args, 'apply-manifest');
|
|
33
|
+
if (manifestArg !== undefined)
|
|
34
|
+
return replay(target, manifestArg);
|
|
35
|
+
const column = str(args, 'column');
|
|
36
|
+
const codeFile = str(args, 'code-file');
|
|
37
|
+
if (!column || !codeFile) {
|
|
38
|
+
o.fail('Pass --column <col> and --code-file <fix.py> (the caller authors the clean()).');
|
|
39
|
+
return 1;
|
|
40
|
+
}
|
|
41
|
+
const code = readFileSync(resolve(codeFile), 'utf8');
|
|
42
|
+
// Read the column's values through the shared opener.
|
|
43
|
+
const opened = await openTarget(target, {});
|
|
44
|
+
try {
|
|
45
|
+
const tableName = opened.defaultTable;
|
|
46
|
+
const q = await opened.query(`SELECT "${column.replace(/"/g, '""')}" AS v FROM "${tableName.replace(/"/g, '""')}"`, 1_000_000);
|
|
47
|
+
if (!q.ok) {
|
|
48
|
+
o.fail(`could not read column "${column}": ${q.error}`);
|
|
49
|
+
return 1;
|
|
50
|
+
}
|
|
51
|
+
const raw = (q.rows ?? []).map((r) => (r.v === null || r.v === '' ? null : String(r.v)));
|
|
52
|
+
let cleaned;
|
|
53
|
+
let errors;
|
|
54
|
+
try {
|
|
55
|
+
({ cleaned, errors } = runPythonClean(code, raw));
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
o.fail(`clean() rejected: ${e?.message ?? String(e)} (nothing written)`);
|
|
59
|
+
return 1;
|
|
60
|
+
}
|
|
61
|
+
const norm = cleaned.map((v) => (v === '' ? null : v));
|
|
62
|
+
const stats = { ...cleanStats(raw, norm), errors };
|
|
63
|
+
const safety = safetyVerdict(raw, norm, errors);
|
|
64
|
+
const sample = previewSample(raw, norm, 20);
|
|
65
|
+
o.heading(`dolex clean — ${opened.displayName}.${column}`);
|
|
66
|
+
o.hint(`${stats.changed} changed · ${stats.nulledFromValue} nulled · ${errors} errors · ${stats.distinctBefore}→${stats.distinctAfter} distinct`);
|
|
67
|
+
for (const s of sample.slice(0, 10))
|
|
68
|
+
o.out(` ${JSON.stringify(s.before)} → ${JSON.stringify(s.after)}`);
|
|
69
|
+
if (!safety.ok) {
|
|
70
|
+
o.fail(`rejected: ${safety.reason} (nothing written)`);
|
|
71
|
+
return 1;
|
|
72
|
+
}
|
|
73
|
+
if (!bool(args, 'apply')) {
|
|
74
|
+
o.hint('Preview only — pass --apply to write <base>.clean.csv (non-destructive).');
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
// --apply: materialize via a single-fix manifest over the source CSV file.
|
|
78
|
+
const csvPath = resolve(target);
|
|
79
|
+
const fix = { column, issue: str(args, 'issue') ?? 'manual', task: 'caller-authored', pythonCode: code, validated: true, summary: `${stats.changed} changed` };
|
|
80
|
+
const manifest = { dataset: basename(csvPath), createdBy: 'dolex clean', createdAt: '', fixes: [fix] };
|
|
81
|
+
const { rows, fields } = applyManifest(csvPath, manifest);
|
|
82
|
+
const outArg = str(args, 'out');
|
|
83
|
+
const outDir = outArg ? dirname(resolve(outArg)) : dirname(csvPath);
|
|
84
|
+
const base = basename(csvPath, '.csv');
|
|
85
|
+
const cleanedPath = outArg ? resolve(outArg) : join(outDir, `${base}.clean.csv`);
|
|
86
|
+
writeFileSync(cleanedPath, Papa.unparse(rows, { columns: fields }));
|
|
87
|
+
writeFileSync(join(outDir, `${base}.cleanfix.json`), JSON.stringify(manifest, null, 2));
|
|
88
|
+
o.success(`wrote ${cleanedPath} (+ ${base}.cleanfix.json), original column kept as ${column}_raw`);
|
|
89
|
+
return 0;
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
await opened.close();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function replay(target, manifestPath) {
|
|
96
|
+
const csvPath = resolve(target);
|
|
97
|
+
const mPath = manifestPath || join(dirname(csvPath), `${basename(csvPath, '.csv')}.cleanfix.json`);
|
|
98
|
+
const manifest = JSON.parse(readFileSync(resolve(mPath), 'utf8'));
|
|
99
|
+
const { rows, fields } = applyManifest(csvPath, manifest);
|
|
100
|
+
const cleanedPath = join(dirname(csvPath), `${basename(csvPath, '.csv')}.clean.csv`);
|
|
101
|
+
writeFileSync(cleanedPath, Papa.unparse(rows, { columns: fields }));
|
|
102
|
+
o.success(`replayed ${manifest.fixes.length} fix(es) → ${cleanedPath} (no model)`);
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
function printHelp() {
|
|
106
|
+
o.out(`${o.c.bold('dolex clean')} — remediate a column with a Python clean() you (the caller) write
|
|
107
|
+
|
|
108
|
+
${o.c.bold('USAGE')}
|
|
109
|
+
dolex clean <csv> --column <col> --code-file <fix.py> [--apply] [--out <path>] [--issue <type>]
|
|
110
|
+
dolex clean <csv> --apply-manifest [<manifest.cleanfix.json>]
|
|
111
|
+
|
|
112
|
+
${o.c.dim('Preview by default (before→after + stats, no write). --apply materializes')}
|
|
113
|
+
${o.c.dim('<base>.clean.csv + <base>.cleanfix.json, keeping the original as <col>_raw.')}
|
|
114
|
+
${o.c.dim("Authoring the clean() is the caller's job — this command never calls a model. Requires python3.")}`);
|
|
115
|
+
}
|
|
@@ -17,6 +17,7 @@ ${o.c.bold('COMMANDS')}
|
|
|
17
17
|
${o.c.cyan('analyze')} <csv|source> Auto-generate an analysis plan with ready-to-run SQL
|
|
18
18
|
${o.c.cyan('describe')} <csv|source> Profile columns: types, roles, stats, sample rows
|
|
19
19
|
${o.c.cyan('check')} <csv|source> Audit for bad data & footguns (type traps, sentinels, dupes…)
|
|
20
|
+
${o.c.cyan('clean')} <csv> Remediate a column with a Python clean() you write (preview/apply)
|
|
20
21
|
${o.c.cyan('transform')} <csv|source> Add a persisted derived column (--create … --expr …)
|
|
21
22
|
${o.c.cyan('columns')} <csv|source> List columns by layer (source / derived / working)
|
|
22
23
|
${o.c.cyan('drop')} <csv|source> Remove derived/working columns
|
|
@@ -29,6 +29,9 @@ export async function queryCommand(argv) {
|
|
|
29
29
|
}
|
|
30
30
|
const rows = res.rows ?? [];
|
|
31
31
|
const columns = res.columns ?? (rows.length > 0 ? Object.keys(rows[0]) : []);
|
|
32
|
+
// SQL-safety advisories → stderr, so piped stdout (json/csv) stays clean.
|
|
33
|
+
for (const w of res.warnings ?? [])
|
|
34
|
+
o.warn(w);
|
|
32
35
|
switch (format) {
|
|
33
36
|
case 'json':
|
|
34
37
|
o.out(JSON.stringify(rows, null, 2));
|
|
@@ -68,5 +71,5 @@ ${o.c.bold('OPTIONS')}
|
|
|
68
71
|
--limit <n> Max rows (default 10000)
|
|
69
72
|
--from <table> Pick a table when the source has several
|
|
70
73
|
|
|
71
|
-
${o.c.dim('Custom aggregates: MEDIAN, STDDEV,
|
|
74
|
+
${o.c.dim('Custom aggregates: MEDIAN, STDDEV, CV, MAD, P1/P5/P10/P25/P75/P90/P95/P99. Read-only (SELECT/WITH) only.')}`);
|
|
72
75
|
}
|
package/dist/src/cli/index.js
CHANGED
|
@@ -71,6 +71,8 @@ async function main() {
|
|
|
71
71
|
case 'check':
|
|
72
72
|
case 'audit':
|
|
73
73
|
process.exit(await (await import('./commands/check.js')).checkCommand(rest));
|
|
74
|
+
case 'clean':
|
|
75
|
+
process.exit(await (await import('./commands/clean.js')).cleanCommand(rest));
|
|
74
76
|
case 'transform':
|
|
75
77
|
process.exit(await (await import('./commands/transform.js')).transformCommand(rest));
|
|
76
78
|
case 'columns':
|