@myrialabs/clopen 0.4.39 → 0.4.41

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 (173) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +29 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +42 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/index.ts +28 -0
  20. package/backend/database/queries/file-share-queries.ts +163 -0
  21. package/backend/database/queries/index.ts +12 -4
  22. package/backend/database/queries/profile-queries.ts +5 -3
  23. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  24. package/backend/database/queries/push-subscription-queries.ts +99 -0
  25. package/backend/database/queries/skill-queries.ts +96 -18
  26. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  27. package/backend/db-client/cloning.test.ts +161 -0
  28. package/backend/db-client/cloning.ts +672 -0
  29. package/backend/db-client/connection-url.test.ts +117 -0
  30. package/backend/db-client/connection-url.ts +126 -0
  31. package/backend/db-client/drivers/mongodb.ts +2 -14
  32. package/backend/db-client/drivers/mysql.ts +2 -8
  33. package/backend/db-client/drivers/postgres.ts +10 -13
  34. package/backend/db-client/drivers/redis.ts +2 -6
  35. package/backend/db-client/env/detect.ts +438 -0
  36. package/backend/db-client/env/diff.ts +94 -0
  37. package/backend/db-client/env/env.test.ts +574 -0
  38. package/backend/db-client/env/index.ts +15 -0
  39. package/backend/db-client/env/naming.ts +202 -0
  40. package/backend/db-client/env/service.ts +487 -0
  41. package/backend/db-client/integrations/index.ts +7 -0
  42. package/backend/db-client/integrations/links.ts +41 -10
  43. package/backend/db-client/providers/neon/adapter.ts +522 -0
  44. package/backend/db-client/providers/neon/api-types.ts +182 -0
  45. package/backend/db-client/providers/neon/client.ts +298 -0
  46. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  47. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  48. package/backend/db-client/providers/neon/list.test.ts +181 -0
  49. package/backend/db-client/providers/supabase/adapter.ts +25 -2
  50. package/backend/db-client/providers/types.ts +57 -0
  51. package/backend/engine/adapters/claude/stream.ts +2 -1
  52. package/backend/engine/adapters/cline/stream.ts +3 -3
  53. package/backend/engine/adapters/codex/stream.ts +3 -3
  54. package/backend/engine/adapters/copilot/stream.ts +3 -3
  55. package/backend/engine/adapters/cursor/stream.ts +25 -3
  56. package/backend/engine/adapters/opencode/stream.ts +4 -6
  57. package/backend/engine/adapters/pi/stream.ts +2 -2
  58. package/backend/engine/adapters/qwen/stream.ts +2 -2
  59. package/backend/engine/artifact-sync.ts +26 -20
  60. package/backend/engine/docs/artifacts.md +81 -22
  61. package/backend/engine/docs/quick-reference.md +2 -1
  62. package/backend/engine/resolve-model.test.ts +108 -0
  63. package/backend/engine/resolve-model.ts +53 -10
  64. package/backend/engine/structured-helpers.ts +22 -0
  65. package/backend/env-files/discovery.ts +48 -0
  66. package/backend/env-files/edit.ts +213 -0
  67. package/backend/env-files/env-files.test.ts +515 -0
  68. package/backend/env-files/git.ts +27 -0
  69. package/backend/env-files/index.ts +44 -0
  70. package/backend/env-files/keys.ts +69 -0
  71. package/backend/env-files/parse.ts +157 -0
  72. package/backend/env-files/write.ts +229 -0
  73. package/backend/files/file-shares.ts +369 -0
  74. package/backend/files/path-browsing.ts +27 -21
  75. package/backend/http/files-shared.test.ts +505 -0
  76. package/backend/http/files-shared.ts +351 -0
  77. package/backend/http/push.ts +150 -0
  78. package/backend/index.ts +8 -0
  79. package/backend/instructions/index.ts +1 -1
  80. package/backend/instructions/sync.ts +30 -6
  81. package/backend/integrations/health.ts +18 -4
  82. package/backend/integrations/projections/types.ts +9 -2
  83. package/backend/integrations/registry/index.ts +3 -0
  84. package/backend/integrations/registry/providers/context7.ts +1 -0
  85. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  86. package/backend/integrations/registry/providers/github.ts +1 -0
  87. package/backend/integrations/registry/providers/neon.ts +55 -0
  88. package/backend/integrations/registry/providers/supabase.ts +1 -0
  89. package/backend/integrations/registry/providers/vercel.ts +1 -0
  90. package/backend/integrations/registry/types.ts +2 -0
  91. package/backend/memory/compose.ts +2 -2
  92. package/backend/memory/consolidate.ts +2 -2
  93. package/backend/memory/extract/episodic.ts +2 -2
  94. package/backend/memory/judge.ts +2 -2
  95. package/backend/profiles/service.ts +7 -6
  96. package/backend/push/sender.ts +172 -0
  97. package/backend/push/tags.ts +25 -0
  98. package/backend/push/vapid-keys.ts +77 -0
  99. package/backend/push/webpush-crypto.test.ts +200 -0
  100. package/backend/push/webpush-crypto.ts +231 -0
  101. package/backend/skills/detect.ts +28 -0
  102. package/backend/skills/index.ts +22 -4
  103. package/backend/skills/invoke.test.ts +114 -0
  104. package/backend/skills/invoke.ts +222 -0
  105. package/backend/skills/service.ts +194 -44
  106. package/backend/skills/spec.ts +35 -0
  107. package/backend/skills/sync.ts +85 -55
  108. package/backend/subagents/detect.ts +2 -3
  109. package/backend/subagents/sync.ts +15 -8
  110. package/backend/work/pull-requests.ts +2 -2
  111. package/backend/work/start-work.ts +4 -0
  112. package/backend/worktrees/branching/engine.ts +557 -0
  113. package/backend/worktrees/branching/index.ts +56 -0
  114. package/backend/worktrees/branching/naming.test.ts +118 -0
  115. package/backend/worktrees/branching/naming.ts +97 -0
  116. package/backend/worktrees/branching/projector.test.ts +229 -0
  117. package/backend/worktrees/branching/projector.ts +139 -0
  118. package/backend/worktrees/branching/providers/neon.ts +220 -0
  119. package/backend/worktrees/branching/registry.ts +27 -0
  120. package/backend/worktrees/branching/service.ts +620 -0
  121. package/backend/worktrees/branching/suggest.test.ts +154 -0
  122. package/backend/worktrees/branching/suggest.ts +202 -0
  123. package/backend/worktrees/branching/types.ts +88 -0
  124. package/backend/worktrees/index.ts +7 -0
  125. package/backend/worktrees/service.ts +48 -1
  126. package/backend/ws/chat/stream.ts +100 -8
  127. package/backend/ws/db-client/env.ts +142 -0
  128. package/backend/ws/db-client/index.ts +2 -0
  129. package/backend/ws/files/index.ts +4 -0
  130. package/backend/ws/files/share.ts +95 -0
  131. package/backend/ws/git/branch-name.ts +2 -2
  132. package/backend/ws/git/commit-message.ts +2 -2
  133. package/backend/ws/index.ts +3 -4
  134. package/backend/ws/profiles/crud.ts +2 -3
  135. package/backend/ws/projects/index.ts +6 -1
  136. package/backend/ws/projects/info.ts +70 -6
  137. package/backend/ws/projects/overview.test.ts +108 -0
  138. package/backend/ws/projects/overview.ts +300 -0
  139. package/backend/ws/skills/catalog.ts +5 -1
  140. package/backend/ws/skills/crud.ts +128 -22
  141. package/backend/ws/skills/index.ts +4 -1
  142. package/backend/ws/system/device-info.ts +307 -76
  143. package/backend/ws/user/crud.ts +12 -3
  144. package/backend/ws/worktrees/branching.ts +212 -0
  145. package/backend/ws/worktrees/crud.ts +33 -7
  146. package/backend/ws/worktrees/index.ts +14 -0
  147. package/dist/assets/{index-C8Gi-b6U.js → index-CeNKKSDR.js} +1 -1
  148. package/dist/assets/{index-BrF6nqld.js → index-DW89566K.js} +1 -1
  149. package/dist/assets/main-Cy5DXWPT.js +1207 -0
  150. package/dist/assets/main-DJKj_4By.css +1 -0
  151. package/dist/index.html +7 -2
  152. package/dist/sw.js +112 -0
  153. package/package.json +1 -1
  154. package/shared/constants/engine-tools.ts +31 -6
  155. package/shared/constants/notification-messages.ts +142 -0
  156. package/shared/constants/tool-icons.ts +6 -2
  157. package/shared/types/db-client/env.ts +192 -0
  158. package/shared/types/db-client/index.ts +1 -0
  159. package/shared/types/db-client/integrations.ts +30 -0
  160. package/shared/types/integrations.ts +9 -0
  161. package/shared/types/unified/stream.ts +7 -0
  162. package/shared/types/worktree-branching.ts +315 -0
  163. package/shared/utils/logger.ts +1 -0
  164. package/backend/commands/detect.ts +0 -25
  165. package/backend/commands/index.ts +0 -9
  166. package/backend/commands/service.ts +0 -178
  167. package/backend/commands/store.ts +0 -45
  168. package/backend/commands/sync.ts +0 -94
  169. package/backend/database/queries/command-queries.ts +0 -82
  170. package/backend/ws/commands/crud.ts +0 -157
  171. package/backend/ws/commands/index.ts +0 -8
  172. package/dist/assets/main-Bd3gb79F.css +0 -1
  173. package/dist/assets/main-Bo1hD7mt.js +0 -1191
