@outsidedata/dolex 9.0.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 (39) hide show
  1. package/dist/src/cli/commands/sources.js +2 -1
  2. package/dist/src/cli/data-source.d.ts +0 -2
  3. package/dist/src/cli/data-source.js +0 -1
  4. package/dist/src/connectors/manager.js +71 -52
  5. package/dist/src/connectors/mongo/index.d.ts +8 -0
  6. package/dist/src/connectors/mongo/index.js +42 -6
  7. package/dist/src/connectors/pg/index.js +90 -22
  8. package/dist/src/connectors/sql-safety.d.ts +59 -17
  9. package/dist/src/connectors/sql-safety.js +275 -54
  10. package/dist/src/connectors/types.d.ts +8 -0
  11. package/dist/src/connectors/types.js +22 -0
  12. package/dist/src/mcp/index.js +23 -4
  13. package/dist/src/mcp/tools/analyze.js +1 -1
  14. package/dist/src/mcp/tools/clean-schemas.js +1 -1
  15. package/dist/src/mcp/tools/query-source.js +2 -2
  16. package/dist/src/mcp/tools/sources.d.ts +1 -1
  17. package/dist/src/mcp/tools/sources.js +7 -5
  18. package/dist/src/mcp/tools/transform-schemas.js +4 -4
  19. package/dist/src/mcp/tools/visualize-cli.js +1 -1
  20. package/dist/src/mcp/tools/visualize.js +2 -2
  21. package/dist/src/patterns/index.d.ts +1 -1
  22. package/dist/src/patterns/index.js +1 -1
  23. package/dist/src/patterns/registry.d.ts +1 -12
  24. package/dist/src/patterns/registry.js +0 -13
  25. package/dist/src/patterns/utils.d.ts +0 -24
  26. package/dist/src/patterns/utils.js +0 -71
  27. package/dist/src/renderers/d3/shared.d.ts +0 -18
  28. package/dist/src/renderers/d3/shared.js +0 -62
  29. package/dist/src/types.d.ts +1 -1
  30. package/dist/src/utils/capabilities.js +1 -1
  31. package/package.json +4 -4
  32. package/dist/src/analysis/clean-exec.d.ts +0 -23
  33. package/dist/src/analysis/clean-exec.js +0 -87
  34. package/dist/src/cleaning/author.d.ts +0 -30
  35. package/dist/src/cleaning/author.js +0 -7
  36. package/dist/src/cleaning/handlers.d.ts +0 -16
  37. package/dist/src/cleaning/handlers.js +0 -82
  38. package/dist/src/cleaning/manifest.d.ts +0 -35
  39. package/dist/src/cleaning/manifest.js +0 -95
