@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.
Files changed (84) hide show
  1. package/README.md +33 -7
  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/planner.d.ts +2 -1
  7. package/dist/src/analysis/planner.js +2 -2
  8. package/dist/src/analysis/quality.d.ts +23 -0
  9. package/dist/src/analysis/quality.js +386 -11
  10. package/dist/src/analysis/rules.d.ts +22 -2
  11. package/dist/src/analysis/rules.js +100 -18
  12. package/dist/src/cleaning/author.d.ts +30 -0
  13. package/dist/src/cleaning/author.js +7 -0
  14. package/dist/src/cleaning/exec.d.ts +29 -0
  15. package/dist/src/cleaning/exec.js +161 -0
  16. package/dist/src/cleaning/handlers.d.ts +16 -0
  17. package/dist/src/cleaning/handlers.js +82 -0
  18. package/dist/src/cleaning/index.d.ts +4 -0
  19. package/dist/src/cleaning/index.js +9 -0
  20. package/dist/src/cleaning/manifest.d.ts +35 -0
  21. package/dist/src/cleaning/manifest.js +95 -0
  22. package/dist/src/cleaning/replay.d.ts +34 -0
  23. package/dist/src/cleaning/replay.js +58 -0
  24. package/dist/src/cli/commands/analyze.js +13 -1
  25. package/dist/src/cli/commands/check.js +2 -89
  26. package/dist/src/cli/commands/clean.d.ts +1 -0
  27. package/dist/src/cli/commands/clean.js +127 -0
  28. package/dist/src/cli/commands/deps.d.ts +1 -0
  29. package/dist/src/cli/commands/deps.js +41 -0
  30. package/dist/src/cli/commands/help.js +3 -1
  31. package/dist/src/cli/commands/query.js +4 -1
  32. package/dist/src/cli/commands/sources.d.ts +2 -2
  33. package/dist/src/cli/commands/sources.js +138 -12
  34. package/dist/src/cli/commands/transform.js +19 -4
  35. package/dist/src/cli/commands/visualize.js +2 -0
  36. package/dist/src/cli/index.js +5 -0
  37. package/dist/src/connectors/csv.js +110 -8
  38. package/dist/src/connectors/index.d.ts +2 -0
  39. package/dist/src/connectors/index.js +2 -0
  40. package/dist/src/connectors/manager.d.ts +49 -1
  41. package/dist/src/connectors/manager.js +200 -14
  42. package/dist/src/connectors/mongo/index.d.ts +13 -0
  43. package/dist/src/connectors/mongo/index.js +323 -0
  44. package/dist/src/connectors/pg/index.d.ts +2 -0
  45. package/dist/src/connectors/pg/index.js +248 -0
  46. package/dist/src/connectors/source-factory.d.ts +38 -0
  47. package/dist/src/connectors/source-factory.js +80 -0
  48. package/dist/src/connectors/sql-safety.d.ts +68 -0
  49. package/dist/src/connectors/sql-safety.js +167 -0
  50. package/dist/src/connectors/types.d.ts +51 -0
  51. package/dist/src/connectors/types.js +11 -1
  52. package/dist/src/mcp/index.d.ts +1 -1
  53. package/dist/src/mcp/index.js +29 -10
  54. package/dist/src/mcp/tools/analyze.js +11 -1
  55. package/dist/src/mcp/tools/capabilities.d.ts +1 -0
  56. package/dist/src/mcp/tools/capabilities.js +14 -0
  57. package/dist/src/mcp/tools/clean-column.d.ts +5 -0
  58. package/dist/src/mcp/tools/clean-column.js +47 -0
  59. package/dist/src/mcp/tools/clean-schemas.d.ts +23 -0
  60. package/dist/src/mcp/tools/clean-schemas.js +9 -0
  61. package/dist/src/mcp/tools/drop-columns.js +2 -0
  62. package/dist/src/mcp/tools/list-transforms.js +22 -0
  63. package/dist/src/mcp/tools/promote-columns.js +2 -0
  64. package/dist/src/mcp/tools/query-source.d.ts +2 -2
  65. package/dist/src/mcp/tools/query-source.js +2 -1
  66. package/dist/src/mcp/tools/refine-cli.d.ts +4 -4
  67. package/dist/src/mcp/tools/refine.d.ts +4 -4
  68. package/dist/src/mcp/tools/shared.d.ts +6 -0
  69. package/dist/src/mcp/tools/shared.js +12 -5
  70. package/dist/src/mcp/tools/sources.d.ts +46 -3
  71. package/dist/src/mcp/tools/sources.js +44 -4
  72. package/dist/src/mcp/tools/transform-data.js +22 -0
  73. package/dist/src/mcp/tools/visualize-cli.d.ts +2 -2
  74. package/dist/src/mcp/tools/visualize.d.ts +3 -2
  75. package/dist/src/mcp/tools/visualize.js +1 -0
  76. package/dist/src/transforms/evaluator.js +58 -3
  77. package/dist/src/transforms/tokenizer.js +20 -2
  78. package/dist/src/transforms/types.d.ts +6 -6
  79. package/dist/src/types.d.ts +39 -2
  80. package/dist/src/utils/capabilities.d.ts +28 -0
  81. package/dist/src/utils/capabilities.js +58 -0
  82. package/dist/src/utils/optional-deps.d.ts +8 -0
  83. package/dist/src/utils/optional-deps.js +8 -0
  84. package/package.json +9 -3