@@ -0,0 +1,331 @@
1
+ /**
2
+ * Worktree database branching — the binding, and the branches it produced.
3
+ *
4
+ * The binding table holds no secret: a parent ref and four display settings.
5
+ * The branch table holds a whole connection string, password included, so
6
+ * `connection_json` is sealed at rest by the crypto layer — callers here hand in
7
+ * and receive a plain object and never see an envelope.
8
+ *
9
+ * A blob the active key cannot open reads as `null`, which every caller treats
10
+ * exactly as it treats a branch whose connection was never resolved: the branch
11
+ * is still listed, still deletable at the provider, and simply projects no
12
+ * connection. Throwing instead would take down the worktree list itself.
13
+ */
14
+
15
+ import { getDatabase } from '../index';
16
+ import { openRow, openRows, sealFor } from '../crypto';
17
+ import type {
18
+ BranchConnection,
19
+ BranchEnvStatus,
20
+ BranchSourceKind,
21
+ WorktreeBranchConfig
22
+ } from '$shared/types/worktree-branching';
23
+ import { DEFAULT_WORKTREE_BRANCH_CONFIG } from '$shared/types/worktree-branching';
24
+
25
+ const BRANCH_TABLE = 'worktree_branches';
26
+
27
+ export interface WorktreeBranchBindingRow {
28
+ project_id: string;
29
+ source_kind: BranchSourceKind;
30
+ /** Set for an account source, null for a connection one. */
31
+ account_id: string | null;
32
+ /** Set for a connection source, null for an account one. */
33
+ connection_id: string | null;
34
+ parent_ref: string;
35
+ parent_name: string;
36
+ config_json: string;
37
+ created_at: string;
38
+ updated_at: string;
39
+ }
40
+
41
+ export interface WorktreeBranchRow {
42
+ id: string;
43
+ /** Null once the worktree is gone. That is what makes the row an orphan. */
44
+ worktree_id: string | null;
45
+ project_id: string;
46
+ source_kind: BranchSourceKind;
47
+ account_id: string | null;
48
+ /** The DB Client connection copied FROM. No FK — see migration 078. */
49
+ source_connection_id: string | null;
50
+ parent_ref: string;
51
+ branch_ref: string;
52
+ branch_name: string;
53
+ /** Sealed on disk, plain JSON string here. Null when the key could not open it. */
54
+ connection_json: string | null;
55
+ connection_id: string | null;
56
+ env_var: string;
57
+ env_file: string;
58
+ env_status: BranchEnvStatus;
59
+ env_detail: string | null;
60
+ status: 'active' | 'orphaned';
61
+ error: string | null;
62
+ /** Which mechanism made it, for the sentence the manager shows. */
63
+ strategy: string | null;
64
+ /** What that mechanism did not carry, or null. */
65
+ notice: string | null;
66
+ created_at: string;
67
+ updated_at: string;
68
+ }
69
+
70
+ /** The account or connection a row belongs to, whichever it is. */
71
+ export function sourceIdOf(row: { account_id: string | null; connection_id?: string | null; source_connection_id?: string | null }): string {
72
+ return row.account_id ?? row.source_connection_id ?? row.connection_id ?? '';
73
+ }
74
+
75
+ /**
76
+ * Parse the stored config over the defaults.
77
+ *
78
+ * Merged rather than replaced, for the reason `parseDeployConfig` merges: a
79
+ * config written before an option existed must not read back with that option
80
+ * `undefined`. Here that would be worse than a wrong filter — an `envVar` of
81
+ * `undefined` writes the literal string "undefined=" into someone's dotenv file.
82
+ */
83
+ export function parseWorktreeBranchConfig(raw: string | null): WorktreeBranchConfig {
84
+ if (!raw) return { ...DEFAULT_WORKTREE_BRANCH_CONFIG };
85
+ try {
86
+ const parsed = JSON.parse(raw) as Partial<WorktreeBranchConfig> | null;
87
+ return { ...DEFAULT_WORKTREE_BRANCH_CONFIG, ...(parsed ?? {}) };
88
+ } catch {
89
+ return { ...DEFAULT_WORKTREE_BRANCH_CONFIG };
90
+ }
91
+ }
92
+
93
+ export const worktreeBranchBindingQueries = {
94
+ get(projectId: string): WorktreeBranchBindingRow | null {
95
+ const db = getDatabase();
96
+ return db.prepare(
97
+ `SELECT * FROM worktree_branch_bindings WHERE project_id = ?`
98
+ ).get(projectId) as WorktreeBranchBindingRow | null;
99
+ },
100
+
101
+ getForAccount(accountId: string): WorktreeBranchBindingRow[] {
102
+ const db = getDatabase();
103
+ return db.prepare(
104
+ `SELECT * FROM worktree_branch_bindings WHERE account_id = ?`
105
+ ).all(accountId) as WorktreeBranchBindingRow[];
106
+ },
107
+
108
+ upsert(input: {
109
+ projectId: string;
110
+ sourceKind: BranchSourceKind;
111
+ sourceId: string;
112
+ parentRef: string;
113
+ parentName: string;
114
+ config: WorktreeBranchConfig;
115
+ }): WorktreeBranchBindingRow {
116
+ const db = getDatabase();
117
+ const now = new Date().toISOString();
118
+ const existing = this.get(input.projectId);
119
+ const accountId = input.sourceKind === 'account' ? input.sourceId : null;
120
+ const connectionId = input.sourceKind === 'connection' ? input.sourceId : null;
121
+
122
+ db.prepare(`
123
+ INSERT INTO worktree_branch_bindings (
124
+ project_id, source_kind, account_id, connection_id,
125
+ parent_ref, parent_name, config_json, created_at, updated_at
126
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
127
+ ON CONFLICT (project_id) DO UPDATE SET
128
+ source_kind = excluded.source_kind,
129
+ account_id = excluded.account_id,
130
+ connection_id = excluded.connection_id,
131
+ parent_ref = excluded.parent_ref,
132
+ parent_name = excluded.parent_name,
133
+ config_json = excluded.config_json,
134
+ updated_at = excluded.updated_at
135
+ `).run(
136
+ input.projectId,
137
+ input.sourceKind,
138
+ accountId,
139
+ connectionId,
140
+ input.parentRef,
141
+ input.parentName,
142
+ JSON.stringify(input.config),
143
+ existing?.created_at ?? now,
144
+ now
145
+ );
146
+
147
+ return this.get(input.projectId)!;
148
+ },
149
+
150
+ remove(projectId: string): void {
151
+ const db = getDatabase();
152
+ db.prepare(`DELETE FROM worktree_branch_bindings WHERE project_id = ?`).run(projectId);
153
+ }
154
+ };
155
+
156
+ function openBranch<T extends WorktreeBranchRow | null>(row: T): T {
157
+ return (row ? openRow(BRANCH_TABLE, row) : row) as T;
158
+ }
159
+
160
+ export const worktreeBranchQueries = {
161
+ getById(id: string): WorktreeBranchRow | null {
162
+ const db = getDatabase();
163
+ return openBranch(
164
+ db.prepare(`SELECT * FROM worktree_branches WHERE id = ?`).get(id) as WorktreeBranchRow | null
165
+ );
166
+ },
167
+
168
+ /** The branch attached to one worktree, or null when it has none. */
169
+ getForWorktree(worktreeId: string): WorktreeBranchRow | null {
170
+ const db = getDatabase();
171
+ return openBranch(
172
+ db.prepare(
173
+ `SELECT * FROM worktree_branches WHERE worktree_id = ? AND status = 'active'`
174
+ ).get(worktreeId) as WorktreeBranchRow | null
175
+ );
176
+ },
177
+
178
+ getForAccount(accountId: string): WorktreeBranchRow[] {
179
+ const db = getDatabase();
180
+ return openRows(
181
+ BRANCH_TABLE,
182
+ db.prepare(
183
+ `SELECT * FROM worktree_branches WHERE account_id = ? ORDER BY created_at DESC`
184
+ ).all(accountId) as WorktreeBranchRow[]
185
+ );
186
+ },
187
+
188
+ getForProject(projectId: string): WorktreeBranchRow[] {
189
+ const db = getDatabase();
190
+ return openRows(
191
+ BRANCH_TABLE,
192
+ db.prepare(
193
+ `SELECT * FROM worktree_branches WHERE project_id = ? ORDER BY created_at DESC`
194
+ ).all(projectId) as WorktreeBranchRow[]
195
+ );
196
+ },
197
+
198
+ /**
199
+ * Every branch whose worktree is gone, or whose remote delete failed.
200
+ *
201
+ * The two are one query because they are one problem: a branch that still
202
+ * exists at the provider and is no longer attached to anything. Reporting
203
+ * them separately would ask the user to understand how each one got that way
204
+ * before they could act on either.
205
+ */
206
+ orphans(): WorktreeBranchRow[] {
207
+ const db = getDatabase();
208
+ return openRows(
209
+ BRANCH_TABLE,
210
+ db.prepare(`
211
+ SELECT * FROM worktree_branches
212
+ WHERE worktree_id IS NULL OR status = 'orphaned'
213
+ ORDER BY created_at DESC
214
+ `).all() as WorktreeBranchRow[]
215
+ );
216
+ },
217
+
218
+ connectionOf(row: WorktreeBranchRow): BranchConnection | null {
219
+ if (!row.connection_json) return null;
220
+ try {
221
+ const parsed = JSON.parse(row.connection_json) as BranchConnection | null;
222
+ return parsed && typeof parsed.uri === 'string' && parsed.uri ? parsed : null;
223
+ } catch {
224
+ return null;
225
+ }
226
+ },
227
+
228
+ create(input: {
229
+ worktreeId: string;
230
+ projectId: string;
231
+ sourceKind: BranchSourceKind;
232
+ sourceId: string;
233
+ parentRef: string;
234
+ branchRef: string;
235
+ branchName: string;
236
+ connection: BranchConnection;
237
+ envVar: string;
238
+ envFile: string;
239
+ strategy: string | null;
240
+ notice: string | null;
241
+ }): WorktreeBranchRow {
242
+ const db = getDatabase();
243
+ const id = crypto.randomUUID();
244
+ const now = new Date().toISOString();
245
+
246
+ db.prepare(`
247
+ INSERT INTO worktree_branches (
248
+ id, worktree_id, project_id, source_kind, account_id, source_connection_id,
249
+ parent_ref, branch_ref, branch_name,
250
+ connection_json, connection_id, env_var, env_file, env_status, env_detail,
251
+ status, error, strategy, notice, created_at, updated_at
252
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 'failed', NULL, 'active', NULL, ?, ?, ?, ?)
253
+ `).run(
254
+ id,
255
+ input.worktreeId,
256
+ input.projectId,
257
+ input.sourceKind,
258
+ input.sourceKind === 'account' ? input.sourceId : null,
259
+ input.sourceKind === 'connection' ? input.sourceId : null,
260
+ input.parentRef,
261
+ input.branchRef,
262
+ input.branchName,
263
+ sealFor(BRANCH_TABLE, 'connection_json', JSON.stringify(input.connection)),
264
+ input.envVar,
265
+ input.envFile,
266
+ input.strategy,
267
+ input.notice,
268
+ now,
269
+ now
270
+ );
271
+
272
+ return this.getById(id)!;
273
+ },
274
+
275
+ /** Every branch copied from one DB Client connection. */
276
+ getForSourceConnection(connectionId: string): WorktreeBranchRow[] {
277
+ const db = getDatabase();
278
+ return openRows(
279
+ BRANCH_TABLE,
280
+ db.prepare(
281
+ `SELECT * FROM worktree_branches WHERE source_connection_id = ? ORDER BY created_at DESC`
282
+ ).all(connectionId) as WorktreeBranchRow[]
283
+ );
284
+ },
285
+
286
+ /**
287
+ * Record what happened when the connection string was written.
288
+ *
289
+ * Separate from `create` on purpose, and the ORDER is the reason. The row is
290
+ * written BEFORE the dotenv file is touched, so a crash in between leaves a
291
+ * branch that is tracked and deletable rather than one nothing knows about.
292
+ * That means the row exists for a moment with no env result — and the
293
+ * column's default of `failed` is the honest reading of that moment, because
294
+ * a process that died there genuinely did not write anything.
295
+ */
296
+ setEnvResult(id: string, status: BranchEnvStatus, detail: string | null): void {
297
+ const db = getDatabase();
298
+ db.prepare(
299
+ `UPDATE worktree_branches SET env_status = ?, env_detail = ?, updated_at = ? WHERE id = ?`
300
+ ).run(status, detail, new Date().toISOString(), id);
301
+ },
302
+
303
+ /** Remember which DB Client connection this branch projected. */
304
+ setConnectionId(id: string, connectionId: string | null): void {
305
+ const db = getDatabase();
306
+ db.prepare(
307
+ `UPDATE worktree_branches SET connection_id = ?, updated_at = ? WHERE id = ?`
308
+ ).run(connectionId, new Date().toISOString(), id);
309
+ },
310
+
311
+ /**
312
+ * Mark a branch as leaked.
313
+ *
314
+ * Called when the remote delete failed. The row deliberately keeps its
315
+ * connection and its refs: they are exactly what a later retry needs, and
316
+ * clearing them would turn a reportable orphan into an unreachable one.
317
+ */
318
+ markOrphaned(id: string, error: string): void {
319
+ const db = getDatabase();
320
+ db.prepare(`
321
+ UPDATE worktree_branches
322
+ SET status = 'orphaned', error = ?, worktree_id = NULL, updated_at = ?
323
+ WHERE id = ?
324
+ `).run(error, new Date().toISOString(), id);
325
+ },
326
+
327
+ remove(id: string): void {
328
+ const db = getDatabase();
329
+ db.prepare(`DELETE FROM worktree_branches WHERE id = ?`).run(id);
330
+ }
331
+ };
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Tests for copying a database.
3
+ *
4
+ * SQLite is the one engine whose whole copy is exercisable without a server, so
5
+ * it carries the cases that are about the FEATURE rather than about a dialect:
6
+ * a copy is a real copy, "schema only" empties the copy and never the original,
7
+ * and deleting one takes its journal files with it. Getting that last pair
8
+ * wrong destroys the user's actual database, which is why they are here rather
9
+ * than left to runtime QA.
10
+ *
11
+ * The per-driver SQL is not mocked. A fake server that answers `CREATE DATABASE
12
+ * … TEMPLATE` however the test wants proves the test agrees with itself; the
13
+ * things worth checking about those paths — whether Postgres refuses while a
14
+ * session is open, whether `CREATE TABLE LIKE` carries a foreign key — are
15
+ * facts about real servers, so they are declared in `cloneSupport` and shown to
16
+ * the user instead of asserted here.
17
+ */
18
+
19
+ import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
20
+ import { Database } from 'bun:sqlite';
21
+ import fs from 'fs/promises';
22
+ import os from 'os';
23
+ import path from 'path';
24
+ import type { DbClientConnection } from '$shared/types/db-client';
25
+ import { canBranchFrom, cloneDatabase, cloneSupport, dropClonedDatabase } from './cloning';
26
+
27
+ let root: string;
28
+ let source: string;
29
+
30
+ function connection(overrides: Partial<DbClientConnection> = {}): DbClientConnection {
31
+ return {
32
+ id: 'conn-clone-test',
33
+ name: 'Local',
34
+ driver: 'sqlite',
35
+ host: null,
36
+ port: null,
37
+ username: null,
38
+ password: null,
39
+ database: source,
40
+ sslMode: 'disable',
41
+ sslCa: null,
42
+ ssh: {
43
+ enabled: false,
44
+ connectionId: null,
45
+ host: '',
46
+ port: 22,
47
+ username: '',
48
+ authMethod: 'password'
49
+ },
50
+ options: {},
51
+ color: null,
52
+ createdAt: '',
53
+ updatedAt: '',
54
+ lastUsedAt: null,
55
+ ...overrides
56
+ };
57
+ }
58
+
59
+ function rowsIn(file: string): number {
60
+ const db = new Database(file);
61
+ try {
62
+ const row = db.query('SELECT COUNT(*) AS n FROM notes').get() as { n: number };
63
+ return row.n;
64
+ } finally {
65
+ db.close();
66
+ }
67
+ }
68
+
69
+ beforeEach(async () => {
70
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'clopen-clone-'));
71
+ source = path.join(root, 'app.db');
72
+
73
+ const db = new Database(source);
74
+ db.run('CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)');
75
+ db.run("INSERT INTO notes (body) VALUES ('one'), ('two')");
76
+ db.close();
77
+ });
78
+
79
+ afterEach(async () => {
80
+ await fs.rm(root, { recursive: true, force: true });
81
+ });
82
+
83
+ describe('cloneSupport', () => {
84
+ it('says what a copy will not carry, per engine, before it runs', () => {
85
+ // The user decides whether a worktree's database is usable, and they can
86
+ // only decide that if the missing parts are named up front.
87
+ expect(cloneSupport('mysql').notice).toContain('foreign keys');
88
+ expect(cloneSupport('mssql').notice).toContain('indexes');
89
+ expect(cloneSupport('redis').notice).toContain('logical database');
90
+ // Postgres and SQLite copy whole, so there is nothing to apologise for.
91
+ expect(cloneSupport('postgres').notice).toBe(null);
92
+ expect(cloneSupport('sqlite').notice).toBe(null);
93
+ });
94
+ });
95
+
96
+ describe('canBranchFrom', () => {
97
+ it('refuses a connection that only exists inside an SSH tunnel', () => {
98
+ // The tunnel belongs to Clopen's process, so a copy made through one is
99
+ // reachable from Clopen and from nowhere the project runs.
100
+ expect(canBranchFrom(connection())).toBe(true);
101
+ expect(
102
+ canBranchFrom(
103
+ connection({
104
+ ssh: { enabled: true, connectionId: null, host: 'jump', port: 22, username: 'x', authMethod: 'key' }
105
+ })
106
+ )
107
+ ).toBe(false);
108
+ });
109
+ });
110
+
111
+ describe('cloneDatabase — sqlite', () => {
112
+ it('copies the file, data and all', async () => {
113
+ const target = path.join(root, 'copy.db');
114
+ const result = await cloneDatabase({
115
+ connection: connection(),
116
+ source,
117
+ target,
118
+ mode: 'schema-data'
119
+ });
120
+
121
+ expect(result.strategy).toBe('file-copy');
122
+ expect(result.notice).toBe(null);
123
+ expect(rowsIn(target)).toBe(2);
124
+ });
125
+
126
+ it('empties the COPY for schema-only and leaves the original alone', async () => {
127
+ // The direction matters more than the result: emptying the wrong file
128
+ // here would delete the user's development data.
129
+ const target = path.join(root, 'copy.db');
130
+ await cloneDatabase({ connection: connection(), source, target, mode: 'schema' });
131
+
132
+ expect(rowsIn(target)).toBe(0);
133
+ expect(rowsIn(source)).toBe(2);
134
+ });
135
+
136
+ it('writes an empty file for an empty copy', async () => {
137
+ const target = path.join(root, 'copy.db');
138
+ const result = await cloneDatabase({ connection: connection(), source, target, mode: 'empty' });
139
+
140
+ expect(result.strategy).toBe('empty');
141
+ expect((await fs.stat(target)).size).toBe(0);
142
+ });
143
+
144
+ it('takes the journal files with it when the copy is dropped', async () => {
145
+ // A `-wal` left behind is not debris: SQLite reads it on next open, so an
146
+ // orphaned one can resurrect a database that was supposed to be gone.
147
+ const target = path.join(root, 'copy.db');
148
+ await cloneDatabase({ connection: connection(), source, target, mode: 'schema-data' });
149
+ await fs.writeFile(`${target}-wal`, '');
150
+ await fs.writeFile(`${target}-shm`, '');
151
+
152
+ await dropClonedDatabase({ connection: connection(), database: target });
153
+
154
+ for (const suffix of ['', '-wal', '-shm']) {
155
+ await expect(fs.access(`${target}${suffix}`)).rejects.toThrow();
156
+ }
157
+ // The parent is untouched, which is the whole point of passing the copy's
158
+ // own name rather than the connection's.
159
+ expect(rowsIn(source)).toBe(2);
160
+ });
161
+ });