@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,137 @@
1
+ /**
2
+ * Adopting a local Supabase CLI project.
3
+ *
4
+ * A repository that someone has run `supabase init` in already answers the two
5
+ * questions the link dialog would ask — which project this is, and where the
6
+ * local stack listens — and making the user copy them out of a file sitting in
7
+ * their own working tree is the kind of retyping this surface exists to remove.
8
+ *
9
+ * The config is parsed with a deliberately small reader rather than a TOML
10
+ * dependency. Only three values are wanted (`project_id`, and the `[db]` and
11
+ * `[api]` ports), all of them scalars at a known depth, and pulling in a parser
12
+ * for that means one more package whose Bun compatibility has to be kept true.
13
+ * The reader is section-aware precisely because `port` appears under several
14
+ * sections and taking the first one would report the API port as the database's.
15
+ */
16
+
17
+ import { readFile } from 'fs/promises';
18
+ import { join } from 'path';
19
+ import { debug } from '$shared/utils/logger';
20
+
21
+ /** The credentials `supabase start` always uses. They are fixed by the CLI. */
22
+ export const LOCAL_DB_USER = 'postgres';
23
+ export const LOCAL_DB_PASSWORD = 'postgres';
24
+ export const LOCAL_DB_NAME = 'postgres';
25
+ export const LOCAL_DB_HOST = '127.0.0.1';
26
+ const LOCAL_DB_DEFAULT_PORT = 54322;
27
+
28
+ export interface SupabaseLocalProject {
29
+ /** Project ref from `project_id`, which the CLI writes at init time. */
30
+ ref: string;
31
+ configPath: string;
32
+ dbPort: number;
33
+ /** Where `supabase/migrations` lives, whether or not it has any files. */
34
+ migrationsDir: string;
35
+ functionsDir: string;
36
+ }
37
+
38
+ /** Strip a TOML scalar down to its value. */
39
+ function unquote(raw: string): string {
40
+ const trimmed = raw.trim().replace(/\s*#.*$/, '').trim();
41
+ if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
42
+ return trimmed.slice(1, -1);
43
+ }
44
+ return trimmed;
45
+ }
46
+
47
+ interface ParsedConfig {
48
+ projectId: string | null;
49
+ dbPort: number | null;
50
+ }
51
+
52
+ /**
53
+ * Read the handful of values that matter.
54
+ *
55
+ * Section-aware: `port` is set under `[api]`, `[db]`, `[studio]` and more, so a
56
+ * flat scan would pick whichever came first and be confidently wrong.
57
+ */
58
+ export function parseSupabaseConfig(contents: string): ParsedConfig {
59
+ let section = '';
60
+ let projectId: string | null = null;
61
+ let dbPort: number | null = null;
62
+
63
+ for (const rawLine of contents.split(/\r?\n/)) {
64
+ const line = rawLine.trim();
65
+ if (!line || line.startsWith('#')) continue;
66
+
67
+ if (line.startsWith('[')) {
68
+ section = line.replace(/^\[+|\]+$/g, '');
69
+ continue;
70
+ }
71
+
72
+ const equals = line.indexOf('=');
73
+ if (equals === -1) continue;
74
+ const key = line.slice(0, equals).trim();
75
+ const value = unquote(line.slice(equals + 1));
76
+
77
+ if (!section && key === 'project_id') projectId = value || null;
78
+ if (section === 'db' && key === 'port') {
79
+ const port = Number(value);
80
+ if (Number.isFinite(port) && port > 0) dbPort = port;
81
+ }
82
+ }
83
+
84
+ return { projectId, dbPort };
85
+ }
86
+
87
+ /**
88
+ * Detect a Supabase CLI project in a working tree.
89
+ *
90
+ * Returns null rather than throwing for every ordinary reason a project has no
91
+ * Supabase in it — this is called speculatively whenever the panel opens, and a
92
+ * missing file is the common case, not a fault.
93
+ */
94
+ export async function detectLocalSupabase(projectRoot: string): Promise<SupabaseLocalProject | null> {
95
+ if (!projectRoot) return null;
96
+ const configPath = join(projectRoot, 'supabase', 'config.toml');
97
+
98
+ let contents: string;
99
+ try {
100
+ contents = await readFile(configPath, 'utf-8');
101
+ } catch {
102
+ return null;
103
+ }
104
+
105
+ try {
106
+ const parsed = parseSupabaseConfig(contents);
107
+ if (!parsed.projectId) return null;
108
+ return {
109
+ ref: parsed.projectId,
110
+ configPath,
111
+ dbPort: parsed.dbPort ?? LOCAL_DB_DEFAULT_PORT,
112
+ migrationsDir: join(projectRoot, 'supabase', 'migrations'),
113
+ functionsDir: join(projectRoot, 'supabase', 'functions')
114
+ };
115
+ } catch (error) {
116
+ debug.warn('db-client', `Could not read ${configPath}:`, error);
117
+ return null;
118
+ }
119
+ }
120
+
121
+ /** The connection a detected local stack would become, ready to prefill a form. */
122
+ export function localConnectionInput(local: SupabaseLocalProject) {
123
+ return {
124
+ name: `Supabase (local) — ${local.ref}`,
125
+ driver: 'postgres' as const,
126
+ host: LOCAL_DB_HOST,
127
+ port: local.dbPort,
128
+ username: LOCAL_DB_USER,
129
+ password: LOCAL_DB_PASSWORD,
130
+ database: LOCAL_DB_NAME,
131
+ sslMode: 'disable' as const,
132
+ // The marker the panel recognises. A local stack has no account and
133
+ // therefore no projection, so this options entry is the only thing that
134
+ // tells DB Client the Supabase surface applies to it.
135
+ options: { supabase: { ref: local.ref, local: true } }
136
+ };
137
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * The contract a database provider implements.
3
+ *
4
+ * DB Client is the surface that owns the `database` capability, and unlike
5
+ * Issues and Deployments it owns a TABLE — so a provider here feeds a
6
+ * projection rather than answering reads. The adapter's whole job is to turn
7
+ * "this account, this remote database" into the fields a `db_client_connections`
8
+ * row needs, and to answer the two questions the link dialog asks: what can this
9
+ * credential reach, and is it working.
10
+ *
11
+ * Everything a provider knows about its own service stays inside its directory,
12
+ * the way `Task 3` kept Vercel's per-endpoint API versions inside the Vercel
13
+ * adapter. Turso, Neon and PlanetScale should each be one directory here plus
14
+ * one line in `registry.ts`.
15
+ *
16
+ * NOTE THE SPLIT between resolving an endpoint and projecting a row.
17
+ * `reproject()` is synchronous — it runs inside account mutations — while
18
+ * working out a pooled endpoint's hostname is a network call. So the endpoint is
19
+ * resolved ONCE, when the link is created or refreshed, and stored on the link;
20
+ * the projector then builds the row from stored fields without touching the
21
+ * network. That also means a credential rotation re-projects instantly instead
22
+ * of making every account save wait on a third-party API.
23
+ */
24
+
25
+ import type {
26
+ DbDriver,
27
+ DbProviderCreateOptions,
28
+ DbProviderInfo,
29
+ DbRemoteDatabase,
30
+ DbSslMode
31
+ } from '$shared/types/db-client';
32
+ import type { IntegrationStatus } from '$shared/types/integrations';
33
+
34
+ /** Everything an adapter is given about the account it is acting for. */
35
+ export interface DbProviderContext {
36
+ accountId: string;
37
+ /** Decoded account credentials. Empty when the active key could not open them. */
38
+ credentials: Record<string, string>;
39
+ }
40
+
41
+ /**
42
+ * Where a linked database actually answers.
43
+ *
44
+ * Stored on the link as `config.endpoint`, and the only thing the projector
45
+ * reads besides the password. `options` is merged into the connection's options
46
+ * map, which is how the panel later recognises a Supabase-backed connection
47
+ * without db-client having to learn what a provider is.
48
+ */
49
+ export interface DbProviderEndpoint {
50
+ host: string;
51
+ port: number;
52
+ username: string;
53
+ database: string;
54
+ sslMode: DbSslMode;
55
+ options?: Record<string, unknown>;
56
+ /**
57
+ * Secrets the provider resolved for itself, for the providers that can.
58
+ *
59
+ * Supabase cannot: its Management API has no endpoint that reads a database
60
+ * password back, so a link asks the user for one and stores it. Neon can —
61
+ * `/reveal_password` exists — so it hands one back here and its
62
+ * `secretFields` is empty, which removes the only manual step in linking a
63
+ * database.
64
+ *
65
+ * `links.ts` PEELS THIS OFF before the endpoint is stored. An endpoint lives
66
+ * in the link's `config_json`, which is NOT a sealed column; the secrets go
67
+ * into `secrets`, which is. Leaving the password on the endpoint would write
68
+ * a working credential to disk in plaintext — the exact thing `Task 1`'s
69
+ * encryption layer exists to prevent.
70
+ */
71
+ secrets?: Record<string, string>;
72
+ }
73
+
74
+ /**
75
+ * What this provider's own documentation calls the connection in a dotenv file.
76
+ *
77
+ * Declared rather than derived, because both halves are vendor vocabulary that
78
+ * nothing outside the provider's directory can know: Neon's docs name the pair
79
+ * `DATABASE_URL` / `DATABASE_URL_UNPOOLED`, Supabase's name it `POSTGRES_URL` /
80
+ * `POSTGRES_URL_NON_POOLING`, and which of a provider's connection modes counts
81
+ * as "not behind a pooler" is a fact about its infrastructure.
82
+ *
83
+ * A DEFAULT only. Whatever the project's own files already call the variable
84
+ * wins over this — see `db-client/env/detect.ts`. These names are what a
85
+ * project with nothing in it is offered.
86
+ *
87
+ * The second endpoint is what makes this worth declaring at all. A pooled URL
88
+ * is the right default for an application and the WRONG one for migrations —
89
+ * Prisma's `DIRECT_URL` exists for exactly this — so a connection linked in
90
+ * pooled mode has a counterpart worth writing, and one already on the direct
91
+ * endpoint has none: a `DIRECT_URL` equal to `DATABASE_URL` would look like
92
+ * configuration and change nothing.
93
+ */
94
+ export interface DbProviderEnvHints {
95
+ /** What this provider's docs prefix the URL with — `DATABASE`, `POSTGRES`. */
96
+ urlPrefix?: string;
97
+ /** What its docs suffix the second endpoint with — `_UNPOOLED`, `_NON_POOLING`. */
98
+ altKeySuffix?: string;
99
+ /** The mode that is not behind a pooler, when the provider has one. */
100
+ directMode?: string;
101
+ /** Modes that ARE pooled, so a connection on one has a counterpart. */
102
+ pooledModes?: string[];
103
+ /** One sentence naming what the direct endpoint costs, where it costs something. */
104
+ directNotice?: string;
105
+ }
106
+
107
+ export interface DbProviderAdapter {
108
+ /** Matches the integration provider id, so the brand mark is the same one. */
109
+ provider: string;
110
+ driver: DbDriver;
111
+ /** How the link dialog renders this provider. */
112
+ info(): DbProviderInfo;
113
+
114
+ /** Every database this credential can reach. */
115
+ listDatabases(context: DbProviderContext): Promise<DbRemoteDatabase[]>;
116
+
117
+ /** Resolve where one database answers, in the requested connection mode. */
118
+ resolveEndpoint(
119
+ context: DbProviderContext,
120
+ target: { remoteRef: string; mode: string }
121
+ ): Promise<DbProviderEndpoint>;
122
+
123
+ /** Health of the credential itself, for the hub's status strip. */
124
+ probe(context: DbProviderContext): Promise<{ status: IntegrationStatus; detail: string | null }>;
125
+
126
+ /**
127
+ * Optional: what this provider's docs call the connection in a dotenv file.
128
+ *
129
+ * Absent means DB Client offers its generic presets and no second endpoint,
130
+ * which is the correct answer for a provider with one endpoint per database.
131
+ */
132
+ envHints?(): DbProviderEnvHints;
133
+
134
+ /**
135
+ * Optional: create a database rather than only listing existing ones.
136
+ *
137
+ * Declared as a pair so the UI can offer it only where it exists. A provider
138
+ * that cannot create simply omits both, and the dialog shows no such entry
139
+ * rather than a button that fails.
140
+ *
141
+ * `createDatabase` RETURNS THE SECRETS it generated. That is the whole reason
142
+ * this is worth building: the one awkward step of linking an existing project
143
+ * is typing a password the API refuses to hand back, and a project WE created
144
+ * is one whose password we set ourselves — so there is nothing to ask for.
145
+ * The caller stores them before waiting for the database to come up, because
146
+ * a password lost while provisioning is a password only a reset can recover.
147
+ */
148
+ createOptions?(context: DbProviderContext): Promise<DbProviderCreateOptions>;
149
+ createDatabase?(
150
+ context: DbProviderContext,
151
+ input: { name: string; group: string; region: string }
152
+ ): Promise<{ ref: string; secrets: Record<string, string> }>;
153
+
154
+ /**
155
+ * Optional: create the owning container too — a Supabase organisation, a
156
+ * Turso group.
157
+ *
158
+ * Offered because the alternative is a dead end that Clopen cannot get the
159
+ * user out of: an account whose token reaches no organisation cannot create a
160
+ * database anywhere, and telling someone to go to the vendor's dashboard is
161
+ * exactly the read-only-window feeling this surface exists to remove. It
162
+ * stays separate from `createDatabase` because it is a different consequence
163
+ * — an organisation is a BILLING entity, not a database.
164
+ */
165
+ createGroup?(
166
+ context: DbProviderContext,
167
+ input: { name: string }
168
+ ): Promise<{ value: string; label: string }>;
169
+
170
+ /**
171
+ * Optional: delete a database at the provider.
172
+ *
173
+ * Separate from unlinking, and the distinction is the whole point: unlinking
174
+ * removes Clopen's connection and leaves the database alone, while this
175
+ * destroys it and everything in it. Only offered where the provider has an
176
+ * endpoint for it — Supabase can delete a project but has NO endpoint for
177
+ * deleting an organisation, so that one is absent rather than faked.
178
+ */
179
+ deleteDatabase?(context: DbProviderContext, remoteRef: string): Promise<void>;
180
+
181
+ /**
182
+ * Optional: rename a database at the provider.
183
+ *
184
+ * Renames the DATABASE, not the link — `updateLink` already relabels
185
+ * Clopen's own copy, and the two are different things: one is what every
186
+ * collaborator sees in the provider's dashboard, the other is what this
187
+ * install calls its connection.
188
+ *
189
+ * Only offered where the provider has an endpoint. Supabase can rename a
190
+ * project (`PATCH /v1/projects/{ref}`) but exposes NO update for an
191
+ * organisation, so that one stays absent rather than faked.
192
+ */
193
+ renameDatabase?(context: DbProviderContext, remoteRef: string, name: string): Promise<void>;
194
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Reading `owner/repo` off a git remote.
3
+ *
4
+ * This is half of how a deployment binding is detected, and it is the half that
5
+ * can be wrong silently: match the wrong remote and a project is bound to
6
+ * someone else's deploy target, where "redeploy" and "roll back" both mean
7
+ * something nobody asked for.
8
+ *
9
+ * Host-agnostic on purpose — a deploy target reports `acme/web` without saying
10
+ * which host it is on, and the account that reaches it already decided the host.
11
+ */
12
+
13
+ import { describe, it, expect } from 'bun:test';
14
+
15
+ import { repoPathOf } from './bindings';
16
+
17
+ describe('repoPathOf', () => {
18
+ it('reads an scp-style remote', () => {
19
+ expect(repoPathOf('git@github.com:acme/web.git')).toBe('acme/web');
20
+ });
21
+
22
+ it('reads an https remote, with or without .git', () => {
23
+ expect(repoPathOf('https://github.com/acme/web.git')).toBe('acme/web');
24
+ expect(repoPathOf('https://github.com/acme/web')).toBe('acme/web');
25
+ });
26
+
27
+ it('reads an ssh:// remote', () => {
28
+ expect(repoPathOf('ssh://git@github.com/acme/web.git')).toBe('acme/web');
29
+ });
30
+
31
+ it('keeps a nested group path, which GitLab has and GitHub does not', () => {
32
+ expect(repoPathOf('git@gitlab.com:acme/team/web.git')).toBe('acme/team/web');
33
+ });
34
+
35
+ it('lowercases, so a case difference is not a failed match', () => {
36
+ expect(repoPathOf('https://github.com/Acme/Web.git')).toBe('acme/web');
37
+ });
38
+
39
+ it('answers null for something that is not a remote', () => {
40
+ expect(repoPathOf('')).toBeNull();
41
+ expect(repoPathOf('not a url')).toBeNull();
42
+ });
43
+ });
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Which remote project a Clopen project deploys to.
3
+ *
4
+ * Discovered rather than asked for, in two passes that go from certain to
5
+ * plausible:
6
+ *
7
+ * 1. The provider's own CLI config in the working tree. A project someone has
8
+ * run `vercel link` in already carries the answer in `.vercel/project.json`,
9
+ * and making them pick it out of a dropdown would be asking them to retype
10
+ * a file that is sitting in their repository.
11
+ * 2. The git remote. Every deploy target names the repository it builds from,
12
+ * so a project whose `origin` matches one of them has answered the question
13
+ * too — just less definitively, since two Vercel projects can build the same
14
+ * repository from different directories.
15
+ *
16
+ * Both are recorded as detection (`detected: true`) so the UI can say where the
17
+ * answer came from, and both are always overridable. A monorepo deploying three
18
+ * apps from one repository is a real, ordinary case, and it is exactly the case
19
+ * pass 2 gets wrong.
20
+ */
21
+
22
+ import { join } from 'path';
23
+ import { gitService } from '$backend/git/git-service';
24
+ import {
25
+ deployBindingQueries,
26
+ integrationAccountQueries,
27
+ parseDeployConfig,
28
+ type IntegrationAccountRow
29
+ } from '$backend/database/queries';
30
+ import type { DeployBinding, DeployTarget } from '$shared/types/deployments';
31
+ import { DEFAULT_DEPLOY_BINDING_CONFIG } from '$shared/types/deployments';
32
+ import type { DeployProviderAdapter, ResolvedDeployBinding } from './types';
33
+ import { debug } from '$shared/utils/logger';
34
+
35
+ /** The stored binding for one account on one project, or null. */
36
+ export function readDeployBinding(projectId: string, accountId: string): ResolvedDeployBinding | null {
37
+ const row = deployBindingQueries.get(projectId, accountId);
38
+ if (!row) return null;
39
+ return {
40
+ locator: row.locator,
41
+ displayName: row.display_name,
42
+ detected: row.detected === 1,
43
+ teamId: row.team_id,
44
+ config: parseDeployConfig(row.config_json)
45
+ };
46
+ }
47
+
48
+ /**
49
+ * `owner/repo` for every remote this project has, lowercased for comparison.
50
+ *
51
+ * Host-agnostic on purpose: a deploy target reports the repository as
52
+ * `acme/web` without saying which host it is on, and the account that reaches
53
+ * it has already decided the host. Comparing the path alone is what lets a
54
+ * self-hosted GitLab mirror match.
55
+ */
56
+ async function remoteRepoPaths(projectRoot: string): Promise<Set<string>> {
57
+ const paths = new Set<string>();
58
+ let remotes: { name: string; fetchUrl: string; pushUrl: string }[] = [];
59
+ try {
60
+ remotes = await gitService.getRemotes(projectRoot);
61
+ } catch (error) {
62
+ // A project that is not a repository has no remotes, which is a normal
63
+ // state: it can still be bound by hand or by the CLI config.
64
+ debug.log('deployments', `No git remotes for ${projectRoot}: ${error instanceof Error ? error.message : error}`);
65
+ return paths;
66
+ }
67
+
68
+ for (const remote of remotes) {
69
+ for (const url of [remote.fetchUrl, remote.pushUrl]) {
70
+ const path = repoPathOf(url);
71
+ if (path) paths.add(path);
72
+ }
73
+ }
74
+ return paths;
75
+ }
76
+
77
+ /** `owner/repo` out of either git URL form, without the `.git` suffix. */
78
+ export function repoPathOf(url: string): string | null {
79
+ if (!url) return null;
80
+ const trimmed = url.trim().replace(/\.git$/, '');
81
+ // scp-like: git@host:owner/repo
82
+ const scp = trimmed.match(/^[^@]+@[^:]+:(.+)$/);
83
+ if (scp) return scp[1].toLowerCase();
84
+ // URL form: https://host/owner/repo, ssh://git@host/owner/repo
85
+ try {
86
+ const parsed = new URL(trimmed);
87
+ const path = parsed.pathname.replace(/^\/+/, '');
88
+ return path ? path.toLowerCase() : null;
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Targets worth offering for this project, most likely first.
96
+ *
97
+ * Ordered rather than filtered: a repository match is a strong hint, not a
98
+ * fact, so the ones that do not match stay in the list below them instead of
99
+ * disappearing. A user deploying from a directory this project does not push to
100
+ * must still be able to find their project.
101
+ */
102
+ export async function suggestTargets(
103
+ adapter: DeployProviderAdapter,
104
+ context: { projectId: string; account: IntegrationAccountRow; credentials: Record<string, string> },
105
+ projectRoot: string
106
+ ): Promise<DeployTarget[]> {
107
+ const targets = await adapter.listTargets(context);
108
+ const repos = await remoteRepoPaths(projectRoot);
109
+ if (repos.size === 0) return targets;
110
+
111
+ const matches = (target: DeployTarget): boolean =>
112
+ target.gitRepo !== null && repos.has(target.gitRepo.toLowerCase());
113
+
114
+ return [...targets].sort((a, b) => Number(matches(b)) - Number(matches(a)));
115
+ }
116
+
117
+ /**
118
+ * The binding, detecting and persisting one when there is none.
119
+ *
120
+ * Persisting the detected value rather than re-deriving it on every call is
121
+ * deliberate: it gives the user a row to edit, and it means adding a second
122
+ * Vercel project to the same repository later does not silently repoint a
123
+ * project someone has been deploying from.
124
+ */
125
+ export async function resolveDeployBinding(
126
+ adapter: DeployProviderAdapter,
127
+ account: IntegrationAccountRow,
128
+ projectId: string,
129
+ projectRoot: string
130
+ ): Promise<ResolvedDeployBinding | null> {
131
+ const existing = readDeployBinding(projectId, account.id);
132
+ if (existing) return existing;
133
+
134
+ const credentials = integrationAccountQueries.credentialsOf(account);
135
+ const context = { projectId, account, credentials };
136
+
137
+ const detected = await detectLocator(adapter, context, projectRoot);
138
+ if (!detected) return null;
139
+
140
+ deployBindingQueries.upsert({
141
+ projectId,
142
+ accountId: account.id,
143
+ locator: detected.locator,
144
+ displayName: detected.displayName,
145
+ teamId: detected.teamId,
146
+ detected: true,
147
+ config: { ...DEFAULT_DEPLOY_BINDING_CONFIG }
148
+ });
149
+ debug.log('deployments', `Bound project ${projectId} to ${account.provider}:${detected.displayName} (${detected.via})`);
150
+
151
+ return readDeployBinding(projectId, account.id);
152
+ }
153
+
154
+ /** The two detection passes, in order, or null when neither answers. */
155
+ async function detectLocator(
156
+ adapter: DeployProviderAdapter,
157
+ context: { projectId: string; account: IntegrationAccountRow; credentials: Record<string, string> },
158
+ projectRoot: string
159
+ ): Promise<{ locator: string; teamId: string | null; displayName: string; via: string } | null> {
160
+ if (adapter.detectFromProject) {
161
+ try {
162
+ const linked = await adapter.detectFromProject(projectRoot);
163
+ if (linked) {
164
+ // The name is worth one extra call: a binding bar showing `prj_8Qc…`
165
+ // is unreadable, and this is the only moment we know we need it.
166
+ const described = await adapter
167
+ .describeTarget(context, linked.locator, linked.teamId)
168
+ .catch(() => null);
169
+ return {
170
+ locator: linked.locator,
171
+ teamId: linked.teamId,
172
+ displayName: described?.name ?? linked.locator,
173
+ via: 'the linked CLI project'
174
+ };
175
+ }
176
+ } catch (error) {
177
+ debug.warn('deployments', 'CLI-config detection failed:', error);
178
+ }
179
+ }
180
+
181
+ try {
182
+ const repos = await remoteRepoPaths(projectRoot);
183
+ if (repos.size === 0) return null;
184
+
185
+ const targets = await adapter.listTargets(context);
186
+ const match = targets.find((target) => target.gitRepo && repos.has(target.gitRepo.toLowerCase()));
187
+ if (!match) return null;
188
+
189
+ return {
190
+ locator: match.id,
191
+ teamId: match.teamId,
192
+ displayName: match.name,
193
+ via: 'a matching git remote'
194
+ };
195
+ } catch (error) {
196
+ debug.warn('deployments', 'Git-remote detection failed:', error);
197
+ return null;
198
+ }
199
+ }
200
+
201
+ /** Shape a binding for the client, or null when the project has none. */
202
+ export function toDeployBindingInfo(binding: ResolvedDeployBinding | null): DeployBinding | null {
203
+ if (!binding) return null;
204
+ return {
205
+ locator: binding.locator,
206
+ displayName: binding.displayName || binding.locator,
207
+ detected: binding.detected,
208
+ teamId: binding.teamId,
209
+ config: binding.config
210
+ };
211
+ }
212
+
213
+ /** Where a provider's CLI config would live, for adapters that have one. */
214
+ export function projectConfigPath(projectRoot: string, ...segments: string[]): string {
215
+ return join(projectRoot, ...segments);
216
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The Deployments surface.
3
+ *
4
+ * Deployments for the current project — list, state, build logs, and the URL a
5
+ * build is reachable at — behind one provider-agnostic interface. Vercel is the
6
+ * first provider; Netlify, Railway, Fly.io, Render, Coolify/Dokploy and
7
+ * Cloudflare Pages are meant to be a directory in `providers/` and a line below.
8
+ *
9
+ * types.ts the adapter contract
10
+ * registry.ts provider id → adapter
11
+ * bindings.ts which remote project this project deploys to
12
+ * service.ts the operations every route goes through
13
+ * log-streams.ts following a running build
14
+ * prompts.ts the text this surface sends into a chat session
15
+ *
16
+ * Importing this module is what wires a provider up, so it must be imported for
17
+ * its side effects before any route runs — `backend/ws/deployments/` does that.
18
+ */
19
+
20
+ import { registerAccountProbe } from '$backend/integrations';
21
+ import { registerDeployProvider } from './registry';
22
+ import { vercelDeployAdapter } from './providers/vercel/adapter';
23
+ import { deployService } from './service';
24
+
25
+ registerDeployProvider(vercelDeployAdapter);
26
+
27
+ // Health for accounts whose capability projects no MCP row. Without this the
28
+ // hub would report "Nothing to probe yet" for a Vercel account forever — the
29
+ // same gap the Issues surface found and closed.
30
+ registerAccountProbe('vercel', (accountId, projectId) => deployService.probe(accountId, projectId));
31
+
32
+ export { deployService } from './service';
33
+ export { getDeployAdapter, listDeployAdapters, registerDeployProvider } from './registry';
34
+ export {
35
+ readDeployBinding,
36
+ resolveDeployBinding,
37
+ suggestTargets,
38
+ toDeployBindingInfo
39
+ } from './bindings';
40
+ export {
41
+ startBuildLogStream,
42
+ stopAllBuildLogStreams,
43
+ stopBuildLogStream,
44
+ stopBuildLogStreamsForUser
45
+ } from './log-streams';
46
+ export { buildDeployFailurePrompt } from './prompts';
47
+ export type {
48
+ DeployContext,
49
+ DeployProviderAdapter,
50
+ DeploymentQuery,
51
+ ResolvedDeployBinding,
52
+ UnboundDeployContext
53
+ } from './types';