@jini-ai/db 0.2.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 (157) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/LICENSE.pglite-socket +176 -0
  3. package/NOTICE.md +27 -0
  4. package/README.md +210 -0
  5. package/dist/core/artifact-naming.d.ts +34 -0
  6. package/dist/core/artifact-naming.js +34 -0
  7. package/dist/core/index.d.ts +8 -0
  8. package/dist/core/index.js +10 -0
  9. package/dist/core/messages.d.ts +43 -0
  10. package/dist/core/messages.js +26 -0
  11. package/dist/core/pg-types.d.ts +22 -0
  12. package/dist/core/pg-types.js +26 -0
  13. package/dist/core/ports.d.ts +70 -0
  14. package/dist/core/ports.js +22 -0
  15. package/dist/core/row-values.d.ts +32 -0
  16. package/dist/core/row-values.js +42 -0
  17. package/dist/core/socket.d.ts +8 -0
  18. package/dist/core/socket.js +8 -0
  19. package/dist/kernel/dialect.d.ts +83 -0
  20. package/dist/kernel/dialect.js +191 -0
  21. package/dist/kernel/index.d.ts +15 -0
  22. package/dist/kernel/index.js +15 -0
  23. package/dist/kernel/kernel-core.d.ts +43 -0
  24. package/dist/kernel/kernel-core.js +98 -0
  25. package/dist/kernel/ops.d.ts +48 -0
  26. package/dist/kernel/ops.js +49 -0
  27. package/dist/kernel/pg-types.d.ts +22 -0
  28. package/dist/kernel/pg-types.js +26 -0
  29. package/dist/kernel/pglite/dialect.d.ts +11 -0
  30. package/dist/kernel/pglite/dialect.js +88 -0
  31. package/dist/kernel/pglite/driver.d.ts +30 -0
  32. package/dist/kernel/pglite/driver.js +47 -0
  33. package/dist/kernel/pglite/index.d.ts +5 -0
  34. package/dist/kernel/pglite/index.js +5 -0
  35. package/dist/kernel/pglite/ops.d.ts +39 -0
  36. package/dist/kernel/pglite/ops.js +78 -0
  37. package/dist/kernel/port.d.ts +82 -0
  38. package/dist/kernel/port.js +11 -0
  39. package/dist/kernel/postgres/driver.d.ts +23 -0
  40. package/dist/kernel/postgres/driver.js +42 -0
  41. package/dist/kernel/postgres/index.d.ts +5 -0
  42. package/dist/kernel/postgres/index.js +5 -0
  43. package/dist/kernel/postgres/ops.d.ts +12 -0
  44. package/dist/kernel/postgres/ops.js +46 -0
  45. package/dist/kernel/postgres/pglite-socket.d.ts +23 -0
  46. package/dist/kernel/postgres/pglite-socket.js +52 -0
  47. package/dist/kernel/postgres-lock.d.ts +8 -0
  48. package/dist/kernel/postgres-lock.js +10 -0
  49. package/dist/kernel/schema-scope.d.ts +14 -0
  50. package/dist/kernel/schema-scope.js +20 -0
  51. package/dist/kernel/schema-shape.d.ts +26 -0
  52. package/dist/kernel/schema-shape.js +83 -0
  53. package/dist/kernel/socket.d.ts +8 -0
  54. package/dist/kernel/socket.js +8 -0
  55. package/dist/kernel/sqlite/driver.d.ts +71 -0
  56. package/dist/kernel/sqlite/driver.js +132 -0
  57. package/dist/kernel/sqlite/index.d.ts +4 -0
  58. package/dist/kernel/sqlite/index.js +4 -0
  59. package/dist/kernel/sqlite/ops.d.ts +12 -0
  60. package/dist/kernel/sqlite/ops.js +40 -0
  61. package/dist/kernel/store-copy.d.ts +82 -0
  62. package/dist/kernel/store-copy.js +240 -0
  63. package/dist/kernel/turn-lock.d.ts +21 -0
  64. package/dist/kernel/turn-lock.js +42 -0
  65. package/dist/kernel/typegen.d.ts +13 -0
  66. package/dist/kernel/typegen.js +76 -0
  67. package/dist/migrate/checksum.d.ts +11 -0
  68. package/dist/migrate/checksum.js +14 -0
  69. package/dist/migrate/index.d.ts +8 -0
  70. package/dist/migrate/index.js +8 -0
  71. package/dist/migrate/runner.d.ts +33 -0
  72. package/dist/migrate/runner.js +126 -0
  73. package/dist/migrate/step.d.ts +37 -0
  74. package/dist/migrate/step.js +31 -0
  75. package/dist/pglite/dialect.d.ts +11 -0
  76. package/dist/pglite/dialect.js +88 -0
  77. package/dist/pglite/driver.d.ts +30 -0
  78. package/dist/pglite/driver.js +46 -0
  79. package/dist/pglite/index.d.ts +5 -0
  80. package/dist/pglite/index.js +4 -0
  81. package/dist/pglite/ops.d.ts +39 -0
  82. package/dist/pglite/ops.js +78 -0
  83. package/dist/pglite/owner.d.ts +107 -0
  84. package/dist/pglite/owner.js +359 -0
  85. package/dist/pglite/socket-server.d.ts +38 -0
  86. package/dist/pglite/socket-server.js +375 -0
  87. package/dist/pglite/types.d.ts +9 -0
  88. package/dist/pglite/types.js +2 -0
  89. package/dist/postgres/driver.d.ts +23 -0
  90. package/dist/postgres/driver.js +41 -0
  91. package/dist/postgres/index.d.ts +3 -0
  92. package/dist/postgres/index.js +3 -0
  93. package/dist/postgres/ops.d.ts +12 -0
  94. package/dist/postgres/ops.js +46 -0
  95. package/dist/postgres/pglite-socket.d.ts +23 -0
  96. package/dist/postgres/pglite-socket.js +51 -0
  97. package/dist/postgres/types.d.ts +53 -0
  98. package/dist/postgres/types.js +14 -0
  99. package/dist/sqlite/db-ops.d.ts +59 -0
  100. package/dist/sqlite/db-ops.js +82 -0
  101. package/dist/sqlite/driver.d.ts +71 -0
  102. package/dist/sqlite/driver.js +132 -0
  103. package/dist/sqlite/index.d.ts +9 -0
  104. package/dist/sqlite/index.js +4 -0
  105. package/dist/sqlite/inspect.d.ts +60 -0
  106. package/dist/sqlite/inspect.js +153 -0
  107. package/dist/sqlite/open.d.ts +58 -0
  108. package/dist/sqlite/open.js +43 -0
  109. package/dist/sqlite/ops.d.ts +12 -0
  110. package/dist/sqlite/ops.js +40 -0
  111. package/dist/sqlite/restore-types.d.ts +42 -0
  112. package/dist/sqlite/restore-types.js +2 -0
  113. package/dist/sqlite/sync-types.d.ts +34 -0
  114. package/dist/sqlite/sync-types.js +2 -0
  115. package/dist/sqlite/types.d.ts +37 -0
  116. package/dist/sqlite/types.js +8 -0
  117. package/dist/tools/database-catalog.d.ts +61 -0
  118. package/dist/tools/database-catalog.js +201 -0
  119. package/dist/tools/destination-port.d.ts +27 -0
  120. package/dist/tools/destination-port.js +2 -0
  121. package/dist/tools/index.d.ts +13 -0
  122. package/dist/tools/index.js +11 -0
  123. package/dist/tools/plan-store.d.ts +61 -0
  124. package/dist/tools/plan-store.js +39 -0
  125. package/dist/tools/read-tools.d.ts +53 -0
  126. package/dist/tools/read-tools.js +97 -0
  127. package/dist/tools/registration.d.ts +18 -0
  128. package/dist/tools/registration.js +10 -0
  129. package/dist/tools/restore-points.d.ts +125 -0
  130. package/dist/tools/restore-points.js +54 -0
  131. package/dist/tools/surface-port.d.ts +43 -0
  132. package/dist/tools/surface-port.js +2 -0
  133. package/dist/tools/timeline.d.ts +63 -0
  134. package/dist/tools/timeline.js +46 -0
  135. package/dist/tools/transfer-catalog.d.ts +25 -0
  136. package/dist/tools/transfer-catalog.js +59 -0
  137. package/dist/tools/transfer-tools.d.ts +82 -0
  138. package/dist/tools/transfer-tools.js +346 -0
  139. package/dist/transfer/copy-engine.d.ts +129 -0
  140. package/dist/transfer/copy-engine.js +233 -0
  141. package/dist/transfer/index.d.ts +9 -0
  142. package/dist/transfer/index.js +9 -0
  143. package/dist/transfer/internal-ddl.d.ts +23 -0
  144. package/dist/transfer/internal-ddl.js +119 -0
  145. package/dist/transfer/plan.d.ts +28 -0
  146. package/dist/transfer/plan.js +19 -0
  147. package/dist/transfer/postgres-ddl.d.ts +36 -0
  148. package/dist/transfer/postgres-ddl.js +16 -0
  149. package/dist/transfer/postgres-target.d.ts +65 -0
  150. package/dist/transfer/postgres-target.js +95 -0
  151. package/dist/transfer/sqlite-source.d.ts +78 -0
  152. package/dist/transfer/sqlite-source.js +79 -0
  153. package/dist/transfer/table-catalog.d.ts +44 -0
  154. package/dist/transfer/table-catalog.js +109 -0
  155. package/dist/transfer/types.d.ts +47 -0
  156. package/dist/transfer/types.js +2 -0
  157. package/package.json +184 -0
