@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
@@ -0,0 +1 @@
1
+ export declare function depsCommand(argv: string[]): Promise<number>;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * `dolex deps` — report which optional capabilities are available in THIS environment, so a
3
+ * human (or an AI agent driving Dolex) can see what's ready and how to enable the rest BEFORE
4
+ * trying it. The sibling of `dolex check` (which audits DATA health); this audits ENVIRONMENT health.
5
+ *
6
+ * `--json` emits the shared capability report for an agent to reason on. Exit code is non-zero only
7
+ * when a CORE dependency is missing (the base install is broken), like `dolex check`.
8
+ */
9
+ import { parseArgs, bool } from '../args.js';
10
+ import * as o from '../output.js';
11
+ import { probeCapabilities } from '../../utils/capabilities.js';
12
+ export async function depsCommand(argv) {
13
+ const args = parseArgs(argv, { booleans: ['json', 'help'], aliases: { h: 'help' } });
14
+ if (bool(args, 'help')) {
15
+ o.out('dolex deps — report which optional capabilities are available in this environment.');
16
+ o.out(' --json machine-readable report (for an AI agent to check readiness before acting)');
17
+ return 0;
18
+ }
19
+ const cap = probeCapabilities();
20
+ if (bool(args, 'json')) {
21
+ o.out(JSON.stringify(cap, null, 2));
22
+ return cap.coreOk ? 0 : 1;
23
+ }
24
+ o.heading('Data sources — what can I connect to here');
25
+ o.out(o.table(['source', 'status'], [
26
+ { source: 'CSV / SQLite', status: cap.sources.csv },
27
+ { source: 'PostgreSQL', status: cap.sources.postgres },
28
+ { source: 'MongoDB', status: cap.sources.mongodb },
29
+ ]));
30
+ o.out();
31
+ o.heading('Optional features');
32
+ o.out(o.table(['feature', 'installed', 'how to enable'], [
33
+ ...cap.deps.map((d) => ({ feature: d.enables, installed: d.installed ? `✓ ${d.version ?? ''}`.trim() : '—', 'how to enable': d.install ?? '' })),
34
+ { feature: cap.python.enables, installed: cap.python.available ? `✓ ${cap.python.version ?? ''}`.trim() : '—', 'how to enable': cap.python.install ?? '' },
35
+ ]));
36
+ if (!cap.coreOk) {
37
+ o.out();
38
+ o.fail('core engine (better-sqlite3) is missing — reinstall dolex.');
39
+ }
40
+ return cap.coreOk ? 0 : 1;
41
+ }
@@ -22,7 +22,8 @@ ${o.c.bold('COMMANDS')}
22
22
  ${o.c.cyan('columns')} <csv|source> List columns by layer (source / derived / working)
23
23
  ${o.c.cyan('drop')} <csv|source> Remove derived/working columns
24
24
  ${o.c.cyan('patterns')} [id] List the 43 chart patterns, or show one
25
- ${o.c.cyan('sources')} <list|add|rm> Manage the persistent CSV registry
25
+ ${o.c.cyan('sources')} <list|add|rm> Register & manage data sources (CSV / Postgres / MongoDB)
26
+ ${o.c.cyan('deps')} Report which data sources & optional features are available here
26
27
  ${o.c.cyan('mcp')} Run the MCP stdio server (Claude Desktop / agents)
