@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/README.md CHANGED
@@ -11,11 +11,11 @@
11
11
 
12
12
  A B2B data-analysis product that gives your AI assistant a rigorous analyst's discipline, working on your own files and handing back artifacts you keep.
13
13
 
14
- Dolex connects to your data, audits it, runs the analysis, and returns real results you own. It runs locally on your CSV files and loads a folder of them as one joinable database. It profiles every column, classifies what each one is, and builds a prioritized analysis plan with ready-to-run queries. Every answer traces back to an inspectable query, and the findings come back as artifacts you keep. Dolex ships as a published npm package with two front ends over one core: an MCP server any AI assistant can call, and a command-line tool your terminals, scripts, and pipelines run directly.
14
+ Dolex connects to your data — a folder of CSV files, or a live PostgreSQL or MongoDB database — audits it, runs the analysis, and returns real results you own. It runs locally: point it at a folder of CSVs and they load as one joinable database, or connect a Postgres/MongoDB source and query it in place. It profiles every column, classifies what each one is, and builds a prioritized analysis plan with ready-to-run queries. Every answer traces back to an inspectable query, and the findings come back as artifacts you keep. Dolex ships as a published npm package with two front ends over one core: an MCP server any AI assistant can call, and a command-line tool your terminals, scripts, and pipelines run directly.
15
15
 
16
16
  ## What you get
17
17
 
18
- - **Analysis on your own data.** Dolex runs locally on your CSV files, and a folder of them becomes one database your assistant can join across.
18
+ - **Analysis on your own data.** Point Dolex at a folder of CSV files — they become one database your assistant can join across — or connect a live PostgreSQL or MongoDB database and query it in place. Same tools, same analysis, whatever the source.
19
19
  - **Data you can stand behind.** A built-in audit surfaces type traps, sentinel values, leaked and duplicate columns, and outliers before they reach a conclusion.
20
20
  - **Rigor on every result.** Full column profiling and statistics back the analysis, and each finding traces to a query you can inspect.
21
21
  - **A real analysis plan.** Dolex classifies your columns and produces a prioritized analysis plan with ready-to-run queries; derived columns persist across sessions.
@@ -108,15 +108,36 @@ dolex columns diamonds.csv # list source / derived / working columns
108
108
  | `columns` | List columns by layer (source / derived / working) |
109
109
  | `drop` | Remove derived/working columns |
110
110
  | `patterns` | List the 43 chart patterns, or show one in detail |
111
- | `sources` | Manage a persistent CSV registry (shared with the MCP server) |
111
+ | `sources` | Register & manage data sources — CSV, Postgres, MongoDB (shared with the MCP server) |
112
+ | `deps` | Report which data sources & optional features are available in this environment |
112
113
  | `mcp` | Run the MCP stdio server |
113
114
 
114
115
  Charts default to `~/.dolex/charts/`; pipe-friendly via `--stdout` / `--json`.
