@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
@@ -35,5 +35,15 @@ export type { ProfileRow, ProfileItemRow, ProfileInput, ProfileItemInput, Profil
35
35
  export { noteQueries, noteCollectionQueries, noteImageQueries } from './note-queries';
36
36
  export { integrationAccountQueries, integrationProjectionQueries, integrationWebhookQueries } from './integration-queries';
37
37
  export type { IntegrationAccountRow, IntegrationAccountInput, IntegrationProjectionRow } from './integration-queries';
38
+ export { integrationDbLinkQueries } from './integration-db-link-queries';
39
+ export type { IntegrationDbLinkRow, IntegrationDbLinkInput } from './integration-db-link-queries';
38
40
  export { workBindingQueries, workLinkQueries, parseBindingConfig } from './work-queries';
39
41
  export type { WorkBindingRow, WorkLinkRow } from './work-queries';
42
+ export { deployBindingQueries, parseDeployConfig } from './deploy-queries';
43
+ export type { DeployBindingRow } from './deploy-queries';
44
+ export {
45
+ worktreeBranchBindingQueries,
46
+ worktreeBranchQueries,
47
+ parseWorktreeBranchConfig
48
+ } from './worktree-branch-queries';
49
+ export type { WorktreeBranchBindingRow, WorktreeBranchRow } from './worktree-branch-queries';
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Which remote databases an account brought into DB Client.
3
+ *
4
+ * A link is the answer to "which one", asked once per database rather than once
5
+ * per credential. It is the database counterpart of `deploy_bindings`: the
6
+ * account holds the token, and everything that varies per remote database —
7
+ * which project, which connection mode, and the password the provider will not
8
+ * hand back — lives here.
9
+ *
10
+ * `secrets` is sealed at rest by the crypto layer, so callers here hand in and
11
+ * receive a plain object and never see an envelope. A blob that the active key
12
+ * cannot open reads as `{}`, which the projector treats exactly as it treats a
13
+ * link whose password was never entered: it projects a connection that cannot
14
+ * log in and says so, rather than throwing on every read path.
15
+ */
16
+
17
+ import { getDatabase } from '../index';
18
+ import { openRow, sealFor } from '../crypto';
19
+ import type { DbDriver } from '$shared/types/db-client';
20
+
21
+ const TABLE = 'integration_db_links';
22
+
23
+ export interface IntegrationDbLinkRow {
24
+ id: string;
25
+ account_id: string;
26
+ /** The provider's own id for the database — a Supabase project ref. */
27
+ remote_ref: string;
28
+ label: string;
29
+ driver: DbDriver;
30
+ mode: string;
31
+ /** Sealed on disk, plain JSON string here. Null when the key could not open it. */
32
+ secrets: string | null;
33
+ config_json: string;
34
+ detected: number;
35
+ created_at: string;
36
+ updated_at: string;
37
+ }
38
+
39
+ export interface IntegrationDbLinkInput {
40
+ accountId: string;
41
+ remoteRef: string;
42
+ label: string;
43
+ driver: DbDriver;
44
+ mode: string;
45
+ secrets: Record<string, string>;
46
+ config: Record<string, unknown>;
47
+ detected?: boolean;
48
+ }
49
+
50
+ function parse<T>(raw: string | null, fallback: T): T {
51
+ if (!raw) return fallback;
52
+ try {
53
+ const parsed = JSON.parse(raw);
54
+ return (parsed ?? fallback) as T;
55
+ } catch {
56
+ return fallback;
57
+ }
58
+ }
59
+
60
+ function openLink<T extends IntegrationDbLinkRow | null>(row: T): T {
61
+ return (row ? openRow(TABLE, row) : row) as T;
62
+ }
63
+
64
+ export const integrationDbLinkQueries = {
65
+ getForAccount(accountId: string): IntegrationDbLinkRow[] {
66
+ const db = getDatabase();
67
+ return (db.prepare(
68
+ `SELECT * FROM integration_db_links WHERE account_id = ? ORDER BY label ASC`
69
+ ).all(accountId) as IntegrationDbLinkRow[]).map((row) => openLink(row));
70
+ },
71
+
72
+ getById(id: string): IntegrationDbLinkRow | null {
73
+ const db = getDatabase();
74
+ return openLink(
75
+ db.prepare(`SELECT * FROM integration_db_links WHERE id = ?`).get(id) as IntegrationDbLinkRow | null
76
+ );
77
+ },
78
+
79
+ getByRef(accountId: string, remoteRef: string): IntegrationDbLinkRow | null {
80
+ const db = getDatabase();
81
+ return openLink(
82
+ db.prepare(
83
+ `SELECT * FROM integration_db_links WHERE account_id = ? AND remote_ref = ?`
84
+ ).get(accountId, remoteRef) as IntegrationDbLinkRow | null
85
+ );
86
+ },
87
+
88
+ secretsOf(row: IntegrationDbLinkRow): Record<string, string> {
89
+ return parse<Record<string, string>>(row.secrets, {});
90
+ },
91
+
92
+ configOf<T = Record<string, unknown>>(row: IntegrationDbLinkRow): T {
93
+ return parse<T>(row.config_json, {} as T);
94
+ },
95
+
96
+ create(input: IntegrationDbLinkInput): IntegrationDbLinkRow {
97
+ const db = getDatabase();
98
+ const id = crypto.randomUUID();
99
+ const now = new Date().toISOString();
100
+
101
+ db.prepare(`
102
+ INSERT INTO integration_db_links (
103
+ id, account_id, remote_ref, label, driver, mode,
104
+ secrets, config_json, detected, created_at, updated_at
105
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
106
+ `).run(
107
+ id,
108
+ input.accountId,
109
+ input.remoteRef,
110
+ input.label,
111
+ input.driver,
112
+ input.mode,
113
+ sealFor(TABLE, 'secrets', JSON.stringify(input.secrets)),
114
+ JSON.stringify(input.config),
115
+ input.detected ? 1 : 0,
116
+ now,
117
+ now
118
+ );
119
+
120
+ return this.getById(id)!;
121
+ },
122
+
123
+ /**
124
+ * Patch a link.
125
+ *
126
+ * `secrets` is REPLACED rather than merged, and the caller merges — an empty
127
+ * password field means "not re-typed", not "clear it", the same rule the
128
+ * db-client and SSH forms already use.
129
+ */
130
+ update(
131
+ id: string,
132
+ patch: { label?: string; mode?: string; secrets?: Record<string, string>; config?: Record<string, unknown> }
133
+ ): IntegrationDbLinkRow | null {
134
+ const db = getDatabase();
135
+ const sets: string[] = [];
136
+ const values: unknown[] = [];
137
+
138
+ if (patch.label !== undefined) {
139
+ sets.push('label = ?');
140
+ values.push(patch.label);
141
+ }
142
+ if (patch.mode !== undefined) {
143
+ sets.push('mode = ?');
144
+ values.push(patch.mode);
145
+ }
146
+ if (patch.secrets !== undefined) {
147
+ sets.push('secrets = ?');
148
+ values.push(sealFor(TABLE, 'secrets', JSON.stringify(patch.secrets)));
149
+ }
150
+ if (patch.config !== undefined) {
151
+ sets.push('config_json = ?');
152
+ values.push(JSON.stringify(patch.config));
153
+ }
154
+
155
+ if (sets.length === 0) return this.getById(id);
156
+
157
+ sets.push('updated_at = ?');
158
+ values.push(new Date().toISOString(), id);
159
+
160
+ db.prepare(`UPDATE integration_db_links SET ${sets.join(', ')} WHERE id = ?`).run(...values);
161
+ return this.getById(id);
162
+ },
163
+
164
+ remove(id: string): void {
165
+ const db = getDatabase();
166
+ db.prepare(`DELETE FROM integration_db_links WHERE id = ?`).run(id);
167
+ }
168
+ };
@@ -231,6 +231,20 @@ export const integrationProjectionQueries = {
231
231
  ).get(targetKind, targetId) as IntegrationProjectionRow | null;
232
232
  },
