@outsidedata/dolex 8.1.0 → 9.0.2

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 (79) hide show
  1. package/README.md +30 -7
  2. package/dist/src/analysis/planner.d.ts +2 -1
  3. package/dist/src/analysis/planner.js +2 -2
  4. package/dist/src/analysis/quality.js +96 -5
  5. package/dist/src/analysis/rules.d.ts +22 -2
  6. package/dist/src/analysis/rules.js +64 -23
  7. package/dist/src/cleaning/index.d.ts +2 -6
  8. package/dist/src/cleaning/index.js +8 -3
  9. package/dist/src/cleaning/replay.d.ts +34 -0
  10. package/dist/src/cleaning/replay.js +58 -0
  11. package/dist/src/cli/commands/analyze.js +13 -1
  12. package/dist/src/cli/commands/clean.js +15 -3
  13. package/dist/src/cli/commands/deps.d.ts +1 -0
  14. package/dist/src/cli/commands/deps.js +41 -0
  15. package/dist/src/cli/commands/help.js +2 -1
  16. package/dist/src/cli/commands/sources.d.ts +2 -2
  17. package/dist/src/cli/commands/sources.js +139 -12
  18. package/dist/src/cli/commands/transform.js +19 -4
  19. package/dist/src/cli/data-source.d.ts +0 -2
  20. package/dist/src/cli/data-source.js +0 -1
  21. package/dist/src/cli/index.js +3 -0
  22. package/dist/src/connectors/csv.js +29 -0
  23. package/dist/src/connectors/index.d.ts +2 -0
  24. package/dist/src/connectors/index.js +2 -0
  25. package/dist/src/connectors/manager.d.ts +39 -1
  26. package/dist/src/connectors/manager.js +191 -45
  27. package/dist/src/connectors/mongo/index.d.ts +21 -0
  28. package/dist/src/connectors/mongo/index.js +359 -0
  29. package/dist/src/connectors/pg/index.d.ts +2 -0
  30. package/dist/src/connectors/pg/index.js +316 -0
  31. package/dist/src/connectors/source-factory.d.ts +38 -0
  32. package/dist/src/connectors/source-factory.js +80 -0
  33. package/dist/src/connectors/sql-safety.d.ts +59 -17
  34. package/dist/src/connectors/sql-safety.js +275 -54
  35. package/dist/src/connectors/types.d.ts +59 -0
  36. package/dist/src/connectors/types.js +33 -1
  37. package/dist/src/mcp/index.d.ts +1 -1
  38. package/dist/src/mcp/index.js +43 -13
  39. package/dist/src/mcp/tools/analyze.js +12 -2
  40. package/dist/src/mcp/tools/capabilities.d.ts +1 -0
  41. package/dist/src/mcp/tools/capabilities.js +14 -0
  42. package/dist/src/mcp/tools/clean-column.js +2 -0
  43. package/dist/src/mcp/tools/clean-schemas.js +1 -1
  44. package/dist/src/mcp/tools/drop-columns.js +2 -0
  45. package/dist/src/mcp/tools/list-transforms.js +22 -0
  46. package/dist/src/mcp/tools/promote-columns.js +2 -0
  47. package/dist/src/mcp/tools/query-source.js +2 -2
  48. package/dist/src/mcp/tools/refine-cli.d.ts +4 -4
  49. package/dist/src/mcp/tools/refine.d.ts +4 -4
  50. package/dist/src/mcp/tools/shared.d.ts +5 -0
  51. package/dist/src/mcp/tools/shared.js +11 -4
  52. package/dist/src/mcp/tools/sources.d.ts +47 -4
  53. package/dist/src/mcp/tools/sources.js +51 -9
  54. package/dist/src/mcp/tools/transform-data.js +22 -0
  55. package/dist/src/mcp/tools/transform-schemas.js +4 -4
  56. package/dist/src/mcp/tools/visualize-cli.js +1 -1
  57. package/dist/src/mcp/tools/visualize.js +2 -2
  58. package/dist/src/patterns/index.d.ts +1 -1
  59. package/dist/src/patterns/index.js +1 -1
  60. package/dist/src/patterns/registry.d.ts +1 -12
  61. package/dist/src/patterns/registry.js +0 -13
  62. package/dist/src/patterns/utils.d.ts +0 -24
  63. package/dist/src/patterns/utils.js +0 -71
  64. package/dist/src/renderers/d3/shared.d.ts +0 -18
  65. package/dist/src/renderers/d3/shared.js +0 -62
  66. package/dist/src/types.d.ts +30 -3
  67. package/dist/src/utils/capabilities.d.ts +28 -0
  68. package/dist/src/utils/capabilities.js +58 -0
  69. package/dist/src/utils/optional-deps.d.ts +8 -0
  70. package/dist/src/utils/optional-deps.js +8 -0
  71. package/package.json +5 -2
  72. package/dist/src/analysis/clean-exec.d.ts +0 -23
  73. package/dist/src/analysis/clean-exec.js +0 -87
  74. package/dist/src/cleaning/author.d.ts +0 -30
  75. package/dist/src/cleaning/author.js +0 -7
  76. package/dist/src/cleaning/handlers.d.ts +0 -16
  77. package/dist/src/cleaning/handlers.js +0 -82
  78. package/dist/src/cleaning/manifest.d.ts +0 -35
  79. package/dist/src/cleaning/manifest.js +0 -95
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outsidedata/dolex",
3
- "version": "8.1.0",
3
+ "version": "9.0.2",
4
4
  "description": "Turn your AI assistant into a data analyst you can trust on your own CSV files — column profiling, data-quality auditing, a prioritized analysis plan, and findings rendered across 43 chart types.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -87,7 +87,9 @@
