@jini-ai/db 0.3.5 → 0.6.10

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.
@@ -1,4 +1,29 @@
1
1
  import type { PGlite } from "@electric-sql/pglite";
2
+ /** Per-connection pending input ceiling, including the typed-message tag byte. */
3
+ export declare const MAX_CLIENT_FRAME_BYTES: number;
4
+ /** The parts of a client socket (`net.Socket`) the server uses. */
5
+ export interface SocketServerClient {
6
+ readonly writable: boolean;
7
+ setNoDelay(noDelay: boolean): unknown;
8
+ on(event: "data", listener: (data: Buffer) => void): unknown;
9
+ on(event: "error", listener: (error: Error) => void): unknown;
10
+ on(event: "close", listener: () => void): unknown;
11
+ pause(): unknown;
12
+ resume(): unknown;
13
+ write(data: Uint8Array | string): unknown;
14
+ end(): unknown;
15
+ destroy(): unknown;
16
+ }
17
+ /** The parts of a listening server (`net.Server`) the server uses. */
18
+ export interface SocketServerListener {
19
+ listen(path: string, onListening: () => void): unknown;
20
+ once(event: "error", listener: (error: Error) => void): unknown;
21
+ off(event: "error", listener: (error: Error) => void): unknown;
22
+ on(event: "error", listener: (error: Error) => void): unknown;
23
+ close(onClosed: () => void): unknown;
24
+ }
25
+ /** Creates the listener that hands each accepted client to `accept`. */
26
+ export type SocketServerFactory = (accept: (socket: SocketServerClient) => void) => SocketServerListener;
2
27
  export interface PgliteSocketServerOptions {
3
28
  /** The PGlite this server owns. Nothing else may query it while the server runs. */
4
29
  db: PGlite;
@@ -9,6 +34,8 @@ export interface PgliteSocketServerOptions {
9
34
  /** A client idle inside an open transaction this long is disconnected and rolled back. Default 30 s; 0 = never. */
10
35
  idleInTransactionTimeoutMs?: number | undefined;
11
36
  log?: ((message: string) => void) | undefined;
37
+ /** Default `node:net`'s `createServer`; a test passes a fake to script a client socket's events. */
38
+ createServer?: SocketServerFactory | undefined;
12
39
  }
13
40
  /** A Postgres ErrorResponse frame. */
14
41
  export declare function errorResponseFrame(severity: "ERROR" | "FATAL", code: string, message: string): Buffer;
@@ -4,7 +4,7 @@
4
4
  * `LICENSE.pglite-socket` at the package root). Modified 2026-09-28: see `NOTICE.md` at the
5
5
  * package root for every change from upstream.
6
6
  */
7
- import { createServer } from "node:net";
7
+ import { createServer as createNetServer } from "node:net";
8
8
  /**
9
9
  * @file One PGlite served to several processes over a Unix socket, speaking the Postgres wire
10
10
  * protocol.
@@ -34,11 +34,19 @@ const SSL_REQUEST_CODE = 80877103;
34
34
  const GSSENC_REQUEST_CODE = 80877104;
35
35
  const CANCEL_REQUEST_CODE = 80877102;
36
36
  const PROTOCOL_3 = 196608;
37
+ /** Per-connection pending input ceiling, including the typed-message tag byte. */
38
+ export const MAX_CLIENT_FRAME_BYTES = 16 * 1024 * 1024;
37
39
  /** Typed messages after which PGlite's ReadyForQuery is legitimate: Sync, Query, FunctionCall, CopyDone, CopyFail. */
38
40
  const ENDS_EXCHANGE = new Set(["S", "Q", "F", "c", "f"].map((c) => c.charCodeAt(0)));
39
41
  const READY_FOR_QUERY = "Z".charCodeAt(0);
40
42
  /** The id of work that belongs to no connection ({@link PgliteSocketServer.runExclusive}). */
41
43
  const OWNER_JOB = 0;
44
+ const netServerFactory = (accept) => createNetServer((socket) => accept(socket));
45
+ /** Refuses invalid protocol lengths before buffering or slicing. O(1) time/space. */
46
+ function assertClientFrameSize({ size, minimum }, _options = {}) {
47
+ if (size < minimum || size > MAX_CLIENT_FRAME_BYTES)
48
+ throw new Error("Invalid client frame length");
49
+ }
42
50
  /** A Postgres ErrorResponse frame. */
