@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,44 @@
1
+ /**
2
+ * Account-backed connections in DB Client.
3
+ *
4
+ * Importing this module is what wires the `database` capability up, so it must
5
+ * be imported for its side effects before any account is connected —
6
+ * `backend/ws/db-client/` does that, the same way the Deployments router is
7
+ * what makes Vercel exist.
8
+ *
9
+ * projector.ts link → `db_client_connections` row
10
+ * links.ts choosing which remote databases to bring in
11
+ * supabase-service.ts the Supabase surface, resolved against a connection
12
+ *
13
+ * Unlike Issues and Deployments this registers a PROJECTOR rather than an
14
+ * adapter, because DB Client owns a table. A connection is a real row that the
15
+ * drivers, the schema tree and the query console read without knowing where it
16
+ * came from; only the badge and the read-only form know, and they learn it from
17
+ * `integration_projections` rather than from a column on the connection.
18
+ */
19
+
20
+ import { registerAccountProbe, registerProjector } from '$backend/integrations';
21
+ import { registerDbProvider } from '../providers/registry';
22
+ import { neonDbAdapter } from '../providers/neon/adapter';
23
+ import { supabaseDbAdapter } from '../providers/supabase/adapter';
24
+ import { dbConnectionProjector } from './projector';
25
+ import { dbLinks } from './links';
26
+
27
+ registerProjector(dbConnectionProjector);
28
+ registerDbProvider(supabaseDbAdapter);
29
+ registerDbProvider(neonDbAdapter);
30
+
31
+ // Health for an account whose capability projects no MCP row. Without this the
32
+ // hub reports "Nothing to probe yet" forever for a Supabase account — the same
33
+ // gap the Issues surface found and the Deployments surface closed the same way.
34
+ //
35
+ // `dbLinks.probe` answers null when an account has the `database` capability
36
+ // switched off, which is what lets Neon register a SECOND probe from the
37
+ // worktree manager without the two overwriting each other.
38
+ registerAccountProbe('supabase', (accountId) => dbLinks.probe(accountId));
39
+ registerAccountProbe('neon', (accountId) => dbLinks.probe(accountId));
40
+
41
+ export { dbLinks } from './links';
42
+ export { dbConnectionProjector } from './projector';
43
+ export { resolveSupabaseScope, supabaseSurface } from './supabase-service';
44
+ export type { SupabaseScope } from './supabase-service';
@@ -0,0 +1,564 @@
1
+ /**
2
+ * Linking a remote database into DB Client.
3
+ *
4
+ * The asynchronous half of the projection: this is where a provider is asked
5
+ * where a database answers, and the answer is stored on the link so the
6
+ * synchronous projector never has to ask again. Every mutation here ends in
7
+ * `reproject()`, which is what keeps the connection list derived rather than
8
+ * merely created once and then drifting.
9
+ */
10
+
11
+ import {
12
+ dbClientConnectionQueries,
13
+ integrationAccountQueries,
14
+ integrationDbLinkQueries,
15
+ integrationProjectionQueries,
16
+ type IntegrationAccountRow,
17
+ type IntegrationDbLinkRow
18
+ } from '$backend/database/queries';
19
+ import { getProvider, reproject } from '$backend/integrations';
20
+ import type {
21
+ DbAccountLinkInfo,
22
+ DbClientManagedBy,
23
+ DbProviderCreateOptions,
24
+ DbProviderInfo,
25
+ DbRemoteDatabase
26
+ } from '$shared/types/db-client';
27
+ import { connectionManager } from '../connection-manager';
28
+ import { getDbProvider, listDbProviders } from '../providers/registry';
29
+ import type { DbProviderAdapter, DbProviderContext, DbProviderEndpoint } from '../providers/types';
30
+ import { connectionIdOf } from './projector';
31
+ import { debug } from '$shared/utils/logger';
32
+
33
+ function requireAccount(accountId: string): IntegrationAccountRow {
34
+ const account = integrationAccountQueries.getById(accountId);
35
+ if (!account) throw new Error('Integration account not found');
36
+ return account;
37
+ }
38
+
39
+ function requireAdapter(provider: string): DbProviderAdapter {
40
+ const adapter = getDbProvider(provider);
41
+ if (!adapter) throw new Error(`"${provider}" is not a database provider`);
42
+ return adapter;
43
+ }
44
+
45
+ function contextFor(account: IntegrationAccountRow): DbProviderContext {
46
+ return {
47
+ accountId: account.id,
48
+ credentials: integrationAccountQueries.credentialsOf(account)
49
+ };
50
+ }
51
+
52
+ /**
53
+ * Re-project, then drop the live adapters for the rows it touched.
54
+ *
55
+ * `connectionManager` keeps an open driver per connection, and it was opened
56
+ * with the settings the row had at the time. Rotating a password or switching
57
+ * to a different pooler mode rewrites the row but leaves that adapter
58
+ * connected — so the change appears to have worked while every query keeps
59
+ * going to the old endpoint with the old credential until the pool happens to
60
+ * sweep it. `db-client:update` already releases for exactly this reason; the
61
+ * projection path has to as well.
62
+ */
63
+ async function reprojectAndRelease(accountId: string): Promise<void> {
64
+ const before = integrationDbLinkQueries
65
+ .getForAccount(accountId)
66
+ .map((link) => connectionIdOf(link))
67
+ .filter((id): id is string => id !== null);
68
+
69
+ reproject(accountId);
70
+
71
+ const after = integrationDbLinkQueries
72
+ .getForAccount(accountId)
73
+ .map((link) => connectionIdOf(link))
74
+ .filter((id): id is string => id !== null);
75
+
76
+ for (const id of new Set([...before, ...after])) {
77
+ await connectionManager.release(id);
78
+ }
79
+ }
80
+
81
+ function defaultModeOf(adapter: DbProviderAdapter): string {
82
+ const modes = adapter.info().modes;
83
+ return (modes.find((mode) => mode.isDefault) ?? modes[0])?.id ?? 'default';
84
+ }
85
+
86
+ /**
87
+ * Ask a provider where a database answers, and split the answer in two.
88
+ *
89
+ * An endpoint is stored in the link's `config_json`; a secret goes in
90
+ * `secrets`, which is the sealed column. A provider that can resolve its own
91
+ * credential — Neon reveals a role's password, Supabase cannot — returns it
92
+ * alongside the endpoint, and this is the one place the two are separated. Not
93
+ * splitting them would write a working password into an unsealed column, which
94
+ * is precisely what `Task 1`'s encryption layer exists to prevent.
95
+ */
96
+ async function resolveEndpoint(
97
+ adapter: DbProviderAdapter,
98
+ account: IntegrationAccountRow,
99
+ target: { remoteRef: string; mode: string }
100
+ ): Promise<{ endpoint: DbProviderEndpoint; secrets: Record<string, string> }> {
101
+ const { secrets, ...endpoint } = await adapter.resolveEndpoint(contextFor(account), target);
102
+ return { endpoint, secrets: secrets ?? {} };
103
+ }
104
+
105
+ function toLinkInfo(link: IntegrationDbLinkRow, account: IntegrationAccountRow): DbAccountLinkInfo {
106
+ return {
107
+ id: link.id,
108
+ accountId: link.account_id,
109
+ provider: account.provider,
110
+ accountLabel: account.label,
111
+ remoteRef: link.remote_ref,
112
+ label: link.label,
113
+ driver: link.driver,
114
+ mode: link.mode,
115
+ connectionId: connectionIdOf(link),
116
+ configuredSecrets: Object.entries(integrationDbLinkQueries.secretsOf(link))
117
+ .filter(([, value]) => typeof value === 'string' && value.length > 0)
118
+ .map(([name]) => name),
119
+ detected: link.detected === 1
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Refuse a link that is missing a secret the provider says it needs.
125
+ *
126
+ * Checked before the row is written, for the reason the account layer checks
127
+ * its own required fields: a link saved without its password looks connected
128
+ * and fails much later, inside a driver, with a message about authentication
129
+ * rather than about configuration.
130
+ */
131
+ function assertRequiredSecrets(adapter: DbProviderAdapter, secrets: Record<string, string>): void {
132
+ const missing = adapter.info().secretFields
133
+ .filter((field) => field.isRequired && !(secrets[field.name] ?? '').trim())
134
+ .map((field) => field.label);
135
+ if (missing.length > 0) {
136
+ throw new Error(`${adapter.info().name} needs ${missing.join(', ')}`);
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Poll until a newly created database reports itself connectable.
142
+ *
143
+ * Bounded, and a long budget rather than an unbounded one: a call that cannot
144
+ * tell "still provisioning" from "this will never answer" is worse than one
145
+ * that gives up and says so. Supabase takes roughly a minute for a small
146
+ * project, so three minutes is generous without being a hang.
147
+ */
148
+ const READY_POLL_INTERVAL_MS = 5_000;
149
+ const READY_POLL_BUDGET_MS = 180_000;
150
+
151
+ async function waitForReady(
152
+ adapter: DbProviderAdapter,
153
+ context: DbProviderContext,
154
+ ref: string
155
+ ): Promise<boolean> {
156
+ const deadline = Date.now() + READY_POLL_BUDGET_MS;
157
+
158
+ while (Date.now() < deadline) {
159
+ await new Promise((resolve) => setTimeout(resolve, READY_POLL_INTERVAL_MS));
160
+ try {
161
+ const databases = await adapter.listDatabases(context);
162
+ const match = databases.find((database) => database.ref === ref);
163
+ if (match?.isReady) return true;
164
+ } catch (error) {
165
+ // A provider that is briefly unreachable while it provisions is the
166
+ // normal case, not a reason to abandon a database that now exists.
167
+ debug.log('db-client', `Readiness poll for ${ref} failed, retrying: ${error instanceof Error ? error.message : error}`);
168
+ }
169
+ }
170
+
171
+ return false;
172
+ }
173
+
174
+ export const dbLinks = {
175
+ /** Every database provider, as the link dialog renders them. */
176
+ providers(): DbProviderInfo[] {
177
+ // `docsUrl` and `consoleUrl` come from the INTEGRATION registry rather than
178
+ // from the adapter, so a provider declares where its credential is created
179
+ // and where its dashboard lives exactly once. The link dialog renders both
180
+ // per provider instead of naming a vendor in its own markup.
181
+ return listDbProviders().map((adapter) => ({
182
+ ...adapter.info(),
183
+ docsUrl: getProvider(adapter.provider)?.docsUrl,
184
+ consoleUrl: getProvider(adapter.provider)?.consoleUrl
185
+ }));
186
+ },
187
+
188
+ /** Connected, enabled accounts that can supply database connections. */
189
+ accounts(): { accountId: string; provider: string; label: string; status: string }[] {
190
+ return listDbProviders().flatMap((adapter) =>
191
+ integrationAccountQueries
192
+ .getByProvider(adapter.provider)
193
+ .filter((account) => account.is_enabled === 1)
194
+ .filter((account) => integrationAccountQueries.capabilitiesOf(account).includes('database'))
195
+ .map((account) => ({
196
+ accountId: account.id,
197
+ provider: account.provider,
198
+ label: account.label,
199
+ status: account.status
200
+ }))
201
+ );
202
+ },
203
+
204
+ /** Every remote database this account can reach, flagged with what is linked. */
205
+ async remoteDatabases(accountId: string): Promise<DbRemoteDatabase[]> {
206
+ const account = requireAccount(accountId);
207
+ const adapter = requireAdapter(account.provider);
208
+ const linked = new Set(
209
+ integrationDbLinkQueries.getForAccount(accountId).map((link) => link.remote_ref)
210
+ );
211
+ const databases = await adapter.listDatabases(contextFor(account));
212
+ return databases.map((database) => ({ ...database, isLinked: linked.has(database.ref) }));
213
+ },
214
+
215
+ links(accountId: string): DbAccountLinkInfo[] {
216
+ const account = requireAccount(accountId);
217
+ return integrationDbLinkQueries.getForAccount(accountId).map((link) => toLinkInfo(link, account));
218
+ },
219
+
220
+ /** Every link on the install, which is what the panel badges its list from. */
221
+ allLinks(): DbAccountLinkInfo[] {
222
+ return listDbProviders().flatMap((adapter) =>
223
+ integrationAccountQueries.getByProvider(adapter.provider).flatMap((account) =>
224
+ integrationDbLinkQueries.getForAccount(account.id).map((link) => toLinkInfo(link, account))
225
+ )
226
+ );
227
+ },
228
+
229
+ async create(input: {
230
+ accountId: string;
231
+ remoteRef: string;
232
+ label?: string;
233
+ mode?: string;
234
+ secrets: Record<string, string>;
235
+ detected?: boolean;
236
+ /** Write the row now and work out where it answers later. */
237
+ deferEndpoint?: boolean;
238
+ }): Promise<DbAccountLinkInfo> {
239
+ const account = requireAccount(input.accountId);
240
+ const adapter = requireAdapter(account.provider);
241
+ assertRequiredSecrets(adapter, input.secrets);
242
+
243
+ if (integrationDbLinkQueries.getByRef(input.accountId, input.remoteRef)) {
244
+ throw new Error('That database is already linked to this account.');
245
+ }
246
+
247
+ const mode = input.mode ?? defaultModeOf(adapter);
248
+ // Resolved BEFORE the row is written. A link whose endpoint could not be
249
+ // resolved is not a link — it is a row that projects nothing, and failing
250
+ // here puts the error in the dialog that caused it rather than in a
251
+ // connection list that silently stayed the same length.
252
+ //
253
+ // `deferEndpoint` is the one exception, and it exists for a single caller:
254
+ // a database we have just CREATED is not answering yet, and its generated
255
+ // password only exists in memory until this row is written. Storing the
256
+ // secret first and resolving later is the only ordering where a slow
257
+ // provision cannot strand a password that nothing can recover.
258
+ const resolved = input.deferEndpoint
259
+ ? null
260
+ : await resolveEndpoint(adapter, account, { remoteRef: input.remoteRef, mode });
261
+
262
+ const link = integrationDbLinkQueries.create({
263
+ accountId: input.accountId,
264
+ remoteRef: input.remoteRef,
265
+ label: (input.label ?? '').trim() || input.remoteRef,
266
+ driver: adapter.driver,
267
+ mode,
268
+ secrets: { ...input.secrets, ...(resolved?.secrets ?? {}) },
269
+ config: resolved ? { endpoint: resolved.endpoint } : {},
270
+ detected: input.detected
271
+ });
272
+
273
+ await reprojectAndRelease(input.accountId);
274
+ debug.log('db-client', `Linked ${account.provider}:${input.remoteRef} as ${link.id}`);
275
+ return toLinkInfo(integrationDbLinkQueries.getById(link.id)!, account);
276
+ },
277
+
278
+ /** What the create-a-database form needs, or null when the provider cannot. */
279
+ async createOptions(accountId: string): Promise<DbProviderCreateOptions | null> {
280
+ const account = requireAccount(accountId);
281
+ const adapter = requireAdapter(account.provider);
282
+ if (!adapter.createOptions) return null;
283
+ return adapter.createOptions(contextFor(account));
284
+ },
285
+
286
+ /**
287
+ * Delete a database AT THE PROVIDER, and drop its link.
288
+ *
289
+ * Unlinking and deleting are deliberately different operations: one removes
290
+ * Clopen's connection, the other destroys the database. The link goes first
291
+ * so a successful delete cannot leave a projection pointing at something that
292
+ * no longer exists — and if the remote delete then fails, the user has lost a
293
+ * link they can recreate rather than a database they cannot.
294
+ */
295
+ async deleteDatabase(accountId: string, remoteRef: string): Promise<void> {
296
+ const account = requireAccount(accountId);
297
+ const adapter = requireAdapter(account.provider);
298
+ if (!adapter.deleteDatabase) {
299
+ throw new Error(`${adapter.info().name} cannot delete databases from here`);
300
+ }
301
+
302
+ const link = integrationDbLinkQueries.getByRef(accountId, remoteRef);
303
+ if (link) await this.remove(link.id);
304
+
305
+ await adapter.deleteDatabase(contextFor(account), remoteRef);
306
+ debug.log('db-client', `Deleted ${account.provider} database ${remoteRef}`);
307
+ },
308
+
309
+ /**
310
+ * Rename a database AT THE PROVIDER.
311
+ *
312
+ * The link's own label is left alone on purpose. It is what this install
313
+ * calls the connection and is edited in the link form; overwriting a name
314
+ * someone chose here because the project was renamed elsewhere would be a
315
+ * second, unasked-for change.
316
+ */
317
+ async renameDatabase(accountId: string, remoteRef: string, name: string): Promise<void> {
318
+ const account = requireAccount(accountId);
319
+ const adapter = requireAdapter(account.provider);
320
+ if (!adapter.renameDatabase) {
321
+ throw new Error(`${adapter.info().name} cannot rename databases from here`);
322
+ }
323
+ await adapter.renameDatabase(contextFor(account), remoteRef, name);
324
+ debug.log('db-client', `Renamed ${account.provider} database ${remoteRef}`);
325
+ },
326
+
327
+ /**
328
+ * Create the owning container — a Supabase organisation.
329
+ *
330
+ * Separate from `createDatabase` because the consequence is different: this
331
+ * creates a BILLING entity, not a database. It exists so an account whose
332
+ * token reaches no organisation is not a dead end Clopen can only point away
333
+ * from.
334
+ */
335
+ async createGroup(accountId: string, name: string): Promise<{ value: string; label: string }> {
336
+ const account = requireAccount(accountId);
337
+ const adapter = requireAdapter(account.provider);
338
+ if (!adapter.createGroup) {
339
+ throw new Error(`${adapter.info().name} cannot create one from here`);
340
+ }
341
+ const group = await adapter.createGroup(contextFor(account), { name });
342
+ debug.log('db-client', `Created ${account.provider} group ${group.value}`);
343
+ return group;
344
+ },
345
+
346
+ /**
347
+ * Create a database at the provider and link it.
348
+ *
349
+ * The ORDER here is the whole design. A freshly created database is not
350
+ * answering yet, and its password exists only in the reply we just received —
351
+ * no API can read it back later. So the link row is written FIRST, with the
352
+ * secret, and the endpoint is resolved afterwards. Every other ordering has a
353
+ * window where a slow provision, a dropped socket or a restart leaves the user
354
+ * with a real database whose password nothing holds.
355
+ *
356
+ * The wait is bounded and failing it is NOT an error: the project exists, the
357
+ * link exists, and saving the link is the retry. Reporting `ready: false`
358
+ * lets the dialog say what actually happened instead of implying the whole
359
+ * thing failed.
360
+ */
361
+ async createDatabase(input: {
362
+ accountId: string;
363
+ name: string;
364
+ group: string;
365
+ region: string;
366
+ }): Promise<{ link: DbAccountLinkInfo; ready: boolean }> {
367
+ const account = requireAccount(input.accountId);
368
+ const adapter = requireAdapter(account.provider);
369
+ if (!adapter.createDatabase) {
370
+ throw new Error(`${adapter.info().name} cannot create databases from here`);
371
+ }
372
+
373
+ const context = contextFor(account);
374
+ const created = await adapter.createDatabase(context, {
375
+ name: input.name.trim(),
376
+ group: input.group,
377
+ region: input.region
378
+ });
379
+
380
+ const link = await this.create({
381
+ accountId: input.accountId,
382
+ remoteRef: created.ref,
383
+ label: input.name.trim(),
384
+ secrets: created.secrets,
385
+ deferEndpoint: true
386
+ });
387
+ debug.log('db-client', `Created ${account.provider} database ${created.ref}, linked as ${link.id}`);
388
+
389
+ const ready = await waitForReady(adapter, context, created.ref);
390
+ if (!ready) {
391
+ debug.log('db-client', `${created.ref} is still provisioning — the link will resolve on save`);
392
+ return { link, ready: false };
393
+ }
394
+
395
+ // Now it answers: resolve the endpoint and let the projection run.
396
+ return { link: await this.update(link.id, { refreshEndpoint: true }), ready: true };
397
+ },
398
+
399
+ /**
400
+ * Change a link's label, mode or secret.
401
+ *
402
+ * The endpoint is re-resolved only when the mode changes or the caller asks:
403
+ * a password rotation does not move the host, and making every save wait on
404
+ * the provider's API would be a slow way to learn nothing new.
405
+ */
406
+ async update(
407
+ linkId: string,
408
+ patch: { label?: string; mode?: string; secrets?: Record<string, string>; refreshEndpoint?: boolean }
409
+ ): Promise<DbAccountLinkInfo> {
410
+ const link = integrationDbLinkQueries.getById(linkId);
411
+ if (!link) throw new Error('Database link not found');
412
+ const account = requireAccount(link.account_id);
413
+ const adapter = requireAdapter(account.provider);
414
+
415
+ // Empty means "not re-typed", the rule every credential form in Clopen
416
+ // already follows, so the merge happens here rather than in the query.
417
+ const secrets = { ...integrationDbLinkQueries.secretsOf(link) };
418
+ for (const [name, value] of Object.entries(patch.secrets ?? {})) {
419
+ if (typeof value === 'string' && value.length > 0) secrets[name] = value;
420
+ }
421
+ assertRequiredSecrets(adapter, secrets);
422
+
423
+ const mode = patch.mode ?? link.mode;
424
+ const config = integrationDbLinkQueries.configOf<Record<string, unknown>>(link);
425
+ // A link with NO endpoint is one that was deferred — a database that was
426
+ // still provisioning when it was created. Saving it is the retry, so the
427
+ // user never has to know which button re-resolves.
428
+ if (patch.refreshEndpoint || mode !== link.mode || !config.endpoint) {
429
+ const resolved = await resolveEndpoint(adapter, account, {
430
+ remoteRef: link.remote_ref,
431
+ mode
432
+ });
433
+ config.endpoint = resolved.endpoint;
434
+ // A provider that resolves its own credential re-resolves it here, which
435
+ // is what makes a password rotated at Neon picked up by saving the link
436
+ // rather than by finding a second button.
437
+ for (const [name, value] of Object.entries(resolved.secrets)) {
438
+ if (value) secrets[name] = value;
439
+ }
440
+ }
441
+
442
+ integrationDbLinkQueries.update(linkId, {
443
+ label: patch.label?.trim() || undefined,
444
+ mode,
445
+ secrets,
446
+ config
447
+ });
448
+
449
+ await reprojectAndRelease(link.account_id);
450
+ return toLinkInfo(integrationDbLinkQueries.getById(linkId)!, account);
451
+ },
452
+
453
+ /**
454
+ * Drop a link.
455
+ *
456
+ * The row is deleted first and `reproject()` does the rest: the connection
457
+ * this link owned is no longer in the projected set, so the pass releases it
458
+ * exactly the way disconnecting the whole account would — deleting a row we
459
+ * created, handing back one we adopted.
460
+ */
461
+ async remove(linkId: string): Promise<void> {
462
+ const link = integrationDbLinkQueries.getById(linkId);
463
+ if (!link) return;
464
+ const accountId = link.account_id;
465
+ const connectionId = connectionIdOf(link);
466
+ integrationDbLinkQueries.remove(linkId);
467
+ reproject(accountId);
468
+ // The row is gone or handed back; either way the open driver for it is
469
+ // no longer ours to keep.
470
+ if (connectionId) await connectionManager.release(connectionId);
471
+ debug.log('db-client', `Unlinked ${linkId}`);
472
+ },
473
+
474
+ /**
475
+ * Who owns each projected connection, keyed by connection id.
476
+ *
477
+ * One pass over the projections rather than a lookup per connection: the
478
+ * panel asks this for a whole list on every refresh.
479
+ */
480
+ managedIndex(): Map<string, DbClientManagedBy> {
481
+ const index = new Map<string, DbClientManagedBy>();
482
+ const linksByAccount = new Map<string, Map<string, IntegrationDbLinkRow>>();
483
+
484
+ const linksOf = (accountId: string): Map<string, IntegrationDbLinkRow> => {
485
+ let cached = linksByAccount.get(accountId);
486
+ if (!cached) {
487
+ cached = new Map();
488
+ for (const link of integrationDbLinkQueries.getForAccount(accountId)) {
489
+ const connectionId = connectionIdOf(link);
490
+ if (connectionId) cached.set(connectionId, link);
491
+ }
492
+ linksByAccount.set(accountId, cached);
493
+ }
494
+ return cached;
495
+ };
496
+
497
+ for (const projection of integrationProjectionQueries.getAllByKind('db_client_connection')) {
498
+ const account = integrationAccountQueries.getById(projection.account_id);
499
+ if (!account) continue;
500
+
501
+ const link = linksOf(projection.account_id).get(projection.target_id) ?? null;
502
+
503
+ index.set(projection.target_id, {
504
+ accountId: account.id,
505
+ provider: account.provider,
506
+ providerName: getProvider(account.provider)?.name ?? account.provider,
507
+ accountLabel: account.label,
508
+ linkId: link?.id ?? null,
509
+ remoteRef: link?.remote_ref ?? null,
510
+ adopted: projection.adopted === 1
511
+ });
512
+ }
513
+
514
+ return index;
515
+ },
516
+
517
+ /** The owner of one connection, or null when it was typed in by hand. */
518
+ managedBy(connectionId: string): DbClientManagedBy | null {
519
+ return this.managedIndex().get(connectionId) ?? null;
520
+ },
521
+
522
+ /** Attach ownership to a list of connections on its way to the panel. */
523
+ decorate<T extends { id: string }>(connections: T[]): (T & { managedBy: DbClientManagedBy | null })[] {
524
+ const index = this.managedIndex();
525
+ return connections.map((connection) => ({
526
+ ...connection,
527
+ managedBy: index.get(connection.id) ?? null
528
+ }));
529
+ },
530
+
531
+ /** The link behind a connection, for the surfaces that need its remote ref. */
532
+ linkForConnection(connectionId: string): { link: IntegrationDbLinkRow; account: IntegrationAccountRow } | null {
533
+ const projection = integrationProjectionQueries.getByTarget('db_client_connection', connectionId);
534
+ if (!projection) return null;
535
+ const account = integrationAccountQueries.getById(projection.account_id);
536
+ if (!account) return null;
537
+ const link = integrationDbLinkQueries
538
+ .getForAccount(account.id)
539
+ .find((candidate) => connectionIdOf(candidate) === connectionId);
540
+ return link ? { link, account } : null;
541
+ },
542
+
543
+ /** Health for the hub, delegated to whichever adapter owns the provider. */
544
+ async probe(accountId: string) {
545
+ const account = requireAccount(accountId);
546
+ const adapter = getDbProvider(account.provider);
547
+ if (!adapter) return null;
548
+ if (!integrationAccountQueries.capabilitiesOf(account).includes('database')) return null;
549
+ return adapter.probe(contextFor(account));
550
+ },
551
+
552
+ /** Connections a projection owns, so the panel can refuse to delete them. */
553
+ isManaged(connectionId: string): boolean {
554
+ return integrationProjectionQueries.getByTarget('db_client_connection', connectionId) !== null;
555
+ },
556
+
557
+ /** Every projected connection id — used by tests and the audit path. */
558
+ projectedConnectionIds(): string[] {
559
+ return integrationProjectionQueries
560
+ .getAllByKind('db_client_connection')
561
+ .map((projection) => projection.target_id)
562
+ .filter((id) => dbClientConnectionQueries.get(id) !== null);
563
+ }
564
+ };