@@ -16,7 +16,7 @@ import { columnsSchema, dataShapeHintsSchema, handleVisualizeCore } from './visu
16
16
  export const visualizeCliInputSchema = z.object({
17
17
  data: z.array(z.record(z.any())).optional().describe('Array of data rows to visualize. Optional if resultId or sourceId+sql is provided.'),
18
18
  resultId: z.string().optional().describe('Result ID from a previous query_data call'),
19
- sourceId: z.string().optional().describe('Dataset ID returned by load_csv'),
19
+ sourceId: z.string().optional().describe('Dataset ID returned by load_source'),
20
20
  sql: z.string().optional().describe('SQL SELECT query to slice/aggregate the data before visualizing.'),
21
21
  intent: z.string().describe('What the user wants to see'),
22
22
  columns: columnsSchema,
@@ -37,8 +37,8 @@ export const dataShapeHintsSchema = z.object({
37
37
  export const visualizeInputSchema = z.object({
38
38
  data: z.array(z.record(z.any())).optional().describe('Array of data rows to visualize. Optional if resultId or sourceId+sql is provided.'),
39
39
  resultId: z.string().optional().describe('Result ID from a previous query_data call — reuses cached data without re-sending it'),
40
- sourceId: z.string().optional().describe('Dataset ID returned by load_csv — use with sql to query server-side (saves tokens)'),
41
- sql: z.string().optional().describe('SQL SELECT query to slice/aggregate the data before visualizing. Use table and column names from load_csv/describe_data.'),
40
+ sourceId: z.string().optional().describe('Dataset ID returned by load_source — use with sql to query server-side (saves tokens)'),
41
+ sql: z.string().optional().describe('SQL SELECT query to slice/aggregate the data before visualizing. Use table and column names from load_source/describe_data.'),
42
42
  intent: z.string().describe('What the user wants to see — e.g., "compare sales by region", "show distribution of ages", "how do rankings change over time"'),
43
43
  columns: columnsSchema,
44
44
  dataShapeHints: dataShapeHintsSchema,
@@ -13,7 +13,7 @@
13
13
  export { registry } from './registry.js';
14
14
  export { selectPattern, quickRecommend, scoreSpecificPattern } from './selector.js';
15
15
  export type { SelectionResult } from './selector.js';
16
- export { buildMatchContext, parseIntent, hasTimeSeriesColumn, countCategories, countSeries, hasNegativeValues, getValueRange, detectHierarchy, findColumnByType, findColumnsByType, inferFieldType, inferEncoding, } from './utils.js';
16
+ export { buildMatchContext, parseIntent, hasTimeSeriesColumn, countCategories, countSeries, hasNegativeValues, getValueRange, detectHierarchy, } from './utils.js';
17
17
  export { barPattern, divergingBarPattern, slopeChartPattern, connectedDotPlotPattern, bumpChartPattern, } from './definitions/comparison/index.js';
18
18
  export { histogramPattern, beeswarmPattern, violinPattern, ridgelinePattern, stripPlotPattern, } from './definitions/distribution/index.js';
19
19
  export { stackedBarPattern, wafflePattern, treemapPattern, sunburstPattern, } from './definitions/composition/index.js';
@@ -14,7 +14,7 @@
14
14
  export { registry } from './registry.js';
15
15
  export { selectPattern, quickRecommend, scoreSpecificPattern } from './selector.js';
16
16
  // ─── UTILITIES ───────────────────────────────────────────────────────────────
17
- export { buildMatchContext, parseIntent, hasTimeSeriesColumn, countCategories, countSeries, hasNegativeValues, getValueRange, detectHierarchy, findColumnByType, findColumnsByType, inferFieldType, inferEncoding, } from './utils.js';
17
+ export { buildMatchContext, parseIntent, hasTimeSeriesColumn, countCategories, countSeries, hasNegativeValues, getValueRange, detectHierarchy, } from './utils.js';
18
18
  // ─── PATTERN DEFINITIONS ─────────────────────────────────────────────────────
19
19
  // Re-exported for direct access when needed.
20
20
  // Comparison
@@ -5,7 +5,7 @@
5
5
  * Patterns register themselves on import, and the registry provides
6
6
  * methods to query patterns by ID, category, or data requirements.
7
7
  */
8
- import type { VisualizationPattern, PatternCategory, DataRequirements } from '../types.js';
8
+ import type { VisualizationPattern, PatternCategory } from '../types.js';
9
9
  declare class PatternRegistry {
10
10
  private patterns;
11
11
  /**
@@ -45,17 +45,6 @@ declare class PatternRegistry {
45
45
  hasHierarchy?: boolean;
46
46
  hasTimeSeries?: boolean;
47
47
  }): VisualizationPattern[];
48
- /**
49
- * Get a summary of all patterns suitable for external listing.
50
- */
51
- listPatterns(): {
52
- id: string;
53
- name: string;
54
- category: PatternCategory;
55
- description: string;
56
- bestFor: string;
57
- dataRequirements: DataRequirements;
58
- }[];
59
48
  /**
60
49
  * Total number of registered patterns.
61
50
  */
@@ -112,19 +112,6 @@ class PatternRegistry {
112
112
  return isCompatible(req, opts);
113
113
  });
114
114
  }
115
- /**
116
- * Get a summary of all patterns suitable for external listing.
117
- */
118
- listPatterns() {
119
- return this.getAll().map((p) => ({
120
- id: p.id,
121
- name: p.name,
122
- category: p.category,
123
- description: p.description,
124
- bestFor: p.bestFor,
125
- dataRequirements: p.dataRequirements,
126
- }));
127
- }
128
115
  /**
129
116
  * Total number of registered patterns.
130
117
  */
@@ -50,27 +50,3 @@ export declare function parseIntent(intent: string): {
50
50
  * that pattern selection rules evaluate against.
51
51
  */
52
52
  export declare function buildMatchContext(data: Record<string, any>[], columns: DataColumn[], intent: string): PatternMatchContext;
53
- /**
54
- * Find the first column of a given type from a list of column names
55
- * using the full DataColumn metadata.
56
- */
57
- export declare function findColumnByType(columns: DataColumn[], type: DataColumn['type']): DataColumn | undefined;
58
- /**
59
- * Find all columns of a given type.
60
- */
61
- export declare function findColumnsByType(columns: DataColumn[], type: DataColumn['type']): DataColumn[];
62
- /**
63
- * Infer the Vega-Lite field type from a DataColumn type.
64
- */
65
- export declare function inferFieldType(colType: DataColumn['type']): 'quantitative' | 'nominal' | 'ordinal' | 'temporal';
66
- /**
67
- * Given an array of column names and full DataColumn metadata,
68
- * determine the best x, y, color, and size columns.
69
- * A best-effort heuristic for generateSpec functions.
70
- */
71
- export declare function inferEncoding(columnNames: string[], columns: DataColumn[]): {
72
- x: string | null;
73
- y: string | null;
74
- color: string | null;
75
- size: string | null;
76
- };
@@ -279,74 +279,3 @@ export function buildMatchContext(data, columns, intent) {
279
279
  },
280
280
  };
281
281
  }
282
- // ─── COLUMN UTILITIES ─────────────────────────────────────────────────────────
283
- /**
284
- * Find the first column of a given type from a list of column names
285
- * using the full DataColumn metadata.
286
- */
287
- export function findColumnByType(columns, type) {
288
- return columns.find((c) => c.type === type);
289
- }
290
- /**
291
- * Find all columns of a given type.
292
- */
293
- export function findColumnsByType(columns, type) {
294
- return columns.filter((c) => c.type === type);
295
- }
296
- /**
297
- * Infer the Vega-Lite field type from a DataColumn type.
298
- */
299
- export function inferFieldType(colType) {
300
- switch (colType) {
301
- case 'numeric':
302
- return 'quantitative';
303
- case 'date':
304
- return 'temporal';
305
- case 'categorical':
306
- return 'nominal';
307
- case 'id':
308
- return 'nominal';
309
- case 'text':
310
- return 'nominal';
311
- default:
312
- return 'nominal';
313
- }
314
- }
315
- /**
316
- * Given an array of column names and full DataColumn metadata,
317
- * determine the best x, y, color, and size columns.
318
- * A best-effort heuristic for generateSpec functions.
319
- */
320
- export function inferEncoding(columnNames, columns) {
321
- const colMap = new Map(columns.map((c) => [c.name, c]));
322
- const available = columnNames.filter((n) => colMap.has(n));
323
- const categoricalCols = available.filter((n) => {
324
- const c = colMap.get(n);
325
- return c.type === 'categorical' || c.type === 'id' || c.type === 'text';
326
- });
327
- const numericCols = available.filter((n) => colMap.get(n).type === 'numeric');
328
- const dateCols = available.filter((n) => colMap.get(n).type === 'date');
329
- let x = null;
330
- let y = null;
331
- let color = null;
332
- let size = null;
333
- // Prefer date for x-axis if present
334
- if (dateCols.length > 0) {
335
- x = dateCols[0];
336
- }
337
- else if (categoricalCols.length > 0) {
338
- x = categoricalCols[0];
339
- }
340
- // First numeric for y-axis
341
- if (numericCols.length > 0) {
342
- y = numericCols[0];
343
- }
344
- // Second categorical for color, or second numeric for size
345
- if (categoricalCols.length > 1) {
346
- color = categoricalCols.find((n) => n !== x) ?? null;
347
- }
348
- if (numericCols.length > 1) {
349
- size = numericCols.find((n) => n !== y) ?? null;
350
- }
351
- return { x, y, color, size };
352
- }
@@ -115,8 +115,6 @@ export declare function isAllZeros(data: Record<string, any>[], field: string):
115
115
  * For vertical bars: check bandwidth (width) >= 35px
116
116
  */
117
117
  export declare function shouldShowValueLabels(config: VisualizationSpec['config'], barDimension: number, isHorizontal: boolean): boolean;
118
- export declare function drawXAxis(g: any, xScale: any, innerHeight: number, label?: string, isOrdinal?: boolean): void;
119
- export declare function drawYAxis(g: any, yScale: any, innerWidth: number, label?: string): void;
120
118
  /**
121
119
  * Apply consistent axis styling: grid lines, domain stroke, tick text.
122
120
  * Also applies smart formatting to fix tiny-decimal "0.00" labels and
@@ -169,19 +167,3 @@ export declare function renderPlaceholder(container: HTMLElement, spec: Visualiz
169
167
  */
170
168
  export declare function addSortControls(svg: any, container: HTMLElement, spec: VisualizationSpec, dims: ChartDimensions, renderFn: (container: HTMLElement, spec: VisualizationSpec) => void): void;
171
169
  export declare function formatValue(v: number): string;
172
- /**
173
- * Set up a flex-column container with dark background for charts that
174
- * render SVG inside a wrapper div (with optional legend below).
175
- * Returns the chart wrapper div.
176
- */
177
- export declare function setupFlexContainer(container: HTMLElement): HTMLDivElement;
178
- /**
179
- * Apply -35° rotation to x-axis tick labels.
180
- * Call after the axis has been rendered.
181
- */
182
- export declare function applyLabelRotation(axis: any): void;
183
- /**
184
- * Shared curve interpolation map for time-series renderers.
185
- * Must be called inside the renderer (needs d3 reference).
186
- */
187
- export declare function getCurveMap(): Record<string, any>;
@@ -451,25 +451,6 @@ export function shouldShowValueLabels(config, barDimension, isHorizontal) {
451
451
  return isHorizontal ? barDimension >= 20 : barDimension >= 35;
452
452
  }
453
453
  // ─── AXES ────────────────────────────────────────────────────────────────────
454
- export function drawXAxis(g, xScale, innerHeight, label, isOrdinal = false) {
455
- const axis = g
456
- .append('g')
457
- .attr('class', 'x-axis')
458
- .attr('transform', `translate(0,${innerHeight})`)
459
- .call(d3
460
- .axisBottom(xScale)
461
- .ticks(isOrdinal ? null : 6)
462
- .tickSize(-innerHeight)
463
- .tickPadding(8));
464
- styleAxis(axis);
465
- }
466
- export function drawYAxis(g, yScale, innerWidth, label) {
467
- const axis = g
468
- .append('g')
469
- .attr('class', 'y-axis')
470
- .call(d3.axisLeft(yScale).ticks(6).tickSize(-innerWidth).tickPadding(8));
471
- styleAxis(axis);
472
- }
473
454
  /**
474
455
  * Apply consistent axis styling: grid lines, domain stroke, tick text.
475
456
  * Also applies smart formatting to fix tiny-decimal "0.00" labels and
@@ -915,46 +896,3 @@ export function formatValue(v) {
915
896
  }
916
897
  return Number.isInteger(v) ? v.toFixed(0) : v.toFixed(1);
917
898
  }
918
- // ── Container / Layout Helpers ────────────────────────────────────────────────
919
- /**
920
- * Set up a flex-column container with dark background for charts that
921
- * render SVG inside a wrapper div (with optional legend below).
922
- * Returns the chart wrapper div.
923
- */
924
- export function setupFlexContainer(container) {
925
- container.style.display = 'flex';
926
- container.style.flexDirection = 'column';
927
- container.style.background = DARK_BG;
928
- container.style.borderRadius = '8px';
929
- container.style.overflow = 'hidden';
930
- const chartWrapper = document.createElement('div');
931
- chartWrapper.style.flex = '1';
932
- chartWrapper.style.minHeight = '0';
933
- container.appendChild(chartWrapper);
934
- return chartWrapper;
935
- }
936
- /**
937
- * Apply -35° rotation to x-axis tick labels.
938
- * Call after the axis has been rendered.
939
- */
940
- export function applyLabelRotation(axis) {
941
- axis.selectAll('.tick text')
942
- .attr('transform', 'rotate(-35)')
943
- .attr('text-anchor', 'end')
944
- .attr('dx', '-0.5em')
945
- .attr('dy', '0.15em');
946
- }
947
- /**
948
- * Shared curve interpolation map for time-series renderers.
949
- * Must be called inside the renderer (needs d3 reference).
950
- */
951
- export function getCurveMap() {
952
- return {
953
- linear: d3.curveLinear,
954
- monotone: d3.curveMonotoneX,
955
- basis: d3.curveBasis,
956
- step: d3.curveStepAfter,
957
- cardinal: d3.curveCardinal,
958
- catmullRom: d3.curveCatmullRom,
959
- };
960
- }
@@ -41,7 +41,7 @@ export interface DataTable {
41
41
  columns: DataColumn[];
42
42
  rowCount: number;
43
43
  }
44
- /** Enhanced table profile returned by load_csv — includes sample rows */
44
+ /** Enhanced table profile returned by load_source — includes sample rows */
45
45
  export interface DataProfiledTable extends DataTable {
46
46
  /** 5 representative sample rows picked for variety */
47
47
  sampleRows: Record<string, any>[];
@@ -43,7 +43,7 @@ export function probeCapabilities() {
43
43
  const python = { available: !!pyVersion, version: pyVersion, enables: 'data cleaning (clean_column / dolex clean)', install: pyVersion ? undefined : 'install python3 and put it on PATH' };
44
44
  let dolexVersion;
45
45
  try {
46
- dolexVersion = JSON.parse(readFileSync(packagePath('package.json'), 'utf8')).version;
46
+ dolexVersion = JSON.parse(readFileSync(packagePath(import.meta.url, 'package.json'), 'utf8')).version;
47
47
  }
48
48
  catch { /* best-effort */ }
49
49
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outsidedata/dolex",
3
- "version": "9.0.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,10 +87,10 @@
87
87
  },
88
88
  "optionalDependencies": {
89
89
  "@modelcontextprotocol/ext-apps": "^1.0.1",
90
- "@modelcontextprotocol/sdk": "^1.26.0",
91
- "topojson-client": "^3.1.0",
90
+ "@modelcontextprotocol/sdk": "^1.30.1",
91
+ "mongodb": "^7.4.0",
92
92
  "pg": "^8.22.0",
93
- "mongodb": "^7.4.0"
93
+ "topojson-client": "^3.1.0"
94
94
  },
95
95
  "peerDependencies": {
96
96
  "react": ">=18",
@@ -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
- }>;