@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.
- package/README.md +33 -7
- 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/planner.d.ts +2 -1
- package/dist/src/analysis/planner.js +2 -2
- package/dist/src/analysis/quality.d.ts +23 -0
- package/dist/src/analysis/quality.js +386 -11
- package/dist/src/analysis/rules.d.ts +22 -2
- package/dist/src/analysis/rules.js +100 -18
- 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 +4 -0
- package/dist/src/cleaning/index.js +9 -0
- package/dist/src/cleaning/manifest.d.ts +35 -0
- package/dist/src/cleaning/manifest.js +95 -0
- package/dist/src/cleaning/replay.d.ts +34 -0
- package/dist/src/cleaning/replay.js +58 -0
- package/dist/src/cli/commands/analyze.js +13 -1
- 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 +127 -0
- package/dist/src/cli/commands/deps.d.ts +1 -0
- package/dist/src/cli/commands/deps.js +41 -0
- package/dist/src/cli/commands/help.js +3 -1
- package/dist/src/cli/commands/query.js +4 -1
- package/dist/src/cli/commands/sources.d.ts +2 -2
- package/dist/src/cli/commands/sources.js +138 -12
- package/dist/src/cli/commands/transform.js +19 -4
- package/dist/src/cli/commands/visualize.js +2 -0
- package/dist/src/cli/index.js +5 -0
- package/dist/src/connectors/csv.js +110 -8
- package/dist/src/connectors/index.d.ts +2 -0
- package/dist/src/connectors/index.js +2 -0
- package/dist/src/connectors/manager.d.ts +49 -1
- package/dist/src/connectors/manager.js +200 -14
- package/dist/src/connectors/mongo/index.d.ts +13 -0
- package/dist/src/connectors/mongo/index.js +323 -0
- package/dist/src/connectors/pg/index.d.ts +2 -0
- package/dist/src/connectors/pg/index.js +248 -0
- package/dist/src/connectors/source-factory.d.ts +38 -0
- package/dist/src/connectors/source-factory.js +80 -0
- package/dist/src/connectors/sql-safety.d.ts +68 -0
- package/dist/src/connectors/sql-safety.js +167 -0
- package/dist/src/connectors/types.d.ts +51 -0
- package/dist/src/connectors/types.js +11 -1
- package/dist/src/mcp/index.d.ts +1 -1
- package/dist/src/mcp/index.js +29 -10
- package/dist/src/mcp/tools/analyze.js +11 -1
- package/dist/src/mcp/tools/capabilities.d.ts +1 -0
- package/dist/src/mcp/tools/capabilities.js +14 -0
- package/dist/src/mcp/tools/clean-column.d.ts +5 -0
- package/dist/src/mcp/tools/clean-column.js +47 -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/drop-columns.js +2 -0
- package/dist/src/mcp/tools/list-transforms.js +22 -0
- package/dist/src/mcp/tools/promote-columns.js +2 -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/refine-cli.d.ts +4 -4
- package/dist/src/mcp/tools/refine.d.ts +4 -4
- package/dist/src/mcp/tools/shared.d.ts +6 -0
- package/dist/src/mcp/tools/shared.js +12 -5
- package/dist/src/mcp/tools/sources.d.ts +46 -3
- package/dist/src/mcp/tools/sources.js +44 -4
- package/dist/src/mcp/tools/transform-data.js +22 -0
- 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 +39 -2
- package/dist/src/utils/capabilities.d.ts +28 -0
- package/dist/src/utils/capabilities.js +58 -0
- package/dist/src/utils/optional-deps.d.ts +8 -0
- package/dist/src/utils/optional-deps.js +8 -0
- package/package.json +9 -3
|
@@ -42,19 +42,49 @@ export function isIsoDateColumn(col) {
|
|
|
42
42
|
return vals.length > 0 && vals.every((v) => /^\d{4}-\d{2}-\d{2}([ T]|$)/.test(v));
|
|
43
43
|
}
|
|
44
44
|
/**
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
* produces a single NULL bucket summing the whole table.
|
|
45
|
+
* Raised when analysis-plan generation is asked to run against a source whose
|
|
46
|
+
* query paradigm the planner can't emit. The planner produces SELECT SQL, so a
|
|
47
|
+
* document store (mongodb → aggregation pipeline) is REFUSED here rather than
|
|
48
|
+
* silently handed SQLite SQL — the caller surfaces `message` as a clean error.
|
|
50
49
|
*/
|
|
51
|
-
export
|
|
50
|
+
export class PlannerUnsupportedSourceError extends Error {
|
|
51
|
+
sourceType;
|
|
52
|
+
constructor(sourceType, message) {
|
|
53
|
+
super(message);
|
|
54
|
+
this.sourceType = sourceType;
|
|
55
|
+
this.name = 'PlannerUnsupportedSourceError';
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Resolve a registered source's `type` to the SQL flavor the planner emits.
|
|
60
|
+
* The ONE place source-type → planner-dialect is decided, so no call site
|
|
61
|
+
* re-derives it with a `type === 'postgres' ? …` ternary that silently maps an
|
|
62
|
+
* unrecognized (e.g. mongodb) source to SQLite. csv/undefined → sqlite,
|
|
63
|
+
* postgres → postgres; a pipeline source (mongodb) or unknown type THROWS.
|
|
64
|
+
*/
|
|
65
|
+
export function plannerDialectForSource(type) {
|
|
66
|
+
switch (type) {
|
|
67
|
+
case undefined:
|
|
68
|
+
case 'csv':
|
|
69
|
+
return 'sqlite';
|
|
70
|
+
case 'postgres':
|
|
71
|
+
return 'postgres';
|
|
72
|
+
case 'mongodb':
|
|
73
|
+
throw new PlannerUnsupportedSourceError('mongodb', 'analyze builds SQL analysis plans and cannot plan a MongoDB source ' +
|
|
74
|
+
'(aggregation-pipeline paradigm, not SQL). Query it directly, or drive it through the orchestrator/recon path.');
|
|
75
|
+
default:
|
|
76
|
+
throw new PlannerUnsupportedSourceError(type, `analyze: unknown source type "${type}" — no analysis-plan dialect mapping (expected csv | postgres).`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export function timeBucketing(col, dialect = 'sqlite') {
|
|
52
80
|
if (isYearColumn(col)) {
|
|
53
81
|
const c = q(col.name);
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
82
|
+
// A year stored as a number → its integer year as text, guarded to a plausible range.
|
|
83
|
+
// Postgres is type-strict (can't CAST('1980.0' AS INTEGER)), so it numeric-guards first.
|
|
84
|
+
const expr = dialect === 'postgres'
|
|
85
|
+
? `CASE WHEN (${c})::text ~ '^ *-?[0-9]+([.][0-9]+)? *$' AND (${c})::double precision BETWEEN 1000 AND 2200 THEN floor((${c})::double precision)::int::text END`
|
|
86
|
+
: `CASE WHEN CAST(${c} AS REAL) BETWEEN 1000 AND 2200 THEN CAST(CAST(${c} AS INTEGER) AS TEXT) END`;
|
|
87
|
+
return { label: 'year', expr };
|
|
58
88
|
}
|
|
59
89
|
// Skip only on POSITIVE evidence the dates are non-ISO (top values present and
|
|
60
90
|
// not ISO). Absent top values, assume ISO and bucket as before — a real date
|
|
@@ -63,7 +93,7 @@ export function timeBucketing(col) {
|
|
|
63
93
|
if (vals.length > 0 && !isIsoDateColumn(col))
|
|
64
94
|
return null;
|
|
65
95
|
const bucket = pickTimeBucket(col);
|
|
66
|
-
return { label: bucket, expr: sqlTimeBucket(col.name, bucket) };
|
|
96
|
+
return { label: bucket, expr: sqlTimeBucket(col.name, bucket, dialect) };
|
|
67
97
|
}
|
|
68
98
|
function findByRole(columns, role) {
|
|
69
99
|
return columns.filter(c => c.role === role);
|
|
@@ -74,8 +104,18 @@ function first(columns, role) {
|
|
|
74
104
|
function sumAlias(measureName) {
|
|
75
105
|
return `total_${measureName}`;
|
|
76
106
|
}
|
|
77
|
-
function sqlTimeBucket(col, bucket) {
|
|
107
|
+
function sqlTimeBucket(col, bucket, dialect = 'sqlite') {
|
|
78
108
|
const c = q(col);
|
|
109
|
+
if (dialect === 'postgres') {
|
|
110
|
+
const ts = `(${c})::timestamp`;
|
|
111
|
+
switch (bucket) {
|
|
112
|
+
case 'year': return `EXTRACT(YEAR FROM ${ts})::int::text`;
|
|
113
|
+
case 'quarter': return `to_char(${ts}, 'YYYY') || '-Q' || EXTRACT(QUARTER FROM ${ts})::int::text`;
|
|
114
|
+
case 'month': return `to_char(${ts}, 'YYYY-MM')`;
|
|
115
|
+
case 'week': return `to_char(${ts}, 'IYYY-"W"IW')`;
|
|
116
|
+
case 'day': return `to_char(${ts}, 'YYYY-MM-DD')`;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
79
119
|
switch (bucket) {
|
|
80
120
|
case 'year':
|
|
81
121
|
return `CASE WHEN typeof(${c}) = 'integer' AND ${c} BETWEEN 1000 AND 2200 THEN CAST(${c} AS TEXT) ELSE strftime('%Y', ${c}) END`;
|
|
@@ -92,25 +132,25 @@ function sqlTimeBucket(col, bucket) {
|
|
|
92
132
|
function makeStep(category, title, question, intent, rationale, sql, table, suggestedPatterns) {
|
|
93
133
|
return { title, question, intent, sql, table, suggestedPatterns, rationale, category };
|
|
94
134
|
}
|
|
95
|
-
const timeTrend = (columns, table) => {
|
|
135
|
+
const timeTrend = (columns, table, dialect) => {
|
|
96
136
|
const timeCol = first(columns, 'time');
|
|
97
137
|
const measureCol = first(columns, 'measure');
|
|
98
138
|
if (!timeCol || !measureCol)
|
|
99
139
|
return null;
|
|
100
|
-
const tb = timeBucketing(timeCol);
|
|
140
|
+
const tb = timeBucketing(timeCol, dialect);
|
|
101
141
|
if (!tb)
|
|
102
142
|
return null; // date column isn't ISO/year-bucketable — skip rather than ship garbage SQL
|
|
103
143
|
const { label: bucket, expr: bucketExpr } = tb;
|
|
104
144
|
const asName = sumAlias(measureCol.name);
|
|
105
145
|
return makeStep('trend', `${capitalize(measureCol.name)} Over Time`, `How does ${capitalize(measureCol.name)} change over time?`, `Show ${measureCol.name} trend over ${timeCol.name}`, `Time column "${timeCol.name}" paired with measure "${measureCol.name}" suggests a time-series trend analysis.`, `SELECT ${bucketExpr} AS ${q(`${timeCol.name}_${bucket}`)}, SUM(${q(measureCol.name)}) AS ${q(asName)} FROM ${q(table)} GROUP BY 1 ORDER BY 1 ASC`, table, ['line', 'area', 'sparkline-grid']);
|
|
106
146
|
};
|
|
107
|
-
const trendByGroup = (columns, table) => {
|
|
147
|
+
const trendByGroup = (columns, table, dialect) => {
|
|
108
148
|
const timeCol = first(columns, 'time');
|
|
109
149
|
const measureCol = first(columns, 'measure');
|
|
110
150
|
const dimCol = findByRole(columns, 'dimension').find(d => d.uniqueCount <= 8);
|
|
111
151
|
if (!timeCol || !measureCol || !dimCol)
|
|
112
152
|
return null;
|
|
113
|
-
const tb = timeBucketing(timeCol);
|
|
153
|
+
const tb = timeBucketing(timeCol, dialect);
|
|
114
154
|
if (!tb)
|
|
115
155
|
return null; // non-ISO/non-year date — skip rather than ship garbage SQL
|
|
116
156
|
const { label: bucket, expr: bucketExpr } = tb;
|
|
@@ -173,10 +213,52 @@ const composition = (columns, table) => {
|
|
|
173
213
|
}
|
|
174
214
|
return null;
|
|
175
215
|
};
|
|
216
|
+
// Period-over-period growth: the change and % change of a measure vs the previous
|
|
217
|
+
// time bucket (WoW/MoM/YoY depending on the bucket). Uses LAG; the % change is
|
|
218
|
+
// guarded with NULLIF (div-by-zero) and 100.0 (real division) — the SQL-safety
|
|
219
|
+
// traps this engine warns about, avoided at the source.
|
|
220
|
+
const periodOverPeriod = (columns, table, dialect) => {
|
|
221
|
+
const timeCol = first(columns, 'time');
|
|
222
|
+
const measureCol = first(columns, 'measure');
|
|
223
|
+
if (!timeCol || !measureCol)
|
|
224
|
+
return null;
|
|
225
|
+
const tb = timeBucketing(timeCol, dialect);
|
|
226
|
+
if (!tb)
|
|
227
|
+
return null;
|
|
228
|
+
const { label: bucket, expr: bucketExpr } = tb;
|
|
229
|
+
const period = q(`${timeCol.name}_${bucket}`);
|
|
230
|
+
const total = q(sumAlias(measureCol.name));
|
|
231
|
+
const sql = `WITH t AS (SELECT ${bucketExpr} AS ${period}, SUM(${q(measureCol.name)}) AS ${total} FROM ${q(table)} GROUP BY 1) ` +
|
|
232
|
+
`SELECT ${period}, ${total}, ${total} - LAG(${total}) OVER (ORDER BY ${period}) AS change, ` +
|
|
233
|
+
`ROUND(100.0 * (${total} - LAG(${total}) OVER (ORDER BY ${period})) / NULLIF(LAG(${total}) OVER (ORDER BY ${period}), 0), 1) AS pct_change ` +
|
|
234
|
+
`FROM t ORDER BY ${period} ASC`;
|
|
235
|
+
return makeStep('trend', `${capitalize(measureCol.name)} Growth (period over period)`, `How fast is ${capitalize(measureCol.name)} growing from one ${bucket} to the next?`, `Show ${bucket}-over-${bucket} change and % change in ${measureCol.name}`, `Time column "${timeCol.name}" + measure "${measureCol.name}" supports period-over-period growth (${bucket}). % change is NULLIF-guarded against a zero base.`, sql, table, ['bar', 'line', 'waterfall']);
|
|
236
|
+
};
|
|
237
|
+
// Seasonality: average a measure by month-of-year ACROSS years, isolating the
|
|
238
|
+
// recurring seasonal shape from the long-run trend. Only meaningful with sub-year
|
|
239
|
+
// (ISO date) resolution — skipped for year-only columns.
|
|
240
|
+
const seasonality = (columns, table, dialect) => {
|
|
241
|
+
const timeCol = first(columns, 'time');
|
|
242
|
+
const measureCol = first(columns, 'measure');
|
|
243
|
+
if (!timeCol || !measureCol)
|
|
244
|
+
return null;
|
|
245
|
+
if (isYearColumn(timeCol))
|
|
246
|
+
return null; // year-only → no within-year season
|
|
247
|
+
const vals = (timeCol.topValues ?? []).map((t) => String(t.value));
|
|
248
|
+
if (vals.length > 0 && !isIsoDateColumn(timeCol))
|
|
249
|
+
return null; // non-ISO date → strftime would NULL
|
|
250
|
+
const c = q(timeCol.name);
|
|
251
|
+
const monthExpr = dialect === 'postgres' ? `to_char((${c})::timestamp, 'MM')` : `strftime('%m', ${c})`;
|
|
252
|
+
const sql = `SELECT ${monthExpr} AS month, AVG(${q(measureCol.name)}) AS ${q(`avg_${measureCol.name}`)} ` +
|
|
253
|
+
`FROM ${q(table)} WHERE ${monthExpr} IS NOT NULL GROUP BY 1 ORDER BY 1 ASC`;
|
|
254
|
+
return makeStep('trend', `${capitalize(measureCol.name)} Seasonality (by month)`, `Does ${capitalize(measureCol.name)} follow a recurring monthly/seasonal pattern?`, `Show average ${measureCol.name} by month of year across all years`, `ISO date "${timeCol.name}" + measure "${measureCol.name}" lets us average by month-of-year to separate seasonality from trend.`, sql, table, ['bar', 'line', 'radar']);
|
|
255
|
+
};
|
|
176
256
|
// --- All Rules --------------------------------------------------------------
|
|
177
257
|
const ALL_RULES = [
|
|
178
258
|
timeTrend,
|
|
179
259
|
trendByGroup,
|
|
260
|
+
periodOverPeriod,
|
|
261
|
+
seasonality,
|
|
180
262
|
comparison,
|
|
181
263
|
distribution,
|
|
182
264
|
relationship,
|
|
@@ -184,9 +266,9 @@ const ALL_RULES = [
|
|
|
184
266
|
composition,
|
|
185
267
|
];
|
|
186
268
|
// --- Main Export -------------------------------------------------------------
|
|
187
|
-
export function generateCandidates(columns, table) {
|
|
269
|
+
export function generateCandidates(columns, table, dialect = 'sqlite') {
|
|
188
270
|
return ALL_RULES.flatMap(rule => {
|
|
189
|
-
const result = rule(columns, table);
|
|
271
|
+
const result = rule(columns, table, dialect);
|
|
190
272
|
return result ? [result] : [];
|
|
191
273
|
});
|
|
192
274
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authoring prompt + constrained-output schema — the SHARED knowledge of HOW to
|
|
3
|
+
* ask a model to write a Python clean(). The core never calls a model; a caller
|
|
4
|
+
* (orchestrator's local model, or any agent) does the transport and passes the
|
|
5
|
+
* resulting code in as a CleanAuthor.
|
|
6
|
+
*/
|
|
7
|
+
export interface AuthorRequest {
|
|
8
|
+
column: string;
|
|
9
|
+
issue: string;
|
|
10
|
+
task: string;
|
|
11
|
+
samples: string[];
|
|
12
|
+
feedback?: string;
|
|
13
|
+
}
|
|
14
|
+
export type CleanAuthor = (req: AuthorRequest) => Promise<string>;
|
|
15
|
+
export declare const PY_SCHEMA: {
|
|
16
|
+
type: string;
|
|
17
|
+
properties: {
|
|
18
|
+
code: {
|
|
19
|
+
type: string;
|
|
20
|
+
};
|
|
21
|
+
note: {
|
|
22
|
+
type: string;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
required: string[];
|
|
26
|
+
};
|
|
27
|
+
export declare function buildAuthorPrompt(req: AuthorRequest): {
|
|
28
|
+
system: string;
|
|
29
|
+
user: string;
|
|
30
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export const PY_SCHEMA = { type: 'object', properties: { code: { type: 'string' }, note: { type: 'string' } }, required: ['code', 'note'] };
|
|
2
|
+
export function buildAuthorPrompt(req) {
|
|
3
|
+
const system = 'Write a Python 3 function `def clean(value):` taking ONE raw cell value (string) and returning the CLEANED value (None for missing/sentinel). May import stdlib (datetime, re). Output JSON {code, note}: code = the COMPLETE function plus any imports. No I/O.';
|
|
4
|
+
const user = `Column "${req.column}". Detected issue: ${req.issue}. Sample values: ${req.samples.map((s) => JSON.stringify(s)).join(', ')}.\nTASK: ${req.task}` +
|
|
5
|
+
(req.feedback ? `\n\nYour PREVIOUS attempt FAILED validation: ${req.feedback}. Write a corrected function.` : '');
|
|
6
|
+
return { system, user };
|
|
7
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Thrown when the static screen rejects model code (banned import/call/dunder) or the
|
|
2
|
+
* code defines no clean(). Callers (MCP/CLI) surface the message; the autonomous author
|
|
3
|
+
* loop turns it into validation feedback so the model retries with safe code. */
|
|
4
|
+
export declare class CleanRejected extends Error {
|
|
5
|
+
constructor(reason: string);
|
|
6
|
+
}
|
|
7
|
+
export declare function pythonAvailable(): boolean;
|
|
8
|
+
export declare function runPythonClean(code: string, values: (string | null)[]): {
|
|
9
|
+
cleaned: (string | null)[];
|
|
10
|
+
errors: number;
|
|
11
|
+
};
|
|
12
|
+
export interface CleanStats {
|
|
13
|
+
rows: number;
|
|
14
|
+
errors: number;
|
|
15
|
+
changed: number;
|
|
16
|
+
nulledFromValue: number;
|
|
17
|
+
distinctBefore: number;
|
|
18
|
+
distinctAfter: number;
|
|
19
|
+
}
|
|
20
|
+
export declare function cleanStats(raw: (string | null)[], cleaned: (string | null)[]): CleanStats;
|
|
21
|
+
export declare function safetyVerdict(raw: (string | null)[], cleaned: (string | null)[], errors: number): {
|
|
22
|
+
ok: boolean;
|
|
23
|
+
reason?: string;
|
|
24
|
+
};
|
|
25
|
+
export declare function previewSample(raw: (string | null)[], cleaned: (string | null)[], n: number): {
|
|
26
|
+
before: string | null;
|
|
27
|
+
after: string | null;
|
|
28
|
+
}[];
|
|
29
|
+
export declare function applyCleanColumn(db: any, table: string, newColumn: string, rowids: number[], cleaned: (string | null)[]): void;
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Data-cleaning execution core (no MCP, no SourceManager) — runs a model-authored
|
|
3
|
+
* Python clean(value) over a column's values and applies the result non-destructively.
|
|
4
|
+
*
|
|
5
|
+
* SECURITY (Tier 1): the author of this code is an LLM whose prompt embeds raw CSV cell
|
|
6
|
+
* values, so a malicious cell can steer it into writing exfiltration/RCE (proven: see
|
|
7
|
+
* local-orchestration/experiments/016-prompt-injection-author.ts — the default clean
|
|
8
|
+
* model emitted `eval(open('~/.config/...'))` on a disguised payload). Before ANY model
|
|
9
|
+
* code runs, the harness STATICALLY screens it (import allowlist + banned-name/dunder
|
|
10
|
+
* deny) and runs it under POSIX resource limits (CPU/AS/FSIZE — enforced on Linux; macOS
|
|
11
|
+
* honors a subset). Rejected code throws CleanRejected; the executor is NEVER reached.
|
|
12
|
+
* This is a hardened deny-list, not a true jail — a hosted/multi-tenant deployment must
|
|
13
|
+
* STILL run the whole engine in a network-denied, read-only container (see CLAUDE.md).
|
|
14
|
+
*/
|
|
15
|
+
import { execFileSync } from 'child_process';
|
|
16
|
+
import { mkdtempSync, writeFileSync, rmSync } from 'fs';
|
|
17
|
+
import { tmpdir } from 'os';
|
|
18
|
+
import { join } from 'path';
|
|
19
|
+
/** Thrown when the static screen rejects model code (banned import/call/dunder) or the
|
|
20
|
+
* code defines no clean(). Callers (MCP/CLI) surface the message; the autonomous author
|
|
21
|
+
* loop turns it into validation feedback so the model retries with safe code. */
|
|
22
|
+
export class CleanRejected extends Error {
|
|
23
|
+
constructor(reason) { super(reason); this.name = 'CleanRejected'; }
|
|
24
|
+
}
|
|
25
|
+
export function pythonAvailable() {
|
|
26
|
+
try {
|
|
27
|
+
execFileSync('python3', ['--version'], { stdio: 'ignore' });
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// The trusted runner: screens the model code (argv[1]) with `ast` BEFORE compiling/exec'ing
|
|
35
|
+
// it, sets resource limits, then runs clean() over the values (argv[2]). The model code is
|
|
36
|
+
// loaded from a FILE (never interpolated into this string) so it cannot break out of the
|
|
37
|
+
// harness. Allowlist imports (the prompt only needs datetime/re); deny dangerous builtins by
|
|
38
|
+
// NAME (rebind-proof: `e = eval; e(...)` is caught) and all dunder attribute access (closes
|
|
39
|
+
// the `().__class__.__bases__[0].__subclasses__()` escape).
|
|
40
|
+
const RUNNER = String.raw `
|
|
41
|
+
import ast, sys, json, resource
|
|
42
|
+
ALLOWED_IMPORTS = {"datetime","time","re","math","json","string","decimal","fractions",
|
|
43
|
+
"unicodedata","collections","itertools","calendar","statistics","numbers"}
|
|
44
|
+
BANNED_NAMES = {"eval","exec","compile","open","input","breakpoint","__import__","__builtins__",
|
|
45
|
+
"globals","locals","vars","getattr","setattr","delattr","memoryview","exit","quit"}
|
|
46
|
+
def screen(src):
|
|
47
|
+
tree = ast.parse(src)
|
|
48
|
+
for n in ast.walk(tree):
|
|
49
|
+
if isinstance(n, ast.Import):
|
|
50
|
+
for a in n.names:
|
|
51
|
+
if a.name.split('.')[0] not in ALLOWED_IMPORTS: raise ValueError("import not allowed: " + a.name)
|
|
52
|
+
elif isinstance(n, ast.ImportFrom):
|
|
53
|
+
mod = (n.module or "").split('.')[0]
|
|
54
|
+
if mod not in ALLOWED_IMPORTS: raise ValueError("import not allowed: " + str(n.module))
|
|
55
|
+
elif isinstance(n, ast.Name) and n.id in BANNED_NAMES:
|
|
56
|
+
raise ValueError("name not allowed: " + n.id)
|
|
57
|
+
elif isinstance(n, ast.Attribute) and n.attr.startswith("__") and n.attr.endswith("__"):
|
|
58
|
+
raise ValueError("dunder attribute not allowed: " + n.attr)
|
|
59
|
+
return tree
|
|
60
|
+
def limits():
|
|
61
|
+
GB = 1024*1024*1024
|
|
62
|
+
for res, lim in ((resource.RLIMIT_CPU, (10, 10)), (resource.RLIMIT_AS, (GB, GB)),
|
|
63
|
+
(resource.RLIMIT_FSIZE, (16*1024*1024, 16*1024*1024))):
|
|
64
|
+
try: resource.setrlimit(res, lim)
|
|
65
|
+
except Exception: pass
|
|
66
|
+
src = open(sys.argv[1]).read()
|
|
67
|
+
try:
|
|
68
|
+
tree = screen(src)
|
|
69
|
+
except (ValueError, SyntaxError) as e:
|
|
70
|
+
print(json.dumps({"rejected": str(e)})); sys.exit(0)
|
|
71
|
+
limits()
|
|
72
|
+
ns = {}
|
|
73
|
+
try:
|
|
74
|
+
exec(compile(tree, "<clean>", "exec"), ns)
|
|
75
|
+
except Exception as e:
|
|
76
|
+
print(json.dumps({"rejected": "module-level error: " + str(e)})); sys.exit(0)
|
|
77
|
+
clean = ns.get("clean")
|
|
78
|
+
if not callable(clean):
|
|
79
|
+
print(json.dumps({"rejected": "no clean(value) function defined"})); sys.exit(0)
|
|
80
|
+
vals = json.load(open(sys.argv[2]))
|
|
81
|
+
out = []; err = 0
|
|
82
|
+
for v in vals:
|
|
83
|
+
try:
|
|
84
|
+
r = clean(v); out.append(None if r is None else str(r))
|
|
85
|
+
except Exception:
|
|
86
|
+
err += 1; out.append(None)
|
|
87
|
+
print(json.dumps({"cleaned": out, "errors": err}))
|
|
88
|
+
`;
|
|
89
|
+
// NOTE (scale): runs python3 synchronously and JSON.parses the result in one shot (maxBuffer 512MB,
|
|
90
|
+
// overflow ⇒ a graceful execFileSync error). Fine for the local single-user model; a hosted/multi-client
|
|
91
|
+
// deployment would stream + parse off the event loop. Out of scope here — see the security note above.
|
|
92
|
+
export function runPythonClean(code, values) {
|
|
93
|
+
const dir = mkdtempSync(join(tmpdir(), 'dolex-clean-'));
|
|
94
|
+
try {
|
|
95
|
+
const cf = join(dir, 'clean_src.py');
|
|
96
|
+
writeFileSync(cf, code); // model code — read, never interpolated
|
|
97
|
+
const vf = join(dir, 'v.json');
|
|
98
|
+
writeFileSync(vf, JSON.stringify(values));
|
|
99
|
+
const rf = join(dir, 'runner.py');
|
|
100
|
+
writeFileSync(rf, RUNNER); // trusted harness
|
|
101
|
+
const raw = execFileSync('python3', [rf, cf, vf], { timeout: 60000, encoding: 'utf8', maxBuffer: 512 * 1024 * 1024 });
|
|
102
|
+
// Parse ONLY the final non-empty line: model-authored clean() (or imported modules)
|
|
103
|
+
// may print debug output, which would otherwise poison JSON.parse. The protocol line
|
|
104
|
+
// is always the last thing we print.
|
|
105
|
+
const lines = raw.trimEnd().split('\n');
|
|
106
|
+
const parsed = JSON.parse(lines[lines.length - 1]);
|
|
107
|
+
if (parsed.rejected)
|
|
108
|
+
throw new CleanRejected(parsed.rejected); // screen/exec/shape rejection
|
|
109
|
+
return { cleaned: parsed.cleaned, errors: parsed.errors };
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
rmSync(dir, { recursive: true, force: true });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const isBlank = (x) => x === null || x === '' || x === undefined;
|
|
116
|
+
export function cleanStats(raw, cleaned) {
|
|
117
|
+
let changed = 0, nulledFromValue = 0;
|
|
118
|
+
for (let i = 0; i < raw.length; i++) {
|
|
119
|
+
if (String(raw[i] ?? '') !== String(cleaned[i] ?? ''))
|
|
120
|
+
changed++;
|
|
121
|
+
if (!isBlank(raw[i]) && isBlank(cleaned[i]))
|
|
122
|
+
nulledFromValue++;
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
rows: raw.length, errors: 0, changed, nulledFromValue,
|
|
126
|
+
distinctBefore: new Set(raw.filter((v) => !isBlank(v))).size,
|
|
127
|
+
distinctAfter: new Set(cleaned.filter((v) => !isBlank(v))).size,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
export function safetyVerdict(raw, cleaned, errors) {
|
|
131
|
+
const rows = raw.length;
|
|
132
|
+
if (rows === 0)
|
|
133
|
+
return { ok: false, reason: 'no rows to clean' };
|
|
134
|
+
if (errors > rows * 0.5)
|
|
135
|
+
return { ok: false, reason: `the function errored on ${errors}/${rows} rows` };
|
|
136
|
+
const nonBlankBefore = raw.filter((v) => !isBlank(v)).length;
|
|
137
|
+
const nonBlankAfter = cleaned.filter((v) => !isBlank(v)).length;
|
|
138
|
+
if (nonBlankBefore > 0 && nonBlankAfter === 0)
|
|
139
|
+
return { ok: false, reason: 'every value became blank/null — the function likely destroyed the column' };
|
|
140
|
+
return { ok: true };
|
|
141
|
+
}
|
|
142
|
+
export function previewSample(raw, cleaned, n) {
|
|
143
|
+
const out = [];
|
|
144
|
+
for (let i = 0; i < raw.length && out.length < n; i++) {
|
|
145
|
+
if (String(raw[i] ?? '') !== String(cleaned[i] ?? ''))
|
|
146
|
+
out.push({ before: raw[i], after: cleaned[i] });
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
const q = (s) => `"${s.replace(/"/g, '""')}"`;
|
|
151
|
+
export function applyCleanColumn(db, table, newColumn, rowids, cleaned) {
|
|
152
|
+
db.exec(`ALTER TABLE ${q(table)} ADD COLUMN ${q(newColumn)}`);
|
|
153
|
+
const upd = db.prepare(`UPDATE ${q(table)} SET ${q(newColumn)} = ? WHERE rowid = ?`);
|
|
154
|
+
const tx = db.transaction((pairs) => {
|
|
155
|
+
// '' = missing — match the connector's "empty string is null" convention so the
|
|
156
|
+
// stored value agrees with stats/safety (which treat '' as blank). [second-look fix]
|
|
157
|
+
for (const [val, rid] of pairs)
|
|
158
|
+
upd.run(val === '' ? null : val, rid);
|
|
159
|
+
});
|
|
160
|
+
tx(cleaned.map((v, i) => [v, rowids[i]]));
|
|
161
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { QualityFinding } from '../analysis/quality.js';
|
|
2
|
+
export interface AcceptResult {
|
|
3
|
+
ok: boolean;
|
|
4
|
+
summary: string;
|
|
5
|
+
fail?: string;
|
|
6
|
+
}
|
|
7
|
+
interface Handler {
|
|
8
|
+
task: (f: QualityFinding) => string | null;
|
|
9
|
+
accept: (pairs: [string, any][], f: QualityFinding) => AcceptResult;
|
|
10
|
+
}
|
|
11
|
+
export declare const HANDLERS: Record<string, Handler>;
|
|
12
|
+
/** Run the model-authored code over the sample values and apply the issue's
|
|
13
|
+
* acceptance test. Uses the shared exec (string|null normalized) — the same
|
|
14
|
+
* executor the MCP tool uses, so there is exactly ONE python runner. */
|
|
15
|
+
export declare function validateFix(finding: QualityFinding, code: string, sampleVals: string[]): AcceptResult;
|
|
16
|
+
export {};
|
|
@@ -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,4 @@
|
|
|
1
|
+
export { pythonAvailable, runPythonClean, cleanStats, safetyVerdict, previewSample, applyCleanColumn, CleanRejected } from './exec.js';
|
|
2
|
+
export type { CleanStats } from './exec.js';
|
|
3
|
+
export { applyManifest, applyFixesToRows, readCleanfixManifest, resolveCleanfixPath } from './replay.js';
|
|
4
|
+
export type { FixRecord, CleanManifest } from './replay.js';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// PUBLIC cleaning PRIMITIVES — what the shipped surfaces use to let a USER's own model/agent
|
|
2
|
+
// drive cleaning (BYO orchestrator): the Python sandbox executor, the per-column author
|
|
3
|
+
// helper, and model-free manifest replay. The deterministic CHECKS REGISTRY + conservation
|
|
4
|
+
// guard + the autoclean LOOP are NOT here — they are the private LO orchestrator
|
|
5
|
+
// (local-orchestration/src/checks.ts + autoclean.ts) and are not shipped. dolex stays a
|
|
6
|
+
// toolbox (`dolex check` lints, `dolex clean` fixes one column); the orchestration is the
|
|
7
|
+
// caller's (Claude, or any BYO model/loop).
|
|
8
|
+
export { pythonAvailable, runPythonClean, cleanStats, safetyVerdict, previewSample, applyCleanColumn, CleanRejected } from './exec.js';
|
|
9
|
+
export { applyManifest, applyFixesToRows, readCleanfixManifest, resolveCleanfixPath } from './replay.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
|
+
}>;
|