87
87
  },
88
88
  "optionalDependencies": {
89
89
  "@modelcontextprotocol/ext-apps": "^1.0.1",
90
- "@modelcontextprotocol/sdk": "^1.26.0",
90
+ "@modelcontextprotocol/sdk": "^1.30.1",
91
+ "mongodb": "^7.4.0",
92
+ "pg": "^8.22.0",
91
93
  "topojson-client": "^3.1.0"
92
94
  },
93
95
  "peerDependencies": {
@@ -110,6 +112,7 @@
110
112
  "@types/better-sqlite3": "^7.6.13",
111
113
  "@types/node": "^20",
112
114
  "@types/papaparse": "^5.3.16",
115
+ "@types/pg": "^8.20.0",
113
116
  "@types/react": "^19.2.13",
114
117
  "@types/react-dom": "^19.2.3",
115
118
  "@types/topojson-client": "^3.1.5",
@@ -1,23 +0,0 @@
1
- export declare function pythonAvailable(): boolean;
2
- export declare function runPythonClean(code: string, values: (string | null)[]): {
3
- cleaned: (string | null)[];
4
- errors: number;
5
- };
6
- export interface CleanStats {
7
- rows: number;
8
- errors: number;
9
- changed: number;
10
- nulledFromValue: number;
11
- distinctBefore: number;
12
- distinctAfter: number;
13
- }
14
- export declare function cleanStats(raw: (string | null)[], cleaned: (string | null)[]): CleanStats;
15
- export declare function safetyVerdict(raw: (string | null)[], cleaned: (string | null)[], errors: number): {
16
- ok: boolean;
17
- reason?: string;
18
- };
19
- export declare function previewSample(raw: (string | null)[], cleaned: (string | null)[], n: number): {
20
- before: string | null;
21
- after: string | null;
22
- }[];
23
- export declare function applyCleanColumn(db: any, table: string, newColumn: string, rowids: number[], cleaned: (string | null)[]): void;
@@ -1,87 +0,0 @@
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
- * SECURITY: executes model Python via python3. Local-self-run trust model only;
5
- * a hosted deployment must sandbox this.
6
- */
7
- import { execFileSync } from 'child_process';
8
- import { mkdtempSync, writeFileSync, rmSync } from 'fs';
9
- import { tmpdir } from 'os';
10
- import { join } from 'path';
11
- export function pythonAvailable() {
12
- try {
13
- execFileSync('python3', ['--version'], { stdio: 'ignore' });
14
- return true;
15
- }
16
- catch {
17
- return false;
18
- }
19
- }
20
- export function runPythonClean(code, values) {
21
- const dir = mkdtempSync(join(tmpdir(), 'dolex-clean-'));
22
- try {
23
- const vf = join(dir, 'v.json');
24
- writeFileSync(vf, JSON.stringify(values));
25
- const sf = join(dir, 'c.py');
26
- writeFileSync(sf, `${code}\n\nimport json, sys\n` +
27
- `vals = json.load(open(sys.argv[1]))\n` +
28
- `out = []\nerr = 0\n` +
29
- `for v in vals:\n` +
30
- ` try:\n r = clean(v)\n out.append(None if r is None else str(r))\n` +
31
- ` except Exception:\n err += 1\n out.append(None)\n` +
32
- `print(json.dumps({"cleaned": out, "errors": err}))\n`);
33
- const raw = execFileSync('python3', [sf, vf], { timeout: 60000, encoding: 'utf8', maxBuffer: 512 * 1024 * 1024 });
34
- const parsed = JSON.parse(raw);
35
- return { cleaned: parsed.cleaned, errors: parsed.errors };
36
- }
37
- finally {
38
- rmSync(dir, { recursive: true, force: true });
39
- }
40
- }
41
- const isBlank = (x) => x === null || x === '' || x === undefined;
42
- export function cleanStats(raw, cleaned) {
43
- let changed = 0, nulledFromValue = 0;
44
- for (let i = 0; i < raw.length; i++) {
45
- if (String(raw[i] ?? '') !== String(cleaned[i] ?? ''))
46
- changed++;
47
- if (!isBlank(raw[i]) && isBlank(cleaned[i]))
48
- nulledFromValue++;
49
- }
50
- return {
51
- rows: raw.length, errors: 0, changed, nulledFromValue,
52
- distinctBefore: new Set(raw.filter((v) => !isBlank(v))).size,
53
- distinctAfter: new Set(cleaned.filter((v) => !isBlank(v))).size,
54
- };
55
- }
56
- export function safetyVerdict(raw, cleaned, errors) {
57
- const rows = raw.length;
58
- if (rows === 0)
59
- return { ok: false, reason: 'no rows to clean' };
60
- if (errors > rows * 0.5)
61
- return { ok: false, reason: `the function errored on ${errors}/${rows} rows` };
62
- const nonBlankBefore = raw.filter((v) => !isBlank(v)).length;
63
- const nonBlankAfter = cleaned.filter((v) => !isBlank(v)).length;
64
- if (nonBlankBefore > 0 && nonBlankAfter === 0)
65
- return { ok: false, reason: 'every value became blank/null — the function likely destroyed the column' };
66
- return { ok: true };
67
- }
68
- export function previewSample(raw, cleaned, n) {
69
- const out = [];
70
- for (let i = 0; i < raw.length && out.length < n; i++) {
71
- if (String(raw[i] ?? '') !== String(cleaned[i] ?? ''))
72
- out.push({ before: raw[i], after: cleaned[i] });
73
- }
74
- return out;
75
- }
76
- const q = (s) => `"${s.replace(/"/g, '""')}"`;
77
- export function applyCleanColumn(db, table, newColumn, rowids, cleaned) {
78
- db.exec(`ALTER TABLE ${q(table)} ADD COLUMN ${q(newColumn)}`);
79
- const upd = db.prepare(`UPDATE ${q(table)} SET ${q(newColumn)} = ? WHERE rowid = ?`);
80
- const tx = db.transaction((pairs) => {
81
- // '' = missing — match the connector's "empty string is null" convention so the
82
- // stored value agrees with stats/safety (which treat '' as blank). [second-look fix]
83
- for (const [val, rid] of pairs)
84
- upd.run(val === '' ? null : val, rid);
85
- });
86
- tx(cleaned.map((v, i) => [v, rowids[i]]));
87
- }
@@ -1,30 +0,0 @@
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
- };
@@ -1,7 +0,0 @@
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
- }
@@ -1,16 +0,0 @@
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 {};
@@ -1,82 +0,0 @@
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
- }
@@ -1,35 +0,0 @@
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
- }>;
@@ -1,95 +0,0 @@
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
- }