@@ -1,13 +1,17 @@
1
1
  /**
2
- * `dolex sources` — manage the persistent CSV registry at
3
- * `~/.dolex/sources.json` (shared with the MCP server's `load_csv`).
2
+ * `dolex sources` — manage the persistent data-source registry at
3
+ * `~/.dolex/sources.json` (CSV / Postgres / MongoDB; shared with the MCP server's `load_source`).
4
4
  */
5
5
  import { resolve } from 'path';
6
- import { parseArgs, bool } from '../args.js';
6
+ import { parseArgs, bool, str, num, list } from '../args.js';
7
7
  import * as o from '../output.js';
8
8
  import { persistentManager } from '../data-source.js';
9
+ import { resolveSourceConfig } from '../../connectors/source-factory.js';
9
10
  export async function sourcesCommand(argv) {
10
- const args = parseArgs(argv, { booleans: ['json', 'help'], aliases: { h: 'help' } });
11
+ const args = parseArgs(argv, {
12
+ booleans: ['json', 'help', 'verify'],
13
+ aliases: { h: 'help' },
14
+ });
11
15
  if (bool(args, 'help')) {
12
16
  printHelp();
13
17
  return 0;
@@ -25,23 +29,118 @@ export async function sourcesCommand(argv) {
25
29
  o.hint('No registered sources. Add one: dolex sources add <name> <path.csv>');
26
30
  return 0;
27
31
  }
28
- o.out(o.table(['name', 'id', 'type', 'path'], entries.map((e) => ({ name: e.name, id: e.id, type: e.type, path: e.config.path ?? '' }))));
32
+ o.out(o.table(['name', 'id', 'type', 'location'], entries.map((e) => ({ name: e.name, id: e.id, type: e.type, location: describeLocation(e.config) }))));
29
33
  return 0;
30
34
  }
31
35
  case 'add': {
32
36
  const name = args._[1];
33
- const path = args._[2];
34
- if (!name || !path) {
37
+ const pathArg = args._[2];
38
+ if (!name) {
35
39
  o.fail('Usage: dolex sources add <name> <path-to-csv-or-dir>');
40
+ o.hint('Or a database source: dolex sources add <name> --type postgres|mongodb --uri <conn-string>');
36
41
  return 1;
37
42
  }
38
- const res = await manager.add(name, { type: 'csv', path: resolve(path) });
43
+ const type = str(args, 'type');
44
+ // CSV path may come as a positional (backward-compatible) or --path.
45
+ const path = str(args, 'path') ?? pathArg;
46
+ let config;
47
+ try {
48
+ config = resolveSourceConfig({
49
+ type,
50
+ // Resolve CSV paths to absolute so the registry entry is cwd-independent.
51
+ path: path !== undefined ? resolve(path) : undefined,
52
+ uri: str(args, 'uri'),
53
+ host: str(args, 'host'),
54
+ port: num(args, 'port'),
55
+ database: str(args, 'database'),
56
+ user: str(args, 'user'),
57
+ password: str(args, 'password'),
58
+ passwordEnv: str(args, 'password-env'),
59
+ schema: str(args, 'schema'),
60
+ collections: list(args, 'collections'),
61
+ });
62
+ }
63
+ catch (e) {
64
+ o.fail(e instanceof Error ? e.message : String(e));
65
+ return 1;
66
+ }
67
+ if (str(args, 'password')) {
68
+ o.warn('--password is stored in plaintext in ~/.dolex/sources.json (locked to your user). Prefer --password-env <VAR> to keep the secret out of the file.');
69
+ }
70
+ // Config-first: register even if the DB is unreachable right now (unless --verify). liveness is
71
+ // reported, not required — so setup never depends on the DB being up this second.
72
+ const res = await manager.add(name, config, { verify: bool(args, 'verify') });
39
73
  if (!res.ok) {
40
74
  o.fail(res.error ?? 'Failed to add source.');
41
75
  return 1;
42
76
  }
43
- o.success(`Added "${name}" (${res.entry.id})`);
44
- o.hint(`Use it: dolex visualize ${name} -i "…" · dolex analyze ${name}`);
77
+ o.success(`Added "${name}" (${res.entry.id}) [${config.type}]`);
78
+ if (config.type !== 'csv' && res.verified === false) {
79
+ o.warn(`Registered, but couldn't connect yet: ${res.warning}`);
80
+ o.hint(`Fix the DB/credentials, then verify: dolex sources test ${name} (or update: dolex sources update ${name} --host … )`);
81
+ }
82
+ else {
83
+ o.hint(`Use it: dolex visualize ${name} -i "…" · dolex analyze ${name}`);
84
+ }
85
+ return 0;
86
+ }
87
+ case 'test': {
88
+ const idOrName = args._[1];
89
+ if (!idOrName) {
90
+ o.fail('Usage: dolex sources test <name|id>');
91
+ return 1;
92
+ }
93
+ const r = await manager.testSource(idOrName);
94
+ if (bool(args, 'json')) {
95
+ o.out(JSON.stringify({ source: idOrName, ...r }, null, 2));
96
+ return r.ok ? 0 : 1;
97
+ }
98
+ if (r.ok) {
99
+ o.success(`"${idOrName}" is reachable ✓`);
100
+ return 0;
101
+ }
102
+ o.fail(`"${idOrName}" is not reachable [${r.kind}]: ${r.error}`);
103
+ const nextStep = {
104
+ 'driver-missing': 'install the driver (see the message above), then retry',
105
+ 'unreachable': 'start the database / check host+port, then: dolex sources test ' + idOrName,
106
+ 'host-not-found': 'fix the host, then: dolex sources update ' + idOrName + ' --host <host>',
107
+ 'timeout': 'check the network/firewall or the DB is slow to accept connections',
108
+ 'auth-failed': 'fix credentials: dolex sources update ' + idOrName + ' --user <u> --password-env <VAR>',
109
+ 'db-not-found': 'fix the database name: dolex sources update ' + idOrName + ' --database <db>',
110
+ };
111
+ if (r.kind && nextStep[r.kind])
112
+ o.hint(nextStep[r.kind]);
113
+ return 1;
114
+ }
115
+ case 'update': {
116
+ const idOrName = args._[1];
117
+ if (!idOrName) {
118
+ o.fail('Usage: dolex sources update <name|id> [--host … --port … --database … --user … --password-env … --uri …]');
119
+ return 1;
120
+ }
121
+ const patch = {};
122
+ for (const k of ['uri', 'host', 'database', 'user', 'password', 'password-env', 'schema']) {
123
+ const v = str(args, k);
124
+ if (v !== undefined)
125
+ patch[k === 'uri' ? 'connectionString' : k === 'password-env' ? 'passwordEnv' : k] = v;
126
+ }
127
+ const p = num(args, 'port');
128
+ if (p !== undefined)
129
+ patch.port = p;
130
+ if (Object.keys(patch).length === 0) {
131
+ o.fail('Nothing to update. Pass at least one of --host/--port/--database/--user/--password-env/--uri/--schema.');
132
+ return 1;
133
+ }
134
+ if (patch.password)
135
+ o.warn('--password is stored in plaintext. Prefer --password-env <VAR>.');
136
+ const res = await manager.update(idOrName, patch, { verify: bool(args, 'verify') });
137
+ if (!res.ok) {
138
+ o.fail(res.error ?? 'Failed to update source.');
139
+ return 1;
140
+ }
141
+ o.success(`Updated "${idOrName}"`);
142
+ if (res.verified === false)
143
+ o.warn(`Saved, but still can't connect: ${res.warning}. Test again: dolex sources test ${idOrName}`);
45
144
  return 0;
46
145
  }
47
146
  case 'remove':
@@ -65,13 +164,40 @@ export async function sourcesCommand(argv) {
65
164
  return 1;
66
165
  }
67
166
  }
167
+ /** One-line summary of where a source lives, for the `list` table. */
168
+ /** host:port/database for a live DB source (the connection string wins if present). */
169
+ const hostPortDb = (connStr, host, port, database) => connStr ?? [host, port].filter(Boolean).join(':') + (database ? `/${database}` : '');
170
+ function describeLocation(config) {
171
+ switch (config.type) {
172
+ case 'csv':
173
+ return config.path ?? '';
174
+ case 'postgres':
175
+ return hostPortDb(config.connectionString, config.host, config.port, config.database);
176
+ case 'mongodb':
177
+ return hostPortDb(config.uri, config.host, config.port, config.database);
178
+ }
179
+ }
68
180
  function printHelp() {
69
- o.out(`${o.c.bold('dolex sources')} — manage the persistent CSV registry
181
+ o.out(`${o.c.bold('dolex sources')} — manage the persistent source registry
70
182
 
71
183
  ${o.c.bold('USAGE')}
72
184
  dolex sources list
73
185
  dolex sources add <name> <path-to-csv-or-dir>
186
+ dolex sources add <name> --type postgres --host <h> --database <db> [--user <u> --password-env PGPASSWORD]
187
+ dolex sources add <name> --type mongodb --host <h> --port <p> --database <db>
188
+ dolex sources test <name|id> # is the saved DB reachable? (classified reason)
189
+ dolex sources update <name|id> [--host … --port … --database … --user … --password-env … --uri …]
74
190
  dolex sources remove <name|id>
75
191
 
76
- ${o.c.dim('Stored in ~/.dolex/sources.json — shared with the MCP server.')}`);
192
+ ${o.c.bold('OPTIONS (add / update)')}
193
+ --type csv | postgres | mongodb (default: csv)
194
+ --uri connection string (libpq DSN for postgres, URI for mongodb)
195
+ --host/--port/--database/--user/--schema discrete connection fields
196
+ --password-env name of an env var holding the password (preferred — keeps the secret OUT of the file)
197
+ --password literal password (stored in plaintext; --password-env is safer)
198
+ --verify require a successful connection to register (default: register config-first even if the DB is down)
199
+ --collections mongodb: comma-separated list to restrict introspection
200
+
201
+ ${o.c.dim('Config-first: a source registers even if its DB is momentarily down — run `sources test` once it is up.')}
202
+ ${o.c.dim('Stored in ~/.dolex/sources.json (locked to your user; passwords via --password-env are NOT written). Shared with the MCP server.')}`);
77
203
  }
@@ -49,8 +49,12 @@ export async function transformCommand(argv) {
49
49
  return 1;
50
50
  }
51
51
  const col = tBody.created?.[0] ?? { column: create, expr, type: 'unknown' };
52
+ // A live source (Postgres/Mongo) derives session-locally — there is no manifest to promote to;
53
+ // the derived column exists for the life of the connection, non-destructive to the base data.
54
+ const srcType = opened.manager.get(opened.sourceId)?.config?.type;
55
+ const persistable = srcType === 'csv';
52
56
  let manifestPath;
53
- if (!dryRun) {
57
+ if (!dryRun && persistable) {
54
58
  const promote = handlePromoteColumns({ sourceManager: opened.manager });
55
59
  const pRes = await promote({ sourceId: opened.sourceId, table, columns: [create] });
56
60
  const pBody = JSON.parse(pRes.content[0].text);
@@ -63,11 +67,16 @@ export async function transformCommand(argv) {
63
67
  manifestPath = resolveManifestPath(entry.config);
64
68
  }
65
69
  if (bool(args, 'json')) {
66
- o.out(JSON.stringify({ ...tBody, persisted: !dryRun, manifest: manifestPath }, null, 2));
70
+ o.out(JSON.stringify({ ...tBody, persisted: !dryRun && persistable, sessionLocal: !persistable, manifest: manifestPath }, null, 2));
67
71
  return 0;
68
72
  }
69
73
  o.success(`${dryRun ? 'Previewed' : 'Created'} ${o.c.bold(col.column)} ${o.c.dim('= ' + col.expr)}`);
70
- o.kv('type', col.type);
74
+ // CSV returns a typed working column; a live source returns { layer, materialization }
75
+ // instead — show whichever the connector actually reported (never "type undefined").
76
+ if (col.type !== undefined)
77
+ o.kv('type', col.type);
78
+ else if (col.materialization)
79
+ o.kv('materialization', col.materialization);
71
80
  if (col.stats && typeof col.stats === 'object') {
72
81
  const fmt = (v) => typeof v === 'number' ? (Number.isInteger(v) ? String(v) : v.toFixed(3)) : String(v);
73
82
  for (const [k, v] of Object.entries(col.stats))
@@ -79,11 +88,17 @@ export async function transformCommand(argv) {
79
88
  if (dryRun) {
80
89
  o.warn('Preview only — not persisted. Re-run without --dry-run to keep it.');
81
90
  }
82
- else {
91
+ else if (persistable) {
83
92
  if (manifestPath)
84
93
  o.kv('persisted', manifestPath);
85
94
  o.hint(`Use it: dolex query ${target} "SELECT ${col.column} FROM ${table} LIMIT 5"`);
86
95
  }
96
+ else {
97
+ // Live PG/Mongo source: the derived column lives only on this connection, which a
98
+ // stateless CLI closes on exit — so a separate `dolex query` cannot see it, and for
99
+ // Mongo a SELECT hint would be invalid anyway. Be honest instead of promising a query.
100
+ o.warn(`Session-local — derived on the live ${srcType} connection only. The CLI is stateless, so this column is not persisted and a separate command cannot see it. Create it inside an MCP session, or inline the expression in your query.`);
101
+ }
87
102
  return 0;
88
103
  }
89
104
  finally {
@@ -41,6 +41,8 @@ export async function visualizeCommand(argv) {
41
41
  }
42
42
  data = res.rows ?? [];
43
43
  queryMeta = { truncated: res.truncated, totalSourceRows: res.totalRows };
44
+ for (const w of res.warnings ?? [])
45
+ o.warn(w);
44
46
  }
45
47
  finally {
46
48
  await opened.close();
@@ -71,6 +71,8 @@ async function main() {
71
71
  case 'check':
72
72
  case 'audit':
73
73
  process.exit(await (await import('./commands/check.js')).checkCommand(rest));
74
+ case 'clean':
75
+ process.exit(await (await import('./commands/clean.js')).cleanCommand(rest));
74
76
  case 'transform':
75
77
  process.exit(await (await import('./commands/transform.js')).transformCommand(rest));
76
78
  case 'columns':
@@ -84,6 +86,9 @@ async function main() {
84
86
  case 'sources':
85
87
  case 'source':
86
88
  process.exit(await (await import('./commands/sources.js')).sourcesCommand(rest));
89
+ case 'deps':
90
+ case 'doctor':
91
+ process.exit(await (await import('./commands/deps.js')).depsCommand(rest));
87
92
  case 'mcp':
88
93
  case 'serve':
89
94
  await startMcpServer();
@@ -8,10 +8,12 @@
8
8
  */
9
9
  import Database from 'better-sqlite3';
10
10
  import * as fs from 'fs';
11
+ import * as os from 'os';
11
12
  import * as path from 'path';
12
13
  import Papa from 'papaparse';
13
14
  import { resolveManifestPath, readManifest, replayManifest } from '../transforms/manifest.js';
14
15
  import { TransformMetadata } from '../transforms/metadata.js';
16
+ import { applyManifest as applyCleanfix, readCleanfixManifest } from '../cleaning/replay.js';
15
17
  const SAMPLE_LIMIT = 30;
16
18
  const SAMPLE_DISPLAY_LIMIT = 20;
17
19
  /**
@@ -93,6 +95,19 @@ function toTableName(filename) {
93
95
  */
94
96
  function registerCustomAggregates(db) {
95
97
  const sortedNums = (values) => values.filter(v => v != null && !isNaN(v)).sort((a, b) => a - b);
98
+ // Accumulate ONLY real numeric values. SQLite NULL arrives as JS null and empty
99
+ // cells as '' — both coerce to 0 via Number(), which would silently count missing
100
+ // values as zero and corrupt median/stddev/cv/mad/percentiles (and disagree with
101
+ // native AVG/COUNT, which ignore NULLs). Skip them BEFORE coercion. Non-numeric
102
+ // strings → NaN → also skipped. (Regression: __tests__/connectors/aggregates.test.ts)
103
+ const pushNum = (acc, val) => {
104
+ if (val === null || val === undefined || val === '')
105
+ return acc;
106
+ const n = Number(val);
107
+ if (Number.isFinite(n))
108
+ acc.push(n);
109
+ return acc;
110
+ };
96
111
  const computePercentile = (sorted, p) => {
97
112
  if (sorted.length === 0)
98
113
  return null;
@@ -107,12 +122,12 @@ function registerCustomAggregates(db) {
107
122
  };
108
123
  db.aggregate('median', {
109
124
  start: () => [],
110
- step: (acc, val) => { acc.push(Number(val)); return acc; },
125
+ step: (acc, val) => pushNum(acc, val),
111
126
  result: (acc) => computePercentile(sortedNums(acc), 0.5),
112
127
  });
113
128
  db.aggregate('stddev', {
114
129
  start: () => [],
115
- step: (acc, val) => { acc.push(Number(val)); return acc; },
130
+ step: (acc, val) => pushNum(acc, val),
116
131
  result: (acc) => {
117
132
  const nums = sortedNums(acc);
118
133
  if (nums.length === 0)
@@ -124,24 +139,63 @@ function registerCustomAggregates(db) {
124
139
  });
125
140
  db.aggregate('p25', {
126
141
  start: () => [],
127
- step: (acc, val) => { acc.push(Number(val)); return acc; },
142
+ step: (acc, val) => pushNum(acc, val),
128
143
  result: (acc) => computePercentile(sortedNums(acc), 0.25),
129
144
  });
130
145
  db.aggregate('p75', {
131
146
  start: () => [],
132
- step: (acc, val) => { acc.push(Number(val)); return acc; },
147
+ step: (acc, val) => pushNum(acc, val),
133
148
  result: (acc) => computePercentile(sortedNums(acc), 0.75),
134
149
  });
135
150
  db.aggregate('p10', {
136
151
  start: () => [],
137
- step: (acc, val) => { acc.push(Number(val)); return acc; },
152
+ step: (acc, val) => pushNum(acc, val),
138
153
  result: (acc) => computePercentile(sortedNums(acc), 0.10),
139
154
  });
140
155
  db.aggregate('p90', {
141
156
  start: () => [],
142
- step: (acc, val) => { acc.push(Number(val)); return acc; },
157
+ step: (acc, val) => pushNum(acc, val),
143
158
  result: (acc) => computePercentile(sortedNums(acc), 0.90),
144
159
  });
160
+ // Extended tail percentiles (floor/ceiling extremes) — same shape as p10..p90.
161
+ for (const [name, p] of [['p1', 0.01], ['p5', 0.05], ['p95', 0.95], ['p99', 0.99]]) {
162
+ db.aggregate(name, {
163
+ start: () => [],
164
+ step: (acc, val) => pushNum(acc, val),
165
+ result: (acc) => computePercentile(sortedNums(acc), p),
166
+ });
167
+ }
168
+ // Coefficient of variation — stddev/mean (population). Scale-free dispersion, for
169
+ // comparing variability across different-magnitude metrics. NULL when mean is 0
170
+ // (the ratio is undefined) or there are no values.
171
+ db.aggregate('cv', {
172
+ start: () => [],
173
+ step: (acc, val) => pushNum(acc, val),
174
+ result: (acc) => {
175
+ const nums = sortedNums(acc);
176
+ if (nums.length === 0)
177
+ return null;
178
+ const mean = nums.reduce((a, b) => a + b, 0) / nums.length;
179
+ if (mean === 0)
180
+ return null;
181
+ const variance = nums.reduce((sum, v) => sum + (v - mean) ** 2, 0) / nums.length;
182
+ return Math.sqrt(variance) / mean;
183
+ },
184
+ });
185
+ // Median absolute deviation — median(|x - median(x)|). A robust (outlier-resistant)
186
+ // dispersion measure; pairs with median better than stddev does for skewed data.
187
+ db.aggregate('mad', {
188
+ start: () => [],
189
+ step: (acc, val) => pushNum(acc, val),
190
+ result: (acc) => {
191
+ const nums = sortedNums(acc);
192
+ if (nums.length === 0)
193
+ return null;
194
+ const med = computePercentile(nums, 0.5);
195
+ const devs = sortedNums(nums.map((v) => Math.abs(v - med)));
196
+ return computePercentile(devs, 0.5);
197
+ },
198
+ });
145
199
  }
146
200
  /**
147
201
  * Load CSV files into an in-memory SQLite database and build schema metadata.
@@ -183,6 +237,10 @@ function loadCsvs(csvPaths) {
183
237
  let nullCount = 0; // undefined/null/\N
184
238
  let emptyCount = 0; // ''
185
239
  let nonNumericCount = 0; // non-empty values that are not numbers
240
+ // Tally the NON-EMPTY non-numeric tokens (e.g. "Undrafted") so a recurring
241
+ // string sentinel hiding in a numeric column can be surfaced to the auditor —
242
+ // NUMERIC affinity coerces it to NULL, erasing it from the stored data.
243
+ const nonNumericTokens = new Map();
186
244
  for (const row of rows) {
187
245
  const v = row[col];
188
246
  if (v === undefined || v === null || v === '\\N') {
@@ -200,8 +258,10 @@ function loadCsvs(csvPaths) {
200
258
  }
201
259
  if (isNumericStr(v))
202
260
  numericDistinct.add(v);
203
- else
261
+ else {
204
262
  nonNumericCount++;
263
+ nonNumericTokens.set(v, (nonNumericTokens.get(v) ?? 0) + 1);
264
+ }
205
265
  }
206
266
  const type = inferColumnType(col, samples, distinct.size, rows.length);
207
267
  // Zero-padded codes (zip '00501', '007') look numeric but must stay TEXT
@@ -213,7 +273,21 @@ function loadCsvs(csvPaths) {
213
273
  // ORDER BY (SQLite ranks text above all numbers). Counts reflect that.
214
274
  const finalNullCount = numericAffinity ? nullCount + emptyCount + nonNumericCount : nullCount;
215
275
  const finalUnique = numericAffinity ? numericDistinct.size : distinct.size;
216
- return { col, type, samples, distinctCount: finalUnique, nullCount: finalNullCount, numericAffinity };
276
+ // The dominant non-empty token coerced to NULL (numeric columns only) — the
277
+ // fingerprint of a string-sentinel affinity trap. Empty strings don't count;
278
+ // they're plain missing values the auditor reports via the null ratio.
279
+ let coercedNonNumeric;
280
+ if (numericAffinity && nonNumericTokens.size > 0) {
281
+ let token = '';
282
+ let count = 0;
283
+ for (const [tok, c] of nonNumericTokens)
284
+ if (c > count) {
285
+ token = tok;
286
+ count = c;
287
+ }
288
+ coercedNonNumeric = { token, count };
289
+ }
290
+ return { col, type, samples, distinctCount: finalUnique, nullCount: finalNullCount, numericAffinity, coercedNonNumeric };
217
291
  });
218
292
  const numericCols = new Set(colMeta.filter((m) => m.numericAffinity).map((m) => m.col));
219
293
  // Create table with NUMERIC affinity for numeric columns, TEXT otherwise.
@@ -307,6 +381,7 @@ function loadCsvs(csvPaths) {
307
381
  totalCount: rows.length,
308
382
  stats: columnStats,
309
383
  topValues,
384
+ coercedNonNumeric: meta.coercedNonNumeric,
310
385
  };
311
386
  columns.push(column);
312
387
  allColumns.push({ table: tableName, col: column });
@@ -485,6 +560,13 @@ class CsvConnectedSource {
485
560
  getDatabase() {
486
561
  return this.db;
487
562
  }
563
+ /**
564
+ * CSV derives columns the way it always has: ALTER TABLE + rowid-keyed UPDATE on the
565
+ * in-memory SQLite db (getDatabase still drives the actual work). Byte-identical behavior.
566
+ */
567
+ derivationCapabilities() {
568
+ return { canDerive: true, materialization: 'sqlite-alter', rowKey: 'rowid', serverSideQueryable: true };
569
+ }
488
570
  async close() {
489
571
  try {
490
572
  this.db.close();
@@ -546,6 +628,26 @@ export const csvConnector = {
546
628
  },
547
629
  ];
548
630
  }
631
+ // If a `<base>.cleanfix.json` sits next to a CSV, load the manifest-cleaned columns
632
+ // instead of the raw ones — so recon/query never re-hit a footgun the offline autoclean
633
+ // already solved. Replaying over the CURRENT raw file gives newly-arrived rows the same
634
+ // treatment; the original CSV is never written. Best-effort: any error → raw load.
635
+ csvPaths = csvPaths.map((cp) => {
636
+ const manifest = readCleanfixManifest(cp.filePath);
637
+ if (!manifest)
638
+ return cp;
639
+ try {
640
+ const { rows } = applyCleanfix(cp.filePath, manifest, false); // cleaned columns, no _raw noise
641
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dolex-cleanfix-'));
642
+ const cleanedPath = path.join(dir, path.basename(cp.filePath));
643
+ fs.writeFileSync(cleanedPath, Papa.unparse(rows));
644
+ return { ...cp, filePath: cleanedPath }; // tableName stays derived from the original file
645
+ }
646
+ catch (err) {
647
+ console.warn(`[csv-connector] cleanfix replay failed for ${cp.filePath}, loading raw: ${err?.message}`);
648
+ return cp;
649
+ }
650
+ });
549
651
  const { db, tables, foreignKeys, warnings } = loadCsvs(csvPaths);
550
652
  if (warnings.length > 0) {
551
653
  for (const w of warnings) {
@@ -5,4 +5,6 @@
5
5
  */
6
6
  export type { DataConnector, ConnectedSource, QueryExecutionResult, ConnectorResult, SourceRegistryEntry, } from './types.js';
7
7
  export { csvConnector } from './csv.js';
8
+ export { pgConnector } from './pg/index.js';
9
+ export { mongoConnector } from './mongo/index.js';
8
10
  export { SourceManager } from './manager.js';
@@ -5,5 +5,7 @@
5
5
  */
6
6
  // ─── Connectors ─────────────────────────────────────────────────────────────
7
7
  export { csvConnector } from './csv.js';
8
+ export { pgConnector } from './pg/index.js';
9
+ export { mongoConnector } from './mongo/index.js';
8
10
  // ─── Manager ────────────────────────────────────────────────────────────────
9
11
  export { SourceManager } from './manager.js';
@@ -17,7 +17,14 @@ export interface SqlQueryResult {
17
17
  totalRows?: number;
18
18
  truncated?: boolean;
19
19
  error?: string;
20
+ /** Advisory SQL-safety diagnostics (e.g. integer-division truncation). The
21
+ * query still ran; these signal silent-wrong-answer traps so the caller can
22
+ * re-issue a corrected query. The engine never rewrites the SQL itself. */
23
+ warnings?: string[];
20
24
  }
25
+ /** Classify a connection failure into an actionable kind, so callers can give a specific next step
26
+ * (install the driver / start the DB / fix credentials) instead of relaying a raw driver string. */
27
+ export declare function classifyConnError(msg?: string): 'driver-missing' | 'unreachable' | 'host-not-found' | 'timeout' | 'auth-failed' | 'db-not-found' | 'error';
21
28
  export declare class SourceManager {
22
29
  private registry;
23
30
  private connections;
@@ -34,10 +41,38 @@ export declare class SourceManager {
34
41
  * Add a data source to the registry.
35
42
  * Does NOT connect immediately — connection is lazy on first query or explicit connect().
36
43
  */
37
- add(name: string, config: DataSourceConfig): Promise<{
44
+ add(name: string, config: DataSourceConfig, opts?: {
45
+ verify?: boolean;
46
+ }): Promise<{
38
47
  ok: boolean;
39
48
  entry?: SourceRegistryEntry;
40
49
  error?: string;
50
+ verified?: boolean;
51
+ warning?: string;
52
+ }>;
53
+ /**
54
+ * Update a registered source's config in place (DB moved, password rotated, driver now installed)
55
+ * WITHOUT losing its id — so every existing reference keeps working. `patch` is merged over the
56
+ * stored config; the type is immutable. Any live connection is closed so the next use reconnects.
57
+ */
58
+ update(idOrName: string, patch: Partial<DataSourceConfig>, opts?: {
59
+ verify?: boolean;
60
+ }): Promise<{
61
+ ok: boolean;
62
+ entry?: SourceRegistryEntry;
63
+ error?: string;
64
+ verified?: boolean;
65
+ warning?: string;
66
+ }>;
67
+ /**
68
+ * Connectivity health-check for a REGISTERED source (the return-user's "is my saved DB still
69
+ * reachable?" and an agent's pre-flight). Returns a classified failure so the caller can give an
70
+ * actionable next step rather than a raw driver string.
71
+ */
72
+ testSource(idOrName: string): Promise<{
73
+ ok: boolean;
74
+ error?: string;
75
+ kind?: string;
41
76
  }>;
42
77
  /**
43
78
  * Remove a data source by ID or name. Closes the connection if active.
@@ -78,6 +113,19 @@ export declare class SourceManager {
78
113
  * Error messages are enriched with available table/column names.
79
114
  */
80
115
  querySql(idOrName: string, sql: string, maxRows?: number): Promise<SqlQueryResult>;
116
+ /**
117
+ * Run a read-only aggregation pipeline against a document store and return rows + columns,
118
+ * capped to maxRows. The pipeline string is the {collection, pipeline} seam the connector
119
+ * parses. No SQL safety pass (those footguns are SQL-only); Mongo-specific footgun
120
+ * detection is the language-plane work, added later. Never throws (audit-on-load relies on it).
121
+ */
122
+ private queryPipeline;
123
+ /**
124
+ * Advisory SQL-safety pass over a successful query. Best-effort: any failure
125
+ * yields no warnings (never blocks or breaks the query). Gated on a cheap
126
+ * syntactic pre-filter so the type probes only run when a risky term exists.
127
+ */
128
+ private analyzeSqlSafety;
81
129
  /**
82
130
  * Enrich SQLite error messages with available table/column info.
83
131
  */