@myrialabs/clopen 0.4.38 → 0.4.40

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 (177) hide show
  1. package/backend/auth/permissions.ts +48 -0
  2. package/backend/chat/stream-manager.ts +1 -1
  3. package/backend/database/crypto/secret-columns.ts +9 -1
  4. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  5. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  6. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  7. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  8. package/backend/database/migrations/index.ts +28 -0
  9. package/backend/database/queries/db-client-connection-queries.ts +19 -0
  10. package/backend/database/queries/deploy-queries.ts +124 -0
  11. package/backend/database/queries/graph-queries.ts +291 -247
  12. package/backend/database/queries/index.ts +10 -0
  13. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  14. package/backend/database/queries/integration-queries.ts +34 -6
  15. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  16. package/backend/db-client/cloning.test.ts +161 -0
  17. package/backend/db-client/cloning.ts +672 -0
  18. package/backend/db-client/connection-url.test.ts +117 -0
  19. package/backend/db-client/connection-url.ts +126 -0
  20. package/backend/db-client/drivers/mongodb.ts +2 -14
  21. package/backend/db-client/drivers/mysql.ts +2 -8
  22. package/backend/db-client/drivers/postgres.ts +10 -13
  23. package/backend/db-client/drivers/redis.ts +2 -6
  24. package/backend/db-client/env/detect.ts +438 -0
  25. package/backend/db-client/env/diff.ts +94 -0
  26. package/backend/db-client/env/env.test.ts +574 -0
  27. package/backend/db-client/env/index.ts +15 -0
  28. package/backend/db-client/env/naming.ts +202 -0
  29. package/backend/db-client/env/service.ts +487 -0
  30. package/backend/db-client/integrations/index.ts +44 -0
  31. package/backend/db-client/integrations/links.ts +564 -0
  32. package/backend/db-client/integrations/projector.test.ts +280 -0
  33. package/backend/db-client/integrations/projector.ts +256 -0
  34. package/backend/db-client/integrations/supabase-service.ts +266 -0
  35. package/backend/db-client/providers/neon/adapter.ts +522 -0
  36. package/backend/db-client/providers/neon/api-types.ts +182 -0
  37. package/backend/db-client/providers/neon/client.ts +298 -0
  38. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  39. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  40. package/backend/db-client/providers/neon/list.test.ts +181 -0
  41. package/backend/db-client/providers/registry.ts +27 -0
  42. package/backend/db-client/providers/supabase/adapter.ts +523 -0
  43. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  44. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  45. package/backend/db-client/providers/supabase/client.ts +259 -0
  46. package/backend/db-client/providers/supabase/features.ts +502 -0
  47. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  48. package/backend/db-client/providers/supabase/local.ts +137 -0
  49. package/backend/db-client/providers/types.ts +194 -0
  50. package/backend/deployments/bindings.test.ts +43 -0
  51. package/backend/deployments/bindings.ts +216 -0
  52. package/backend/deployments/index.ts +53 -0
  53. package/backend/deployments/log-streams.ts +214 -0
  54. package/backend/deployments/prompts.ts +70 -0
  55. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  56. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  57. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  58. package/backend/deployments/providers/vercel/client.ts +203 -0
  59. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  60. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  61. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  62. package/backend/deployments/providers/vercel/types.ts +104 -0
  63. package/backend/deployments/registry.ts +27 -0
  64. package/backend/deployments/service.ts +458 -0
  65. package/backend/deployments/types.ts +278 -0
  66. package/backend/env-files/discovery.ts +48 -0
  67. package/backend/env-files/edit.ts +213 -0
  68. package/backend/env-files/env-files.test.ts +515 -0
  69. package/backend/env-files/git.ts +27 -0
  70. package/backend/env-files/index.ts +44 -0
  71. package/backend/env-files/keys.ts +69 -0
  72. package/backend/env-files/parse.ts +157 -0
  73. package/backend/env-files/write.ts +229 -0
  74. package/backend/index.ts +4 -0
  75. package/backend/integrations/health.ts +18 -4
  76. package/backend/integrations/projections/index.ts +0 -0
  77. package/backend/integrations/projections/mcp-projector.ts +7 -3
  78. package/backend/integrations/projections/types.ts +28 -9
  79. package/backend/integrations/registry/index.ts +8 -1
  80. package/backend/integrations/registry/providers/context7.ts +1 -0
  81. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  82. package/backend/integrations/registry/providers/github.ts +1 -0
  83. package/backend/integrations/registry/providers/neon.ts +55 -0
  84. package/backend/integrations/registry/providers/supabase.ts +62 -0
  85. package/backend/integrations/registry/providers/vercel.ts +47 -0
  86. package/backend/integrations/registry/types.ts +2 -0
  87. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  88. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  89. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  90. package/backend/memory/README.md +57 -34
  91. package/backend/memory/compose.test.ts +3 -3
  92. package/backend/memory/compose.ts +6 -9
  93. package/backend/memory/config.ts +0 -5
  94. package/backend/memory/consolidate.ts +1 -2
  95. package/backend/memory/context.test.ts +8 -54
  96. package/backend/memory/context.ts +19 -25
  97. package/backend/memory/extract/episodic.ts +10 -12
  98. package/backend/memory/extract/index.ts +23 -52
  99. package/backend/memory/extract/scheduler.ts +3 -6
  100. package/backend/memory/index.ts +6 -5
  101. package/backend/memory/invalidate.ts +36 -48
  102. package/backend/memory/layout.ts +319 -130
  103. package/backend/memory/retention.ts +12 -42
  104. package/backend/memory/retrieval.eval.test.ts +2 -2
  105. package/backend/memory/retrieval.test.ts +228 -183
  106. package/backend/memory/retrieval.ts +22 -21
  107. package/backend/memory/revise.test.ts +62 -116
  108. package/backend/memory/revise.ts +0 -1
  109. package/backend/memory/view.ts +8 -5
  110. package/backend/snapshot/helpers.ts +35 -41
  111. package/backend/snapshot/snapshot-service.ts +90 -0
  112. package/backend/snapshot/turn-changes.test.ts +163 -0
  113. package/backend/snapshot/turn-changes.ts +131 -0
  114. package/backend/work/start-work.ts +4 -0
  115. package/backend/worktrees/branching/engine.ts +557 -0
  116. package/backend/worktrees/branching/index.ts +56 -0
  117. package/backend/worktrees/branching/naming.test.ts +118 -0
  118. package/backend/worktrees/branching/naming.ts +97 -0
  119. package/backend/worktrees/branching/projector.test.ts +229 -0
  120. package/backend/worktrees/branching/projector.ts +139 -0
  121. package/backend/worktrees/branching/providers/neon.ts +220 -0
  122. package/backend/worktrees/branching/registry.ts +27 -0
  123. package/backend/worktrees/branching/service.ts +620 -0
  124. package/backend/worktrees/branching/suggest.test.ts +154 -0
  125. package/backend/worktrees/branching/suggest.ts +202 -0
  126. package/backend/worktrees/branching/types.ts +88 -0
  127. package/backend/worktrees/index.ts +7 -0
  128. package/backend/worktrees/service.ts +48 -1
  129. package/backend/ws/db-client/accounts.ts +225 -0
  130. package/backend/ws/db-client/connections.ts +34 -3
  131. package/backend/ws/db-client/context.ts +37 -0
  132. package/backend/ws/db-client/env.ts +142 -0
  133. package/backend/ws/db-client/index.ts +22 -1
  134. package/backend/ws/db-client/supabase.ts +188 -0
  135. package/backend/ws/deployments/actions.ts +360 -0
  136. package/backend/ws/deployments/context.ts +43 -0
  137. package/backend/ws/deployments/crud.ts +152 -0
  138. package/backend/ws/deployments/index.ts +15 -0
  139. package/backend/ws/deployments/schemas.ts +183 -0
  140. package/backend/ws/index.ts +6 -2
  141. package/backend/ws/memory/crud.ts +4 -16
  142. package/backend/ws/projects/index.ts +6 -1
  143. package/backend/ws/projects/info.ts +70 -6
  144. package/backend/ws/projects/overview.test.ts +108 -0
  145. package/backend/ws/projects/overview.ts +300 -0
  146. package/backend/ws/snapshot/changes.ts +279 -0
  147. package/backend/ws/snapshot/index.ts +4 -3
  148. package/backend/ws/system/device-info.ts +307 -76
  149. package/backend/ws/worktrees/branching.ts +212 -0
  150. package/backend/ws/worktrees/crud.ts +33 -7
  151. package/backend/ws/worktrees/index.ts +14 -0
  152. package/dist/assets/{index-DSHIANSy.js → index-D4igjF6e.js} +1 -1
  153. package/dist/assets/{index-CyH7fSbR.js → index-DONNwiXm.js} +1 -1
  154. package/dist/assets/main-BrfXH1bL.js +1205 -0
  155. package/dist/assets/main-CT1PygsW.css +1 -0
  156. package/dist/index.html +2 -2
  157. package/package.json +1 -1
  158. package/shared/constants/tool-icons.ts +13 -0
  159. package/shared/types/db-client/connection.ts +6 -0
  160. package/shared/types/db-client/env.ts +192 -0
  161. package/shared/types/db-client/index.ts +3 -0
  162. package/shared/types/db-client/integrations.ts +204 -0
  163. package/shared/types/db-client/supabase.ts +131 -0
  164. package/shared/types/deployments.ts +382 -0
  165. package/shared/types/integrations.ts +9 -0
  166. package/shared/types/memory.ts +34 -51
  167. package/shared/types/ui/components.ts +1 -1
  168. package/shared/types/worktree-branching.ts +315 -0
  169. package/shared/utils/diff-calculator.test.ts +89 -0
  170. package/shared/utils/diff-calculator.ts +30 -65
  171. package/shared/utils/logger.ts +2 -0
  172. package/backend/memory/extract/languages.ts +0 -176
  173. package/backend/memory/extract/structural.test.ts +0 -215
  174. package/backend/memory/extract/structural.ts +0 -364
  175. package/backend/ws/snapshot/content.ts +0 -85
  176. package/dist/assets/main-D2IOjftb.css +0 -1
  177. package/dist/assets/main-DM-tHKbW.js +0 -1152