27
28
  ${o.c.cyan('help')} [command] Show help; \`--version\` for version
28
29
 
@@ -1,5 +1,5 @@
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
  export declare function sourcesCommand(argv: string[]): Promise<number>;
@@ -1,13 +1,18 @@
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';
10
+ import { redactUri } from '../../connectors/types.js';
9
11
  export async function sourcesCommand(argv) {
10
- const args = parseArgs(argv, { booleans: ['json', 'help'], aliases: { h: 'help' } });
12
+ const args = parseArgs(argv, {
13
+ booleans: ['json', 'help', 'verify'],
14
+ aliases: { h: 'help' },
15
+ });
11
16
  if (bool(args, 'help')) {
12
17
  printHelp();
13
18
  return 0;
@@ -25,23 +30,118 @@ export async function sourcesCommand(argv) {
25
30
  o.hint('No registered sources. Add one: dolex sources add <name> <path.csv>');
26
31
  return 0;
27
32
  }
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 ?? '' }))));
33
+ 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
34
  return 0;
30
35
  }
31
36
  case 'add': {
32
37
  const name = args._[1];
33
- const path = args._[2];
34
- if (!name || !path) {
38
+ const pathArg = args._[2];
39
+ if (!name) {
35
40
  o.fail('Usage: dolex sources add <name> <path-to-csv-or-dir>');
41
+ o.hint('Or a database source: dolex sources add <name> --type postgres|mongodb --uri <conn-string>');
36
42
  return 1;
37
43
  }
38
- const res = await manager.add(name, { type: 'csv', path: resolve(path) });
44
+ const type = str(args, 'type');
45
+ // CSV path may come as a positional (backward-compatible) or --path.
46
+ const path = str(args, 'path') ?? pathArg;
47
+ let config;
48
+ try {
49
+ config = resolveSourceConfig({
50
+ type,
51
+ // Resolve CSV paths to absolute so the registry entry is cwd-independent.
52
+ path: path !== undefined ? resolve(path) : undefined,
53
+ uri: str(args, 'uri'),
54
+ host: str(args, 'host'),
55
+ port: num(args, 'port'),
56
+ database: str(args, 'database'),
57
+ user: str(args, 'user'),
58
+ password: str(args, 'password'),
59
+ passwordEnv: str(args, 'password-env'),
60
+ schema: str(args, 'schema'),
61
+ collections: list(args, 'collections'),
62
+ });
63
+ }
64
+ catch (e) {
65
+ o.fail(e instanceof Error ? e.message : String(e));
66
+ return 1;
67
+ }
68
+ if (str(args, 'password')) {
69
+ 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.');
70
+ }
71
+ // Config-first: register even if the DB is unreachable right now (unless --verify). liveness is
72
+ // reported, not required — so setup never depends on the DB being up this second.
73
+ const res = await manager.add(name, config, { verify: bool(args, 'verify') });
39
74
  if (!res.ok) {
40
75
  o.fail(res.error ?? 'Failed to add source.');
41
76
  return 1;
42
77
  }
43
- o.success(`Added "${name}" (${res.entry.id})`);
44
- o.hint(`Use it: dolex visualize ${name} -i "…" · dolex analyze ${name}`);
78
+ o.success(`Added "${name}" (${res.entry.id}) [${config.type}]`);
79
+ if (config.type !== 'csv' && res.verified === false) {
80
+ o.warn(`Registered, but couldn't connect yet: ${res.warning}`);
81
+ o.hint(`Fix the DB/credentials, then verify: dolex sources test ${name} (or update: dolex sources update ${name} --host … )`);
82
+ }
83
+ else {
84
+ o.hint(`Use it: dolex visualize ${name} -i "…" · dolex analyze ${name}`);
85
+ }
86
+ return 0;
87
+ }
88
+ case 'test': {
89
+ const idOrName = args._[1];
90
+ if (!idOrName) {
91
+ o.fail('Usage: dolex sources test <name|id>');
92
+ return 1;
93
+ }
94
+ const r = await manager.testSource(idOrName);
95
+ if (bool(args, 'json')) {
96
+ o.out(JSON.stringify({ source: idOrName, ...r }, null, 2));
97
+ return r.ok ? 0 : 1;
98
+ }
99
+ if (r.ok) {
100
+ o.success(`"${idOrName}" is reachable ✓`);
101
+ return 0;
102
+ }
103
+ o.fail(`"${idOrName}" is not reachable [${r.kind}]: ${r.error}`);
104
+ const nextStep = {
105
+ 'driver-missing': 'install the driver (see the message above), then retry',
106
+ 'unreachable': 'start the database / check host+port, then: dolex sources test ' + idOrName,
107
+ 'host-not-found': 'fix the host, then: dolex sources update ' + idOrName + ' --host <host>',
108
+ 'timeout': 'check the network/firewall or the DB is slow to accept connections',
109
+ 'auth-failed': 'fix credentials: dolex sources update ' + idOrName + ' --user <u> --password-env <VAR>',
110
+ 'db-not-found': 'fix the database name: dolex sources update ' + idOrName + ' --database <db>',
111
+ };
112
+ if (r.kind && nextStep[r.kind])
113
+ o.hint(nextStep[r.kind]);
114
+ return 1;
115
+ }
116
+ case 'update': {
117
+ const idOrName = args._[1];
118
+ if (!idOrName) {
119
+ o.fail('Usage: dolex sources update <name|id> [--host … --port … --database … --user … --password-env … --uri …]');
120
+ return 1;
121
+ }
122
+ const patch = {};
123
+ for (const k of ['uri', 'host', 'database', 'user', 'password', 'password-env', 'schema']) {
124
+ const v = str(args, k);
125
+ if (v !== undefined)
126
+ patch[k === 'uri' ? 'connectionString' : k === 'password-env' ? 'passwordEnv' : k] = v;
127
+ }
128
+ const p = num(args, 'port');
129
+ if (p !== undefined)
130
+ patch.port = p;
131
+ if (Object.keys(patch).length === 0) {
132
+ o.fail('Nothing to update. Pass at least one of --host/--port/--database/--user/--password-env/--uri/--schema.');
133
+ return 1;
134
+ }
135
+ if (patch.password)
136
+ o.warn('--password is stored in plaintext. Prefer --password-env <VAR>.');
137
+ const res = await manager.update(idOrName, patch, { verify: bool(args, 'verify') });
138
+ if (!res.ok) {
139
+ o.fail(res.error ?? 'Failed to update source.');
140
+ return 1;
141
+ }
142
+ o.success(`Updated "${idOrName}"`);
143
+ if (res.verified === false)
144
+ o.warn(`Saved, but still can't connect: ${res.warning}. Test again: dolex sources test ${idOrName}`);
45
145
  return 0;
46
146
  }