115
116
  Full reference: [`docs/CLI.md`](https://github.com/outsidedata/dolex/blob/master/docs/CLI.md).
116
117
 
118
+ ## Data Sources
119
+
120
+ Dolex works the same whether your data is files or a live database. Point it at:
121
+
122
+ - **CSV** — a single file or a whole folder, loaded as one joinable in-memory database (SQLite under the hood).
123
+ - **PostgreSQL** — a live database queried in place with real SQL; declared foreign keys are read straight from the schema.
124
+ - **MongoDB** — collections profiled as tables and queried with aggregation pipelines.
125
+
126
+ The Postgres and MongoDB drivers are **optional** — the base install stays lean and requires neither. Run `dolex deps` (or ask the assistant for `capabilities`) to see which sources are ready here and the exact one-line command to enable anything missing, so you get an install hint instead of a crash. Credentials stay out of the registry file: a Postgres password is read from an env var at connect time, and a source can be registered even while its database is down, then health-checked with `dolex sources test` / the `test_source` tool once it is up.
127
+
128
+ ```bash
129
+ # CSV stays the zero-config default
130
+ dolex sources add sales ./data/sales.csv
131
+
132
+ # Live databases — driver installed on demand, secret via env var
133
+ dolex sources add warehouse --type postgres --host db.internal --database analytics --user reader --password-env PGPASSWORD
134
+ dolex sources add events --type mongodb --host localhost --port 27017 --database app
135
+ dolex sources test warehouse # confirm it's reachable with its saved credentials
136
+ ```
137
+
117
138
  ## The Query Engine
118
139
 
119
- Point your assistant at a folder of CSV files and start asking questions. Dolex loads every file and profiles your data — column types, distributions, cardinality, sample values — giving your assistant everything it needs to answer.
140
+ Point your assistant at a folder of CSV files — or a live Postgres/MongoDB database — and start asking questions. Dolex profiles your data — column types, distributions, cardinality, sample values — giving your assistant everything it needs to answer.
120
141
 
121
142
  The built-in query language covers the analysis your assistant runs:
122
143
 
@@ -148,13 +169,15 @@ Every query is validated before execution — field names are checked against th
148
169
 
149
170
  | Tool | What it does |
150
171
  |------|-------------|
151
- | `load_csv` | Load a CSV file or directory |
172
+ | `load_source` | Load a data source — CSV file/directory, PostgreSQL, or MongoDB |
152
173
  | `list_data` | List loaded datasets |
153
174
  | `remove_data` | Remove a loaded dataset |
175
+ | `capabilities` | Report which source types & optional drivers are available in this environment |
176
+ | `test_source` | Health-check a registered Postgres/Mongo source (reachable? credentials valid?) |
154
177
  | `describe_data` | Profile columns, stats, sample rows |
155
178
  | `analyze_data` | Auto-generate an analysis plan |
156
- | `query_data` | Run SQL queries (JOINs, GROUP BY, window functions, CTEs) |
157
- | `visualize` | Data → ranked chart recommendations (inline, cached, or CSV+SQL) |
179
+ | `query_data` | Run queries (SQL for CSV/Postgres; aggregation pipelines for MongoDB) |
180
+ | `visualize` | Data → ranked chart recommendations (inline, cached, or source + query) |
158
181
  | `refine_visualization` | Iterate on a chart |
159
182
  | `transform_data` | Create derived columns with expressions |
160
183
  | `promote_columns` | Persist working columns to disk |
@@ -1,3 +1,4 @@
1
1
  import type { DataColumn } from '../types.js';
2
2
  import type { AnalysisPlan } from './types.js';
3
- export declare function buildAnalysisPlan(columns: DataColumn[], table: string, sourceName: string, maxSteps?: number): AnalysisPlan;
3
+ import { type PlannerDialect } from './rules.js';
4
+ export declare function buildAnalysisPlan(columns: DataColumn[], table: string, sourceName: string, maxSteps?: number, dialect?: PlannerDialect): AnalysisPlan;
@@ -12,9 +12,9 @@ const DEFAULT_MAX_STEPS = 6;
12
12
  function plural(n, word) {
13
13
  return `${n} ${word}${n !== 1 ? 's' : ''}`;
14
14
  }
15
- export function buildAnalysisPlan(columns, table, sourceName, maxSteps = DEFAULT_MAX_STEPS) {
15
+ export function buildAnalysisPlan(columns, table, sourceName, maxSteps = DEFAULT_MAX_STEPS, dialect = 'sqlite') {
16
16
  const classified = classifyColumns(columns);
17
- const candidates = generateCandidates(classified, table);
17
+ const candidates = generateCandidates(classified, table, dialect);
18
18
  candidates.sort((a, b) => CATEGORY_PRIORITY[a.category] - CATEGORY_PRIORITY[b.category]);
19
19
  // Deduplicate by category: first encountered wins after priority sort
20
20
  const seen = new Set();
@@ -31,6 +31,17 @@ const COERCED_SENTINEL_MIN = 10;
31
31
  const THOUSANDS_NUM = /^-?\d{1,3}(,\d{3})+(\.\d+)?$/; // 1,200 / 12,500.50 / -3,000
32
32
  const CURRENCY_NUM = /^[-+]?[$€£¥]\s?\d[\d,]*(\.\d+)?$/; // $1,200 / €980 / £12,500.50
33
33
  const PERCENT_NUM = /^[-+]?\d[\d,]*(\.\d+)?\s*%$/; // 45% / 12.5% / 1,200%
34
+ const ACCOUNTING_NUM = /^\(\s?[$€£¥]?\s?\d[\d,]*(\.\d+)?\s?\)$/; // (1,234) / ($1,234.50) — parens = negative
35
+ // Boolean columns written inconsistently (Yes/Y/1/true vs No/N/0/false).
36
+ const BOOL_TRUE = new Set(['true', 't', 'yes', 'y', '1']);
37
+ const BOOL_FALSE = new Set(['false', 'f', 'no', 'n', '0']);
38
+ const canonBool = (v) => {
39
+ const k = v.trim().toLowerCase();
40
+ return BOOL_TRUE.has(k) ? 'true' : BOOL_FALSE.has(k) ? 'false' : null;
41
+ };
42
+ // Invisible dirt: leading/trailing whitespace, non-breaking/zero-width spaces,
43
+ // smart quotes, BOM — splits otherwise-identical values.
44
+ const DIRTY_WS = /^\s|\s$|[\u00A0\u200B\u2018\u2019\u201C\u201D\uFEFF]/; // NBSP, ZWSP, smart quotes, BOM
34
45
  function isNumericStr(s) {
35
46
  const t = s.trim();
36
47
  return t !== '' && !Number.isNaN(Number(t));
@@ -47,6 +58,29 @@ function looksLikeYear(col) {
47
58
  function isDatePartName(name) {
48
59
  return /(^|_)(month|months|hour|hours|minute|minutes|second|seconds|day|days|week|weeks|time|date)(_|$)/i.test(name);
49
60
  }
61
+ function classifyDateFmt(v) {
62
+ const s = v.trim();
63
+ if (/^\d{4}-\d{2}-\d{2}/.test(s))
64
+ return 'iso';
65
+ if (/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(s))
66
+ return 'us';
67
+ if (/^\d{1,2}\.\d{1,2}\.\d{4}$/.test(s))
68
+ return 'eu';
69
+ if (/^\d{1,2}\s+[A-Za-z]{3,}\s+\d{4}$/.test(s))
70
+ return 'text';
71
+ if (/^[A-Za-z]{3,}\s+\d{1,2},?\s+\d{4}$/.test(s))
72
+ return 'text';
73
+ return null;
74
+ }
75
+ function detectDateFormats(values) {
76
+ const found = new Set();
77
+ for (const v of values) {
78
+ const f = classifyDateFmt(v);
79
+ if (f)
80
+ found.add(f);
81
+ }
82
+ return found;
83
+ }
50
84
  /** Profile-based data-quality checks for one table's columns. */
51
85
  export function auditColumns(table, columns, rowCount) {
52
86
  const findings = [];
@@ -130,6 +164,7 @@ export function auditColumns(table, columns, rowCount) {
130
164
  const lenPool = samples.length ? samples : catPool;
131
165
  const avgValLen = lenPool.length ? lenPool.reduce((s, v) => s + v.length, 0) / lenPool.length : 0;
132
166
  const looksFreeText = avgValLen > 45;
167
+ let dirtyCatFired = false;
133
168
  if ((col.type === 'categorical' || col.type === 'text') && (col.topValues?.length ?? 0) >= 2 && !looksFreeText) {
134
169
  const seen = new Map();
135
170
  let collision;
@@ -146,6 +181,7 @@ export function auditColumns(table, columns, rowCount) {
146
181
  seen.set(key, raw);
147
182
  }
148
183
  if (collision) {
184
+ dirtyCatFired = true;
149
185
  // Keep the TRIM(LOWER) remedy (correct for case/whitespace dirt), but when the
150
186
  // column is high-cardinality, ADD a caveat that it won't canonicalize
151
187
  // model-specific fragments (body: 87 distinct, "granturismo convertible") —
@@ -157,6 +193,30 @@ export function auditColumns(table, columns, rowCount) {
157
193
  add('medium', col.name, 'dirty-categories', `Values differ only by case/whitespace and are counted as separate categories (e.g. "${collision[0]}" vs "${collision[1]}").`, `They split one logical category across rows, distorting counts and the top category. Normalize: GROUP BY TRIM(LOWER(${esc(col.name)})).${frag}`);
158
194
  }
159
195
  }
196
+ // ── Boolean column written inconsistently (Yes/Y/1 vs No/N/0/true/false) ──
197
+ // Same true/false data in mixed encodings splits filters and groupings. Gate
198
+ // on an ALPHABETIC form present so a pure numeric 1/0 column isn't swept in.
199
+ if ((col.type === 'categorical' || col.type === 'text')) {
200
+ const boolForms = [...new Set(catPool.map((v) => v.trim()).filter((v) => v !== ''))];
201
+ if (boolForms.length >= 2 && boolForms.length <= 8) {
202
+ const canon = boolForms.map(canonBool);
203
+ const allBool = canon.every((c) => c !== null);
204
+ const hasAlpha = boolForms.some((v) => /[a-z]/i.test(v));
205
+ const distinctCanon = new Set(canon).size;
206
+ if (allBool && hasAlpha && boolForms.length > distinctCanon) {
207
+ add('low', col.name, 'boolean-variants', `Boolean column with inconsistent encodings (e.g. ${boolForms.slice(0, 3).map((v) => `"${v}"`).join(', ')}).`, 'These are the same true/false values written differently — they split filters and GROUP BY. Canonicalize to one form.');
208
+ }
209
+ }
210
+ }
211
+ // ── Invisible dirt: whitespace / non-standard unicode in string values ──
212
+ // Skipped when dirty-categories already fired (its TRIM(LOWER) remedy covers
213
+ // the same column, and the two fixes would otherwise conflict).
214
+ if ((col.type === 'categorical' || col.type === 'text') && !dirtyCatFired) {
215
+ const dirty = catPool.find((v) => v !== '' && DIRTY_WS.test(v));
216
+ if (dirty !== undefined) {
217
+ add('low', col.name, 'dirty-whitespace', `Values carry leading/trailing whitespace or non-standard characters (e.g. ${JSON.stringify(dirty)}).`, 'Invisible differences split otherwise-identical values; TRIM and normalize unicode (NBSP, zero-width, smart quotes).');
218
+ }
219
+ }
160
220
  // ── Missing-value sentinels hiding in categorical data ──
161
221
  const valuePool = (col.topValues?.map((t) => String(t.value)) ?? []).concat(samples);
162
222
  const sentinel = valuePool.find((v) => SENTINELS.has(v.trim().toLowerCase()));
@@ -209,12 +269,33 @@ export function auditColumns(table, columns, rowCount) {
209
269
  if (col.type === 'date' && looksLikeYear(col)) {
210
270
  add('low', col.name, 'year-column', `Holds 4-digit years, not full dates.`, 'Group by it directly — do not apply month/day date math (strftime) to it.');
211
271
  }
212
- // ── Non-ISO date columns (time-series footgun) ──
272
+ // ── Non-ISO / mixed date formats (time-series footgun) ──
273
+ // Use topValues (frequency-ranked) NOT sampleValues — the first N rows of a CSV
274
+ // are often format-homogeneous (e.g. all ISO), so sampleValues misses the tail.
213
275
  if (col.type === 'date' && !looksLikeYear(col)) {
214
- const dvals = samples;
215
- const nonIso = dvals.filter((v) => !/^\d{4}-\d{2}-\d{2}/.test(v));
216
- if (dvals.length >= 3 && nonIso.length > 0) {
217
- add('medium', col.name, 'non-iso-date', `Looks like dates but not ISO YYYY-MM-DD (e.g. ${nonIso.slice(0, 2).join(', ')}).`, 'Time bucketing (strftime) only parses ISO — non-ISO dates collapse to NULL, so analyze skips the trend. Reformat to YYYY-MM-DD for time-series analysis.');
276
+ const topVals = (col.topValues ?? []).map((t) => String(t.value)).filter(Boolean);
277
+ const dateProbe = [...new Set([...samples, ...topVals])].filter(Boolean);
278
+ if (dateProbe.length >= 3) {
279
+ const formats = detectDateFormats(dateProbe);
280
+ if (formats.size >= 2) {
281
+ // Multiple incompatible formats in the same column — HIGH, and prompt-worthy.
282
+ // strftime + BETWEEN silently discard non-ISO rows; the model must normalize first.
283
+ const examples = [];
284
+ for (const fmt of formats) {
285
+ const ex = dateProbe.find((v) => classifyDateFmt(v) === fmt);
286
+ if (ex)
287
+ examples.push(`"${ex}" (${fmt})`);
288
+ }
289
+ add('high', col.name, 'mixed-date-format', `Column has ${formats.size} incompatible date formats: ${examples.join(', ')}.`, `strftime/BETWEEN silently ignore non-ISO rows — ISO rows only are counted. Normalize to YYYY-MM-DD with a clean() function before filtering or aggregating by date.`);
290
+ }
291
+ else {
292
+ // Single non-ISO format — keep existing MEDIUM advisory (not prompt-worthy,
293
+ // but surfaced in `dolex check` for awareness).
294
+ const nonIso = dateProbe.filter((v) => !/^\d{4}-\d{2}-\d{2}/.test(v));
295
+ if (nonIso.length > 0) {
296
+ add('medium', col.name, 'non-iso-date', `Looks like dates but not ISO YYYY-MM-DD (e.g. ${nonIso.slice(0, 2).join(', ')}).`, 'Time bucketing (strftime) only parses ISO — non-ISO dates collapse to NULL, so analyze skips the trend. Reformat to YYYY-MM-DD for time-series analysis.');
297
+ }
298
+ }
218
299
  }
219
300
  }
220
301
  }
@@ -242,6 +323,15 @@ function classifyNumericText(probe) {
242
323
  if (vals.length < 2)
243
324
  return null;
244
325
  const frac = (xs) => xs.length / vals.length;
326
+ // Accounting negatives first — "(1,234)" matches neither currency nor sep, but
327
+ // it IS a number (a negative one), and missing it loses the sign silently.
328
+ const accounting = vals.filter((v) => ACCOUNTING_NUM.test(v));
329
+ if (frac(accounting) >= 0.6)
330
+ return {
331
+ issue: 'numeric-text-parens', label: 'accounting-style negatives', examples: accounting.slice(0, 2),
332
+ harm: 'SQLite reads "(1,234)" as 0 and loses the negative sign — SUM/AVG/ORDER BY are silently wrong.',
333
+ fix: (c) => `CASE WHEN ${c} LIKE '(%' THEN -CAST(REPLACE(REPLACE(REPLACE(${c}, '(', ''), ')', ''), ',', '') AS REAL) ELSE CAST(REPLACE(${c}, ',', '') AS REAL) END`,
334
+ };
245
335
  const currency = vals.filter((v) => CURRENCY_NUM.test(v));
246
336
  if (frac(currency) >= 0.6) {
247
337
  // Tailor the fix to the ACTUAL symbol present → a 2-REPLACE expression the
@@ -360,6 +450,7 @@ const SEV_RANK = { high: 0, medium: 1, low: 2 };
360
450
  // list tight — every line added is a line that competes with the user's question.
361
451
  const PROMPT_WORTHY_ISSUES = new Set([
362
452
  'numeric-text-symbol', 'numeric-text-separators', 'mixed-type', // type traps
453
+ 'mixed-date-format', // ≥2 incompatible date formats — strftime silently drops non-ISO rows
363
454
  'sentinel-value', // missing-value markers that poison aggregates
364
455
  'dirty-categories', // case/space splits that change the GROUP BY winner
365
456
  'duplicate-rows', // inflate counts
@@ -21,8 +21,28 @@ export declare function isIsoDateColumn(col: ClassifiedColumn): boolean;
21
21
  * date column — we'd rather skip the trend than ship strftime SQL that silently
22
22
  * produces a single NULL bucket summing the whole table.
23
23
  */
24
- export declare function timeBucketing(col: ClassifiedColumn): {
24
+ /** SQL flavor for planner-generated date/time SQL. */
25
+ export type PlannerDialect = 'sqlite' | 'postgres';
26
+ /**
27
+ * Raised when analysis-plan generation is asked to run against a source whose
28
+ * query paradigm the planner can't emit. The planner produces SELECT SQL, so a
29
+ * document store (mongodb → aggregation pipeline) is REFUSED here rather than
30
+ * silently handed SQLite SQL — the caller surfaces `message` as a clean error.
31
+ */
32
+ export declare class PlannerUnsupportedSourceError extends Error {
33
+ readonly sourceType: string;
34
+ constructor(sourceType: string, message: string);
35
+ }
36
+ /**
37
+ * Resolve a registered source's `type` to the SQL flavor the planner emits.
38
+ * The ONE place source-type → planner-dialect is decided, so no call site
39
+ * re-derives it with a `type === 'postgres' ? …` ternary that silently maps an
40
+ * unrecognized (e.g. mongodb) source to SQLite. csv/undefined → sqlite,
41
+ * postgres → postgres; a pipeline source (mongodb) or unknown type THROWS.
42
+ */
43
+ export declare function plannerDialectForSource(type: string | undefined): PlannerDialect;
44
+ export declare function timeBucketing(col: ClassifiedColumn, dialect?: PlannerDialect): {
25
45
  label: string;
26
46
  expr: string;
27
47
  } | null;
28
- export declare function generateCandidates(columns: ClassifiedColumn[], table: string): AnalysisStep[];
48
+ export declare function generateCandidates(columns: ClassifiedColumn[], table: string, dialect?: PlannerDialect): AnalysisStep[];
@@ -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
- * Choose the time-bucket label + a SQL expression robust to how the value is
46
- * stored. Year columns extract the integer year (works for '1980', '1980.0',
47
- * numeric 1980); ISO dates use strftime. Returns null for a non-ISO, non-year
48
- * date column — we'd rather skip the trend than ship strftime SQL that silently
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 function timeBucketing(col) {
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
- return {
55
- label: 'year',
56
- expr: `CASE WHEN CAST(${c} AS REAL) BETWEEN 1000 AND 2200 THEN CAST(CAST(${c} AS INTEGER) AS TEXT) END`,
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;
@@ -177,12 +217,12 @@ const composition = (columns, table) => {
177
217
  // time bucket (WoW/MoM/YoY depending on the bucket). Uses LAG; the % change is
178
218
  // guarded with NULLIF (div-by-zero) and 100.0 (real division) — the SQL-safety
179
219
  // traps this engine warns about, avoided at the source.
180
- const periodOverPeriod = (columns, table) => {
220
+ const periodOverPeriod = (columns, table, dialect) => {
181
221
  const timeCol = first(columns, 'time');
182
222
  const measureCol = first(columns, 'measure');
183
223
  if (!timeCol || !measureCol)
184
224
  return null;
185
- const tb = timeBucketing(timeCol);
225
+ const tb = timeBucketing(timeCol, dialect);
186
226
  if (!tb)
187
227
  return null;
188
228
  const { label: bucket, expr: bucketExpr } = tb;
@@ -197,7 +237,7 @@ const periodOverPeriod = (columns, table) => {
197
237
  // Seasonality: average a measure by month-of-year ACROSS years, isolating the
198
238
  // recurring seasonal shape from the long-run trend. Only meaningful with sub-year
199
239
  // (ISO date) resolution — skipped for year-only columns.
200
- const seasonality = (columns, table) => {
240
+ const seasonality = (columns, table, dialect) => {
201
241
  const timeCol = first(columns, 'time');
202
242
  const measureCol = first(columns, 'measure');
203
243
  if (!timeCol || !measureCol)
@@ -208,8 +248,9 @@ const seasonality = (columns, table) => {
208
248
  if (vals.length > 0 && !isIsoDateColumn(timeCol))
209
249
  return null; // non-ISO date → strftime would NULL
210
250
  const c = q(timeCol.name);
211
- const sql = `SELECT strftime('%m', ${c}) AS month, AVG(${q(measureCol.name)}) AS ${q(`avg_${measureCol.name}`)} ` +
212
- `FROM ${q(table)} WHERE strftime('%m', ${c}) IS NOT NULL GROUP BY 1 ORDER BY 1 ASC`;
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`;
213
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']);
214
255
  };
215
256
  // --- All Rules --------------------------------------------------------------
@@ -225,9 +266,9 @@ const ALL_RULES = [
225
266
  composition,
226
267
  ];
227
268
  // --- Main Export -------------------------------------------------------------
228
- export function generateCandidates(columns, table) {
269
+ export function generateCandidates(columns, table, dialect = 'sqlite') {
229
270
  return ALL_RULES.flatMap(rule => {
230
- const result = rule(columns, table);
271
+ const result = rule(columns, table, dialect);
231
272
  return result ? [result] : [];
232
273
  });
233
274
  }
@@ -1,8 +1,4 @@
1
1
  export { pythonAvailable, runPythonClean, cleanStats, safetyVerdict, previewSample, applyCleanColumn, CleanRejected } from './exec.js';
2
2
  export type { CleanStats } from './exec.js';
3
- export { HANDLERS, validateFix } from './handlers.js';
4
- export type { AcceptResult } from './handlers.js';
5
- export { PY_SCHEMA, buildAuthorPrompt } from './author.js';
6
- export type { AuthorRequest, CleanAuthor } from './author.js';
7
- export { buildCleanManifest, applyManifest, cleanDataset } from './manifest.js';
8
- export type { FixRecord, CleanManifest } from './manifest.js';
3
+ export { applyManifest, applyFixesToRows, readCleanfixManifest, resolveCleanfixPath } from './replay.js';
4
+ export type { FixRecord, CleanManifest } from './replay.js';
@@ -1,4 +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).
1
8
  export { pythonAvailable, runPythonClean, cleanStats, safetyVerdict, previewSample, applyCleanColumn, CleanRejected } from './exec.js';
2
- export { HANDLERS, validateFix } from './handlers.js';
3
- export { PY_SCHEMA, buildAuthorPrompt } from './author.js';
4
- export { buildCleanManifest, applyManifest, cleanDataset } from './manifest.js';
9
+ export { applyManifest, applyFixesToRows, readCleanfixManifest, resolveCleanfixPath } from './replay.js';
@@ -0,0 +1,34 @@
1
+ export interface FixRecord {
2
+ column: string;
3
+ issue: string;
4
+ task: string;
5
+ pythonCode: string;
6
+ validated: boolean;
7
+ summary: string;
8
+ }
9
+ export interface CleanManifest {
10
+ dataset: string;
11
+ createdBy: string;
12
+ createdAt: string;
13
+ fixes: FixRecord[];
14
+ }
15
+ type Row = Record<string, string>;
16
+ export declare function parseCsv(p: string): {
17
+ rows: Row[];
18
+ fields: string[];
19
+ };
20
+ /** Apply validated fixes to in-memory rows (mutates). When `keepRaw`, also writes a
21
+ * `<col>_raw` provenance column from the value the fix saw before overwriting `<col>`.
22
+ * The autoclean loop applies with keepRaw=false (provenance columns re-trigger the healed
23
+ * findings on re-audit); materialization keeps it for lineage. */
24
+ export declare function applyFixesToRows(rows: Row[], fixes: FixRecord[], keepRaw?: boolean): void;
25
+ /** Replay validated fixes over a CSV. NO model. `keepRaw` retains `<col>_raw` lineage. */
26
+ export declare function applyManifest(rawPath: string, manifest: CleanManifest, keepRaw?: boolean): {
27
+ rows: Row[];
28
+ fields: string[];
29
+ };
30
+ /** `<base>.cleanfix.json` co-located with the CSV (matches cleanDataset's default outDir). */
31
+ export declare function resolveCleanfixPath(csvPath: string): string;
32
+ /** Read + shape-validate a cleanfix manifest. Returns null if absent/invalid/empty. */
33
+ export declare function readCleanfixManifest(csvPath: string): CleanManifest | null;
34
+ export {};
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Cleanfix replay — the model-free, SourceManager-free half of the cleaning core. Lives in
3
+ * its own module so the CSV connector can replay a cleanfix manifest at load time WITHOUT
4
+ * pulling in SourceManager (manifest.ts → SourceManager → connectors → manifest.ts would be
5
+ * a cycle). Imports only papaparse + the python executor.
6
+ *
7
+ * The manifest (`<base>.cleanfix.json`) is the durable recipe: replaying it over the CURRENT
8
+ * raw CSV is what gives newly-arrived rows the same treatment as the data it was authored on.
9
+ */
10
+ import * as fs from 'fs';
11
+ import * as path from 'path';
12
+ import Papa from 'papaparse';
13
+ import { runPythonClean } from './exec.js';
14
+ const blank = (x) => x === null || x === '' || x === undefined;
15
+ export function parseCsv(p) {
16
+ const parsed = Papa.parse(fs.readFileSync(p, 'utf8'), { header: true, skipEmptyLines: true });
17
+ return { rows: parsed.data, fields: parsed.meta.fields || [] };
18
+ }
19
+ /** Apply validated fixes to in-memory rows (mutates). When `keepRaw`, also writes a
20
+ * `<col>_raw` provenance column from the value the fix saw before overwriting `<col>`.
21
+ * The autoclean loop applies with keepRaw=false (provenance columns re-trigger the healed
22
+ * findings on re-audit); materialization keeps it for lineage. */
23
+ export function applyFixesToRows(rows, fixes, keepRaw = true) {
24
+ for (const fix of fixes) {
25
+ if (rows.length > 0 && !(fix.column in rows[0]))
26
+ continue; // column gone (renamed/dropped) — skip gracefully
27
+ const { cleaned } = runPythonClean(fix.pythonCode, rows.map((r) => r[fix.column] ?? ''));
28
+ rows.forEach((r, i) => { if (keepRaw)
29
+ r[`${fix.column}_raw`] = r[fix.column] ?? ''; r[fix.column] = blank(cleaned[i]) ? '' : String(cleaned[i]); });
30
+ }
31
+ }
32
+ /** Replay validated fixes over a CSV. NO model. `keepRaw` retains `<col>_raw` lineage. */
33
+ export function applyManifest(rawPath, manifest, keepRaw = true) {
34
+ const { rows, fields } = parseCsv(rawPath);
35
+ const present = manifest.fixes.filter((f) => rows.length === 0 || f.column in rows[0]);
36
+ applyFixesToRows(rows, manifest.fixes, keepRaw);
37
+ return { rows, fields: keepRaw ? [...fields, ...present.map((f) => `${f.column}_raw`)] : fields };
38
+ }
39
+ /** `<base>.cleanfix.json` co-located with the CSV (matches cleanDataset's default outDir). */
40
+ export function resolveCleanfixPath(csvPath) {
41
+ return path.join(path.dirname(csvPath), `${path.basename(csvPath, path.extname(csvPath))}.cleanfix.json`);
42
+ }
43
+ /** Read + shape-validate a cleanfix manifest. Returns null if absent/invalid/empty. */
44
+ export function readCleanfixManifest(csvPath) {
45
+ try {
46
+ const p = resolveCleanfixPath(csvPath);
47
+ if (!fs.existsSync(p))
48
+ return null;
49
+ const m = JSON.parse(fs.readFileSync(p, 'utf8'));
50
+ if (!m || !Array.isArray(m.fixes))
51
+ return null;
52
+ const fixes = m.fixes.filter((f) => f && f.validated && f.column && f.pythonCode);
53
+ return fixes.length > 0 ? { ...m, fixes } : null;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
@@ -6,6 +6,7 @@ import { parseArgs, str, num, bool } from '../args.js';
6
6
  import * as o from '../output.js';
7
7
  import { openTarget } from '../data-source.js';
8
8
  import { buildAnalysisPlan } from '../../analysis/planner.js';
9
+ import { plannerDialectForSource, PlannerUnsupportedSourceError } from '../../analysis/rules.js';
9
10
  import { classifyColumns } from '../../analysis/classify.js';
10
11
  const BOOLEANS = ['json', 'help'];
11
12
  const ALIASES = { h: 'help', table: 'from' };
@@ -47,7 +48,18 @@ export async function analyzeCommand(argv) {
47
48
  const tableObj = autoPicked
48
49
  ? pickRichestTable(opened.tables)
49
50
  : opened.tables.find((t) => t.name === opened.defaultTable);
50
- const plan = buildAnalysisPlan(tableObj.columns, tableObj.name, opened.displayName, num(args, 'max-steps') ?? 6);
51
+ let dialect;
52
+ try {
53
+ dialect = plannerDialectForSource(opened.schema.source?.type);
54
+ }
55
+ catch (err) {
56
+ if (err instanceof PlannerUnsupportedSourceError) {
57
+ o.fail(err.message);
58
+ return 1;
59
+ }
60
+ throw err;
61
+ }
62
+ const plan = buildAnalysisPlan(tableObj.columns, tableObj.name, opened.displayName, num(args, 'max-steps') ?? 6, dialect);
51
63
  // No steps = nothing to analyze (only ids/text/empty columns). Fail loud
52
64
  // rather than print a success-looking empty plan.
53
65
  const noSteps = plan.steps.length === 0;
@@ -29,9 +29,12 @@ export async function cleanCommand(argv) {
29
29
  o.fail('dolex clean requires python3 on PATH (not found).');
30
30
  return 1;
31
31
  }
32
- const manifestArg = str(args, 'apply-manifest');
33
- if (manifestArg !== undefined)
34
- return replay(target, manifestArg);
32
+ // --apply-manifest may be bare (replay the sibling <base>.cleanfix.json) or take an explicit
33
+ // path. A bare value flag parses to boolean `true`, so test presence, not string-ness —
34
+ // otherwise the documented no-arg form fell through to the author-mode usage error.
35
+ if (args['apply-manifest'] !== undefined) {
36
+ return replay(target, str(args, 'apply-manifest') ?? '');
37
+ }
35
38
  const column = str(args, 'column');
36
39
  const codeFile = str(args, 'code-file');
37
40
  if (!column || !codeFile) {
@@ -42,6 +45,15 @@ export async function cleanCommand(argv) {
42
45
  // Read the column's values through the shared opener.
43
46
  const opened = await openTarget(target, {});
44
47
  try {
48
+ // clean writes a non-destructive cleaned CSV from a CSV file — a live DB source has no
49
+ // file to rewrite. Reject up front with the same redirect the MCP clean_column twin gives,
50
+ // instead of previewing and then failing with a confusing ENOENT on the source name.
51
+ const srcType = opened.manager.get(opened.sourceId)?.config?.type;
52
+ if (srcType && srcType !== 'csv') {
53
+ const nativeExpr = srcType === 'mongodb' ? 'native aggregation ($set) expression' : 'native SQL expression';
54
+ o.fail(`dolex clean writes a non-destructive cleaned CSV and works on CSV sources only. On a live ${srcType} source, express the fix as a derived column via \`dolex transform\` using a ${nativeExpr} — non-destructive and server-side.`);
55
+ return 1;
56
+ }
45
57
  const tableName = opened.defaultTable;
46
58
  const q = await opened.query(`SELECT "${column.replace(/"/g, '""')}" AS v FROM "${tableName.replace(/"/g, '""')}"`, 1_000_000);
47
59
  if (!q.ok) {