233
233
 
234
+ /**
235
+ * Every projection of one kind, keyed by target id.
236
+ *
237
+ * The badge on a db-client connection needs to answer "is this row managed,
238
+ * and by whom" for a whole list at once. Asking `getByTarget` per row would
239
+ * be one statement per connection on every list call.
240
+ */
241
+ getAllByKind(targetKind: IntegrationTargetKind): IntegrationProjectionRow[] {
242
+ const db = getDatabase();
243
+ return db.prepare(
244
+ `SELECT * FROM integration_projections WHERE target_kind = ?`
245
+ ).all(targetKind) as IntegrationProjectionRow[];
246
+ },
247
+
234
248
  upsert(input: {
235
249
  accountId: string;
236
250
  capability: IntegrationCapability;
@@ -240,12 +254,20 @@ export const integrationProjectionQueries = {
240
254
  restore: unknown | null;
241
255
  }): void {
242
256
  const db = getDatabase();
257
+ // The conflict target is the full key: one account can own SEVERAL rows of
258
+ // the same kind for the same capability (a database account with two
259
+ // linked projects), so `target_id` identifies the row rather than being
260
+ // something an upsert overwrites.
261
+ //
262
+ // `restore_json` is deliberately NOT updated on conflict. It is the
263
+ // snapshot of what the row looked like before we adopted it, and
264
+ // re-projecting must never replace it with a picture of our own
265
+ // credential — that is the bug the MCP projector's comment describes.
243
266
  db.prepare(`
244
267
  INSERT INTO integration_projections (account_id, capability, target_kind, target_id, adopted, restore_json, created_at)
245
268
  VALUES (?, ?, ?, ?, ?, ?, ?)
246
- ON CONFLICT (account_id, capability, target_kind) DO UPDATE SET
247
- target_id = excluded.target_id,
248
- adopted = excluded.adopted
269
+ ON CONFLICT (account_id, capability, target_kind, target_id) DO UPDATE SET
270
+ adopted = excluded.adopted
249
271
  `).run(
250
272
  input.accountId,
251
273
  input.capability,
@@ -257,11 +279,17 @@ export const integrationProjectionQueries = {
257
279
  );
258
280
  },
259
281
 
260
- remove(accountId: string, capability: IntegrationCapability, targetKind: IntegrationTargetKind): void {
282
+ remove(
283
+ accountId: string,
284
+ capability: IntegrationCapability,
285
+ targetKind: IntegrationTargetKind,
286
+ targetId: string
287
+ ): void {
261
288
  const db = getDatabase();
262
289
  db.prepare(
263
- `DELETE FROM integration_projections WHERE account_id = ? AND capability = ? AND target_kind = ?`
264
- ).run(accountId, capability, targetKind);
290
+ `DELETE FROM integration_projections
291
+ WHERE account_id = ? AND capability = ? AND target_kind = ? AND target_id = ?`
292
+ ).run(accountId, capability, targetKind, targetId);
265
293
  },
266
294
 
267
295
  /** The snapshot taken when an existing row was adopted, or null. */
@@ -0,0 +1,331 @@
1
+ /**
2
+ * Worktree database branching — the binding, and the branches it produced.
3
+ *
4
+ * The binding table holds no secret: a parent ref and four display settings.
5
+ * The branch table holds a whole connection string, password included, so
6
+ * `connection_json` is sealed at rest by the crypto layer — callers here hand in
7
+ * and receive a plain object and never see an envelope.
8
+ *
9
+ * A blob the active key cannot open reads as `null`, which every caller treats
10
+ * exactly as it treats a branch whose connection was never resolved: the branch
11
+ * is still listed, still deletable at the provider, and simply projects no
12
+ * connection. Throwing instead would take down the worktree list itself.
13
+ */
14
+
15
+ import { getDatabase } from '../index';
16
+ import { openRow, openRows, sealFor } from '../crypto';
17
+ import type {
18
+ BranchConnection,
19
+ BranchEnvStatus,
20
+ BranchSourceKind,
21
+ WorktreeBranchConfig
22
+ } from '$shared/types/worktree-branching';
23
+ import { DEFAULT_WORKTREE_BRANCH_CONFIG } from '$shared/types/worktree-branching';
24
+
25
+ const BRANCH_TABLE = 'worktree_branches';
26
+
27
+ export interface WorktreeBranchBindingRow {
28
+ project_id: string;
29
+ source_kind: BranchSourceKind;
30
+ /** Set for an account source, null for a connection one. */
31
+ account_id: string | null;
32
+ /** Set for a connection source, null for an account one. */
33
+ connection_id: string | null;
34
+ parent_ref: string;
35
+ parent_name: string;
36
+ config_json: string;
37
+ created_at: string;
38
+ updated_at: string;
39
+ }
40
+
41
+ export interface WorktreeBranchRow {
42
+ id: string;
43
+ /** Null once the worktree is gone. That is what makes the row an orphan. */
44
+ worktree_id: string | null;
45
+ project_id: string;
46
+ source_kind: BranchSourceKind;
47
+ account_id: string | null;
48
+ /** The DB Client connection copied FROM. No FK — see migration 078. */
49
+ source_connection_id: string | null;
50
+ parent_ref: string;
51
+ branch_ref: string;
52
+ branch_name: string;
53
+ /** Sealed on disk, plain JSON string here. Null when the key could not open it. */
54
+ connection_json: string | null;
55
+ connection_id: string | null;
56
+ env_var: string;
57
+ env_file: string;
58
+ env_status: BranchEnvStatus;
59
+ env_detail: string | null;
60
+ status: 'active' | 'orphaned';
61
+ error: string | null;
62
+ /** Which mechanism made it, for the sentence the manager shows. */
63
+ strategy: string | null;
64
+ /** What that mechanism did not carry, or null. */
65
+ notice: string | null;
66
+ created_at: string;
67
+ updated_at: string;
68
+ }
69
+
70
+ /** The account or connection a row belongs to, whichever it is. */
71
+ export function sourceIdOf(row: { account_id: string | null; connection_id?: string | null; source_connection_id?: string | null }): string {
72
+ return row.account_id ?? row.source_connection_id ?? row.connection_id ?? '';
73
+ }
74
+
75
+ /**
76
+ * Parse the stored config over the defaults.
77
+ *
78
+ * Merged rather than replaced, for the reason `parseDeployConfig` merges: a
79
+ * config written before an option existed must not read back with that option
80
+ * `undefined`. Here that would be worse than a wrong filter — an `envVar` of
81
+ * `undefined` writes the literal string "undefined=" into someone's dotenv file.
82
+ */
83
+ export function parseWorktreeBranchConfig(raw: string | null): WorktreeBranchConfig {
84
+ if (!raw) return { ...DEFAULT_WORKTREE_BRANCH_CONFIG };
85
+ try {
86
+ const parsed = JSON.parse(raw) as Partial<WorktreeBranchConfig> | null;
87
+ return { ...DEFAULT_WORKTREE_BRANCH_CONFIG, ...(parsed ?? {}) };
88
+ } catch {
89
+ return { ...DEFAULT_WORKTREE_BRANCH_CONFIG };
90
+ }
91
+ }
92
+
93
+ export const worktreeBranchBindingQueries = {
94
+ get(projectId: string): WorktreeBranchBindingRow | null {
95
+ const db = getDatabase();
96
+ return db.prepare(
97
+ `SELECT * FROM worktree_branch_bindings WHERE project_id = ?`
98
+ ).get(projectId) as WorktreeBranchBindingRow | null;
99
+ },
100
+
101
+ getForAccount(accountId: string): WorktreeBranchBindingRow[] {
102
+ const db = getDatabase();
103
+ return db.prepare(
104
+ `SELECT * FROM worktree_branch_bindings WHERE account_id = ?`
105
+ ).all(accountId) as WorktreeBranchBindingRow[];
106
+ },
107
+
108
+ upsert(input: {
109
+ projectId: string;
110
+ sourceKind: BranchSourceKind;
111
+ sourceId: string;
112
+ parentRef: string;
113
+ parentName: string;
114
+ config: WorktreeBranchConfig;
115
+ }): WorktreeBranchBindingRow {
116
+ const db = getDatabase();
117
+ const now = new Date().toISOString();
118
+ const existing = this.get(input.projectId);
119
+ const accountId = input.sourceKind === 'account' ? input.sourceId : null;
120
+ const connectionId = input.sourceKind === 'connection' ? input.sourceId : null;
121
+
122
+ db.prepare(`
123
+ INSERT INTO worktree_branch_bindings (
124
+ project_id, source_kind, account_id, connection_id,
125
+ parent_ref, parent_name, config_json, created_at, updated_at
126
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
127
+ ON CONFLICT (project_id) DO UPDATE SET
128
+ source_kind = excluded.source_kind,
129
+ account_id = excluded.account_id,
130
+ connection_id = excluded.connection_id,
131
+ parent_ref = excluded.parent_ref,
132
+ parent_name = excluded.parent_name,
133
+ config_json = excluded.config_json,
134
+ updated_at = excluded.updated_at
135
+ `).run(
136
+ input.projectId,
137
+ input.sourceKind,
138
+ accountId,
139
+ connectionId,
140
+ input.parentRef,
141
+ input.parentName,
142
+ JSON.stringify(input.config),
143
+ existing?.created_at ?? now,
144
+ now
145
+ );
146
+
147
+ return this.get(input.projectId)!;
148
+ },
149
+
150
+ remove(projectId: string): void {
151
+ const db = getDatabase();
152
+ db.prepare(`DELETE FROM worktree_branch_bindings WHERE project_id = ?`).run(projectId);
153
+ }
154
+ };
155
+
156
+ function openBranch<T extends WorktreeBranchRow | null>(row: T): T {
157
+ return (row ? openRow(BRANCH_TABLE, row) : row) as T;
158
+ }
159
+
160
+ export const worktreeBranchQueries = {
161
+ getById(id: string): WorktreeBranchRow | null {
162
+ const db = getDatabase();
163
+ return openBranch(
164
+ db.prepare(`SELECT * FROM worktree_branches WHERE id = ?`).get(id) as WorktreeBranchRow | null
165
+ );
166
+ },
167
+
168
+ /** The branch attached to one worktree, or null when it has none. */
169
+ getForWorktree(worktreeId: string): WorktreeBranchRow | null {
170
+ const db = getDatabase();
171
+ return openBranch(
172
+ db.prepare(
173
+ `SELECT * FROM worktree_branches WHERE worktree_id = ? AND status = 'active'`
174
+ ).get(worktreeId) as WorktreeBranchRow | null
175
+ );
176
+ },
177
+
178
+ getForAccount(accountId: string): WorktreeBranchRow[] {
179
+ const db = getDatabase();
180
+ return openRows(
181
+ BRANCH_TABLE,
182
+ db.prepare(
183
+ `SELECT * FROM worktree_branches WHERE account_id = ? ORDER BY created_at DESC`
184
+ ).all(accountId) as WorktreeBranchRow[]
185
+ );
186
+ },
187
+
188
+ getForProject(projectId: string): WorktreeBranchRow[] {
189
+ const db = getDatabase();
190
+ return openRows(
191
+ BRANCH_TABLE,
192
+ db.prepare(
193
+ `SELECT * FROM worktree_branches WHERE project_id = ? ORDER BY created_at DESC`
194
+ ).all(projectId) as WorktreeBranchRow[]
195
+ );
196
+ },
197
+
198
+ /**
199
+ * Every branch whose worktree is gone, or whose remote delete failed.
200
+ *
201
+ * The two are one query because they are one problem: a branch that still
202
+ * exists at the provider and is no longer attached to anything. Reporting
203
+ * them separately would ask the user to understand how each one got that way
204
+ * before they could act on either.
205
+ */
206
+ orphans(): WorktreeBranchRow[] {
207
+ const db = getDatabase();
208
+ return openRows(
209
+ BRANCH_TABLE,
210
+ db.prepare(`
211
+ SELECT * FROM worktree_branches
212
+ WHERE worktree_id IS NULL OR status = 'orphaned'
213
+ ORDER BY created_at DESC
214
+ `).all() as WorktreeBranchRow[]
215
+ );
216
+ },
217
+
218
+ connectionOf(row: WorktreeBranchRow): BranchConnection | null {
219
+ if (!row.connection_json) return null;
220
+ try {
221
+ const parsed = JSON.parse(row.connection_json) as BranchConnection | null;
222
+ return parsed && typeof parsed.uri === 'string' && parsed.uri ? parsed : null;
223
+ } catch {
224
+ return null;
225
+ }
226
+ },
227
+
228
+ create(input: {
229
+ worktreeId: string;
230
+ projectId: string;
231
+ sourceKind: BranchSourceKind;
232
+ sourceId: string;
233
+ parentRef: string;
234
+ branchRef: string;
235
+ branchName: string;
236
+ connection: BranchConnection;
237
+ envVar: string;
238
+ envFile: string;
239
+ strategy: string | null;
240
+ notice: string | null;
241
+ }): WorktreeBranchRow {
242
+ const db = getDatabase();
243
+ const id = crypto.randomUUID();
244
+ const now = new Date().toISOString();
245
+
246
+ db.prepare(`
247
+ INSERT INTO worktree_branches (
248
+ id, worktree_id, project_id, source_kind, account_id, source_connection_id,
249
+ parent_ref, branch_ref, branch_name,
250
+ connection_json, connection_id, env_var, env_file, env_status, env_detail,
251
+ status, error, strategy, notice, created_at, updated_at
252
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 'failed', NULL, 'active', NULL, ?, ?, ?, ?)
253
+ `).run(
254
+ id,
255
+ input.worktreeId,
256
+ input.projectId,
257
+ input.sourceKind,
258
+ input.sourceKind === 'account' ? input.sourceId : null,
259
+ input.sourceKind === 'connection' ? input.sourceId : null,
260
+ input.parentRef,
261
+ input.branchRef,
262
+ input.branchName,
263
+ sealFor(BRANCH_TABLE, 'connection_json', JSON.stringify(input.connection)),
264
+ input.envVar,
265
+ input.envFile,
266
+ input.strategy,
267
+ input.notice,
268
+ now,
269
+ now
270
+ );
271
+
272
+ return this.getById(id)!;
273
+ },
274
+
275
+ /** Every branch copied from one DB Client connection. */
276
+ getForSourceConnection(connectionId: string): WorktreeBranchRow[] {
277
+ const db = getDatabase();
278
+ return openRows(
279
+ BRANCH_TABLE,
280
+ db.prepare(
281
+ `SELECT * FROM worktree_branches WHERE source_connection_id = ? ORDER BY created_at DESC`
282
+ ).all(connectionId) as WorktreeBranchRow[]
283
+ );
284
+ },
285
+
286
+ /**
287
+ * Record what happened when the connection string was written.
288
+ *
289
+ * Separate from `create` on purpose, and the ORDER is the reason. The row is
290
+ * written BEFORE the dotenv file is touched, so a crash in between leaves a
291
+ * branch that is tracked and deletable rather than one nothing knows about.
292
+ * That means the row exists for a moment with no env result — and the
293
+ * column's default of `failed` is the honest reading of that moment, because
294
+ * a process that died there genuinely did not write anything.
295
+ */
296
+ setEnvResult(id: string, status: BranchEnvStatus, detail: string | null): void {
297
+ const db = getDatabase();
298
+ db.prepare(
299
+ `UPDATE worktree_branches SET env_status = ?, env_detail = ?, updated_at = ? WHERE id = ?`
300
+ ).run(status, detail, new Date().toISOString(), id);
301
+ },
302
+
303
+ /** Remember which DB Client connection this branch projected. */
304
+ setConnectionId(id: string, connectionId: string | null): void {
305
+ const db = getDatabase();
306
+ db.prepare(
307
+ `UPDATE worktree_branches SET connection_id = ?, updated_at = ? WHERE id = ?`
308
+ ).run(connectionId, new Date().toISOString(), id);
309
+ },
310
+
311
+ /**
312
+ * Mark a branch as leaked.
313
+ *
314
+ * Called when the remote delete failed. The row deliberately keeps its
315
+ * connection and its refs: they are exactly what a later retry needs, and
316
+ * clearing them would turn a reportable orphan into an unreachable one.
317
+ */
318
+ markOrphaned(id: string, error: string): void {
319
+ const db = getDatabase();
320
+ db.prepare(`
321
+ UPDATE worktree_branches
322
+ SET status = 'orphaned', error = ?, worktree_id = NULL, updated_at = ?
323
+ WHERE id = ?
324
+ `).run(error, new Date().toISOString(), id);
325
+ },
326
+
327
+ remove(id: string): void {
328
+ const db = getDatabase();
329
+ db.prepare(`DELETE FROM worktree_branches WHERE id = ?`).run(id);
330
+ }
331
+ };