47
147
  case 'remove':
@@ -65,13 +165,40 @@ export async function sourcesCommand(argv) {
65
165
  return 1;
66
166
  }
67
167
  }
168
+ /** One-line summary of where a source lives, for the `list` table. */
169
+ /** host:port/database for a live DB source (the connection string wins if present). */
170
+ const hostPortDb = (connStr, host, port, database) => connStr ? redactUri(connStr) : [host, port].filter(Boolean).join(':') + (database ? `/${database}` : '');
171
+ function describeLocation(config) {
172
+ switch (config.type) {
173
+ case 'csv':
174
+ return config.path ?? '';
175
+ case 'postgres':
176
+ return hostPortDb(config.connectionString, config.host, config.port, config.database);
177
+ case 'mongodb':
178
+ return hostPortDb(config.uri, config.host, config.port, config.database);
179
+ }
180
+ }
68
181
  function printHelp() {
69
- o.out(`${o.c.bold('dolex sources')} — manage the persistent CSV registry
182
+ o.out(`${o.c.bold('dolex sources')} — manage the persistent source registry
70
183
 
71
184
  ${o.c.bold('USAGE')}
72
185
  dolex sources list
73
186
  dolex sources add <name> <path-to-csv-or-dir>
187
+ dolex sources add <name> --type postgres --host <h> --database <db> [--user <u> --password-env PGPASSWORD]
188
+ dolex sources add <name> --type mongodb --host <h> --port <p> --database <db>
189
+ dolex sources test <name|id> # is the saved DB reachable? (classified reason)
190
+ dolex sources update <name|id> [--host … --port … --database … --user … --password-env … --uri …]
74
191
  dolex sources remove <name|id>
75
192
 
76
- ${o.c.dim('Stored in ~/.dolex/sources.json — shared with the MCP server.')}`);
193
+ ${o.c.bold('OPTIONS (add / update)')}
194
+ --type csv | postgres | mongodb (default: csv)
195
+ --uri connection string (libpq DSN for postgres, URI for mongodb)
196
+ --host/--port/--database/--user/--schema discrete connection fields
197
+ --password-env name of an env var holding the password (preferred — keeps the secret OUT of the file)
198
+ --password literal password (stored in plaintext; --password-env is safer)
199
+ --verify require a successful connection to register (default: register config-first even if the DB is down)
200
+ --collections mongodb: comma-separated list to restrict introspection
201
+
202
+ ${o.c.dim('Config-first: a source registers even if its DB is momentarily down — run `sources test` once it is up.')}
203
+ ${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
204
  }
@@ -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 {
@@ -13,8 +13,6 @@
13
13
  */
14
14
  import type { DataColumn, DataSchema } from '../types.js';
15
15
  import type { SourceManager, SqlQueryResult } from '../connectors/manager.js';
16
- import { dolexHome } from './paths.js';
17
- export { dolexHome };
18
16
  export interface OpenedSource {
19
17
  manager: SourceManager;
20
18
  sourceId: string;
@@ -14,7 +14,6 @@
14
14
  import { existsSync, statSync, readFileSync } from 'fs';
15
15
  import { resolve, basename, join } from 'path';
16
16
  import { dolexHome } from './paths.js';
17
- export { dolexHome };
18
17
  /**
19
18
  * Import the SourceManager module, turning a better-sqlite3 native-binding
20
19
  * load failure (e.g. a binary built for a different Node ABI) into an
@@ -86,6 +86,9 @@ async function main() {
86
86
  case 'sources':
87
87
  case 'source':
88
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));
89
92
  case 'mcp':
90
93
  case 'serve':
91
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
  /**
@@ -558,6 +560,13 @@ class CsvConnectedSource {
558
560
  getDatabase() {
559
561
  return this.db;
560
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
+ }
561
570
  async close() {
562
571
  try {
563
572
  this.db.close();
@@ -619,6 +628,26 @@ export const csvConnector = {
619
628
  },
620
629
  ];
621
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
+ });
622
651
  const { db, tables, foreignKeys, warnings } = loadCsvs(csvPaths);
623
652
  if (warnings.length > 0) {
624
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';
@@ -22,6 +22,9 @@ export interface SqlQueryResult {
22
22
  * re-issue a corrected query. The engine never rewrites the SQL itself. */
23
23
  warnings?: string[];
24
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';
25
28
  export declare class SourceManager {
26
29
  private registry;
27
30
  private connections;
@@ -38,10 +41,38 @@ export declare class SourceManager {
38
41
  * Add a data source to the registry.
39
42
  * Does NOT connect immediately — connection is lazy on first query or explicit connect().
40
43
  */
41
- add(name: string, config: DataSourceConfig): Promise<{
44
+ add(name: string, config: DataSourceConfig, opts?: {
45
+ verify?: boolean;
46
+ }): Promise<{
42
47
  ok: boolean;
43
48
  entry?: SourceRegistryEntry;
44
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;
45
76
  }>;
46
77
  /**
47
78
  * Remove a data source by ID or name. Closes the connection if active.
@@ -82,6 +113,13 @@ export declare class SourceManager {
82
113
  * Error messages are enriched with available table/column names.
83
114
  */
84
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;
85
123
  /**
86
124
  * Advisory SQL-safety pass over a successful query. Best-effort: any failure
87
125
  * yields no warnings (never blocks or breaks the query). Gated on a cheap