@outsidedata/dolex 8.0.2 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +3 -0
  2. package/dist/src/analysis/clean-exec.d.ts +23 -0
  3. package/dist/src/analysis/clean-exec.js +87 -0
  4. package/dist/src/analysis/data-context.d.ts +140 -0
  5. package/dist/src/analysis/data-context.js +96 -0
  6. package/dist/src/analysis/quality.d.ts +23 -0
  7. package/dist/src/analysis/quality.js +290 -6
  8. package/dist/src/analysis/rules.js +41 -0
  9. package/dist/src/cleaning/author.d.ts +30 -0
  10. package/dist/src/cleaning/author.js +7 -0
  11. package/dist/src/cleaning/exec.d.ts +29 -0
  12. package/dist/src/cleaning/exec.js +161 -0
  13. package/dist/src/cleaning/handlers.d.ts +16 -0
  14. package/dist/src/cleaning/handlers.js +82 -0
  15. package/dist/src/cleaning/index.d.ts +8 -0
  16. package/dist/src/cleaning/index.js +4 -0
  17. package/dist/src/cleaning/manifest.d.ts +35 -0
  18. package/dist/src/cleaning/manifest.js +95 -0
  19. package/dist/src/cli/commands/check.js +2 -89
  20. package/dist/src/cli/commands/clean.d.ts +1 -0
  21. package/dist/src/cli/commands/clean.js +115 -0
  22. package/dist/src/cli/commands/help.js +1 -0
  23. package/dist/src/cli/commands/query.js +4 -1
  24. package/dist/src/cli/commands/visualize.js +2 -0
  25. package/dist/src/cli/index.js +2 -0
  26. package/dist/src/connectors/csv.js +81 -8
  27. package/dist/src/connectors/manager.d.ts +10 -0
  28. package/dist/src/connectors/manager.js +60 -1
  29. package/dist/src/connectors/sql-safety.d.ts +68 -0
  30. package/dist/src/connectors/sql-safety.js +167 -0
  31. package/dist/src/mcp/index.js +9 -1
  32. package/dist/src/mcp/tools/clean-column.d.ts +5 -0
  33. package/dist/src/mcp/tools/clean-column.js +45 -0
  34. package/dist/src/mcp/tools/clean-schemas.d.ts +23 -0
  35. package/dist/src/mcp/tools/clean-schemas.js +9 -0
  36. package/dist/src/mcp/tools/query-source.d.ts +2 -2
  37. package/dist/src/mcp/tools/query-source.js +2 -1
  38. package/dist/src/mcp/tools/shared.d.ts +1 -0
  39. package/dist/src/mcp/tools/shared.js +1 -1
  40. package/dist/src/mcp/tools/visualize-cli.d.ts +2 -2
  41. package/dist/src/mcp/tools/visualize.d.ts +3 -2
  42. package/dist/src/mcp/tools/visualize.js +1 -0
  43. package/dist/src/transforms/evaluator.js +58 -3
  44. package/dist/src/transforms/tokenizer.js +20 -2
  45. package/dist/src/transforms/types.d.ts +6 -6
  46. package/dist/src/types.d.ts +10 -0
  47. package/package.json +5 -2
package/README.md CHANGED
@@ -149,6 +149,8 @@ Every query is validated before execution — field names are checked against th
149
149
  | Tool | What it does |
150
150
  |------|-------------|
151
151
  | `load_csv` | Load a CSV file or directory |
152
+ | `list_data` | List loaded datasets |
153
+ | `remove_data` | Remove a loaded dataset |
152
154
  | `describe_data` | Profile columns, stats, sample rows |
153
155
  | `analyze_data` | Auto-generate an analysis plan |
154
156
  | `query_data` | Run SQL queries (JOINs, GROUP BY, window functions, CTEs) |
@@ -158,6 +160,7 @@ Every query is validated before execution — field names are checked against th
158
160
  | `promote_columns` | Persist working columns to disk |
159
161
  | `list_transforms` | List columns by layer (source/derived/working) |
160
162
  | `drop_columns` | Drop derived or working columns |
163
+ | `clean_column` | Fix one column with a Python `clean(value)` — parse dates, null sentinels, canonicalize categories; preview then non-destructive apply (requires python3) |
161
164
  | `list_patterns` | Browse all 43 patterns |