@@ -0,0 +1,82 @@
1
+ import { type ToolRegistration } from "@jini-ai/core";
2
+ import { type PostgresTargetPort, type TransferSource, type TransferNaming, type SnapshotTablePlan } from "../transfer/index.js";
3
+ import { type DbMessages, type DbTransferMessages } from "../core/messages.js";
4
+ import type { DatabaseDestinationStorePort } from "./destination-port.js";
5
+ import type { DatabaseTransferPlanStore } from "./plan-store.js";
6
+ import type { TransferSurfacePorts } from "./surface-port.js";
7
+ import { type InputReaders } from "./registration.js";
8
+ /**
9
+ * @file `database_transfer_plan` (read-only) and `database_transfer_run` (human-confirmed for replacement): COPY this
10
+ * site's database into a host-named private area of any Postgres database, while the site keeps running
11
+ * on its built-in storage. Plan slice P0 of `ADS-memory/reports/2026-09-27-assistant-db-transfer-plan.md`
12
+ * — core tables, row-count check. Vendor-blind: a plugin (e.g. Supabase) supplies the destination
13
+ * later; core never names one.
14
+ *
15
+ * The destination is never a tool input: `database_transfer_set_destination` raises a private form the
16
+ * human pastes the address into (`destination-ui.ts`), and every other tool reads it from
17
+ * `destination-store.ts`. `database_transfer_status` reports the destination, the last run and the copy
18
+ * found there.
19
+ *
20
+ * Two calls, the `site_backup_plan`/`site_backup_push` shape: the plan snapshots the database
21
+ * (`DbOpsPort.captureRestorePoint`, never the live file), connects to the destination, counts every
22
+ * table and refuses anything that would fail (unreachable, too old, someone else's private area). The
23
+ * replacement run raises the Copy/Cancel card and, on Copy, writes exactly the planned snapshot in one
24
+ * transaction (`copy-engine.ts`); a first copy runs immediately without a card.
25
+ *
26
+ * The connection string is never returned, shown or logged: results carry only host, port, database
27
+ * and user.
28
+ */
29
+ /** All host policy, schema and UI effects enter through these ports; no consumer import is permitted. */
30
+ export interface DatabaseTransferToolPorts {
31
+ workspaceId: string;
32
+ site: string;
33
+ naming: TransferNaming;
34
+ clock: {
35
+ nowIso(): string;
36
+ };
37
+ dbOps: {
38
+ getCapabilities(): Promise<{
39
+ restorePoint: {
40
+ costClass: string;
41
+ kind: string;
42
+ };
43
+ }>;
44
+ captureRestorePoint(input: {
45
+ scopeId: string;
46
+ }): Promise<{
47
+ artifactRef: string;
48
+ }>;
49
+ };
50
+ plans: Pick<DatabaseTransferPlanStore, "save" | "take">;
51
+ destinations: DatabaseDestinationStorePort;
52
+ target(connectionString: string): PostgresTargetPort;
53
+ requirePermission(input: {
54
+ principalId: string;
55
+ permission: string;
56
+ entityType: string;
57
+ }): Promise<void>;
58
+ openSource(bytes: Buffer): TransferSource;
59
+ catalog(name: string, source: TransferSource): SnapshotTablePlan;
60
+ partialExclusions(name: string, source: TransferSource): {
61
+ table: string;
62
+ rows: number;
63
+ reason: string;
64
+ }[];
65
+ captureChatSnapshot(): Promise<Buffer>;
66
+ failureLog(line: string): void;
67
+ describeError(error: unknown): string;
68
+ readonly schemaMismatchGuidance: string;
69
+ readers: Pick<InputReaders, "inputRecord" | "string">;
70
+ surfaces: TransferSurfacePorts;
71
+ }
72
+ /**
73
+ * Returns core registrations; the host applies its independent risk/error plumbing.
74
+ * Descriptions reflect required persisted naming; optional messages replace model-facing copy only.
75
+ * Construction performs no I/O. Host formatter exceptions propagate without mutating ports.
76
+ * @complexity O(1) fixed tool records plus the description formatter's text length.
77
+ * @example createDatabaseTransferTools(ports, { messages: defaultDbMessages })
78
+ */
79
+ export declare function createDatabaseTransferTools(deps: DatabaseTransferToolPorts, optional?: {
80
+ messages?: DbTransferMessages & Partial<DbMessages>;
81
+ }): ToolRegistration[];
82
+ //# sourceMappingURL=transfer-tools.d.ts.map
@@ -0,0 +1,346 @@
1
+ import { readFile, unlink } from "node:fs/promises";
2
+ import { ToolInputError } from "@jini-ai/core";
3
+ import { countSourceRows, inspectTarget, runCopy, planTransfer, SourceSchemaMismatchError, IncompleteTransferPlanError, InvalidConnectionStringError, LEFT_OUT_REASON } from "../transfer/index.js";
4
+ import { DOMAIN, PLAN_TOOL_ID, STATUS_TOOL_ID, RUN_PERMISSION, SNAPSHOT_SCOPE_ID, MIN_SERVER_VERSION_NUM, getDatabaseTransferAgentToolCatalog } from "./transfer-catalog.js";
5
+ import { defaultDbMessages } from "../core/messages.js";
6
+ import { registrations } from "./registration.js";
7
+ const SET_DESTINATION_TOOL_ID = "database_transfer_set_destination";
8
+ const DATABASE_TRANSFER_RUN_TOOL_ID = "database_transfer_run";
9
+ function destinationsOf(deps) {
10
+ return deps.ports.destinations;
11
+ }
12
+ function targetFor(deps, connectionString) {
13
+ return deps.ports.target(connectionString);
14
+ }
15
+ function log(deps, line) {
16
+ deps.ports.failureLog(`[database-transfer] ${line}`);
17
+ }
18
+ /**
19
+ * A consistent copy of the site database, as bytes. The restore-point file is deleted as soon as it
20
+ * is read.
21
+ *
22
+ * @complexity O(database size).
23
+ */
24
+ async function captureSnapshot(deps) {
25
+ const { restorePoint } = await deps.ports.dbOps.getCapabilities();
26
+ if (restorePoint.costClass !== "cheap" || restorePoint.kind !== "file-snapshot") {
27
+ return { code: "UNAVAILABLE", message: "only a site on built-in storage (SQLite) can be copied" };
28
+ }
29
+ let artifactRef;
30
+ try {
31
+ ({ artifactRef } = await deps.ports.dbOps.captureRestorePoint({ scopeId: SNAPSHOT_SCOPE_ID }));
32
+ }
33
+ catch (err) {
34
+ log(deps, `snapshot failed: ${deps.ports.describeError(err)}`);
35
+ return { code: "DATABASE_SNAPSHOT_FAILED", message: "the site database could not be snapshotted; nothing was copied" };
36
+ }
37
+ try {
38
+ return { ok: true, bytes: await readFile(artifactRef) };
39
+ }
40
+ catch (err) {
41
+ log(deps, `snapshot read failed: ${deps.ports.describeError(err)}`);
42
+ return { code: "DATABASE_SNAPSHOT_FAILED", message: "the site database snapshot could not be read; nothing was copied" };
43
+ }
44
+ finally {
45
+ await unlink(artifactRef).catch(() => undefined);
46
+ }
47
+ }
48
+ /** The site name copies are marked with; it also picks the site's schema (`copy-engine.ts`). */
49
+ function siteOf(deps) {
50
+ return deps.ports.site;
51
+ }
52
+ /** Connection, version, permission, and which private schema this site's copy goes to. */
53
+ async function checkTarget(deps, target, site) {
54
+ const inspected = await inspectTarget({ target, site, naming: deps.ports.naming });
55
+ const where = `${target.describe().database} on ${target.describe().host}`;
56
+ if (!inspected.ok)
57
+ return { code: "UNREACHABLE", message: `could not connect to ${where}: ${inspected.error}` };
58
+ if (inspected.serverVersionNum < MIN_SERVER_VERSION_NUM)
59
+ return { code: "SERVER_TOO_OLD", message: `${where} runs Postgres ${inspected.serverVersionNum}; version 14 or later is needed` };
60
+ if (inspected.schema === null) {
61
+ return { code: "TARGET_NOT_OURS", message: deps.messages.privateAreasTaken({ where }) };
62
+ }
63
+ if (inspected.schemaState === "absent" && !inspected.canCreateSchema)
64
+ return { code: "NO_CREATE_PERMISSION", message: `the user '${target.describe().user}' may not create a private area in ${where}` };
65
+ return { ok: true, schema: inspected.schema, replaces: inspected.lastCopy?.snapshotAt ?? null };
66
+ }
67
+ /** Open every planned snapshot and check source completeness before counting or writing. */
68
+ function snapshotSources(deps, snapshot, chatSnapshot) {
69
+ const opened = [];
70
+ try {
71
+ for (const [name, bytes] of [["content", snapshot], ...(chatSnapshot === undefined ? [] : [["chat", chatSnapshot]])]) {
72
+ const source = deps.ports.openSource(bytes);
73
+ try {
74
+ opened.push({ name, source, ...deps.ports.catalog(name, source) });
75
+ }
76
+ catch (error) {
77
+ source.close();
78
+ throw error;
79
+ }
80
+ }
81
+ return [...planTransfer({ sources: opened }).sources];
82
+ }
83
+ catch (error) {
84
+ for (const entry of opened)
85
+ entry.source.close();
86
+ throw error;
87
+ }
88
+ }
89
+ /** Row counts and reasons use each physical source's own catalog; no raw-SQL tables disappear. */
90
+ function countSnapshot(deps, bytes, chatSnapshot) {
91
+ let sources = [];
92
+ try {
93
+ sources = snapshotSources(deps, bytes, chatSnapshot);
94
+ const counts = sources.flatMap(entry => countSourceRows({ source: entry.source, tables: entry.tables }, { messages: deps.messages }));
95
+ // The human hears about their own data left behind; bookkeeping and derived search indexes
96
+ // are not theirs to miss. This is the original disclosure rule, applied to every source.
97
+ const leftOut = sources.flatMap(entry => [
98
+ ...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
+ ...deps.ports.partialExclusions(entry.name, entry.source),
100
+ ]);
101
+ return { ok: true, tableCount: counts.length, rowCount: counts.reduce((sum, count) => sum + count.rows, 0), leftOut };
102
+ }
103
+ catch (err) {
104
+ if (err instanceof SourceSchemaMismatchError || err instanceof IncompleteTransferPlanError)
105
+ return { code: "SCHEMA_MISMATCH", message: `${err.message}; ${deps.ports.schemaMismatchGuidance}` };
106
+ throw err;
107
+ }
108
+ finally {
109
+ for (const entry of sources)
110
+ entry.source.close();
111
+ }
112
+ }
113
+ function planResult(plan) {
114
+ return {
115
+ planned: true,
116
+ planId: plan.planId,
117
+ expiresAt: new Date(plan.expiresAtMs).toISOString(),
118
+ destination: plan.destination,
119
+ area: plan.schema,
120
+ snapshotAt: plan.snapshotAt,
121
+ tableCount: plan.tableCount,
122
+ rowCount: plan.rowCount,
123
+ replaces: plan.replaces,
124
+ leftOut: plan.leftOut.filter((entry) => entry.rows > 0),
125
+ notes: ["The site keeps running on its built-in storage; this is a copy.", "Photos and files stay where they are; only their records are copied."],
126
+ nextStep: "Tell the human what will be copied, then call database_transfer_run with this planId. It shows a Copy/Cancel card.",
127
+ };
128
+ }
129
+ /**
130
+ * The plan: parse, check permission, reach the destination, then snapshot and count. A refusal before
131
+ * the snapshot costs no snapshot.
132
+ *
133
+ * @complexity One connection check plus O(database size) for the snapshot and O(tables) counts.
134
+ */
135
+ async function handlePlan(deps, ctx) {
136
+ await deps.ports.requirePermission({ principalId: ctx.principal.id, permission: RUN_PERMISSION, entityType: DOMAIN });
137
+ const destination = await destinationsOf(deps).get(deps.ports.workspaceId);
138
+ if (destination === null) {
139
+ return {
140
+ planned: false,
141
+ code: "NO_DESTINATION",
142
+ message: deps.messages.noDestination,
143
+ nextStep: `Call ${SET_DESTINATION_TOOL_ID}. It shows the human a private form for the database address; you never see it.`,
144
+ };
145
+ }
146
+ const { connectionString } = destination;
147
+ const target = targetFor(deps, connectionString);
148
+ const checked = await checkTarget(deps, target, siteOf(deps));
149
+ if (!("ok" in checked))
150
+ return { planned: false, ...checked };
151
+ const snapshot = await captureSnapshot(deps);
152
+ if (!("ok" in snapshot))
153
+ return { planned: false, ...snapshot };
154
+ let chatSnapshot;
155
+ try {
156
+ chatSnapshot = await deps.ports.captureChatSnapshot();
157
+ }
158
+ catch (error) {
159
+ log(deps, `chat snapshot failed: ${deps.ports.describeError(error)}`);
160
+ return { planned: false, code: "DATABASE_SNAPSHOT_FAILED", message: "the chat database could not be snapshotted; nothing was copied" };
161
+ }
162
+ const counted = countSnapshot(deps, snapshot.bytes, chatSnapshot);
163
+ if (!("ok" in counted))
164
+ return { planned: false, ...counted };
165
+ const plan = deps.ports.plans.save({
166
+ principalId: ctx.principal.id,
167
+ workspaceId: deps.ports.workspaceId,
168
+ content: {
169
+ connectionString,
170
+ destination: target.describe(),
171
+ replaces: checked.replaces,
172
+ snapshot: snapshot.bytes,
173
+ chatSnapshot,
174
+ snapshotAt: deps.ports.clock.nowIso(),
175
+ site: siteOf(deps),
176
+ schema: checked.schema,
177
+ tableCount: counted.tableCount,
178
+ rowCount: counted.rowCount,
179
+ leftOut: counted.leftOut,
180
+ },
181
+ });
182
+ return planResult(plan);
183
+ }
184
+ async function askToConfirm(ctx, surfaces, plan, emitSurface) {
185
+ const exchange = surfaces.open({ toolId: DATABASE_TRANSFER_RUN_TOOL_ID, principalId: ctx.principal.id }, emitSurface);
186
+ const emission = surfaces.confirmation(plan, exchange.id);
187
+ const closeOnAbort = () => exchange.close();
188
+ ctx.signal.addEventListener("abort", closeOnAbort, { once: true });
189
+ try {
190
+ const outcome = await surfaces.resolveDecision(exchange, emission);
191
+ if (outcome.confirmed)
192
+ return { confirmed: true };
193
+ if (outcome.reason === "declined")
194
+ return { confirmed: false, result: { copied: false, cancelled: true } };
195
+ return { confirmed: false, result: { copied: false, cancelled: false, reason: outcome.reason } };
196
+ }
197
+ finally {
198
+ ctx.signal.removeEventListener("abort", closeOnAbort);
199
+ }
200
+ }
201
+ /** @complexity O(total rows), streamed. */
202
+ async function copyPlanned(deps, plan) {
203
+ const sources = snapshotSources(deps, plan.snapshot, plan.chatSnapshot);
204
+ try {
205
+ const result = await runCopy({ sources, naming: deps.ports.naming, target: targetFor(deps, plan.connectionString), schema: plan.schema, marker: { site: plan.site, snapshotAt: plan.snapshotAt }, replaceExisting: plan.replaces !== null }, { messages: deps.messages });
206
+ if (!result.ok) {
207
+ if (result.logDetail !== undefined)
208
+ log(deps, `${DATABASE_TRANSFER_RUN_TOOL_ID}: ${result.code} ${result.logDetail}`);
209
+ await destinationsOf(deps).recordRun(deps.ports.workspaceId, { copied: false, snapshotAt: plan.snapshotAt, code: result.code, message: result.message });
210
+ return { copied: false, cancelled: false, code: result.code, message: result.message };
211
+ }
212
+ if (result.warning !== undefined)
213
+ log(deps, `${DATABASE_TRANSFER_RUN_TOOL_ID}: ${result.warning}`);
214
+ const rowCount = result.tables.reduce((sum, table) => sum + table.rows, 0);
215
+ await destinationsOf(deps).recordRun(deps.ports.workspaceId, { copied: true, snapshotAt: plan.snapshotAt, tableCount: result.tables.length, rowCount });
216
+ return {
217
+ copied: true,
218
+ destination: plan.destination,
219
+ area: plan.schema,
220
+ snapshotAt: plan.snapshotAt,
221
+ tableCount: result.tables.length,
222
+ rowCount,
223
+ tables: result.tables,
224
+ ...(result.unvalidatedConstraints.length === 0
225
+ ? {}
226
+ : {
227
+ unvalidatedConstraints: result.unvalidatedConstraints,
228
+ note: deps.messages.uncheckedLinks,
229
+ }),
230
+ };
231
+ }
232
+ finally {
233
+ for (const entry of sources)
234
+ entry.source.close();
235
+ }
236
+ }
237
+ const PLAN_TAKE_MESSAGES = {
238
+ PLAN_NOT_FOUND: "no copy plan with that planId is waiting (a planId works once, for this principal, and a server restart drops plans). Call database_transfer_plan again.",
239
+ PLAN_EXPIRED: "that copy plan expired (plans last 10 minutes). Call database_transfer_plan again.",
240
+ };
241
+ async function handleRun(deps, surfaces, ctx, optional = {}) {
242
+ const planId = deps.ports.readers.string(deps.ports.readers.inputRecord(ctx.input), "planId");
243
+ await deps.ports.requirePermission({ principalId: ctx.principal.id, permission: RUN_PERMISSION, entityType: DOMAIN });
244
+ if (ctx.signal.aborted)
245
+ return { copied: false, cancelled: false, reason: "abandoned" };
246
+ const taken = deps.ports.plans.take({ planId, principalId: ctx.principal.id, workspaceId: deps.ports.workspaceId });
247
+ if (!taken.ok)
248
+ return { copied: false, cancelled: false, code: taken.code, message: PLAN_TAKE_MESSAGES[taken.code] };
249
+ if (taken.plan.replaces !== null) {
250
+ if (!optional.emitSurface) {
251
+ 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.` });
252
+ }
253
+ const decision = await askToConfirm(ctx, surfaces, taken.plan, optional.emitSurface);
254
+ if (!decision.confirmed)
255
+ return decision.result;
256
+ }
257
+ return copyPlanned(deps, taken.plan);
258
+ }
259
+ function failedDestination(surfaces, exchangeId, code, message) {
260
+ return { result: { saved: false, code, message }, outcome: surfaces.destinationOutcome({ exchangeId, state: "failure", message: `Not saved: ${message}.` }) };
261
+ }
262
+ /**
263
+ * The submitted address lives in one local for the width of this function: parsed, checked against
264
+ * the real server, then saved. It is never returned, logged or put in the outcome card.
265
+ *
266
+ * @complexity One connection check.
267
+ */
268
+ async function handleDestinationAnswer(deps, surfaces, exchangeId, answer) {
269
+ if (answer.status !== "received")
270
+ return { result: { saved: false, reason: answer.status } };
271
+ if (answer.params[surfaces.dismissedParam] === true)
272
+ return { result: { saved: false, reason: "cancelled" } };
273
+ const address = typeof answer.params[surfaces.addressField] === "string" ? answer.params[surfaces.addressField].trim() : "";
274
+ let target;
275
+ try {
276
+ target = targetFor(deps, address);
277
+ }
278
+ catch (err) {
279
+ if (err instanceof InvalidConnectionStringError)
280
+ return failedDestination(surfaces, exchangeId, "INVALID_CONNECTION_STRING", err.message);
281
+ throw err;
282
+ }
283
+ const checked = await checkTarget(deps, target, siteOf(deps));
284
+ if (!("ok" in checked))
285
+ return failedDestination(surfaces, exchangeId, checked.code, checked.message);
286
+ const destination = { connectionString: address, description: target.describe(), savedAt: deps.ports.clock.nowIso() };
287
+ await destinationsOf(deps).save(deps.ports.workspaceId, destination);
288
+ const { database, host } = destination.description;
289
+ return {
290
+ result: { saved: true, destination: destination.description, replaces: checked.replaces },
291
+ outcome: surfaces.destinationOutcome({ exchangeId, state: "success", message: deps.messages.destinationSaved({ database, host }) }),
292
+ };
293
+ }
294
+ async function handleSetDestination(deps, surfaces, ctx, optional = {}) {
295
+ await deps.ports.requirePermission({ principalId: ctx.principal.id, permission: RUN_PERMISSION, entityType: DOMAIN });
296
+ if (!optional.emitSurface) {
297
+ throw new ToolInputError({ message: `${SET_DESTINATION_TOOL_ID}: this execution context has no interactive form channel (no emitSurface), so the human cannot type the address here. Nothing was saved.` });
298
+ }
299
+ if (ctx.signal.aborted)
300
+ return { saved: false, reason: "abandoned" };
301
+ const exchange = surfaces.open({ toolId: SET_DESTINATION_TOOL_ID, principalId: ctx.principal.id }, optional.emitSurface);
302
+ const closeOnAbort = () => exchange.close();
303
+ ctx.signal.addEventListener("abort", closeOnAbort, { once: true });
304
+ try {
305
+ return await surfaces.askThenReport(exchange, surfaces.destinationForm(exchange.id), (answer) => handleDestinationAnswer(deps, surfaces, exchange.id, answer));
306
+ }
307
+ finally {
308
+ ctx.signal.removeEventListener("abort", closeOnAbort);
309
+ }
310
+ }
311
+ /**
312
+ * The saved destination (described, never the address), this process's last run, and the copy the
313
+ * destination itself holds (its marker), when it can be reached.
314
+ *
315
+ * @complexity One connection check when a destination is saved.
316
+ */
317
+ async function handleStatus(deps, ctx) {
318
+ await deps.ports.requirePermission({ principalId: ctx.principal.id, permission: RUN_PERMISSION, entityType: DOMAIN });
319
+ const destination = await destinationsOf(deps).get(deps.ports.workspaceId);
320
+ const lastRun = await destinationsOf(deps).lastRun(deps.ports.workspaceId);
321
+ if (destination === null)
322
+ return { destination: null, lastRun, copyOnDestination: null };
323
+ const inspected = await inspectTarget({ target: targetFor(deps, destination.connectionString), site: siteOf(deps), naming: deps.ports.naming });
324
+ const copyOnDestination = inspected.ok ? inspected.lastCopy : { unreachable: inspected.error };
325
+ return { destination: destination.description, lastRun, copyOnDestination };
326
+ }
327
+ /**
328
+ * Returns core registrations; the host applies its independent risk/error plumbing.
329
+ * Descriptions reflect required persisted naming; optional messages replace model-facing copy only.
330
+ * Construction performs no I/O. Host formatter exceptions propagate without mutating ports.
331
+ * @complexity O(1) fixed tool records plus the description formatter's text length.
332
+ * @example createDatabaseTransferTools(ports, { messages: defaultDbMessages })
333
+ */
334
+ export function createDatabaseTransferTools(deps, optional = {}) {
335
+ const runtime = { ports: deps, messages: { ...defaultDbMessages, ...optional.messages } };
336
+ const handlers = {
337
+ [PLAN_TOOL_ID]: ctx => handlePlan(runtime, ctx),
338
+ [DATABASE_TRANSFER_RUN_TOOL_ID]: (ctx, optional) => handleRun(runtime, runtime.ports.surfaces, ctx, optional),
339
+ [SET_DESTINATION_TOOL_ID]: (ctx, optional) => handleSetDestination(runtime, runtime.ports.surfaces, ctx, optional),
340
+ [STATUS_TOOL_ID]: ctx => handleStatus(runtime, ctx),
341
+ };
342
+ // Read checks and snapshot planning do not mutate durable state; run and saved destination do.
343
+ const risks = new Map([[PLAN_TOOL_ID, "none"], [STATUS_TOOL_ID, "none"], [DATABASE_TRANSFER_RUN_TOOL_ID, "mutates-durable-state"], [SET_DESTINATION_TOOL_ID, "mutates-durable-state"]]);
344
+ return registrations({ catalog: getDatabaseTransferAgentToolCatalog({}, { naming: deps.naming, messages: runtime.messages }), handlers, risks });
345
+ }
346
+ //# sourceMappingURL=transfer-tools.js.map
@@ -0,0 +1,129 @@
1
+ import { type DbMessages } from "../core/messages.js";
2
+ import type { PostgresTargetPort } from "./postgres-target.js";
3
+ import type { TransferSource } from "./sqlite-source.js";
4
+ import type { TransferTable } from "./types.js";
5
+ /**
6
+ * @file The COPY-mode engine (plan slice P0): which tables go, the target DDL, the psql script, and
7
+ * the target-state check. Vendor-blind: it knows "a Postgres database", never a provider.
8
+ *
9
+ * Where a copy goes (several sites may share one database, each in its own schema; never `public`,
10
+ * which hosted Postgres products such as Supabase expose through their data APIs):
11
+ * - a site that already has a copy there keeps its schema: the marker table names the site, so a
12
+ * re-copy always lands in the same place, whatever other sites did since;
13
+ * - otherwise the first free schema of the host default, {@link siteSchemaName} (the host prefix plus the site name),
14
+ * then that name plus a hash of the site name.
15
+ *
16
+ * What one run does, as ONE Postgres transaction (psql `ON_ERROR_STOP`, so the first error aborts it
17
+ * and the previous copy, if any, stays exactly as it was):
18
+ * 1. refuse unless the schema is absent or holds THIS site's copy (its marker names this site and no
19
+ * other) — checked inside the transaction, so a stale plan or a race can never wipe another
20
+ * site's copy or someone else's data;
21
+ * 2. drop the site's previous copy and create its schema — never `public`, never any other schema;
22
+ * 3. create every table the host plans (core tables from its catalog, the
23
+ * snapshot's other tables from its own layout): columns, defaults, identity, primary key;
24
+ * 4. `COPY ... FROM STDIN` every table's rows (minus the logins, saved keys and secret settings in
25
+ * the host exclusion policy);
26
+ * 5. check every table's `count(*)` against the source count and abort on any difference;
27
+ * 6. move identity counters past the copied numbers, build the indexes, then add CHECKs and foreign
28
+ * keys (see `postgres-ddl.ts`: a key the old rows break stays NOT VALID and is reported, it never
29
+ * aborts the copy);
30
+ * 7. write the marker row (site, source snapshot time, counts, unvalidated constraints) and commit.
31
+ *
32
+ * Multiple host-supplied sources share this transaction. Checksums and staging swap remain later slices (T3).
33
+ */
34
+ /** The schema the first site to copy into a database gets. */
35
+ import type { TransferNaming } from "./types.js";
36
+ import { type TransferPlanSource } from "./plan.js";
37
+ export interface TableCount {
38
+ readonly table: TransferTable;
39
+ readonly rows: number;
40
+ }
41
+ export declare class SourceSchemaMismatchError extends Error {
42
+ }
43
+ /**
44
+ * Row counts for every table, after checking the source has each table and column the target will
45
+ * get (a site database is migrated at boot, so a gap means the Postgres schema is out of date).
46
+ *
47
+ * @throws {SourceSchemaMismatchError} Naming the first missing table or column.
48
+ * @param _optional.messages Host schema-error formatters; never used in SQL or persisted naming.
49
+ * @complexity O(tables) queries.
50
+ */
51
+ export declare function countSourceRows({ source, tables }: {
52
+ source: TransferSource;
53
+ tables: readonly TransferTable[];
54
+ }, _optional?: {
55
+ messages?: Pick<DbMessages, "missingSourceTable" | "missingSourceColumn">;
56
+ }): TableCount[];
57
+ /** `ours`: the site's own copy is there; `absent`: a free schema was found; `foreign`: every candidate is taken. */
58
+ export type TargetSchemaState = "absent" | "ours" | "foreign";
59
+ export interface TransferCopyInfo {
60
+ readonly site: string;
61
+ readonly snapshotAt: string;
62
+ }
63
+ export type TargetInspection = {
64
+ readonly ok: true;
65
+ readonly serverVersionNum: number;
66
+ readonly schemaState: TargetSchemaState;
67
+ /** Where this site's copy goes; `null` only when `schemaState` is `foreign`. */
68
+ readonly schema: string | null;
69
+ readonly lastCopy: TransferCopyInfo | null;
70
+ readonly canCreateSchema: boolean;
71
+ } | {
72
+ readonly ok: false;
73
+ readonly error: string;
74
+ };
75
+ /**
76
+ * Connects and reads what a plan needs: the server version, whether this user may create a schema,
77
+ * and where this site's copy goes (see this file's header).
78
+ *
79
+ * @complexity Two queries plus one per schema holding a marker.
80
+ */
81
+ export declare function inspectTarget({ target, site, naming }: {
82
+ target: PostgresTargetPort;
83
+ site: string;
84
+ naming: TransferNaming;
85
+ }, _optional?: {}): Promise<TargetInspection>;
86
+ export interface CopyMarker {
87
+ readonly site: string;
88
+ readonly snapshotAt: string;
89
+ }
90
+ export type CopyResult = {
91
+ readonly ok: true;
92
+ readonly tables: readonly {
93
+ readonly name: string;
94
+ readonly rows: number;
95
+ }[];
96
+ /** `table.constraint` for each CHECK or foreign key the copied rows break: kept, but NOT VALID. */
97
+ readonly unvalidatedConstraints: readonly string[];
98
+ /** Set when the copy committed but its unvalidated list could not be read back. */
99
+ readonly warning?: string;
100
+ } | {
101
+ readonly ok: false;
102
+ readonly code: "TARGET_NOT_OURS" | "COPY_FAILED" | "COUNT_MISMATCH";
103
+ readonly message: string;
104
+ readonly logDetail?: string;
105
+ };
106
+ /**
107
+ * Runs one copy as a single transaction (see this file's header). A failure's message names at most
108
+ * a table; the redacted psql line goes to `logDetail`, for the server log only.
109
+ * Optional messages format source-schema preflight failures; generated SQL never reads them.
110
+ *
111
+ * @complexity O(total rows), streamed in ~256 KiB chunks.
112
+ */
113
+ export interface RunCopyInput {
114
+ readonly sources: readonly TransferPlanSource[];
115
+ readonly target: PostgresTargetPort;
116
+ readonly naming: TransferNaming;
117
+ readonly schema: string;
118
+ readonly marker: CopyMarker;
119
+ readonly replaceExisting: boolean;
120
+ }
121
+ export declare function runCopy(input: RunCopyInput, _optional?: {
122
+ messages?: Pick<DbMessages, "missingSourceTable" | "missingSourceColumn">;
123
+ }): Promise<CopyResult>;
124
+ /** Human-readable schema naming preserves the original hash/63-byte collision rationale above. */
125
+ export declare function siteSchemaName({ site, naming }: {
126
+ site: string;
127
+ naming: TransferNaming;
128
+ }, _optional?: {}): string;
129
+ //# sourceMappingURL=copy-engine.d.ts.map