@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,557 @@
1
+ /**
2
+ * Where a worktree's database comes from, behind one interface.
3
+ *
4
+ * The feature used to be spelled "ask the provider to cut a branch", which made
5
+ * it a Neon feature by construction: a database with no vendor API behind it
6
+ * had no way in at all. What a worktree actually needs is *a database of its
7
+ * own*, and branching is one of several ways to get one — so the provider
8
+ * adapter moves down a level and this interface takes its place.
9
+ *
10
+ * TWO IMPLEMENTATIONS, and the general one is not the vendor one:
11
+ *
12
+ * - **account** — a provider that branches natively. Neon cuts copy-on-write
13
+ * in its own infrastructure, which nothing here can match on speed or cost.
14
+ * Delegates to `BranchProviderAdapter` unchanged.
15
+ * - **connection** — any database DB Client can already reach. A sibling
16
+ * database on the same server, made with that engine's own primitives (see
17
+ * `db-client/cloning.ts`). This is the one that makes the feature true of
18
+ * local Postgres, of MySQL, of SQLite and of Supabase.
19
+ *
20
+ * Everything downstream — the rows, the dotenv write, the orphan sweep, the
21
+ * projected connection — is written against this interface and no longer knows
22
+ * which kind answered.
23
+ */
24
+
25
+ import path from 'path';
26
+ import {
27
+ dbClientConnectionQueries,
28
+ integrationAccountQueries,
29
+ worktreeBranchQueries,
30
+ type IntegrationAccountRow,
31
+ type WorktreeBranchBindingRow,
32
+ type WorktreeBranchRow
33
+ } from '$backend/database/queries';
34
+ import { getProvider } from '$backend/integrations';
35
+ import { buildConnectionUrl } from '$backend/db-client/connection-url';
36
+ import {
37
+ canBranchFrom,
38
+ cloneDatabase,
39
+ cloneSupport,
40
+ dropClonedDatabase,
41
+ listDatabaseNames,
42
+ type DbCloneMode
43
+ } from '$backend/db-client/cloning';
44
+ import type { DbClientConnection, DbDriver } from '$shared/types/db-client';
45
+ import type {
46
+ BranchConnection,
47
+ BranchDataMode,
48
+ BranchSourceKind,
49
+ BranchSourceOption,
50
+ RemoteBranch
51
+ } from '$shared/types/worktree-branching';
52
+ import { getBranchProvider, listBranchProviders } from './registry';
53
+ import { branchDatabaseNameFor, isClopenBranchName, isClopenDatabaseName } from './naming';
54
+ import { debug } from '$shared/utils/logger';
55
+
56
+ /** What a create actually produced, including how. */
57
+ export interface CreatedBranchResult {
58
+ ref: string;
59
+ name: string;
60
+ connection: BranchConnection;
61
+ /** `template`, `server-copy`, `row-copy`, `file-copy`, … or null for native. */
62
+ strategy: string | null;
63
+ /** One sentence naming what the copy did not carry, or null. */
64
+ notice: string | null;
65
+ }
66
+
67
+ export interface BranchEngine {
68
+ sourceKind: BranchSourceKind;
69
+ sourceId: string;
70
+ sourceLabel: string;
71
+ /** Integration provider id for an account, driver id for a connection. */
72
+ provider: string;
73
+ providerName: string;
74
+ noun: string;
75
+ isNative: boolean;
76
+ parentRef: string;
77
+ parentName: string;
78
+ /** What a copy here does not carry, known before it runs. */
79
+ notice: string | null;
80
+
81
+ create(input: {
82
+ /** The deterministic name from `naming.ts`. */
83
+ name: string;
84
+ worktreeSlug: string;
85
+ projectName: string;
86
+ pooled: boolean;
87
+ dataMode: BranchDataMode;
88
+ }): Promise<CreatedBranchResult>;
89
+
90
+ delete(branchRef: string): Promise<void>;
91
+
92
+ /** Everything at the source that looks like ours, for the orphan sweep. */
93
+ list(): Promise<RemoteBranch[]>;
94
+ }
95
+
96
+ function messageOf(error: unknown): string {
97
+ return error instanceof Error ? error.message : String(error);
98
+ }
99
+
100
+ /* ----------------------------------------------------------------- account */
101
+
102
+ function accountEngine(input: {
103
+ account: IntegrationAccountRow;
104
+ parentRef: string;
105
+ parentName: string;
106
+ }): BranchEngine | null {
107
+ const adapter = getBranchProvider(input.account.provider);
108
+ if (!adapter) return null;
109
+
110
+ const context = {
111
+ accountId: input.account.id,
112
+ credentials: integrationAccountQueries.credentialsOf(input.account)
113
+ };
114
+ const info = adapter.info();
115
+
116
+ return {
117
+ sourceKind: 'account',
118
+ sourceId: input.account.id,
119
+ sourceLabel: input.account.label,
120
+ provider: input.account.provider,
121
+ providerName: getProvider(input.account.provider)?.name ?? input.account.provider,
122
+ noun: info.noun,
123
+ isNative: true,
124
+ parentRef: input.parentRef,
125
+ parentName: input.parentName,
126
+ // A native branch is the parent, atomically. There is nothing it fails to
127
+ // bring across, so there is nothing to warn about.
128
+ notice: null,
129
+
130
+ async create(options) {
131
+ const created = await adapter.createBranch(context, {
132
+ parentRef: input.parentRef,
133
+ name: options.name,
134
+ pooled: options.pooled
135
+ });
136
+ return {
137
+ ref: created.ref,
138
+ name: created.name,
139
+ connection: created.connection,
140
+ strategy: 'native',
141
+ notice: null
142
+ };
143
+ },
144
+
145
+ async delete(branchRef) {
146
+ await adapter.deleteBranch(context, { parentRef: input.parentRef, branchRef });
147
+ },
148
+
149
+ async list() {
150
+ const branches = await adapter.listBranches(context, input.parentRef);
151
+ return branches.filter((branch) => !branch.isDefault && isClopenBranchName(branch.name));
152
+ }
153
+ };
154
+ }
155
+
156
+ /* -------------------------------------------------------------- connection */
157
+
158
+ /** What each driver calls the thing a worktree gets. */
159
+ function nounFor(driver: DbDriver): string {
160
+ if (driver === 'redis') return 'database';
161
+ if (driver === 'sqlite') return 'copy';
162
+ return 'copy';
163
+ }
164
+
165
+ const DRIVER_NAMES: Record<DbDriver, string> = {
166
+ postgres: 'PostgreSQL',
167
+ mysql: 'MySQL',
168
+ sqlite: 'SQLite',
169
+ mongodb: 'MongoDB',
170
+ redis: 'Redis',
171
+ mssql: 'SQL Server'
172
+ };
173
+
174
+ /** Redis has sixteen numbered databases and no way to make a seventeenth. */
175
+ const REDIS_DATABASES = 16;
176
+
177
+ /**
178
+ * The name the copy will have.
179
+ *
180
+ * Three shapes, because "a database" means three different things. SQLite's is
181
+ * a FILE, so the copy is a path beside the original — and putting it beside
182
+ * rather than inside the worktree is deliberate: a worktree is a disposable
183
+ * file copy, and a database inside one would be copied again by the next
184
+ * "Apply to Main".
185
+ */
186
+ function targetNameFor(input: {
187
+ driver: DbDriver;
188
+ parentRef: string;
189
+ projectName: string;
190
+ worktreeSlug: string;
191
+ taken: Set<string>;
192
+ }): string {
193
+ const base = branchDatabaseNameFor({
194
+ projectName: input.projectName,
195
+ worktreeSlug: input.worktreeSlug
196
+ });
197
+
198
+ if (input.driver === 'sqlite') {
199
+ const directory = path.dirname(input.parentRef);
200
+ const extension = path.extname(input.parentRef) || '.db';
201
+ return path.join(directory, `${base}${extension}`);
202
+ }
203
+
204
+ if (input.driver === 'redis') {
205
+ // An index, not a name — so the only question is which one is free, and
206
+ // the parent's own index is never a candidate.
207
+ const parent = Number(input.parentRef) || 0;
208
+ for (let index = 0; index < REDIS_DATABASES; index += 1) {
209
+ if (index === parent) continue;
210
+ if (!input.taken.has(String(index))) return String(index);
211
+ }
212
+ throw new Error(
213
+ `Every Redis database on this server is already in use, so there is none left for this worktree.`
214
+ );
215
+ }
216
+
217
+ return base;
218
+ }
219
+
220
+ /** The branch's own connection, derived from the parent's with a new database. */
221
+ function connectionFor(parent: DbClientConnection, database: string): BranchConnection {
222
+ const target: DbClientConnection = { ...parent, database };
223
+ return {
224
+ uri: buildConnectionUrl(target),
225
+ host: parent.host ?? '',
226
+ port: parent.port ?? 0,
227
+ username: parent.username ?? '',
228
+ password: parent.password ?? '',
229
+ database,
230
+ sslMode: parent.sslMode
231
+ };
232
+ }
233
+
234
+ function connectionEngine(input: {
235
+ connection: DbClientConnection;
236
+ parentRef: string;
237
+ parentName: string;
238
+ }): BranchEngine {
239
+ const driver = input.connection.driver;
240
+ const support = cloneSupport(driver);
241
+
242
+ return {
243
+ sourceKind: 'connection',
244
+ sourceId: input.connection.id,
245
+ sourceLabel: input.connection.name,
246
+ provider: driver,
247
+ providerName: DRIVER_NAMES[driver],
248
+ noun: nounFor(driver),
249
+ isNative: false,
250
+ parentRef: input.parentRef,
251
+ parentName: input.parentName,
252
+ notice: support.notice,
253
+
254
+ async create(options) {
255
+ // Which names are already spoken for, so Redis can find a free index
256
+ // and every other driver can fail loudly rather than colliding.
257
+ const taken = new Set(
258
+ worktreeBranchQueries
259
+ .getForSourceConnection(input.connection.id)
260
+ .map((row) => row.branch_ref)
261
+ );
262
+
263
+ const target = targetNameFor({
264
+ driver,
265
+ parentRef: input.parentRef,
266
+ projectName: options.projectName,
267
+ worktreeSlug: options.worktreeSlug,
268
+ taken
269
+ });
270
+
271
+ const result = await cloneDatabase({
272
+ connection: input.connection,
273
+ source: input.parentRef,
274
+ target,
275
+ mode: options.dataMode as DbCloneMode
276
+ });
277
+
278
+ return {
279
+ ref: result.database,
280
+ name: result.database,
281
+ connection: connectionFor(input.connection, result.database),
282
+ strategy: result.strategy,
283
+ notice: result.notice
284
+ };
285
+ },
286
+
287
+ async delete(branchRef) {
288
+ await dropClonedDatabase({ connection: input.connection, database: branchRef });
289
+ },
290
+
291
+ async list() {
292
+ if (driver === 'sqlite' || driver === 'redis') {
293
+ // Neither has a list worth sweeping: SQLite's databases are files in
294
+ // a directory Clopen does not own, and Redis's are sixteen fixed
295
+ // indexes that always exist. Reporting those as leaks would report
296
+ // the server's own shape as a problem.
297
+ return [];
298
+ }
299
+ const names = await listDatabaseNames(input.connection.id);
300
+ return names.filter(isClopenDatabaseName).map((name) => ({
301
+ ref: name,
302
+ name,
303
+ createdAt: null,
304
+ isDefault: false,
305
+ sizeBytes: null
306
+ }));
307
+ }
308
+ };
309
+ }
310
+
311
+ /* ---------------------------------------------------------------- resolving */
312
+
313
+ export type EngineResolution =
314
+ | { ok: true; engine: BranchEngine }
315
+ | { ok: false; reason: string | null };
316
+
317
+ /**
318
+ * The engine behind one binding, or a sentence saying why there is none.
319
+ *
320
+ * Returns a reason rather than throwing, because every caller on the worktree
321
+ * create path has to keep going regardless — and a reason a user can read beats
322
+ * a stack trace in a log nobody opens.
323
+ */
324
+ export function resolveEngine(binding: WorktreeBranchBindingRow | null): EngineResolution {
325
+ // No binding at all is not a problem — it is the default state of every
326
+ // project — so there is nothing to report.
327
+ if (!binding) return { ok: false, reason: null };
328
+
329
+ if (binding.source_kind === 'connection') {
330
+ const connection = binding.connection_id
331
+ ? dbClientConnectionQueries.get(binding.connection_id)
332
+ : null;
333
+ if (!connection) {
334
+ return {
335
+ ok: false,
336
+ reason: 'The connection this project copies its database from has been deleted.'
337
+ };
338
+ }
339
+ if (!canBranchFrom(connection)) {
340
+ return {
341
+ ok: false,
342
+ reason: `Clopen cannot copy a database over an SSH tunnel, so "${connection.name}" cannot give a worktree one.`
343
+ };
344
+ }
345
+ return {
346
+ ok: true,
347
+ engine: connectionEngine({
348
+ connection,
349
+ parentRef: binding.parent_ref,
350
+ parentName: binding.parent_name
351
+ })
352
+ };
353
+ }
354
+
355
+ const account = binding.account_id
356
+ ? integrationAccountQueries.getById(binding.account_id)
357
+ : null;
358
+ if (!account) {
359
+ return { ok: false, reason: 'The account this project branched from has been disconnected.' };
360
+ }
361
+ if (account.is_enabled !== 1) {
362
+ return { ok: false, reason: `The ${account.label} account is switched off, so no branch was created.` };
363
+ }
364
+ if (!integrationAccountQueries.capabilitiesOf(account).includes('worktree-branching')) {
365
+ return { ok: false, reason: `Worktree branching is switched off for the ${account.label} account.` };
366
+ }
367
+
368
+ const engine = accountEngine({
369
+ account,
370
+ parentRef: binding.parent_ref,
371
+ parentName: binding.parent_name
372
+ });
373
+ if (!engine) {
374
+ return { ok: false, reason: `"${account.provider}" cannot create database branches.` };
375
+ }
376
+ return { ok: true, engine };
377
+ }
378
+
379
+ /** The engine for a branch ROW, which may outlive its binding. */
380
+ export function resolveEngineForBranch(row: WorktreeBranchRow): BranchEngine | null {
381
+ if (row.source_kind === 'connection') {
382
+ const connection = row.source_connection_id
383
+ ? dbClientConnectionQueries.get(row.source_connection_id)
384
+ : null;
385
+ if (!connection) return null;
386
+ return connectionEngine({
387
+ connection,
388
+ parentRef: row.parent_ref,
389
+ parentName: row.parent_ref
390
+ });
391
+ }
392
+
393
+ const account = row.account_id ? integrationAccountQueries.getById(row.account_id) : null;
394
+ if (!account) return null;
395
+ return accountEngine({ account, parentRef: row.parent_ref, parentName: row.parent_ref });
396
+ }
397
+
398
+ /* ------------------------------------------------------------------ sources */
399
+
400
+ /** Who is asking, so the list only offers what they may actually use. */
401
+ export interface BranchPrincipal {
402
+ userId: string;
403
+ isAdmin: boolean;
404
+ }
405
+
406
+ /**
407
+ * Everywhere a worktree database could come from.
408
+ *
409
+ * Accounts and connections in ONE list, ordered native-first, because the user
410
+ * is choosing which database and not which mechanism. The mechanism is carried
411
+ * on each row as `isNative` and `notice` so the dialog can say what it costs.
412
+ *
413
+ * SCOPED TO THE CALLER, and the two halves scope differently. An integration
414
+ * account belongs to the INSTALL and spends its quota, so it is admin-only —
415
+ * the same rule `db-client:link` follows. A DB Client connection belongs to
416
+ * whoever saved it, so a member sees their own and an admin sees every one;
417
+ * anything else would let a member copy a database from a credential they
418
+ * cannot otherwise reach.
419
+ */
420
+ export function listBranchSources(principal: BranchPrincipal): BranchSourceOption[] {
421
+ const sources: BranchSourceOption[] = [];
422
+
423
+ for (const adapter of principal.isAdmin ? listBranchProviders() : []) {
424
+ for (const account of integrationAccountQueries.getByProvider(adapter.provider)) {
425
+ if (account.is_enabled !== 1) continue;
426
+ if (!integrationAccountQueries.capabilitiesOf(account).includes('worktree-branching')) continue;
427
+ sources.push({
428
+ kind: 'account',
429
+ id: account.id,
430
+ label: account.label,
431
+ provider: account.provider,
432
+ providerName: getProvider(account.provider)?.name ?? account.provider,
433
+ noun: adapter.info().noun,
434
+ isNative: true,
435
+ notice: null,
436
+ status: account.status
437
+ });
438
+ }
439
+ }
440
+
441
+ for (const connection of dbClientConnectionQueries.listForUser(principal.userId, principal.isAdmin)) {
442
+ if (!canBranchFrom(connection)) continue;
443
+ // A connection that a branch already projected is not a parent: copying a
444
+ // worktree's own copy would nest one disposable database inside another.
445
+ if (connection.options?.worktreeBranch) continue;
446
+ sources.push({
447
+ kind: 'connection',
448
+ id: connection.id,
449
+ label: connection.name,
450
+ provider: connection.driver,
451
+ providerName: DRIVER_NAMES[connection.driver],
452
+ noun: nounFor(connection.driver),
453
+ isNative: false,
454
+ notice: cloneSupport(connection.driver).notice,
455
+ status: 'ok'
456
+ });
457
+ }
458
+
459
+ return sources;
460
+ }
461
+
462
+ /**
463
+ * The databases one connection could copy from.
464
+ *
465
+ * SQLite answers with its own file and Redis with its numbered indexes, because
466
+ * for those two "which database" has an answer that needs no round trip — and
467
+ * a driver that cannot list at all still has the one it is pointed at.
468
+ */
469
+ export async function connectionParents(connectionId: string): Promise<
470
+ { ref: string; name: string; detail: string | null }[]
471
+ > {
472
+ const connection = dbClientConnectionQueries.get(connectionId);
473
+ if (!connection) throw new Error('db-client connection not found');
474
+
475
+ if (connection.driver === 'sqlite') {
476
+ const file = connection.database ?? '';
477
+ return file ? [{ ref: file, name: path.basename(file), detail: file }] : [];
478
+ }
479
+
480
+ if (connection.driver === 'redis') {
481
+ return Array.from({ length: REDIS_DATABASES }, (_, index) => ({
482
+ ref: String(index),
483
+ name: `Database ${index}`,
484
+ detail: null
485
+ }));
486
+ }
487
+
488
+ try {
489
+ const names = await listDatabaseNames(connectionId);
490
+ const usable = names.filter((name) => !isClopenDatabaseName(name));
491
+ if (usable.length > 0) {
492
+ return usable.map((name) => ({ ref: name, name, detail: null }));
493
+ }
494
+ } catch (error) {
495
+ debug.warn('worktree', `Could not list databases on ${connection.name}: ${messageOf(error)}`);
496
+ }
497
+
498
+ // Falling back to the one the connection names beats an empty picker: it is
499
+ // the database the user chose when they made the connection.
500
+ return connection.database
501
+ ? [{ ref: connection.database, name: connection.database, detail: null }]
502
+ : [];
503
+ }
504
+
505
+ /* --------------------------------------------------------------- projection */
506
+
507
+ /**
508
+ * Give a connection-sourced copy its own DB Client row.
509
+ *
510
+ * The account projector cannot do this one: it runs per integration account,
511
+ * and a copy of a local Postgres has none. Written here directly instead, so
512
+ * that being able to INSPECT a worktree's database does not depend on where the
513
+ * database came from — which was the point of the whole refactor.
514
+ */
515
+ export function projectConnectionBranch(row: WorktreeBranchRow, worktreeName: string): void {
516
+ if (row.source_kind !== 'connection') return;
517
+ const parent = row.source_connection_id
518
+ ? dbClientConnectionQueries.get(row.source_connection_id)
519
+ : null;
520
+ const connection = worktreeBranchQueries.connectionOf(row);
521
+ if (!parent || !connection) return;
522
+
523
+ const fields = {
524
+ driver: parent.driver,
525
+ host: parent.host ?? undefined,
526
+ port: parent.port ?? undefined,
527
+ username: parent.username ?? undefined,
528
+ database: connection.database,
529
+ sslMode: parent.sslMode,
530
+ options: {
531
+ ...parent.options,
532
+ worktreeBranch: { branchId: row.id, worktreeId: row.worktree_id }
533
+ }
534
+ };
535
+ const name = `${worktreeName} (${nounFor(parent.driver)})`;
536
+
537
+ const existing = row.connection_id ? dbClientConnectionQueries.get(row.connection_id) : null;
538
+ if (existing) {
539
+ dbClientConnectionQueries.update(existing.id, { name, ...fields });
540
+ dbClientConnectionQueries.replacePassword(existing.id, connection.password || null);
541
+ return;
542
+ }
543
+
544
+ const created = dbClientConnectionQueries.create({
545
+ name,
546
+ password: connection.password,
547
+ ...fields
548
+ });
549
+ worktreeBranchQueries.setConnectionId(row.id, created.id);
550
+ }
551
+
552
+ /** Take that row away again. Silent when there was never one. */
553
+ export function releaseConnectionBranch(row: WorktreeBranchRow): void {
554
+ if (row.source_kind !== 'connection' || !row.connection_id) return;
555
+ dbClientConnectionQueries.delete(row.connection_id);
556
+ worktreeBranchQueries.setConnectionId(row.id, null);
557
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Worktree database branching.
3
+ *
4
+ * Importing this module is what wires the `worktree-branching` capability up,
5
+ * so it must be imported for its side effects before any worktree is created —
6
+ * `backend/ws/worktrees/` does that, the same way the Deployments router is
7
+ * what makes Vercel exist.
8
+ *
9
+ * engine.ts WHERE a worktree's database comes from, behind one interface
10
+ * registry.ts provider id → adapter, for the providers that branch natively
11
+ * naming.ts the deterministic names leak detection depends on
12
+ * suggest.ts the binding a project's own `.env` already implies
13
+ * projector.ts an account's branches → `db_client_connections` rows
14
+ * service.ts attach, detach, the binding, and the orphans
15
+ *
16
+ * NOT A NEON FEATURE, despite Neon being the only provider with a `registry.ts`
17
+ * entry. A worktree needs a database of its own, and branching is one way to
18
+ * get one: `engine.ts` also copies any database DB Client can reach, using that
19
+ * engine's own primitives (`$backend/db-client/cloning.ts`). Local Postgres,
20
+ * MySQL, SQLite and Supabase all work through that path.
21
+ *
22
+ * The dotenv write lives in `$backend/env-files`, shared with DB Client's
23
+ * "apply to .env": both features put a connection string into a project's
24
+ * environment, and one implementation of the managed block, the tracked-file
25
+ * refusal and the precedence order is the only way the two cannot disagree.
26
+ *
27
+ * Like DB Client and unlike Issues and Deployments this registers a PROJECTOR
28
+ * as well as an adapter, because a branch is a real database worth looking at:
29
+ * without the projection a user could see that their agent had run migrations
30
+ * and have no way to inspect what those migrations did.
31
+ */
32
+
33
+ import { registerAccountProbe, registerProjector } from '$backend/integrations';
34
+ import { registerBranchProvider } from './registry';
35
+ import { neonBranchAdapter } from './providers/neon';
36
+ import { worktreeBranchProjector } from './projector';
37
+ import { worktreeBranching } from './service';
38
+
39
+ registerProjector(worktreeBranchProjector);
40
+ registerBranchProvider(neonBranchAdapter);
41
+
42
+ // Neon declares BOTH `database` and `worktree-branching`, so two surfaces
43
+ // register a probe for the same provider. `registerAccountProbe` keeps a LIST
44
+ // per provider for exactly this case: each probe answers null when the
45
+ // capability it speaks for is switched off, and the first real answer wins. A
46
+ // map would have let whichever module loaded last replace the other's silently.
47
+ registerAccountProbe('neon', (accountId) => worktreeBranching.probe(accountId));
48
+
49
+ export { worktreeBranching } from './service';
50
+ export { registerBranchProvider, getBranchProvider, listBranchProviders } from './registry';
51
+ export { worktreeBranchProjector } from './projector';
52
+ export { branchDatabaseNameFor, branchNameFor, isClopenBranchName, isClopenDatabaseName, slugifyForBranch } from './naming';
53
+ export { listBranchSources, resolveEngine, resolveEngineForBranch } from './engine';
54
+ export type { BranchEngine, BranchPrincipal } from './engine';
55
+ export { suggestBranchSource } from './suggest';
56
+ export type { BranchProviderAdapter, BranchProviderContext } from './types';