@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
@@ -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
+ }
@@ -0,0 +1,34 @@
1
+ export interface FixRecord {
2
+ column: string;
3
+ issue: string;
4
+ task: string;
5
+ pythonCode: string;
6
+ validated: boolean;
7
+ summary: string;
8
+ }
9
+ export interface CleanManifest {
10
+ dataset: string;
11
+ createdBy: string;
12
+ createdAt: string;
13
+ fixes: FixRecord[];
14
+ }
15
+ type Row = Record<string, string>;
16
+ export declare function parseCsv(p: string): {
17
+ rows: Row[];
18
+ fields: string[];
19
+ };
20
+ /** Apply validated fixes to in-memory rows (mutates). When `keepRaw`, also writes a
21
+ * `<col>_raw` provenance column from the value the fix saw before overwriting `<col>`.
22
+ * The autoclean loop applies with keepRaw=false (provenance columns re-trigger the healed
23
+ * findings on re-audit); materialization keeps it for lineage. */
24
+ export declare function applyFixesToRows(rows: Row[], fixes: FixRecord[], keepRaw?: boolean): void;
25
+ /** Replay validated fixes over a CSV. NO model. `keepRaw` retains `<col>_raw` lineage. */
26
+ export declare function applyManifest(rawPath: string, manifest: CleanManifest, keepRaw?: boolean): {
27
+ rows: Row[];
28
+ fields: string[];
29
+ };
30
+ /** `<base>.cleanfix.json` co-located with the CSV (matches cleanDataset's default outDir). */
31
+ export declare function resolveCleanfixPath(csvPath: string): string;
32
+ /** Read + shape-validate a cleanfix manifest. Returns null if absent/invalid/empty. */
33
+ export declare function readCleanfixManifest(csvPath: string): CleanManifest | null;
34
+ export {};
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Cleanfix replay — the model-free, SourceManager-free half of the cleaning core. Lives in
3
+ * its own module so the CSV connector can replay a cleanfix manifest at load time WITHOUT
4
+ * pulling in SourceManager (manifest.ts → SourceManager → connectors → manifest.ts would be
5
+ * a cycle). Imports only papaparse + the python executor.
6
+ *
7
+ * The manifest (`<base>.cleanfix.json`) is the durable recipe: replaying it over the CURRENT
8
+ * raw CSV is what gives newly-arrived rows the same treatment as the data it was authored on.
9
+ */
10
+ import * as fs from 'fs';
11
+ import * as path from 'path';
12
+ import Papa from 'papaparse';
13
+ import { runPythonClean } from './exec.js';
14
+ const blank = (x) => x === null || x === '' || x === undefined;
15
+ export function parseCsv(p) {
16
+ const parsed = Papa.parse(fs.readFileSync(p, 'utf8'), { header: true, skipEmptyLines: true });
17
+ return { rows: parsed.data, fields: parsed.meta.fields || [] };
18
+ }
19
+ /** Apply validated fixes to in-memory rows (mutates). When `keepRaw`, also writes a
20
+ * `<col>_raw` provenance column from the value the fix saw before overwriting `<col>`.
21
+ * The autoclean loop applies with keepRaw=false (provenance columns re-trigger the healed
22
+ * findings on re-audit); materialization keeps it for lineage. */
23
+ export function applyFixesToRows(rows, fixes, keepRaw = true) {
24
+ for (const fix of fixes) {
25
+ if (rows.length > 0 && !(fix.column in rows[0]))
26
+ continue; // column gone (renamed/dropped) — skip gracefully
27
+ const { cleaned } = runPythonClean(fix.pythonCode, rows.map((r) => r[fix.column] ?? ''));
28
+ rows.forEach((r, i) => { if (keepRaw)
29
+ r[`${fix.column}_raw`] = r[fix.column] ?? ''; r[fix.column] = blank(cleaned[i]) ? '' : String(cleaned[i]); });
30
+ }
31
+ }
32
+ /** Replay validated fixes over a CSV. NO model. `keepRaw` retains `<col>_raw` lineage. */
33
+ export function applyManifest(rawPath, manifest, keepRaw = true) {
34
+ const { rows, fields } = parseCsv(rawPath);
35
+ const present = manifest.fixes.filter((f) => rows.length === 0 || f.column in rows[0]);
36
+ applyFixesToRows(rows, manifest.fixes, keepRaw);
37
+ return { rows, fields: keepRaw ? [...fields, ...present.map((f) => `${f.column}_raw`)] : fields };
38
+ }
39
+ /** `<base>.cleanfix.json` co-located with the CSV (matches cleanDataset's default outDir). */
40
+ export function resolveCleanfixPath(csvPath) {
41
+ return path.join(path.dirname(csvPath), `${path.basename(csvPath, path.extname(csvPath))}.cleanfix.json`);
42
+ }
43
+ /** Read + shape-validate a cleanfix manifest. Returns null if absent/invalid/empty. */
44
+ export function readCleanfixManifest(csvPath) {
45
+ try {
46
+ const p = resolveCleanfixPath(csvPath);
47
+ if (!fs.existsSync(p))
48
+ return null;
49
+ const m = JSON.parse(fs.readFileSync(p, 'utf8'));
50
+ if (!m || !Array.isArray(m.fixes))
51
+ return null;
52
+ const fixes = m.fixes.filter((f) => f && f.validated && f.column && f.pythonCode);
53
+ return fixes.length > 0 ? { ...m, fixes } : null;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
@@ -6,6 +6,7 @@ import { parseArgs, str, num, bool } from '../args.js';
6
6
  import * as o from '../output.js';
7
7
  import { openTarget } from '../data-source.js';
8
8
  import { buildAnalysisPlan } from '../../analysis/planner.js';
9
+ import { plannerDialectForSource, PlannerUnsupportedSourceError } from '../../analysis/rules.js';
9
10
  import { classifyColumns } from '../../analysis/classify.js';
10
11
  const BOOLEANS = ['json', 'help'];
11
12
  const ALIASES = { h: 'help', table: 'from' };
@@ -47,7 +48,18 @@ export async function analyzeCommand(argv) {
47
48
  const tableObj = autoPicked
48
49
  ? pickRichestTable(opened.tables)
49
50
  : opened.tables.find((t) => t.name === opened.defaultTable);
50
- const plan = buildAnalysisPlan(tableObj.columns, tableObj.name, opened.displayName, num(args, 'max-steps') ?? 6);
51
+ let dialect;
52
+ try {
53
+ dialect = plannerDialectForSource(opened.schema.source?.type);
54
+ }
55
+ catch (err) {
56
+ if (err instanceof PlannerUnsupportedSourceError) {
57
+ o.fail(err.message);
58
+ return 1;
59
+ }
60
+ throw err;
61
+ }
62
+ const plan = buildAnalysisPlan(tableObj.columns, tableObj.name, opened.displayName, num(args, 'max-steps') ?? 6, dialect);
51
63
  // No steps = nothing to analyze (only ids/text/empty columns). Fail loud
52
64
  // rather than print a success-looking empty plan.
53
65
  const noSteps = plan.steps.length === 0;
@@ -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 { auditColumns } from '../../analysis/quality.js';
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,127 @@
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
+ // --apply-manifest may be bare (replay the sibling <base>.cleanfix.json) or take an explicit
33
+ // path. A bare value flag parses to boolean `true`, so test presence, not string-ness —
34
+ // otherwise the documented no-arg form fell through to the author-mode usage error.
35
+ if (args['apply-manifest'] !== undefined) {
36
+ return replay(target, str(args, 'apply-manifest') ?? '');
37
+ }
38
+ const column = str(args, 'column');
39
+ const codeFile = str(args, 'code-file');
40
+ if (!column || !codeFile) {
41
+ o.fail('Pass --column <col> and --code-file <fix.py> (the caller authors the clean()).');
42
+ return 1;
43
+ }
44
+ const code = readFileSync(resolve(codeFile), 'utf8');
45
+ // Read the column's values through the shared opener.
46
+ const opened = await openTarget(target, {});
47
+ try {
48
+ // clean writes a non-destructive cleaned CSV from a CSV file — a live DB source has no
49
+ // file to rewrite. Reject up front with the same redirect the MCP clean_column twin gives,
50
+ // instead of previewing and then failing with a confusing ENOENT on the source name.
51
+ const srcType = opened.manager.get(opened.sourceId)?.config?.type;
52
+ if (srcType && srcType !== 'csv') {
53
+ const nativeExpr = srcType === 'mongodb' ? 'native aggregation ($set) expression' : 'native SQL expression';
54
+ o.fail(`dolex clean writes a non-destructive cleaned CSV and works on CSV sources only. On a live ${srcType} source, express the fix as a derived column via \`dolex transform\` using a ${nativeExpr} — non-destructive and server-side.`);
55
+ return 1;
56
+ }
57
+ const tableName = opened.defaultTable;
58
+ const q = await opened.query(`SELECT "${column.replace(/"/g, '""')}" AS v FROM "${tableName.replace(/"/g, '""')}"`, 1_000_000);
59
+ if (!q.ok) {
60
+ o.fail(`could not read column "${column}": ${q.error}`);
61
+ return 1;
62
+ }
63
+ const raw = (q.rows ?? []).map((r) => (r.v === null || r.v === '' ? null : String(r.v)));
64
+ let cleaned;
65
+ let errors;
66
+ try {
67
+ ({ cleaned, errors } = runPythonClean(code, raw));
68
+ }
69
+ catch (e) {
70
+ o.fail(`clean() rejected: ${e?.message ?? String(e)} (nothing written)`);
71
+ return 1;
72
+ }
73
+ const norm = cleaned.map((v) => (v === '' ? null : v));
74
+ const stats = { ...cleanStats(raw, norm), errors };
75
+ const safety = safetyVerdict(raw, norm, errors);
76
+ const sample = previewSample(raw, norm, 20);
77
+ o.heading(`dolex clean — ${opened.displayName}.${column}`);
78
+ o.hint(`${stats.changed} changed · ${stats.nulledFromValue} nulled · ${errors} errors · ${stats.distinctBefore}→${stats.distinctAfter} distinct`);
79
+ for (const s of sample.slice(0, 10))
80
+ o.out(` ${JSON.stringify(s.before)} → ${JSON.stringify(s.after)}`);
81
+ if (!safety.ok) {
82
+ o.fail(`rejected: ${safety.reason} (nothing written)`);
83
+ return 1;
84
+ }
85
+ if (!bool(args, 'apply')) {
86
+ o.hint('Preview only — pass --apply to write <base>.clean.csv (non-destructive).');
87
+ return 0;
88
+ }
89
+ // --apply: materialize via a single-fix manifest over the source CSV file.
90
+ const csvPath = resolve(target);
91
+ const fix = { column, issue: str(args, 'issue') ?? 'manual', task: 'caller-authored', pythonCode: code, validated: true, summary: `${stats.changed} changed` };
92
+ const manifest = { dataset: basename(csvPath), createdBy: 'dolex clean', createdAt: '', fixes: [fix] };
93
+ const { rows, fields } = applyManifest(csvPath, manifest);
94
+ const outArg = str(args, 'out');
95
+ const outDir = outArg ? dirname(resolve(outArg)) : dirname(csvPath);
96
+ const base = basename(csvPath, '.csv');
97
+ const cleanedPath = outArg ? resolve(outArg) : join(outDir, `${base}.clean.csv`);
98
+ writeFileSync(cleanedPath, Papa.unparse(rows, { columns: fields }));
99
+ writeFileSync(join(outDir, `${base}.cleanfix.json`), JSON.stringify(manifest, null, 2));
100
+ o.success(`wrote ${cleanedPath} (+ ${base}.cleanfix.json), original column kept as ${column}_raw`);
101
+ return 0;
102
+ }
103
+ finally {
104
+ await opened.close();
105
+ }
106
+ }
107
+ function replay(target, manifestPath) {
108
+ const csvPath = resolve(target);
109
+ const mPath = manifestPath || join(dirname(csvPath), `${basename(csvPath, '.csv')}.cleanfix.json`);
110
+ const manifest = JSON.parse(readFileSync(resolve(mPath), 'utf8'));
111
+ const { rows, fields } = applyManifest(csvPath, manifest);
112
+ const cleanedPath = join(dirname(csvPath), `${basename(csvPath, '.csv')}.clean.csv`);
113
+ writeFileSync(cleanedPath, Papa.unparse(rows, { columns: fields }));
114
+ o.success(`replayed ${manifest.fixes.length} fix(es) → ${cleanedPath} (no model)`);
115
+ return 0;
116
+ }
117
+ function printHelp() {
118
+ o.out(`${o.c.bold('dolex clean')} — remediate a column with a Python clean() you (the caller) write
119
+
120
+ ${o.c.bold('USAGE')}
121
+ dolex clean <csv> --column <col> --code-file <fix.py> [--apply] [--out <path>] [--issue <type>]
122
+ dolex clean <csv> --apply-manifest [<manifest.cleanfix.json>]
123
+
124
+ ${o.c.dim('Preview by default (before→after + stats, no write). --apply materializes')}
125
+ ${o.c.dim('<base>.clean.csv + <base>.cleanfix.json, keeping the original as <col>_raw.')}
126
+ ${o.c.dim("Authoring the clean() is the caller's job — this command never calls a model. Requires python3.")}`);
127
+ }
@@ -0,0 +1 @@
1
+ export declare function depsCommand(argv: string[]): Promise<number>;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * `dolex deps` — report which optional capabilities are available in THIS environment, so a
3
+ * human (or an AI agent driving Dolex) can see what's ready and how to enable the rest BEFORE
4
+ * trying it. The sibling of `dolex check` (which audits DATA health); this audits ENVIRONMENT health.
5
+ *
6
+ * `--json` emits the shared capability report for an agent to reason on. Exit code is non-zero only
7
+ * when a CORE dependency is missing (the base install is broken), like `dolex check`.
8
+ */
9
+ import { parseArgs, bool } from '../args.js';
10
+ import * as o from '../output.js';
11
+ import { probeCapabilities } from '../../utils/capabilities.js';
12
+ export async function depsCommand(argv) {
13
+ const args = parseArgs(argv, { booleans: ['json', 'help'], aliases: { h: 'help' } });
14
+ if (bool(args, 'help')) {
15
+ o.out('dolex deps — report which optional capabilities are available in this environment.');
16
+ o.out(' --json machine-readable report (for an AI agent to check readiness before acting)');
17
+ return 0;
18
+ }
19
+ const cap = probeCapabilities();
20
+ if (bool(args, 'json')) {
21
+ o.out(JSON.stringify(cap, null, 2));
22
+ return cap.coreOk ? 0 : 1;
23
+ }
24
+ o.heading('Data sources — what can I connect to here');
25
+ o.out(o.table(['source', 'status'], [
26
+ { source: 'CSV / SQLite', status: cap.sources.csv },
27
+ { source: 'PostgreSQL', status: cap.sources.postgres },
28
+ { source: 'MongoDB', status: cap.sources.mongodb },
29
+ ]));
30
+ o.out();
31
+ o.heading('Optional features');
32
+ o.out(o.table(['feature', 'installed', 'how to enable'], [
33
+ ...cap.deps.map((d) => ({ feature: d.enables, installed: d.installed ? `✓ ${d.version ?? ''}`.trim() : '—', 'how to enable': d.install ?? '' })),
34
+ { feature: cap.python.enables, installed: cap.python.available ? `✓ ${cap.python.version ?? ''}`.trim() : '—', 'how to enable': cap.python.install ?? '' },
35
+ ]));
36
+ if (!cap.coreOk) {
37
+ o.out();
38
+ o.fail('core engine (better-sqlite3) is missing — reinstall dolex.');
39
+ }
40
+ return cap.coreOk ? 0 : 1;
41
+ }
@@ -17,11 +17,13 @@ ${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
23
24
  ${o.c.cyan('patterns')} [id] List the 43 chart patterns, or show one
24
- ${o.c.cyan('sources')} <list|add|rm> Manage the persistent CSV registry
25
+ ${o.c.cyan('sources')} <list|add|rm> Register & manage data sources (CSV / Postgres / MongoDB)
26
+ ${o.c.cyan('deps')} Report which data sources & optional features are available here
25
27
  ${o.c.cyan('mcp')} Run the MCP stdio server (Claude Desktop / agents)
26
28
  ${o.c.cyan('help')} [command] Show help; \`--version\` for version
27
29
 
@@ -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, P25, P75, P10, P90. Read-only (SELECT/WITH) only.')}`);
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
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `dolex sources` — manage the persistent CSV registry at
3
- * `~/.dolex/sources.json` (shared with the MCP server's `load_csv`).
2
+ * `dolex sources` — manage the persistent data-source registry at
3
+ * `~/.dolex/sources.json` (CSV / Postgres / MongoDB; shared with the MCP server's `load_source`).
4
4
  */
5
5
  export declare function sourcesCommand(argv: string[]): Promise<number>;