162
165
  | `export_html` | Get raw HTML |
163
166
  | `screenshot` | Render to PNG |
@@ -0,0 +1,23 @@
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;
@@ -0,0 +1,87 @@
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
+ }
@@ -0,0 +1,140 @@
1
+ export interface DataContextMetric {
2
+ name: string;
3
+ /** Plain-English definition of what the metric means. */
4
+ definition: string;
5
+ /** The exact SQL expression/snippet that computes it. */
6
+ sql: string;
7
+ /** Optional caveats (edge cases, exclusions, known skew). */
8
+ caveats?: string;
9
+ }
10
+ export interface DataContext {
11
+ /** Dataset/table this context describes. */
12
+ dataset: string;
13
+ /** Term/alias → meaning, for entity disambiguation ("ARR" → annual recurring revenue). */
14
+ entities?: {
15
+ term: string;
16
+ meaning: string;
17
+ }[];
18
+ /** Named metrics with English definition + canonical SQL. */
19
+ metrics?: DataContextMetric[];
20
+ /** Filters that should ALWAYS apply unless explicitly overridden (test data, deleted rows). */
21
+ standardFilters?: {
22
+ description: string;
23
+ sql: string;
24
+ }[];
25
+ /** Per-column gotchas: timezone, units, NULL meaning, sentinel values. */
26
+ columnNotes?: {
27
+ column: string;
28
+ note: string;
29
+ }[];
30
+ /** A few canonical question → SQL examples that ground the analyst. */
31
+ queryExamples?: {
32
+ question: string;
33
+ sql: string;
34
+ }[];
35
+ }
36
+ /** The sidecar path for a dataset CSV: `<dir>/<base>.context.json` (sits beside the
37
+ * `.dolex.json` transform manifest, same convention). */
38
+ export declare function dataContextPath(datasetPath: string): string;
39
+ /** Load a sidecar if present and well-formed. Best-effort: a missing or corrupt
40
+ * file yields null (the analyst simply runs without extra grounding). */
41
+ export declare function loadDataContext(datasetPath: string): DataContext | null;
42
+ /** Persist a sidecar atomically (temp + rename — same discipline as the registry). */
43
+ export declare function saveDataContext(datasetPath: string, ctx: DataContext): void;
44
+ /** Render a context into a compact prompt block. Only non-empty sections appear;
45
+ * returns '' for an empty/edge context so nothing is injected. */
46
+ export declare function renderDataContext(ctx: DataContext | null): string;
47
+ /** JSON schema for caller-driven authoring (constrained-output for a model). */
48
+ export declare const DATA_CONTEXT_SCHEMA: {
49
+ type: string;
50
+ properties: {
51
+ dataset: {
52
+ type: string;
53
+ };
54
+ entities: {
55
+ type: string;
56
+ items: {
57
+ type: string;
58
+ properties: {
59
+ term: {
60
+ type: string;
61
+ };
62
+ meaning: {
63
+ type: string;
64
+ };
65
+ };
66
+ required: string[];
67
+ };
68
+ };
69
+ metrics: {
70
+ type: string;
71
+ items: {
72
+ type: string;
73
+ properties: {
74
+ name: {
75
+ type: string;
76
+ };
77
+ definition: {
78
+ type: string;
79
+ };
80
+ sql: {
81
+ type: string;
82
+ };
83
+ caveats: {
84
+ type: string;
85
+ };
86
+ };
87
+ required: string[];
88
+ };
89
+ };
90
+ standardFilters: {
91
+ type: string;
92
+ items: {
93
+ type: string;
94
+ properties: {
95
+ description: {
96
+ type: string;
97
+ };
98
+ sql: {
99
+ type: string;
100
+ };
101
+ };
102
+ required: string[];
103
+ };
104
+ };
105
+ columnNotes: {
106
+ type: string;
107
+ items: {
108
+ type: string;
109
+ properties: {
110
+ column: {
111
+ type: string;
112
+ };
113
+ note: {
114
+ type: string;
115
+ };
116
+ };
117
+ required: string[];
118
+ };
119
+ };
120
+ queryExamples: {
121
+ type: string;
122
+ items: {
123
+ type: string;
124
+ properties: {
125
+ question: {
126
+ type: string;
127
+ };
128
+ sql: {
129
+ type: string;
130
+ };
131
+ };
132
+ required: string[];
133
+ };
134
+ };
135
+ };
136
+ required: string[];
137
+ };
138
+ /** Authoring prompt for a caller's model: turn schema + sample rows + the quality
139
+ * audit into a DataContext. The core stays model-free; the caller runs this. */
140
+ export declare function buildContextAuthorPrompt(dataset: string, schemaText: string, sampleRows: string, auditNote: string): string;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Domain-context sidecar — a persisted SEMANTIC LAYER for a dataset.
3
+ *
4
+ * Mined from Anthropic's knowledge-work `data` plugin (data-context-extractor
5
+ * skill): a reusable document capturing the tribal knowledge a profiler can't see
6
+ * — what entities/terms mean, how metrics are DEFINED (plain English + the exact
7
+ * SQL), standing filters that should always apply (test rows, soft-deletes),
8
+ * column gotchas (timezones, units, NULL conventions), and a few canonical example
9
+ * queries. Injected into the analyst's system prompt, it grounds SQL generation and
10
+ * cuts hallucinated relationships/metric definitions across sessions.
11
+ *
12
+ * Model-free core, exactly like the cleaning core: this module DEFINES the shape,
13
+ * loads/saves the sidecar, and renders it for a prompt. AUTHORING is the caller's
14
+ * job — a model (the loop's local model, the MCP assistant) fills the schema via
15
+ * the authoring prompt, or a human hand-writes the JSON. The core never calls a
16
+ * model.
17
+ */
18
+ import * as fs from 'fs';
19
+ import * as path from 'path';
20
+ /** The sidecar path for a dataset CSV: `<dir>/<base>.context.json` (sits beside the
21
+ * `.dolex.json` transform manifest, same convention). */
22
+ export function dataContextPath(datasetPath) {
23
+ const dir = path.dirname(datasetPath);
24
+ const base = path.basename(datasetPath).replace(/\.[^.]+$/, '');
25
+ return path.join(dir, `${base}.context.json`);
26
+ }
27
+ /** Load a sidecar if present and well-formed. Best-effort: a missing or corrupt
28
+ * file yields null (the analyst simply runs without extra grounding). */
29
+ export function loadDataContext(datasetPath) {
30
+ try {
31
+ const p = dataContextPath(datasetPath);
32
+ if (!fs.existsSync(p))
33
+ return null;
34
+ const ctx = JSON.parse(fs.readFileSync(p, 'utf-8'));
35
+ return ctx && typeof ctx === 'object' && typeof ctx.dataset === 'string' ? ctx : null;
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ /** Persist a sidecar atomically (temp + rename — same discipline as the registry). */
42
+ export function saveDataContext(datasetPath, ctx) {
43
+ const p = dataContextPath(datasetPath);
44
+ const tmp = `${p}.${process.pid}.tmp`;
45
+ fs.writeFileSync(tmp, JSON.stringify(ctx, null, 2), 'utf-8');
46
+ fs.renameSync(tmp, p);
47
+ }
48
+ /** Render a context into a compact prompt block. Only non-empty sections appear;
49
+ * returns '' for an empty/edge context so nothing is injected. */
50
+ export function renderDataContext(ctx) {
51
+ if (!ctx)
52
+ return '';
53
+ const parts = [];
54
+ if (ctx.entities?.length) {
55
+ parts.push('TERMS: ' + ctx.entities.map((e) => `${e.term} = ${e.meaning}`).join('; '));
56
+ }
57
+ if (ctx.metrics?.length) {
58
+ parts.push('METRICS:\n' + ctx.metrics.map((m) => `• ${m.name}: ${m.definition} → SQL: ${m.sql}${m.caveats ? ` (caveat: ${m.caveats})` : ''}`).join('\n'));
59
+ }
60
+ if (ctx.standardFilters?.length) {
61
+ parts.push('STANDARD FILTERS (apply unless the question overrides): ' + ctx.standardFilters.map((f) => `${f.description} [${f.sql}]`).join('; '));
62
+ }
63
+ if (ctx.columnNotes?.length) {
64
+ parts.push('COLUMN NOTES: ' + ctx.columnNotes.map((c) => `${c.column} — ${c.note}`).join('; '));
65
+ }
66
+ if (ctx.queryExamples?.length) {
67
+ parts.push('EXAMPLE QUERIES:\n' + ctx.queryExamples.map((q) => `• ${q.question}\n ${q.sql}`).join('\n'));
68
+ }
69
+ if (parts.length === 0)
70
+ return '';
71
+ return 'DOMAIN CONTEXT — curated knowledge about this dataset. Prefer these definitions and apply the standard filters:\n' + parts.join('\n');
72
+ }
73
+ /** JSON schema for caller-driven authoring (constrained-output for a model). */
74
+ export const DATA_CONTEXT_SCHEMA = {
75
+ type: 'object',
76
+ properties: {
77
+ dataset: { type: 'string' },
78
+ entities: { type: 'array', items: { type: 'object', properties: { term: { type: 'string' }, meaning: { type: 'string' } }, required: ['term', 'meaning'] } },
79
+ metrics: { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, definition: { type: 'string' }, sql: { type: 'string' }, caveats: { type: 'string' } }, required: ['name', 'definition', 'sql'] } },
80
+ standardFilters: { type: 'array', items: { type: 'object', properties: { description: { type: 'string' }, sql: { type: 'string' } }, required: ['description', 'sql'] } },
81
+ columnNotes: { type: 'array', items: { type: 'object', properties: { column: { type: 'string' }, note: { type: 'string' } }, required: ['column', 'note'] } },
82
+ queryExamples: { type: 'array', items: { type: 'object', properties: { question: { type: 'string' }, sql: { type: 'string' } }, required: ['question', 'sql'] } },
83
+ },
84
+ required: ['dataset'],
85
+ };
86
+ /** Authoring prompt for a caller's model: turn schema + sample rows + the quality
87
+ * audit into a DataContext. The core stays model-free; the caller runs this. */
88
+ export function buildContextAuthorPrompt(dataset, schemaText, sampleRows, auditNote) {
89
+ return (`You are documenting a dataset so future analyses are grounded. Produce a DataContext JSON for table "${dataset}".\n\n` +
90
+ `SCHEMA: ${schemaText}\n\n` +
91
+ `SAMPLE ROWS:\n${sampleRows}\n\n` +
92
+ (auditNote ? `DATA-QUALITY AUDIT:\n${auditNote}\n\n` : '') +
93
+ `Capture ONLY what is genuinely useful and supported by the data: ambiguous TERMS, the few KEY METRICS (with the exact SQL to compute each), ` +
94
+ `any STANDARD FILTERS that should usually apply (sentinels/test rows the audit flagged), per-column GOTCHAS (units, timezones, NULL meaning), ` +
95
+ `and 1-3 canonical example queries. Do NOT invent business rules you cannot infer. Omit a section rather than pad it. Output JSON only.`);
96
+ }
@@ -22,3 +22,26 @@ export interface QualityFinding {
22
22
  }
23
23
  /** Profile-based data-quality checks for one table's columns. */
24
24
  export declare function auditColumns(table: string, columns: DataColumn[], rowCount: number): QualityFinding[];
25
+ export type AuditQueryFn = (sql: string) => Promise<{
26
+ ok: boolean;
27
+ rows?: Record<string, unknown>[];
28
+ error?: string;
29
+ }>;
30
+ export declare function tableLevelChecks(t: {
31
+ name: string;
32
+ columns: DataColumn[];
33
+ rowCount: number;
34
+ }, query: AuditQueryFn): Promise<QualityFinding[]>;
35
+ /** The full audit: profile checks + table-level checks, over every table. The ONE
36
+ * entry point both the CLI `check` command and the analysis loop call. */
37
+ export declare function auditDataset(tables: {
38
+ name: string;
39
+ columns: DataColumn[];
40
+ rowCount: number;
41
+ }[], query: AuditQueryFn): Promise<QualityFinding[]>;
42
+ /** Compact, ACTION-GUIDING summary for injection into an LLM system prompt. Filters
43
+ * to the silent-wrong-number issues (PROMPT_WORTHY_ISSUES), collapses repeats of
44
+ * the same issue into ONE line (13 "NULL" sentinel columns → one line, not 13),
45
+ * and caps tightly. '' if nothing actionable. The full audit still lives in
46
+ * `session.audit` / `dolex check`. */
47
+ export declare function formatAuditForPrompt(findings: QualityFinding[], maxLines?: number): string;