@@ -0,0 +1,620 @@
1
+ /**
2
+ * Worktree databases — the lifecycle, the binding, and the leaks.
3
+ *
4
+ * FAIL SOFT IS THE RULE, and it is not a nicety. Creating a worktree is the
5
+ * expensive, visible thing the user asked for; giving it its own database is a
6
+ * convenience layered on top. A provider outage, an expired key, a branch
7
+ * limit, a `CREATE DATABASE` the server refuses — all must cost the convenience
8
+ * and never the worktree. So nothing in `attach()` throws, and what went wrong
9
+ * is reported alongside a worktree that was created successfully.
10
+ *
11
+ * The other half is the mirror image: deleting a worktree deletes its database,
12
+ * and when THAT fails the deletion still goes ahead. Refusing to delete a
13
+ * worktree because a third party is down would trap the user in a state they
14
+ * cannot leave. What the failure earns instead is a row that outlives its
15
+ * worktree and an entry in the orphan list, because a database that nothing
16
+ * knows about is the one outcome this feature must never produce silently.
17
+ *
18
+ * WHERE THE DATABASE COMES FROM is `engine.ts`'s question, not this file's.
19
+ * Everything here works the same whether Neon cut a copy-on-write branch or
20
+ * Clopen ran `CREATE DATABASE … TEMPLATE` against a Postgres on the user's
21
+ * laptop.
22
+ */
23
+
24
+ import {
25
+ integrationAccountQueries,
26
+ projectQueries,
27
+ worktreeBranchBindingQueries,
28
+ worktreeBranchQueries,
29
+ worktreeQueries,
30
+ parseWorktreeBranchConfig,
31
+ type WorktreeBranchRow
32
+ } from '$backend/database/queries';
33
+ import { reproject } from '$backend/integrations';
34
+ import { listDotenvFiles, writeWorktreeEnv } from '$backend/env-files';
35
+ import type { Worktree } from '$shared/types/database/schema';
36
+ import type {
37
+ BranchAttachResult,
38
+ BranchDataMode,
39
+ BranchParent,
40
+ BranchSourceKind,
41
+ BranchSourceOption,
42
+ UnknownRemoteBranch,
43
+ WorktreeBranchBindingInfo,
44
+ WorktreeBranchConfig,
45
+ WorktreeBranchInfo,
46
+ WorktreeBranchingState
47
+ } from '$shared/types/worktree-branching';
48
+ import { DEFAULT_WORKTREE_BRANCH_CONFIG } from '$shared/types/worktree-branching';
49
+ import { isSafeEnvFileName } from '$backend/env-files';
50
+ import { getBranchProvider, listBranchProviders } from './registry';
51
+ import { branchNameFor, isClopenBranchName } from './naming';
52
+ import {
53
+ connectionParents,
54
+ listBranchSources,
55
+ projectConnectionBranch,
56
+ releaseConnectionBranch,
57
+ resolveEngine,
58
+ resolveEngineForBranch,
59
+ type BranchEngine,
60
+ type BranchPrincipal
61
+ } from './engine';
62
+ import { suggestBranchSource, type BranchSuggestion } from './suggest';
63
+ import { debug } from '$shared/utils/logger';
64
+
65
+ function messageOf(error: unknown): string {
66
+ return error instanceof Error ? error.message : String(error);
67
+ }
68
+
69
+ /**
70
+ * The source, if this caller may use it.
71
+ *
72
+ * The authorisation for the whole feature, in one place. `listBranchSources`
73
+ * already answers "what may they use", so asking it rather than re-deriving the
74
+ * rule is what stops the two from drifting — and an id that is not in the list
75
+ * is refused with the same sentence whether it is someone else's connection or
76
+ * an account a member cannot reach.
77
+ */
78
+ function requireSource(
79
+ input: { sourceKind: BranchSourceKind; sourceId: string },
80
+ principal: BranchPrincipal
81
+ ): BranchSourceOption {
82
+ const source = listBranchSources(principal).find(
83
+ (entry) => entry.kind === input.sourceKind && entry.id === input.sourceId
84
+ );
85
+ if (!source) {
86
+ throw new Error('That database source is not available to you, so nothing was saved.');
87
+ }
88
+ return source;
89
+ }
90
+
91
+ /** The engine for one project, plus the settings it was bound with. */
92
+ function resolveBinding(projectId: string):
93
+ | { ok: true; engine: BranchEngine; config: WorktreeBranchConfig }
94
+ | { ok: false; reason: string | null } {
95
+ const binding = worktreeBranchBindingQueries.get(projectId);
96
+ const resolved = resolveEngine(binding);
97
+ if (!resolved.ok) return resolved;
98
+ return {
99
+ ok: true,
100
+ engine: resolved.engine,
101
+ config: parseWorktreeBranchConfig(binding!.config_json)
102
+ };
103
+ }
104
+
105
+ /**
106
+ * Project a freshly created or deleted branch into DB Client.
107
+ *
108
+ * Two routes because there are two ownerships. An account's branches are
109
+ * projected by the integrations layer, which owns the account's whole
110
+ * projection set; a connection's copy has no account, so its row is written
111
+ * directly. Being able to INSPECT a worktree's database must not depend on
112
+ * where the database came from.
113
+ */
114
+ function syncProjection(row: WorktreeBranchRow): void {
115
+ if (row.source_kind === 'account' && row.account_id) {
116
+ reproject(row.account_id);
117
+ return;
118
+ }
119
+ const worktree = row.worktree_id ? worktreeQueries.getById(row.worktree_id) : null;
120
+ if (worktree) projectConnectionBranch(row, worktree.name);
121
+ else releaseConnectionBranch(row);
122
+ }
123
+
124
+ function toBranchInfo(row: WorktreeBranchRow): WorktreeBranchInfo {
125
+ const engine = resolveEngineForBranch(row);
126
+ const worktree = row.worktree_id ? worktreeQueries.getById(row.worktree_id) : null;
127
+ const account = row.account_id ? integrationAccountQueries.getById(row.account_id) : null;
128
+
129
+ return {
130
+ id: row.id,
131
+ worktreeId: row.worktree_id,
132
+ worktreeName: worktree?.name ?? null,
133
+ sourceKind: row.source_kind,
134
+ provider: engine?.provider ?? account?.provider ?? 'unknown',
135
+ providerName: engine?.providerName ?? 'Unknown',
136
+ noun: engine?.noun ?? 'database',
137
+ sourceId: row.account_id ?? row.source_connection_id ?? '',
138
+ sourceLabel:
139
+ engine?.sourceLabel ??
140
+ (row.source_kind === 'account' ? 'Disconnected account' : 'Deleted connection'),
141
+ strategy: row.strategy,
142
+ notice: row.notice,
143
+ parentRef: row.parent_ref,
144
+ branchRef: row.branch_ref,
145
+ branchName: row.branch_name,
146
+ envVar: row.env_var,
147
+ envFile: row.env_file,
148
+ envStatus: row.env_status,
149
+ envDetail: row.env_detail,
150
+ status: row.status,
151
+ error: row.error,
152
+ connectionId: row.connection_id,
153
+ createdAt: row.created_at
154
+ };
155
+ }
156
+
157
+ export const worktreeBranching = {
158
+ /**
159
+ * Give a freshly created worktree a database of its own.
160
+ *
161
+ * Called from `createWorktree` AFTER the clone has succeeded, and the order
162
+ * matters: the clone is the expensive step that genuinely fails, so making
163
+ * the database first would leak one on every failed create.
164
+ *
165
+ * The row is written BEFORE the dotenv file is touched. A crash in between
166
+ * leaves a database that is tracked, listed and deletable; the reverse
167
+ * ordering leaves one that only the orphan sweep could ever find.
168
+ */
169
+ async attach(
170
+ worktree: Worktree,
171
+ options: { skip?: boolean; dataMode?: BranchDataMode } = {}
172
+ ): Promise<BranchAttachResult> {
173
+ const resolved = resolveBinding(worktree.project_id);
174
+ if (!resolved.ok) return { branch: null, error: resolved.reason };
175
+
176
+ // Three states, not two. `skip` is what the New Worktree dialog answered
177
+ // and it wins outright; UNDEFINED is a caller that never asked — Start
178
+ // Work creates a worktree with no dialog at all — and for those the
179
+ // project's own default decides, exactly as before.
180
+ if (options.skip === true) return { branch: null, error: null };
181
+ if (options.skip === undefined && !resolved.config.autoCreate) {
182
+ return { branch: null, error: null };
183
+ }
184
+
185
+ const project = projectQueries.getById(worktree.project_id);
186
+ const projectName = project?.name ?? worktree.project_id;
187
+ const name = branchNameFor({ projectName, worktreeSlug: worktree.slug });
188
+ const engine = resolved.engine;
189
+
190
+ let row: WorktreeBranchRow;
191
+ try {
192
+ const created = await engine.create({
193
+ name,
194
+ projectName,
195
+ worktreeSlug: worktree.slug,
196
+ pooled: resolved.config.pooled,
197
+ // The dialog's per-worktree answer wins over the project's default,
198
+ // because the size of THIS database is what the user just looked at.
199
+ dataMode: options.dataMode ?? resolved.config.dataMode
200
+ });
201
+
202
+ row = worktreeBranchQueries.create({
203
+ worktreeId: worktree.id,
204
+ projectId: worktree.project_id,
205
+ sourceKind: engine.sourceKind,
206
+ sourceId: engine.sourceId,
207
+ parentRef: engine.parentRef,
208
+ branchRef: created.ref,
209
+ branchName: created.name,
210
+ connection: created.connection,
211
+ envVar: resolved.config.envVar,
212
+ envFile: resolved.config.envFile,
213
+ strategy: created.strategy,
214
+ notice: created.notice
215
+ });
216
+ } catch (error) {
217
+ debug.warn('worktree', `Could not give ${worktree.name} its own database: ${messageOf(error)}`);
218
+ return { branch: null, error: messageOf(error) };
219
+ }
220
+
221
+ const connection = worktreeBranchQueries.connectionOf(row);
222
+ const written = await writeWorktreeEnv({
223
+ worktreeRoot: worktree.path,
224
+ fileName: resolved.config.envFile,
225
+ vars: { [resolved.config.envVar]: connection?.uri ?? '' },
226
+ // Only ever seen when the worktree's dotenv file did not already have
227
+ // the key, so it explains a line that would otherwise appear from
228
+ // nowhere. A file that DID have it gets the replacement plus the
229
+ // `# clopen:previous` comment, which says the same thing better.
230
+ note: `${engine.noun} of ${engine.parentName}, created by Clopen for this worktree.`
231
+ });
232
+ worktreeBranchQueries.setEnvResult(row.id, written.status, written.detail);
233
+
234
+ syncProjection(worktreeBranchQueries.getById(row.id)!);
235
+
236
+ const final = worktreeBranchQueries.getById(row.id);
237
+ return {
238
+ branch: final ? toBranchInfo(final) : null,
239
+ error: null,
240
+ notice: row.notice
241
+ };
242
+ },
243
+
244
+ /**
245
+ * Delete the database a worktree owns.
246
+ *
247
+ * Called from `removeWorktree` BEFORE the directory and the row go, so the
248
+ * database is still reachable through its own row. Never throws: the caller
249
+ * is mid-deletion and the user has already said what they want.
250
+ */
251
+ async detach(worktreeId: string): Promise<void> {
252
+ const row = worktreeBranchQueries.getForWorktree(worktreeId);
253
+ if (!row) return;
254
+
255
+ const engine = resolveEngineForBranch(row);
256
+ if (!engine) {
257
+ worktreeBranchQueries.markOrphaned(
258
+ row.id,
259
+ row.source_kind === 'account'
260
+ ? 'The account that created it is no longer connected, so it could not be deleted.'
261
+ : 'The connection it was copied from has been deleted, so it could not be removed.'
262
+ );
263
+ debug.warn('worktree', `${row.branch_name} outlived its source and is now an orphan`);
264
+ releaseConnectionBranch(row);
265
+ return;
266
+ }
267
+
268
+ // Released BEFORE the delete either way: the projected row points at a
269
+ // database that is about to stop existing, or at one that has stopped
270
+ // belonging to a live worktree. Both are reasons for it to go, and doing
271
+ // it once here avoids a second pass over a row that may no longer exist.
272
+ releaseConnectionBranch(row);
273
+
274
+ try {
275
+ await engine.delete(row.branch_ref);
276
+ worktreeBranchQueries.remove(row.id);
277
+ debug.log('worktree', `Deleted ${engine.providerName} ${engine.noun} ${row.branch_name}`);
278
+ } catch (error) {
279
+ // The row SURVIVES, which is the whole point: a database nothing knows
280
+ // about is the one failure this feature must never produce quietly. It
281
+ // keeps its refs and its connection, which is exactly what a retry from
282
+ // the orphan list needs.
283
+ worktreeBranchQueries.markOrphaned(row.id, messageOf(error));
284
+ debug.warn('worktree', `Could not delete ${row.branch_name}: ${messageOf(error)}`);
285
+ }
286
+
287
+ if (row.account_id) reproject(row.account_id);
288
+ },
289
+
290
+ /** Which database a worktree owns, for the manager's list. */
291
+ forWorktree(worktreeId: string): WorktreeBranchInfo | null {
292
+ const row = worktreeBranchQueries.getForWorktree(worktreeId);
293
+ return row ? toBranchInfo(row) : null;
294
+ },
295
+
296
+ /** Every database belonging to one project, live or orphaned. */
297
+ forProject(projectId: string): WorktreeBranchInfo[] {
298
+ return worktreeBranchQueries.getForProject(projectId).map(toBranchInfo);
299
+ },
300
+
301
+ /**
302
+ * Everything the setup dialog renders for one project.
303
+ *
304
+ * The dotenv file list is part of it because there is no default worth
305
+ * guessing: Next.js and Vite read `.env.local` in preference to `.env`, so a
306
+ * project with both has one right answer and picking the other produces a
307
+ * database nothing reads.
308
+ */
309
+ async state(projectId: string, principal: BranchPrincipal): Promise<WorktreeBranchingState> {
310
+ const project = projectQueries.getById(projectId);
311
+ const binding = worktreeBranchBindingQueries.get(projectId);
312
+ const resolved = resolveEngine(binding);
313
+ const engine = resolved.ok ? resolved.engine : null;
314
+
315
+ return {
316
+ providers: listBranchProviders().map((adapter) => adapter.info()),
317
+ sources: listBranchSources(principal),
318
+ binding:
319
+ binding && engine
320
+ ? {
321
+ projectId: binding.project_id,
322
+ sourceKind: engine.sourceKind,
323
+ sourceId: engine.sourceId,
324
+ provider: engine.provider,
325
+ providerName: engine.providerName,
326
+ sourceLabel: engine.sourceLabel,
327
+ parentRef: binding.parent_ref,
328
+ parentName: binding.parent_name,
329
+ isNative: engine.isNative,
330
+ config: parseWorktreeBranchConfig(binding.config_json),
331
+ updatedAt: binding.updated_at
332
+ }
333
+ : null,
334
+ envFiles: project ? await listDotenvFiles(project.path) : [],
335
+ branches: this.forProject(projectId)
336
+ };
337
+ },
338
+
339
+ /**
340
+ * What this project's worktrees should copy, worked out from its own files.
341
+ *
342
+ * Offered only when there is no binding yet: once the user has chosen, a
343
+ * guess arriving beside their choice would be noise.
344
+ */
345
+ async suggest(projectId: string): Promise<BranchSuggestion | null> {
346
+ if (worktreeBranchBindingQueries.get(projectId)) return null;
347
+ const project = projectQueries.getById(projectId);
348
+ if (!project) return null;
349
+ return suggestBranchSource(project.path);
350
+ },
351
+
352
+ /**
353
+ * The databases one source can copy from.
354
+ *
355
+ * Two shapes behind one route: a provider's own list of projects, or the
356
+ * databases on a server Clopen already has a connection to.
357
+ */
358
+ async parents(
359
+ input: { sourceKind: BranchSourceKind; sourceId: string },
360
+ principal: BranchPrincipal
361
+ ): Promise<BranchParent[]> {
362
+ requireSource(input, principal);
363
+ if (input.sourceKind === 'connection') {
364
+ const parents = await connectionParents(input.sourceId);
365
+ return parents.map((parent) => ({
366
+ ref: parent.ref,
367
+ name: parent.name,
368
+ detail: parent.detail,
369
+ group: null,
370
+ isReady: true
371
+ }));
372
+ }
373
+
374
+ const account = integrationAccountQueries.getById(input.sourceId);
375
+ if (!account) throw new Error('Integration account not found');
376
+ const adapter = getBranchProvider(account.provider);
377
+ if (!adapter) throw new Error(`"${account.provider}" cannot create database branches`);
378
+ return adapter.listParents({
379
+ accountId: account.id,
380
+ credentials: integrationAccountQueries.credentialsOf(account)
381
+ });
382
+ },
383
+
384
+ /**
385
+ * Point a project at a parent database.
386
+ *
387
+ * The env file is validated HERE rather than at write time, because a name
388
+ * this refuses would otherwise be accepted by the form and then fail once
389
+ * per worktree, far away from the field that caused it.
390
+ */
391
+ saveBinding(
392
+ input: {
393
+ projectId: string;
394
+ sourceKind: BranchSourceKind;
395
+ sourceId: string;
396
+ parentRef: string;
397
+ parentName: string;
398
+ config: Partial<WorktreeBranchConfig>;
399
+ },
400
+ principal: BranchPrincipal
401
+ ): WorktreeBranchBindingInfo {
402
+ const source = requireSource(input, principal);
403
+
404
+ const config: WorktreeBranchConfig = {
405
+ ...DEFAULT_WORKTREE_BRANCH_CONFIG,
406
+ ...input.config,
407
+ envVar: (input.config.envVar ?? DEFAULT_WORKTREE_BRANCH_CONFIG.envVar).trim(),
408
+ envFile: (input.config.envFile ?? DEFAULT_WORKTREE_BRANCH_CONFIG.envFile).trim()
409
+ };
410
+
411
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(config.envVar)) {
412
+ throw new Error(`"${config.envVar}" is not a valid environment variable name.`);
413
+ }
414
+ if (!isSafeEnvFileName(config.envFile)) {
415
+ throw new Error(`"${config.envFile}" is not a dotenv file in the project root.`);
416
+ }
417
+
418
+ worktreeBranchBindingQueries.upsert({
419
+ projectId: input.projectId,
420
+ sourceKind: input.sourceKind,
421
+ sourceId: input.sourceId,
422
+ parentRef: input.parentRef,
423
+ parentName: input.parentName.trim() || input.parentRef,
424
+ config
425
+ });
426
+
427
+ return {
428
+ projectId: input.projectId,
429
+ sourceKind: input.sourceKind,
430
+ sourceId: input.sourceId,
431
+ provider: source.provider,
432
+ providerName: source.providerName,
433
+ sourceLabel: source.label,
434
+ parentRef: input.parentRef,
435
+ parentName: input.parentName.trim() || input.parentRef,
436
+ isNative: source.isNative,
437
+ config,
438
+ updatedAt: new Date().toISOString()
439
+ };
440
+ },
441
+
442
+ /**
443
+ * Stop giving this project's worktrees their own database.
444
+ *
445
+ * Existing ones are LEFT ALONE. Removing the binding says "no more", not
446
+ * "destroy the ones my worktrees are using" — and the worktrees using them
447
+ * are still open. They go when their worktrees do, exactly as before.
448
+ */
449
+ clearBinding(projectId: string): void {
450
+ worktreeBranchBindingQueries.remove(projectId);
451
+ },
452
+
453
+ /** Every tracked database with no live worktree behind it. */
454
+ orphans(): WorktreeBranchInfo[] {
455
+ return worktreeBranchQueries.orphans().map(toBranchInfo);
456
+ },
457
+
458
+ /**
459
+ * Delete an orphan at its source and drop its row.
460
+ *
461
+ * The remote call goes FIRST here, which is the opposite of `dbLinks.remove`
462
+ * and for the opposite reason: there, a failed delete cost a link that could
463
+ * be recreated. Here the row IS the only record of a real database, so
464
+ * dropping it before the delete succeeded would turn a reportable orphan into
465
+ * an invisible one.
466
+ */
467
+ async deleteOrphan(branchId: string): Promise<void> {
468
+ const row = worktreeBranchQueries.getById(branchId);
469
+ if (!row) return;
470
+
471
+ const engine = resolveEngineForBranch(row);
472
+ if (!engine) {
473
+ throw new Error(
474
+ row.source_kind === 'account'
475
+ ? 'The account that created it is no longer connected, so it cannot be deleted from here.'
476
+ : 'The connection it was copied from has been deleted, so it cannot be removed from here.'
477
+ );
478
+ }
479
+
480
+ await engine.delete(row.branch_ref);
481
+ releaseConnectionBranch(row);
482
+ worktreeBranchQueries.remove(row.id);
483
+ if (row.account_id) reproject(row.account_id);
484
+ debug.log('worktree', `Deleted orphaned ${engine.noun} ${row.branch_name}`);
485
+ },
486
+
487
+ /**
488
+ * Drop the row and leave the database alone.
489
+ *
490
+ * Offered because Clopen is not the only place a database can be deleted:
491
+ * someone who cleaned it up in Neon's console or with `dropdb` is otherwise
492
+ * stuck with a permanent orphan entry whose delete fails with an error they
493
+ * cannot act on.
494
+ */
495
+ forgetOrphan(branchId: string): void {
496
+ const row = worktreeBranchQueries.getById(branchId);
497
+ if (!row) return;
498
+ releaseConnectionBranch(row);
499
+ worktreeBranchQueries.remove(row.id);
500
+ if (row.account_id) reproject(row.account_id);
501
+ },
502
+
503
+ /**
504
+ * Databases at the source that no row here accounts for.
505
+ *
506
+ * The half of leak detection a local table cannot do. A crash between "the
507
+ * database was created" and "the row was written" leaves one that nothing
508
+ * knows about, and the deterministic `clopen` prefix is the only evidence
509
+ * tying it back — which is exactly why `naming.ts` makes it deterministic.
510
+ *
511
+ * Reports only. Something that merely LOOKS like ours — someone could have
512
+ * named a database `clopen_…` by hand — is offered for deletion and never
513
+ * deleted automatically.
514
+ */
515
+ async unknownBranches(projectId: string): Promise<UnknownRemoteBranch[]> {
516
+ const resolved = resolveBinding(projectId);
517
+ if (!resolved.ok) return [];
518
+ const engine = resolved.engine;
519
+
520
+ // Keyed on the SOURCE, not the project. One Postgres server can hold the
521
+ // copies of several projects, and a set built from this project's rows
522
+ // would report every other project's database as a leak — and offer it for
523
+ // deletion.
524
+ const known = new Set(
525
+ (engine.sourceKind === 'account'
526
+ ? worktreeBranchQueries.getForAccount(engine.sourceId)
527
+ : worktreeBranchQueries.getForSourceConnection(engine.sourceId)
528
+ )
529
+ .filter((row) => row.parent_ref === engine.parentRef)
530
+ .map((row) => row.branch_ref)
531
+ );
532
+
533
+ let branches;
534
+ try {
535
+ branches = await engine.list();
536
+ } catch (error) {
537
+ // A sweep that cannot reach the source reports nothing rather than
538
+ // reporting "no orphans" — which would be a claim it never verified.
539
+ throw new Error(`Could not list databases on ${engine.sourceLabel}: ${messageOf(error)}`);
540
+ }
541
+
542
+ return branches
543
+ .filter((branch) => !known.has(branch.ref))
544
+ .map((branch) => ({
545
+ sourceKind: engine.sourceKind,
546
+ sourceId: engine.sourceId,
547
+ provider: engine.provider,
548
+ parentRef: engine.parentRef,
549
+ branch
550
+ }));
551
+ },
552
+
553
+ /** Delete something the sweep found but no row tracks. */
554
+ async deleteUnknown(input: {
555
+ sourceKind: BranchSourceKind;
556
+ sourceId: string;
557
+ parentRef: string;
558
+ branchRef: string;
559
+ }): Promise<void> {
560
+ const resolved = resolveEngine({
561
+ project_id: '',
562
+ source_kind: input.sourceKind,
563
+ account_id: input.sourceKind === 'account' ? input.sourceId : null,
564
+ connection_id: input.sourceKind === 'connection' ? input.sourceId : null,
565
+ parent_ref: input.parentRef,
566
+ parent_name: input.parentRef,
567
+ config_json: '{}',
568
+ created_at: '',
569
+ updated_at: ''
570
+ });
571
+ if (!resolved.ok) throw new Error(resolved.reason ?? 'That source is no longer available.');
572
+
573
+ await resolved.engine.delete(input.branchRef);
574
+ debug.log('worktree', `Deleted untracked database ${input.branchRef}`);
575
+ },
576
+
577
+ /**
578
+ * Put the connection string back into a worktree's dotenv file.
579
+ *
580
+ * The retry for `skipped-tracked` and `failed`, and the reason it is a button
581
+ * rather than an automatic repeat: the fix for a tracked file is a change to
582
+ * `.gitignore` that only the user can make, and retrying on a timer would
583
+ * just re-report the same refusal.
584
+ */
585
+ async rewriteEnv(branchId: string): Promise<WorktreeBranchInfo | null> {
586
+ const row = worktreeBranchQueries.getById(branchId);
587
+ if (!row?.worktree_id) return null;
588
+
589
+ const worktree = worktreeQueries.getById(row.worktree_id);
590
+ const connection = worktreeBranchQueries.connectionOf(row);
591
+ if (!worktree || !connection) return toBranchInfo(row);
592
+
593
+ const engine = resolveEngineForBranch(row);
594
+ const written = await writeWorktreeEnv({
595
+ worktreeRoot: worktree.path,
596
+ fileName: row.env_file,
597
+ vars: { [row.env_var]: connection.uri },
598
+ note: `${engine?.noun ?? 'database'} of ${row.parent_ref}, created by Clopen for this worktree.`
599
+ });
600
+ worktreeBranchQueries.setEnvResult(row.id, written.status, written.detail);
601
+
602
+ return toBranchInfo(worktreeBranchQueries.getById(row.id)!);
603
+ },
604
+
605
+ /** Health for the hub, delegated to whichever adapter owns the provider. */
606
+ async probe(accountId: string) {
607
+ const account = integrationAccountQueries.getById(accountId);
608
+ if (!account) return null;
609
+ const adapter = getBranchProvider(account.provider);
610
+ if (!adapter) return null;
611
+ if (!integrationAccountQueries.capabilitiesOf(account).includes('worktree-branching')) return null;
612
+ return adapter.probe({
613
+ accountId: account.id,
614
+ credentials: integrationAccountQueries.credentialsOf(account)
615
+ });
616
+ }
617
+ };
618
+
619
+ /** Re-exported so the worktree manager can still recognise our own names. */
620
+ export { isClopenBranchName };