43
51
  export function errorResponseFrame(severity, code, message) {
44
52
  const field = (tag, value) => Buffer.concat([Buffer.from(tag), Buffer.from(`${value}\0`)]);
@@ -205,7 +213,11 @@ class Connection {
205
213
  this.onClosed = onClosed;
206
214
  socket.setNoDelay(true);
207
215
  socket.on("data", (data) => {
208
- this.chain = this.chain.then(() => this.handle(data)).catch((error) => this.close(error));
216
+ socket.pause();
217
+ this.chain = this.chain.then(() => this.handle(data)).catch((error) => this.close(error)).then(() => {
218
+ if (!this.closed)
219
+ socket.resume();
220
+ });
209
221
  });
210
222
  socket.on("error", (error) => this.close(error));
211
223
  socket.on("close", () => this.close());
@@ -233,6 +245,8 @@ class Connection {
233
245
  async handle(data) {
234
246
  if (this.closed)
235
247
  return;
248
+ if (this.buffer.length + data.length > MAX_CLIENT_FRAME_BYTES)
249
+ throw new Error("Client frame exceeds the byte limit");
236
250
  this.buffer = Buffer.concat([this.buffer, data]);
237
251
  for (;;) {
238
252
  const message = this.nextMessage();
@@ -251,36 +265,43 @@ class Connection {
251
265
  */
252
266
  nextMessage() {
253
267
  if (!this.started) {
254
- if (this.buffer.length < 8)
268
+ if (this.buffer.length < 4)
255
269
  return undefined;
256
270
  const size = this.buffer.readInt32BE(0);
271
+ assertClientFrameSize({ size, minimum: 8 });
272
+ if (this.buffer.length < 8)
273
+ return undefined;
257
274
  const code = this.buffer.readInt32BE(4);
258
275
  if (this.buffer.length < size)
259
276
  return undefined;
260
277
  const bytes = this.buffer.subarray(0, size);
261
278
  this.buffer = this.buffer.subarray(size);
262
- if (code === SSL_REQUEST_CODE || code === GSSENC_REQUEST_CODE) {
263
- this.socket.write("N");
264
- return "skip";
265
- }
266
- if (code === CANCEL_REQUEST_CODE) {
267
- this.close();
268
- return undefined;
269
- }
270
- if (code !== PROTOCOL_3)
271
- throw new Error(`unsupported protocol ${code}`);
272
- this.started = true;
273
- return { bytes, startup: true };
279
+ return this.startupMessage({ bytes, code });
274
280
  }
275
281
  if (this.buffer.length < 5)
276
282
  return undefined;
277
283
  const size = 1 + this.buffer.readInt32BE(1);
284
+ assertClientFrameSize({ size, minimum: 5 });
278
285
  if (this.buffer.length < size)
279
286
  return undefined;
280
287
  const bytes = this.buffer.subarray(0, size);
281
288
  this.buffer = this.buffer.subarray(size);
282
289
  return { bytes, startup: false };
283
290
  }
291
+ startupMessage({ bytes, code }, _optional = {}) {
292
+ if (code === SSL_REQUEST_CODE || code === GSSENC_REQUEST_CODE) {
293
+ this.socket.write("N");
294
+ return "skip";
295
+ }
296
+ if (code === CANCEL_REQUEST_CODE) {
297
+ this.close();
298
+ return undefined;
299
+ }
300
+ if (code !== PROTOCOL_3)
301
+ throw new Error(`unsupported protocol ${code}`);
302
+ this.started = true;
303
+ return { bytes, startup: true };
304
+ }
284
305
  execute(message) {
285
306
  const dropReady = !message.startup && !ENDS_EXCHANGE.has(message.bytes[0]);
286
307
  const out = frameFilter(dropReady, (data) => {
@@ -315,7 +336,7 @@ export class PgliteSocketServer {
315
336
  if (this.server !== null)
316
337
  throw new Error("socket server already started");
317
338
  await this.options.db.waitReady;
318
- const server = createServer((socket) => this.accept(socket));
339
+ const server = (this.options.createServer ?? netServerFactory)((socket) => this.accept(socket));
319
340
  this.server = server;
320
341
  await new Promise((resolve, reject) => {
321
342
  server.once("error", reject);
@@ -63,6 +63,7 @@ export declare class SqlSecretsVaultRepo implements VaultRepoPort {
63
63
  * EXPLAIN 2026-10-12: SQLite fell back to a raw-column index, Postgres to the label index). */
64
64
  findDefault(input: VaultDefaultQuery, _options?: VaultOptions): Promise<VaultRecord | null>;
65
65
  list(input: VaultQuery, _options?: VaultOptions): Promise<VaultRecord[]>;
66
+ private assertLabelAvailable;
66
67
  put(input: {
67
68
  record: VaultRecord;
68
69
  expectedRevision: number | null;
@@ -102,19 +102,22 @@ export class SqlSecretsVaultRepo {
102
102
  // Sort identifiers in JS to avoid host database collation changing the memory contract.
103
103
  return rows.map(fromRow).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
104
104
  }
105
+ async assertLabelAvailable({ record, existing, moved, scope }, _options = {}) {
106
+ // Unchanged-label rotations need no uniqueness read; DB constraints still guard writes.
107
+ if (moved || existing?.label !== record.label) {
108
+ const duplicate = await this.kernel.run(db => this.scoped({ db, input: scope }).select("id")
109
+ .where("id", "!=", record.id).where("label", "=", record.label).limit(1).executeTakeFirst());
110
+ if (duplicate)
111
+ throw new VaultError({ code: "conflict" });
112
+ }
113
+ }
105
114
  async put(input, _options = {}) {
106
115
  return this.write(input.record.workspaceId, async () => {
107
116
  const existing = await this.find(input.record);
108
117
  assertVaultReplacement({ ...input, existing });
109
118
  const scope = this.group(input.record);
110
- // Unchanged-label rotations need no uniqueness read; DB constraints still guard writes.
111
119
  const moved = existing !== null && existing.provider !== input.record.provider;
112
- if (moved || existing?.label !== input.record.label) {
113
- const duplicate = await this.kernel.run(db => this.scoped({ db, input: scope }).select("id")
114
- .where("id", "!=", input.record.id).where("label", "=", input.record.label).limit(1).executeTakeFirst());
115
- if (duplicate)
116
- throw new VaultError({ code: "conflict" });
117
- }
120
+ await this.assertLabelAvailable({ record: input.record, existing, moved, scope });
118
121
  const hasGroup = (existing !== null && !moved) || input.record.isDefault || Boolean(await this.kernel.run(db => this.scoped({ db, input: scope }).select("id").limit(1).executeTakeFirst()));
119
122
  const saved = { ...input.record, isDefault: input.record.isDefault || !hasGroup };
120
123
  // Clear before insert/update so a partial UNIQUE default index never sees two defaults.
@@ -63,22 +63,9 @@ function readSqliteTableCounts({ db }, { strict = false } = {}) {
63
63
  for (const { name } of names) {
64
64
  if (strict ? name.startsWith('sqlite_') : isSystemTable(name))
65
65
  continue;
66
- try {
67
- const safe = strict ? name : sanitizeTableName(name);
68
- if (!safe)
69
- continue;
70
- const quoted = '"' + safe.replaceAll('"', '""') + '"';
71
- const row = db.prepare(`SELECT count(*) AS c FROM ${quoted}`).get();
72
- if (strict && (!row || !Number.isSafeInteger(row.c) || row.c < 0))
73
- throw new Error(`Could not count table ${name}.`);
74
- tables.push({ name: safe, rowCount: row?.c ?? 0 });
75
- }
76
- catch (error) {
77
- if (strict)
78
- throw error;
79
- // A malformed view / corrupted table shouldn't fail the whole report; record 0 rows.
80
- tables.push({ name, rowCount: 0 });
81
- }
66
+ const count = readSqliteTableCount({ db, name, strict });
67
+ if (count)
68
+ tables.push(count);
82
69
  }
83
70
  }
84
71
  catch (error) {
@@ -89,6 +76,28 @@ function readSqliteTableCounts({ db }, { strict = false } = {}) {
89
76
  }
90
77
  return tables;
91
78
  }
79
+ function requireValidCount({ row, name }, _options = {}) {
80
+ if (!row || !Number.isSafeInteger(row.c) || row.c < 0)
81
+ throw new Error(`Could not count table ${name}.`);
82
+ }
83
+ function readSqliteTableCount({ db, name, strict }, _options = {}) {
84
+ try {
85
+ const safe = strict ? name : sanitizeTableName(name);
86
+ if (!safe)
87
+ return null;
88
+ const quoted = '"' + safe.replaceAll('"', '""') + '"';
89
+ const row = db.prepare(`SELECT count(*) AS c FROM ${quoted}`).get();
90
+ if (strict)
91
+ requireValidCount({ row, name });
92
+ return { name: safe, rowCount: row?.c ?? 0 };
93
+ }
94
+ catch (error) {
95
+ if (strict)
96
+ throw error;
97
+ // A malformed view / corrupted table shouldn't fail the whole report; record 0 rows.
98
+ return { name, rowCount: 0 };
99
+ }
100
+ }
92
101
  async function sumFileSizes(paths) {
93
102
  let total = 0;
94
103
  for (const p of paths) {
@@ -109,25 +118,16 @@ function sanitizeTableName(name) {
109
118
  return null;
110
119
  return name;
111
120
  }
112
- /**
113
- * Runs `PRAGMA integrity_check` (or `quick_check`) plus `PRAGMA foreign_key_check`
114
- * against an open database and returns a structured report so a CLI can
115
- * pretty-print it and automation can parse the JSON.
116
- *
117
- * @param opts - The open database handle and whether to use the faster `quick_check` variant.
118
- * @returns `{ ok: true }` when both pragmas report clean; otherwise the list of issues found.
119
- * A pragma that throws is itself recorded as one `integrity`/`foreign_key` issue rather than
120
- * propagating — a caller polling DB health should always get a report, not an exception.
121
- */
122
- export function verifySqliteIntegrity(opts, { includeRowCounts = false } = {}) {
123
- const { db, quick = false } = opts;
124
- const startedAt = Date.now();
121
+ function hasSuccessfulIntegrityResult({ rows, pragma }, _options = {}) {
122
+ // Exactly one row, read once: `row !== undefined` and an empty `rest` together are `rows.length === 1`.
123
+ const [row, ...rest] = rows;
124
+ return row !== undefined && rest.length === 0 && String(row[pragma] ?? Object.values(row)[0]).toLowerCase() === 'ok';
125
+ }
126
+ function readIntegrityIssues({ db, pragma }, { strict = false } = {}) {
125
127
  const issues = [];
126
- // 1. integrity_check / quick_check.
127
- const pragma = quick ? 'quick_check' : 'integrity_check';
128
128
  try {
129
129
  const rows = db.pragma(pragma);
130
- if (includeRowCounts && (rows.length !== 1 || String(rows[0]?.[pragma] ?? Object.values(rows[0] ?? {})[0]).toLowerCase() !== 'ok')) {
130
+ if (strict && !hasSuccessfulIntegrityResult({ rows, pragma })) {
131
131
  issues.push({ kind: 'integrity', message: 'A stopped transfer requires exactly one successful integrity result.' });
132
132
  }
133
133
  for (const row of rows) {
@@ -144,7 +144,10 @@ export function verifySqliteIntegrity(opts, { includeRowCounts = false } = {}) {
144
144
  catch (err) {
145
145
  issues.push({ kind: 'integrity', message: `pragma ${pragma} threw: ${err.message}` });
146
146
  }
147
- // 2. foreign_key_check.
147
+ return issues;
148
+ }
149
+ function readForeignKeyIssues({ db }, _options = {}) {
150
+ const issues = [];
148
151
  try {
149
152
  const rows = db.pragma('foreign_key_check');
150
153
  for (const row of rows) {
@@ -161,6 +164,26 @@ export function verifySqliteIntegrity(opts, { includeRowCounts = false } = {}) {
161
164
  catch (err) {
162
165
  issues.push({ kind: 'foreign_key', message: `pragma foreign_key_check threw: ${err.message}` });
163
166
  }
167
+ return issues;
168
+ }
169
+ /**
170
+ * Runs `PRAGMA integrity_check` (or `quick_check`) plus `PRAGMA foreign_key_check`
171
+ * against an open database and returns a structured report so a CLI can
172
+ * pretty-print it and automation can parse the JSON.
173
+ *
174
+ * @param opts - The open database handle and whether to use the faster `quick_check` variant.
175
+ * @returns `{ ok: true }` when both pragmas report clean; otherwise the list of issues found.
176
+ * A pragma that throws is itself recorded as one `integrity`/`foreign_key` issue rather than
177
+ * propagating — a caller polling DB health should always get a report, not an exception.
178
+ */
179
+ export function verifySqliteIntegrity(opts, { includeRowCounts = false } = {}) {
180
+ const { db, quick = false } = opts;
181
+ const startedAt = Date.now();
182
+ // 1. integrity_check / quick_check.
183
+ const pragma = quick ? 'quick_check' : 'integrity_check';
184
+ const integrityIssues = readIntegrityIssues({ db, pragma }, { strict: includeRowCounts });
185
+ // 2. foreign_key_check.
186
+ const issues = integrityIssues.concat(readForeignKeyIssues({ db }));
164
187
  let rowCounts;
165
188
  if (includeRowCounts && issues.length === 0) {
166
189
  try {
@@ -173,7 +196,7 @@ export function verifySqliteIntegrity(opts, { includeRowCounts = false } = {}) {
173
196
  return {
174
197
  ...(includeRowCounts ? { rowCounts } : {}),
175
198
  ok: issues.length === 0,
176
- mode: quick ? 'quick_check' : 'integrity_check',
199
+ mode: pragma,
177
200
  issues,
178
201
  elapsedMs: Date.now() - startedAt,
179
202
  generatedAt: Date.now(),
@@ -15,11 +15,12 @@ export class DatabaseTransferPlanStore {
15
15
  if (plan.expiresAtMs <= nowMs)
16
16
  this.plans.delete(id);
17
17
  }
18
- while (this.plans.size >= DEFAULT_MAX_PLANS) {
19
- const oldest = this.plans.keys().next().value;
20
- if (oldest === undefined)
18
+ // Evict oldest-first (a Map iterates in insertion order) until there is room for this plan. The
19
+ // former `oldest === undefined` guard is gone: iterating the keys themselves cannot yield a missing one.
20
+ for (const id of this.plans.keys()) {
21
+ if (this.plans.size < DEFAULT_MAX_PLANS)
21
22
  break;
22
- this.plans.delete(oldest);
23
+ this.plans.delete(id);
23
24
  }
24
25
  const plan = { ...input.content, planId: randomUUID(), principalId: input.principalId, workspaceId: input.workspaceId, expiresAtMs: nowMs + DEFAULT_PLAN_TTL_MS };
25
26
  this.plans.set(plan.planId, plan);
@@ -76,6 +76,9 @@ export function createDatabaseReadTools(ports, _optional = {}) {
76
76
  return captured;
77
77
  },
78
78
  }, { messages });
79
+ // `createDatabaseRestorePoint` resolves only after awaiting `capture()` (restore-points.ts), so
80
+ // `captured` is always set here; the former `captured?.… ?? null` fallbacks could never apply.
81
+ const { watermarkAtCapture, artifactRef } = captured;
79
82
  await ports.restorePoints.save({
80
83
  restorePointId: summary.id,
81
84
  idempotencyKey: ports.idGen.newId(),
@@ -87,8 +90,8 @@ export function createDatabaseReadTools(ports, _optional = {}) {
87
90
  createdBy: ctx.principal.id,
88
91
  costClass: summary.costClass,
89
92
  kind: summary.kind,
90
- watermarkAtCapture: captured?.watermarkAtCapture ?? null,
91
- artifactRef: captured?.artifactRef,
93
+ watermarkAtCapture,
94
+ artifactRef,
92
95
  });
93
96
  return { restorePoint: summary };
94
97
  },
@@ -69,14 +69,21 @@ export interface DatabaseTransferToolPorts {
69
69
  readers: Pick<InputReaders, "inputRecord" | "string">;
70
70
  surfaces: TransferSurfacePorts;
71
71
  }
72
+ /** The restore-point file the plan reads once and then deletes; defaults to `node:fs/promises`. */
73
+ export interface SnapshotFilePort {
74
+ readFile(path: string): Promise<Buffer>;
75
+ unlink(path: string): Promise<void>;
76
+ }
72
77
  /**
73
78
  * Returns core registrations; the host applies its independent risk/error plumbing.
74
79
  * Descriptions reflect required persisted naming; optional messages replace model-facing copy only.
75
80
  * Construction performs no I/O. Host formatter exceptions propagate without mutating ports.
81
+ * `optional.files` reads and deletes the restore-point snapshot file; it defaults to `node:fs/promises`.
76
82
  * @complexity O(1) fixed tool records plus the description formatter's text length.
77
83
  * @example createDatabaseTransferTools(ports, { messages: defaultDbMessages })
78
84
  */
79
85
  export declare function createDatabaseTransferTools(deps: DatabaseTransferToolPorts, optional?: {
80
86
  messages?: DbTransferMessages & Partial<DbMessages>;
87
+ files?: SnapshotFilePort;
81
88
  }): ToolRegistration[];
82
89
  //# sourceMappingURL=transfer-tools.d.ts.map
@@ -6,6 +6,7 @@ import { defaultDbMessages } from "../core/messages.js";
6
6
  import { registrations } from "./registration.js";
7
7
  const SET_DESTINATION_TOOL_ID = "database_transfer_set_destination";
8
8
  const DATABASE_TRANSFER_RUN_TOOL_ID = "database_transfer_run";
9
+ const nodeSnapshotFiles = { readFile, unlink };
9
10
  function destinationsOf(deps) {
10
11
  return deps.ports.destinations;
11
12
  }
@@ -34,16 +35,18 @@ async function captureSnapshot(deps) {
34
35
  log(deps, `snapshot failed: ${deps.ports.describeError(err)}`);
35
36
  return { code: "DATABASE_SNAPSHOT_FAILED", message: "the site database could not be snapshotted; nothing was copied" };
36
37
  }
38
+ let bytes;
37
39
  try {
38
- return { ok: true, bytes: await readFile(artifactRef) };
40
+ bytes = await deps.files.readFile(artifactRef);
39
41
  }
40
42
  catch (err) {
41
43
  log(deps, `snapshot read failed: ${deps.ports.describeError(err)}`);
42
44
  return { code: "DATABASE_SNAPSHOT_FAILED", message: "the site database snapshot could not be read; nothing was copied" };
43
45
  }
44
46
  finally {
45
- await unlink(artifactRef).catch(() => undefined);
47
+ await deps.files.unlink(artifactRef).catch(() => undefined);
46
48
  }
49
+ return { ok: true, bytes };
47
50
  }
48
51
  /** The site name copies are marked with; it also picks the site's schema (`copy-engine.ts`). */
49
52
  function siteOf(deps) {
@@ -89,6 +92,7 @@ function snapshotSources(deps, snapshot, chatSnapshot) {
89
92
  /** Row counts and reasons use each physical source's own catalog; no raw-SQL tables disappear. */
90
93
  function countSnapshot(deps, bytes, chatSnapshot) {
91
94
  let sources = [];
95
+ let counted;
92
96
  try {
93
97
  sources = snapshotSources(deps, bytes, chatSnapshot);
94
98
  const counts = sources.flatMap(entry => countSourceRows({ source: entry.source, tables: entry.tables }, { messages: deps.messages }));
@@ -98,7 +102,7 @@ function countSnapshot(deps, bytes, chatSnapshot) {
98
102
  ...entry.leftOut.filter(item => item.reason !== LEFT_OUT_REASON.bookkeeping && item.reason !== LEFT_OUT_REASON.derived).map(item => ({ ...item, rows: entry.source.countRows(item.table) })),
99
103
  ...deps.ports.partialExclusions(entry.name, entry.source),
100
104
  ]);
101
- return { ok: true, tableCount: counts.length, rowCount: counts.reduce((sum, count) => sum + count.rows, 0), leftOut };
105
+ counted = { ok: true, tableCount: counts.length, rowCount: counts.reduce((sum, count) => sum + count.rows, 0), leftOut };
102
106
  }
103
107
  catch (err) {
104
108
  if (err instanceof SourceSchemaMismatchError || err instanceof IncompleteTransferPlanError)
@@ -109,6 +113,7 @@ function countSnapshot(deps, bytes, chatSnapshot) {
109
113
  for (const entry of sources)
110
114
  entry.source.close();
111
115
  }
116
+ return counted;
112
117
  }
113
118
  function planResult(plan) {
114
119
  return {
@@ -239,8 +244,9 @@ async function handleRun(deps, surfaces, ctx, optional = {}) {
239
244
  askHuman: ({ ctx: snapshot, description }, options) => {
240
245
  if (!options.emitSurface)
241
246
  throw new ToolInputError({ message: `${DATABASE_TRANSFER_RUN_TOOL_ID}: this execution context has no interactive confirmation channel (no emitSurface), so replacement cannot be confirmed here. Nothing was copied.` });
242
- if (!description)
243
- throw new ToolInputError({ message: "No transfer plan can be approved. Nothing was copied." });
247
+ // core's createApprovalHandler asks only when `describe` set `ask`, and `ask` is true only beside a
248
+ // taken plan, so `description` is always that plan here; the former "No transfer plan can be
249
+ // approved" refusal could never run.
244
250
  return surfaces.confirmApproval({ ctx: snapshot, plan: description }, options);
245
251
  },
246
252
  notConfirmed: ({ reason }) => reason === "declined" ? { copied: false, cancelled: true } : { copied: false, cancelled: false, reason },
@@ -327,11 +333,12 @@ async function handleStatus(deps, ctx) {
327
333
  * Returns core registrations; the host applies its independent risk/error plumbing.
328
334
  * Descriptions reflect required persisted naming; optional messages replace model-facing copy only.
329
335
  * Construction performs no I/O. Host formatter exceptions propagate without mutating ports.
336
+ * `optional.files` reads and deletes the restore-point snapshot file; it defaults to `node:fs/promises`.
330
337
  * @complexity O(1) fixed tool records plus the description formatter's text length.
331
338
  * @example createDatabaseTransferTools(ports, { messages: defaultDbMessages })
332
339
  */
333
340
  export function createDatabaseTransferTools(deps, optional = {}) {
334
- const runtime = { ports: deps, messages: { ...defaultDbMessages, ...optional.messages } };
341
+ const runtime = { ports: deps, messages: { ...defaultDbMessages, ...optional.messages }, files: optional.files ?? nodeSnapshotFiles };
335
342
  const handlers = {
336
343
  [PLAN_TOOL_ID]: ctx => handlePlan(runtime, ctx),
337
344
  [DATABASE_TRANSFER_RUN_TOOL_ID]: (ctx, optional) => handleRun(runtime, runtime.ports.surfaces, ctx, optional),
@@ -1,3 +1,4 @@
1
+ import { FOREIGN_SCHEMA_SIGNAL, COUNT_MISMATCH_SIGNAL } from "./signals.js";
1
2
  import { createHash } from "node:crypto";
2
3
  import { defaultDbMessages } from "../core/messages.js";
3
4
  import { constraintSql, createTableSql, indexSql, qualified, quoteIdent, quoteLiteral, reseedIdentitySql } from "./internal-ddl.js";
@@ -124,8 +125,6 @@ function* copyTableData(source, schema, table) {
124
125
  }
125
126
  yield `${batch}\\.\n`;
126
127
  }
127
- const FOREIGN_SCHEMA_SIGNAL = "TRANSFER_TARGET_NOT_OURS";
128
- const COUNT_MISMATCH_SIGNAL = "TRANSFER_COUNT_MISMATCH";
129
128
  /**
130
129
  * Aborts the transaction unless `schema` is absent or holds only this site's copy. The marker is read
131
130
  * with dynamic SQL so a table merely named like it (other columns) also counts as someone else's.
@@ -177,15 +176,25 @@ function* copyScript(sources, naming, schema, counts, marker, replaceExisting) {
177
176
  yield markerSql(schema, marker, counts, naming);
178
177
  yield "COMMIT;\n";
179
178
  }
180
- /** The constraints the committed copy left NOT VALID, from its marker. */
181
- async function readUnvalidated(target, schema, TRANSFER_MARKER_TABLE) {
182
- const read = await target.query(`SELECT unvalidated FROM ${qualified(schema, TRANSFER_MARKER_TABLE)} LIMIT 1`);
183
- const cell = read.ok ? read.value[0]?.[0] : undefined;
184
- if (cell === undefined)
185
- return { unvalidatedConstraints: [], warning: "the copy finished, but its list of unchecked constraints could not be read back" };
186
- return { unvalidatedConstraints: JSON.parse(cell) };
179
+ /** Reads the committed constraint list; malformed or failed readback yields a safe warning.
180
+ * O(n) time/space in marker bytes; performs one target query. */
181
+ async function readUnvalidated({ target, schema, markerTable }, _options = {}) {
182
+ const unreadable = { unvalidatedConstraints: [], warning: "the copy finished, but its list of unchecked constraints could not be read back" };
183
+ try {
184
+ const read = await target.query(`SELECT unvalidated FROM ${qualified(schema, markerTable)} LIMIT 1`);
185
+ const cell = read.ok ? read.value[0]?.[0] : undefined;
186
+ if (cell === undefined)
187
+ return unreadable;
188
+ const constraints = JSON.parse(cell);
189
+ if (!Array.isArray(constraints) || !constraints.every(value => typeof value === "string"))
190
+ return unreadable;
191
+ return { unvalidatedConstraints: constraints };
192
+ }
193
+ catch {
194
+ return unreadable;
195
+ }
187
196
  }
188
- export async function runCopy(input, _optional = {}) {
197
+ function prepareCopy(input, _optional = {}) {
189
198
  if (!/^[a-z_][a-z0-9_]*$/.test(input.naming.sqlTag ?? "transfer"))
190
199
  throw new Error("invalid SQL dollar-quote tag");
191
200
  const { sources } = planTransfer({ sources: input.sources });
@@ -206,6 +215,11 @@ export async function runCopy(input, _optional = {}) {
206
215
  if (schema === "public" || !/^[a-z_][a-z0-9_]*$/.test(schema) || Buffer.byteLength(schema) > MAX_IDENTIFIER_BYTES) {
207
216
  throw new Error(`runCopy: '${schema}' is not a schema this copier may write`);
208
217
  }
218
+ return { counted, counts };
219
+ }
220
+ export async function runCopy(input, _optional = {}) {
221
+ const { counted, counts } = prepareCopy(input, _optional);
222
+ const { schema } = input;
209
223
  let result;
210
224
  try {
211
225
  result = await input.target.runScript(copyScript(counted, input.naming, schema, counts, input.marker, input.replaceExisting));
@@ -216,7 +230,7 @@ export async function runCopy(input, _optional = {}) {
216
230
  throw err;
217
231
  }
218
232
  if (result.ok)
219
- return { ok: true, tables: counts.map(({ table, rows }) => ({ name: table.name, rows })), ...(await readUnvalidated(input.target, schema, input.naming.markerTable)) };
233
+ return { ok: true, tables: counts.map(({ table, rows }) => ({ name: table.name, rows })), ...(await readUnvalidated({ target: input.target, schema, markerTable: input.naming.markerTable })) };
220
234
  if (result.error.includes(FOREIGN_SCHEMA_SIGNAL)) {
221
235
  return { ok: false, code: "TARGET_NOT_OURS", message: `the destination already has a '${schema}' area that holds other data. Nothing was written, and it was left untouched.` };
222
236
  }
@@ -17,8 +17,8 @@ export interface TargetDescription {
17
17
  readonly database: string;
18
18
  readonly user: string;
19
19
  }
20
- /** `error` is psql's first ERROR line with every quoted part blanked (Postgres quotes the offending
21
- * value there); `copyTable` names the table a failed `COPY` was loading. */
20
+ /** `error` is a copier-owned failure code or a fixed safe message; server text is private.
21
+ * `copyTable` names the table a failed COPY was loading. */
22
22
  export type TargetResult<T> = {
23
23
  readonly ok: true;
24
24
  readonly value: T;
@@ -50,16 +50,30 @@ export declare function parseConnectionString({ raw }: {
50
50
  }, { applicationName }?: {
51
51
  applicationName?: string;
52
52
  }): ParsedConnection;
53
+ /** The slice of a spawned `psql` child this adapter drives: its three pipes, `error` and `close`. */
54
+ export interface PsqlProcess {
55
+ readonly stdin: NodeJS.WritableStream;
56
+ readonly stdout: NodeJS.ReadableStream;
57
+ readonly stderr: NodeJS.ReadableStream;
58
+ on(event: "error", listener: (error: Error) => void): unknown;
59
+ on(event: "close", listener: (code: number | null) => void): unknown;
60
+ }
61
+ /** Starts `psql` with the given argv and environment; the default resolves it on the host PATH. */
62
+ export type PsqlSpawn = (args: readonly string[], options: {
63
+ env: Record<string, string>;
64
+ }) => PsqlProcess;
53
65
  /**
54
- * The P0 adapter: every call is one short-lived `psql` process.
66
+ * The P0 adapter: every call is one short-lived `psql` process, started through `spawnProcess`
67
+ * (default: `psql` on the host PATH).
55
68
  *
56
69
  * @throws {InvalidConnectionStringError} When the string cannot be parsed.
57
70
  */
58
71
  export declare function createPsqlPostgresTarget({ connectionString }: {
59
72
  connectionString: string;
60
- }, { parentEnv, applicationName }?: {
73
+ }, { parentEnv, applicationName, spawnProcess }?: {
61
74
  parentEnv?: NodeJS.ProcessEnv;
62
75
  applicationName?: string;
76
+ spawnProcess?: PsqlSpawn;
63
77
  }): PostgresTargetPort;
64
78
  export {};
65
79
  //# sourceMappingURL=postgres-target.d.ts.map