@myrialabs/clopen 0.4.39 → 0.4.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +29 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +42 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/index.ts +28 -0
  20. package/backend/database/queries/file-share-queries.ts +163 -0
  21. package/backend/database/queries/index.ts +12 -4
  22. package/backend/database/queries/profile-queries.ts +5 -3
  23. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  24. package/backend/database/queries/push-subscription-queries.ts +99 -0
  25. package/backend/database/queries/skill-queries.ts +96 -18
  26. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  27. package/backend/db-client/cloning.test.ts +161 -0
  28. package/backend/db-client/cloning.ts +672 -0
  29. package/backend/db-client/connection-url.test.ts +117 -0
  30. package/backend/db-client/connection-url.ts +126 -0
  31. package/backend/db-client/drivers/mongodb.ts +2 -14
  32. package/backend/db-client/drivers/mysql.ts +2 -8
  33. package/backend/db-client/drivers/postgres.ts +10 -13
  34. package/backend/db-client/drivers/redis.ts +2 -6
  35. package/backend/db-client/env/detect.ts +438 -0
  36. package/backend/db-client/env/diff.ts +94 -0
  37. package/backend/db-client/env/env.test.ts +574 -0
  38. package/backend/db-client/env/index.ts +15 -0
  39. package/backend/db-client/env/naming.ts +202 -0
  40. package/backend/db-client/env/service.ts +487 -0
  41. package/backend/db-client/integrations/index.ts +7 -0
  42. package/backend/db-client/integrations/links.ts +41 -10
  43. package/backend/db-client/providers/neon/adapter.ts +522 -0
  44. package/backend/db-client/providers/neon/api-types.ts +182 -0
  45. package/backend/db-client/providers/neon/client.ts +298 -0
  46. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  47. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  48. package/backend/db-client/providers/neon/list.test.ts +181 -0
  49. package/backend/db-client/providers/supabase/adapter.ts +25 -2
  50. package/backend/db-client/providers/types.ts +57 -0
  51. package/backend/engine/adapters/claude/stream.ts +2 -1
  52. package/backend/engine/adapters/cline/stream.ts +3 -3
  53. package/backend/engine/adapters/codex/stream.ts +3 -3
  54. package/backend/engine/adapters/copilot/stream.ts +3 -3
  55. package/backend/engine/adapters/cursor/stream.ts +25 -3
  56. package/backend/engine/adapters/opencode/stream.ts +4 -6
  57. package/backend/engine/adapters/pi/stream.ts +2 -2
  58. package/backend/engine/adapters/qwen/stream.ts +2 -2
  59. package/backend/engine/artifact-sync.ts +26 -20
  60. package/backend/engine/docs/artifacts.md +81 -22
  61. package/backend/engine/docs/quick-reference.md +2 -1
  62. package/backend/engine/resolve-model.test.ts +108 -0
  63. package/backend/engine/resolve-model.ts +53 -10
  64. package/backend/engine/structured-helpers.ts +22 -0
  65. package/backend/env-files/discovery.ts +48 -0
  66. package/backend/env-files/edit.ts +213 -0
  67. package/backend/env-files/env-files.test.ts +515 -0
  68. package/backend/env-files/git.ts +27 -0
  69. package/backend/env-files/index.ts +44 -0
  70. package/backend/env-files/keys.ts +69 -0
  71. package/backend/env-files/parse.ts +157 -0
  72. package/backend/env-files/write.ts +229 -0
  73. package/backend/files/file-shares.ts +369 -0
  74. package/backend/files/path-browsing.ts +27 -21
  75. package/backend/http/files-shared.test.ts +505 -0
  76. package/backend/http/files-shared.ts +351 -0
  77. package/backend/http/push.ts +150 -0
  78. package/backend/index.ts +8 -0
  79. package/backend/instructions/index.ts +1 -1
  80. package/backend/instructions/sync.ts +30 -6
  81. package/backend/integrations/health.ts +18 -4
  82. package/backend/integrations/projections/types.ts +9 -2
  83. package/backend/integrations/registry/index.ts +3 -0
  84. package/backend/integrations/registry/providers/context7.ts +1 -0
  85. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  86. package/backend/integrations/registry/providers/github.ts +1 -0
  87. package/backend/integrations/registry/providers/neon.ts +55 -0
  88. package/backend/integrations/registry/providers/supabase.ts +1 -0
  89. package/backend/integrations/registry/providers/vercel.ts +1 -0
  90. package/backend/integrations/registry/types.ts +2 -0
  91. package/backend/memory/compose.ts +2 -2
  92. package/backend/memory/consolidate.ts +2 -2
  93. package/backend/memory/extract/episodic.ts +2 -2
  94. package/backend/memory/judge.ts +2 -2
  95. package/backend/profiles/service.ts +7 -6
  96. package/backend/push/sender.ts +172 -0
  97. package/backend/push/tags.ts +25 -0
  98. package/backend/push/vapid-keys.ts +77 -0
  99. package/backend/push/webpush-crypto.test.ts +200 -0
  100. package/backend/push/webpush-crypto.ts +231 -0
  101. package/backend/skills/detect.ts +28 -0
  102. package/backend/skills/index.ts +22 -4
  103. package/backend/skills/invoke.test.ts +114 -0
  104. package/backend/skills/invoke.ts +222 -0
  105. package/backend/skills/service.ts +194 -44
  106. package/backend/skills/spec.ts +35 -0
  107. package/backend/skills/sync.ts +85 -55
  108. package/backend/subagents/detect.ts +2 -3
  109. package/backend/subagents/sync.ts +15 -8
  110. package/backend/work/pull-requests.ts +2 -2
  111. package/backend/work/start-work.ts +4 -0
  112. package/backend/worktrees/branching/engine.ts +557 -0
  113. package/backend/worktrees/branching/index.ts +56 -0
  114. package/backend/worktrees/branching/naming.test.ts +118 -0
  115. package/backend/worktrees/branching/naming.ts +97 -0
  116. package/backend/worktrees/branching/projector.test.ts +229 -0
  117. package/backend/worktrees/branching/projector.ts +139 -0
  118. package/backend/worktrees/branching/providers/neon.ts +220 -0
  119. package/backend/worktrees/branching/registry.ts +27 -0
  120. package/backend/worktrees/branching/service.ts +620 -0
  121. package/backend/worktrees/branching/suggest.test.ts +154 -0
  122. package/backend/worktrees/branching/suggest.ts +202 -0
  123. package/backend/worktrees/branching/types.ts +88 -0
  124. package/backend/worktrees/index.ts +7 -0
  125. package/backend/worktrees/service.ts +48 -1
  126. package/backend/ws/chat/stream.ts +100 -8
  127. package/backend/ws/db-client/env.ts +142 -0
  128. package/backend/ws/db-client/index.ts +2 -0
  129. package/backend/ws/files/index.ts +4 -0
  130. package/backend/ws/files/share.ts +95 -0
  131. package/backend/ws/git/branch-name.ts +2 -2
  132. package/backend/ws/git/commit-message.ts +2 -2
  133. package/backend/ws/index.ts +3 -4
  134. package/backend/ws/profiles/crud.ts +2 -3
  135. package/backend/ws/projects/index.ts +6 -1
  136. package/backend/ws/projects/info.ts +70 -6
  137. package/backend/ws/projects/overview.test.ts +108 -0
  138. package/backend/ws/projects/overview.ts +300 -0
  139. package/backend/ws/skills/catalog.ts +5 -1
  140. package/backend/ws/skills/crud.ts +128 -22
  141. package/backend/ws/skills/index.ts +4 -1
  142. package/backend/ws/system/device-info.ts +307 -76
  143. package/backend/ws/user/crud.ts +12 -3
  144. package/backend/ws/worktrees/branching.ts +212 -0
  145. package/backend/ws/worktrees/crud.ts +33 -7
  146. package/backend/ws/worktrees/index.ts +14 -0
  147. package/dist/assets/{index-C8Gi-b6U.js → index-CeNKKSDR.js} +1 -1
  148. package/dist/assets/{index-BrF6nqld.js → index-DW89566K.js} +1 -1
  149. package/dist/assets/main-Cy5DXWPT.js +1207 -0
  150. package/dist/assets/main-DJKj_4By.css +1 -0
  151. package/dist/index.html +7 -2
  152. package/dist/sw.js +112 -0
  153. package/package.json +1 -1
  154. package/shared/constants/engine-tools.ts +31 -6
  155. package/shared/constants/notification-messages.ts +142 -0
  156. package/shared/constants/tool-icons.ts +6 -2
  157. package/shared/types/db-client/env.ts +192 -0
  158. package/shared/types/db-client/index.ts +1 -0
  159. package/shared/types/db-client/integrations.ts +30 -0
  160. package/shared/types/integrations.ts +9 -0
  161. package/shared/types/unified/stream.ts +7 -0
  162. package/shared/types/worktree-branching.ts +315 -0
  163. package/shared/utils/logger.ts +1 -0
  164. package/backend/commands/detect.ts +0 -25
  165. package/backend/commands/index.ts +0 -9
  166. package/backend/commands/service.ts +0 -178
  167. package/backend/commands/store.ts +0 -45
  168. package/backend/commands/sync.ts +0 -94
  169. package/backend/database/queries/command-queries.ts +0 -82
  170. package/backend/ws/commands/crud.ts +0 -157
  171. package/backend/ws/commands/index.ts +0 -8
  172. package/dist/assets/main-Bd3gb79F.css +0 -1
  173. package/dist/assets/main-Bo1hD7mt.js +0 -1191
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Tests for guessing which database a project's worktrees should copy.
3
+ *
4
+ * The cases here are the two failure directions, and they are not symmetric.
5
+ * A MISSED suggestion costs a checkbox the user could have had; a WRONG one
6
+ * offers to copy the wrong database, and the user finds out when their worktree
7
+ * points somewhere unexpected. So the matching is tested for what it refuses as
8
+ * carefully as for what it finds.
9
+ */
10
+
11
+ import { describe, it, expect, beforeAll, beforeEach, afterEach, afterAll } from 'bun:test';
12
+ import fs from 'fs/promises';
13
+ import os from 'os';
14
+ import path from 'path';
15
+ import { closeDatabase, initializeDatabase } from '$backend/database';
16
+ import { dbClientConnectionQueries } from '$backend/database/queries';
17
+ import type { DbClientConnectionInput } from '$shared/types/db-client';
18
+ import { suggestBranchSource } from './suggest';
19
+
20
+ let root: string;
21
+
22
+ function addConnection(overrides: Partial<DbClientConnectionInput> = {}) {
23
+ return dbClientConnectionQueries.create({
24
+ name: 'Local Postgres',
25
+ driver: 'postgres',
26
+ host: 'localhost',
27
+ port: 5432,
28
+ username: 'app',
29
+ password: 'pw',
30
+ database: 'shop',
31
+ sslMode: 'disable',
32
+ ...overrides
33
+ } as DbClientConnectionInput);
34
+ }
35
+
36
+ beforeAll(async () => {
37
+ await initializeDatabase();
38
+ });
39
+
40
+ afterAll(() => {
41
+ closeDatabase();
42
+ });
43
+
44
+ beforeEach(async () => {
45
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'clopen-suggest-'));
46
+ for (const connection of dbClientConnectionQueries.list()) {
47
+ dbClientConnectionQueries.delete(connection.id);
48
+ }
49
+ });
50
+
51
+ afterEach(async () => {
52
+ await fs.rm(root, { recursive: true, force: true });
53
+ });
54
+
55
+ describe('suggestBranchSource', () => {
56
+ it('matches the project’s DATABASE_URL to a saved connection', async () => {
57
+ addConnection();
58
+ await fs.writeFile(
59
+ path.join(root, '.env'),
60
+ 'APP_NAME=shop\nDATABASE_URL=postgres://app:pw@localhost:5432/shop\n'
61
+ );
62
+
63
+ const suggestion = await suggestBranchSource(root);
64
+
65
+ expect(suggestion).toMatchObject({
66
+ sourceKind: 'connection',
67
+ sourceLabel: 'Local Postgres',
68
+ parentRef: 'shop',
69
+ envVar: 'DATABASE_URL',
70
+ envFile: '.env'
71
+ });
72
+ });
73
+
74
+ it('treats localhost and 127.0.0.1 as the same machine', async () => {
75
+ // They are, and a project that writes one while the connection was saved
76
+ // with the other is the ordinary case rather than an edge one.
77
+ addConnection({ host: '127.0.0.1' });
78
+ await fs.writeFile(path.join(root, '.env'), 'DATABASE_URL=postgres://app@localhost/shop\n');
79
+
80
+ expect((await suggestBranchSource(root))?.parentRef).toBe('shop');
81
+ });
82
+
83
+ it('reads the most-precedent file first', async () => {
84
+ // The same order the project's own framework reads them in, which is the
85
+ // only order that can be right.
86
+ addConnection();
87
+ addConnection({ name: 'Other Postgres', port: 5433 });
88
+ await fs.writeFile(path.join(root, '.env'), 'DATABASE_URL=postgres://app@localhost:5433/legacy\n');
89
+ await fs.writeFile(path.join(root, '.env.local'), 'DATABASE_URL=postgres://app@localhost:5432/shop\n');
90
+
91
+ const suggestion = await suggestBranchSource(root);
92
+ expect(suggestion?.envFile).toBe('.env.local');
93
+ expect(suggestion?.parentRef).toBe('shop');
94
+ });
95
+
96
+ it('suggests nothing when no connection reaches that server', async () => {
97
+ // Clopen would have the address but not the password, so the offer would
98
+ // fail at the moment of use — worse than no offer.
99
+ addConnection({ host: 'db.example.com' });
100
+ await fs.writeFile(path.join(root, '.env'), 'DATABASE_URL=postgres://app@localhost:5432/shop\n');
101
+
102
+ expect(await suggestBranchSource(root)).toBe(null);
103
+ });
104
+
105
+ it('does not match a different engine on the same host and port', async () => {
106
+ addConnection({ driver: 'mysql', port: 5432 });
107
+ await fs.writeFile(path.join(root, '.env'), 'DATABASE_URL=postgres://app@localhost:5432/shop\n');
108
+
109
+ expect(await suggestBranchSource(root)).toBe(null);
110
+ });
111
+
112
+ it('ignores a URL that is not a database', async () => {
113
+ addConnection();
114
+ await fs.writeFile(
115
+ path.join(root, '.env'),
116
+ 'NEXT_PUBLIC_API_URL=https://api.example.com\nSENTRY_DSN=https://x@sentry.io/1\n'
117
+ );
118
+
119
+ expect(await suggestBranchSource(root)).toBe(null);
120
+ });
121
+
122
+ it('never reads a live value out of a template', async () => {
123
+ // `.env.example` holds placeholders, and a placeholder that happens to
124
+ // parse would bind the project to a database nobody uses.
125
+ addConnection();
126
+ await fs.writeFile(
127
+ path.join(root, '.env.example'),
128
+ 'DATABASE_URL=postgres://app@localhost:5432/shop\n'
129
+ );
130
+
131
+ expect(await suggestBranchSource(root)).toBe(null);
132
+ });
133
+
134
+ it('resolves a relative SQLite path against the project, not the cwd', async () => {
135
+ const file = path.join(root, 'data', 'dev.db');
136
+ await fs.mkdir(path.dirname(file), { recursive: true });
137
+ await fs.writeFile(file, '');
138
+ addConnection({ driver: 'sqlite', host: undefined, port: undefined, database: file });
139
+ await fs.writeFile(path.join(root, '.env'), 'DATABASE_URL=file:./data/dev.db\n');
140
+
141
+ const suggestion = await suggestBranchSource(root);
142
+ expect(suggestion?.parentRef).toBe(file);
143
+ expect(suggestion?.parentName).toBe('dev.db');
144
+ });
145
+
146
+ it('will not copy a copy', async () => {
147
+ // A worktree's own database is already disposable; nesting one inside
148
+ // another is a tree nobody can reason about.
149
+ addConnection({ options: { worktreeBranch: { branchId: 'b1', worktreeId: 'w1' } } });
150
+ await fs.writeFile(path.join(root, '.env'), 'DATABASE_URL=postgres://app@localhost:5432/shop\n');
151
+
152
+ expect(await suggestBranchSource(root)).toBe(null);
153
+ });
154
+ });
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Working out, unprompted, which database a project's worktrees should copy.
3
+ *
4
+ * This is what turns the feature from "configure it first" into "tick the box".
5
+ * A project that uses a database already says so in its `.env`, and Clopen
6
+ * already has a connection list — so the binding a user would otherwise build
7
+ * by hand, from a picker of servers and a picker of databases, is derivable
8
+ * from two things already on disk.
9
+ *
10
+ * MATCHED, NEVER INVENTED. A URL that corresponds to no saved connection
11
+ * produces no suggestion: Clopen would have the address but not the password,
12
+ * and offering to copy a database it cannot open would be an offer that fails
13
+ * at the moment of use. The user adds the connection in DB Client once, and the
14
+ * suggestion appears by itself afterwards.
15
+ */
16
+
17
+ import path from 'path';
18
+ import fs from 'fs/promises';
19
+ import { dbClientConnectionQueries } from '$backend/database/queries';
20
+ import { listEnvFileEntries, parseDotenv } from '$backend/env-files';
21
+ import { DEFAULT_PORTS } from '$backend/db-client/connection-url';
22
+ import { canBranchFrom, cloneSupport } from '$backend/db-client/cloning';
23
+ import type { DbClientConnection, DbDriver } from '$shared/types/db-client';
24
+ import type { BranchSuggestion } from '$shared/types/worktree-branching';
25
+ import { debug } from '$shared/utils/logger';
26
+
27
+ export type { BranchSuggestion };
28
+
29
+ const DRIVER_NAMES: Record<DbDriver, string> = {
30
+ postgres: 'PostgreSQL',
31
+ mysql: 'MySQL',
32
+ sqlite: 'SQLite',
33
+ mongodb: 'MongoDB',
34
+ redis: 'Redis',
35
+ mssql: 'SQL Server'
36
+ };
37
+
38
+ /** Which driver a URL scheme belongs to. */
39
+ const DRIVER_OF_SCHEME: Record<string, DbDriver> = {
40
+ postgres: 'postgres',
41
+ postgresql: 'postgres',
42
+ mysql: 'mysql',
43
+ mysql2: 'mysql',
44
+ mongodb: 'mongodb',
45
+ 'mongodb+srv': 'mongodb',
46
+ redis: 'redis',
47
+ rediss: 'redis',
48
+ mssql: 'mssql',
49
+ sqlserver: 'mssql',
50
+ sqlite: 'sqlite',
51
+ file: 'sqlite'
52
+ };
53
+
54
+ interface ParsedUrl {
55
+ driver: DbDriver;
56
+ host: string;
57
+ port: number | null;
58
+ database: string;
59
+ }
60
+
61
+ /**
62
+ * A connection URL, reduced to the four things matching needs.
63
+ *
64
+ * Deliberately not `new URL()` alone: SQLite's `file:./dev.db` has no host and
65
+ * no authority, and Mongo's `mongodb+srv://` has no port. Both are ordinary
66
+ * here, so each is handled rather than dropped.
67
+ */
68
+ function parseUrl(raw: string): ParsedUrl | null {
69
+ const match = /^([a-z][a-z0-9+.-]*):/i.exec(raw.trim());
70
+ if (!match) return null;
71
+ const driver = DRIVER_OF_SCHEME[match[1].toLowerCase()];
72
+ if (!driver) return null;
73
+
74
+ if (driver === 'sqlite') {
75
+ const file = raw.trim().replace(/^[a-z][a-z0-9+.-]*:(\/\/)?/i, '');
76
+ return file ? { driver, host: '', port: null, database: file } : null;
77
+ }
78
+
79
+ try {
80
+ const url = new URL(raw.trim());
81
+ return {
82
+ driver,
83
+ host: url.hostname,
84
+ port: url.port ? Number(url.port) : null,
85
+ database: decodeURIComponent(url.pathname.replace(/^\//, ''))
86
+ };
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
92
+ /** `localhost` and `127.0.0.1` are the same machine and must match each other. */
93
+ function normalizeHost(host: string): string {
94
+ const lower = host.toLowerCase();
95
+ if (lower === '127.0.0.1' || lower === '::1' || lower === '0.0.0.0') return 'localhost';
96
+ return lower;
97
+ }
98
+
99
+ function portOf(driver: DbDriver, port: number | null): number | null {
100
+ return port ?? DEFAULT_PORTS[driver];
101
+ }
102
+
103
+ /**
104
+ * The saved connection this URL is pointing at, if Clopen has one.
105
+ *
106
+ * The DATABASE is not part of the match. A project's `.env` names one database
107
+ * on a server, and the connection in DB Client may have been saved against
108
+ * another on the same server — they are still the same credential, and the
109
+ * database is what the suggestion then proposes to copy.
110
+ */
111
+ function matchConnection(parsed: ParsedUrl): DbClientConnection | null {
112
+ for (const connection of dbClientConnectionQueries.list()) {
113
+ if (connection.driver !== parsed.driver) continue;
114
+ if (!canBranchFrom(connection)) continue;
115
+ if (connection.options?.worktreeBranch) continue;
116
+
117
+ if (parsed.driver === 'sqlite') {
118
+ if (path.resolve(connection.database ?? '') === path.resolve(parsed.database)) {
119
+ return connection;
120
+ }
121
+ continue;
122
+ }
123
+
124
+ if (normalizeHost(connection.host ?? '') !== normalizeHost(parsed.host)) continue;
125
+ if (portOf(parsed.driver, connection.port) !== portOf(parsed.driver, parsed.port)) continue;
126
+ return connection;
127
+ }
128
+ return null;
129
+ }
130
+
131
+ /**
132
+ * What this project's worktrees should copy, or null.
133
+ *
134
+ * The files are read most-precedent first and the first usable answer wins, so
135
+ * a `DATABASE_URL` in `.env.local` beats the one in `.env` — the same order the
136
+ * project's own framework reads them in, which is the only order that can be
137
+ * right.
138
+ *
139
+ * Templates are read too. `.env.example` names the variable without a live
140
+ * value, so it cannot be matched to a connection — but it is where the VARIABLE
141
+ * NAME comes from on a fresh clone, and that is half of what the binding needs.
142
+ */
143
+ export async function suggestBranchSource(root: string): Promise<BranchSuggestion | null> {
144
+ let files;
145
+ try {
146
+ files = await listEnvFileEntries(root);
147
+ } catch {
148
+ return null;
149
+ }
150
+
151
+ for (const file of files) {
152
+ if (file.isTemplate) continue;
153
+
154
+ let content: string;
155
+ try {
156
+ content = await fs.readFile(path.join(root, file.name), 'utf-8');
157
+ } catch {
158
+ continue;
159
+ }
160
+
161
+ for (const assignment of parseDotenv(content)) {
162
+ if (assignment.commented || !assignment.value) continue;
163
+
164
+ const parsed = parseUrl(assignment.value);
165
+ if (!parsed) continue;
166
+
167
+ // SQLite's path is relative to the project, not to Clopen's cwd.
168
+ if (parsed.driver === 'sqlite' && !path.isAbsolute(parsed.database)) {
169
+ parsed.database = path.resolve(root, parsed.database);
170
+ }
171
+
172
+ const connection = matchConnection(parsed);
173
+ if (!connection) {
174
+ debug.log(
175
+ 'worktree',
176
+ `${assignment.key} in ${file.name} names a database Clopen has no connection for`
177
+ );
178
+ continue;
179
+ }
180
+
181
+ const parentRef =
182
+ parsed.driver === 'sqlite'
183
+ ? parsed.database
184
+ : parsed.database || connection.database || '';
185
+ if (!parentRef) continue;
186
+
187
+ return {
188
+ sourceKind: 'connection',
189
+ sourceId: connection.id,
190
+ sourceLabel: connection.name,
191
+ providerName: DRIVER_NAMES[connection.driver],
192
+ parentRef,
193
+ parentName: parsed.driver === 'sqlite' ? path.basename(parentRef) : parentRef,
194
+ envVar: assignment.key,
195
+ envFile: file.name,
196
+ notice: cloneSupport(connection.driver).notice
197
+ };
198
+ }
199
+ }
200
+
201
+ return null;
202
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The contract a worktree-branching provider implements.
3
+ *
4
+ * The worktree manager owns a TABLE (`worktree_branches`), so like DB Client
5
+ * and unlike Issues and Deployments this capability feeds a projection. The
6
+ * adapter's whole job is to turn "this account, this parent database" into an
7
+ * isolated database and a connection string, and to answer the two questions
8
+ * the setup dialog asks: what can this credential reach, and is it working.
9
+ *
10
+ * NOT CALLED "branch" in the copy it produces. Neon cuts a real copy-on-write
11
+ * branch; Turso seeds an entire new database from a parent. Both satisfy this
12
+ * interface, and `info().noun` is what lets the dialog say which one is
13
+ * actually happening instead of calling a seeded database a branch. If a
14
+ * provider needs a second dialog, this interface is wrong and fixing it is the
15
+ * work — the same test `Task 2` and `Task 3` set for their surfaces.
16
+ *
17
+ * Everything a provider knows about its own service stays inside its file, the
18
+ * way `Task 3` kept Vercel's per-endpoint API versions inside the Vercel
19
+ * adapter.
20
+ */
21
+
22
+ import type {
23
+ BranchParent,
24
+ BranchProviderInfo,
25
+ CreatedBranch,
26
+ RemoteBranch
27
+ } from '$shared/types/worktree-branching';
28
+ import type { IntegrationStatus } from '$shared/types/integrations';
29
+
30
+ /** Everything an adapter is given about the account it is acting for. */
31
+ export interface BranchProviderContext {
32
+ accountId: string;
33
+ /** Decoded account credentials. Empty when the active key could not open them. */
34
+ credentials: Record<string, string>;
35
+ }
36
+
37
+ export interface BranchProviderAdapter {
38
+ /** Matches the integration provider id, so the brand mark is the same one. */
39
+ provider: string;
40
+ /** How the setup dialog renders this provider. */
41
+ info(): BranchProviderInfo;
42
+
43
+ /** Every database this credential can cut branches from. */
44
+ listParents(context: BranchProviderContext): Promise<BranchParent[]>;
45
+
46
+ /**
47
+ * Cut one, and say where it answers.
48
+ *
49
+ * `name` is the deterministic name computed by `naming.ts` — the adapter
50
+ * must use it verbatim where the provider allows, because it is the only
51
+ * thing tying a leaked branch back to the worktree it belonged to. A
52
+ * provider that rewrites it (a length cap, a character class) reports what
53
+ * it actually got as `CreatedBranch.name`.
54
+ *
55
+ * The returned connection carries a PASSWORD. It is sealed the moment it
56
+ * reaches `worktree_branches` and is never handed to the client.
57
+ */
58
+ createBranch(
59
+ context: BranchProviderContext,
60
+ input: { parentRef: string; name: string; pooled: boolean }
61
+ ): Promise<CreatedBranch>;
62
+
63
+ /**
64
+ * Destroy one.
65
+ *
66
+ * Must be IDEMPOTENT in the direction that matters: a branch that is already
67
+ * gone is a success, not an error. The caller reaches here while deleting a
68
+ * worktree, and turning "it was already deleted" into a failure would mark a
69
+ * perfectly clean deletion as a leaked branch and put it in the orphan list
70
+ * forever.
71
+ */
72
+ deleteBranch(
73
+ context: BranchProviderContext,
74
+ input: { parentRef: string; branchRef: string }
75
+ ): Promise<void>;
76
+
77
+ /**
78
+ * Every branch that exists at the provider right now.
79
+ *
80
+ * Used by the orphan sweep, which is the half of leak detection that a local
81
+ * table cannot do: a crash between "the provider created it" and "the row was
82
+ * written" leaves a branch nothing here knows about.
83
+ */
84
+ listBranches(context: BranchProviderContext, parentRef: string): Promise<RemoteBranch[]>;
85
+
86
+ /** Health of the credential itself, for the hub's status strip. */
87
+ probe(context: BranchProviderContext): Promise<{ status: IntegrationStatus; detail: string | null }>;
88
+ }
@@ -1,5 +1,9 @@
1
1
  /**
2
2
  * Worktrees — isolated copies of a project that chat sessions can run in.
3
+ *
4
+ * `branching/` is re-exported from here so importing this module is what wires
5
+ * the `worktree-branching` capability up — the same side-effect registration
6
+ * `backend/db-client/integrations/` does for `database`.
3
7
  */
4
8
 
5
9
  export {
@@ -27,3 +31,6 @@ export {
27
31
 
28
32
  export { planMerge, type MergeEntry, type MergePlan, type MergeResolution } from './merge';
29
33
  export { getProjectWorktreesDir, getWorktreePath, getWorktreesRootDir, isPathInside, slugifyWorktreeName, uniqueWorktreeSlug } from './paths';
34
+
35
+ export { worktreeBranching } from './branching';
36
+ export type { BranchProviderAdapter, BranchProviderContext } from './branching';
@@ -5,6 +5,7 @@
5
5
  import fs from 'fs/promises';
6
6
  import path from 'path';
7
7
  import type { Worktree } from '$shared/types/database/schema';
8
+ import type { WorktreeBranchInfo } from '$shared/types/worktree-branching';
8
9
  import type { TreeMap } from '../snapshot/blob-store';
9
10
  import { projectQueries, worktreeQueries } from '../database/queries';
10
11
  import { fileWatcher } from '../files/file-watcher';
@@ -23,6 +24,8 @@ import {
23
24
  } from './merge';
24
25
  import { getProjectWorktreesDir, getWorktreePath, uniqueWorktreeSlug } from './paths';
25
26
  import { hashTree, readBlobText } from './tree';
27
+ import { worktreeBranching } from './branching';
28
+ import type { BranchDataMode } from '$shared/types/worktree-branching';
26
29
 
27
30
  /** Worktree → main is `apply`; main → worktree is `sync`. */
28
31
  export type TransferDirection = 'apply' | 'sync';
@@ -59,6 +62,16 @@ export interface WorktreeCreateResult {
59
62
  worktree: Worktree;
60
63
  fileCount: number;
61
64
  carriedIgnoredFiles: boolean;
65
+ /** The database branch cut for it, when the project is bound to a provider. */
66
+ branch: WorktreeBranchInfo | null;
67
+ /**
68
+ * Why no branch was cut, when one was expected.
69
+ *
70
+ * Reported rather than thrown, and that is the rule this whole feature runs
71
+ * on: the worktree is what the user asked for, and losing it because a third
72
+ * party is down or a plan limit was reached would be a poor trade.
73
+ */
74
+ branchError: string | null;
62
75
  }
63
76
 
64
77
  /**
@@ -72,6 +85,10 @@ export async function createWorktree(input: {
72
85
  projectId: string;
73
86
  name: string;
74
87
  createdBy?: string | null;
88
+ /** Skip the project's database branch for this one worktree. */
89
+ skipBranch?: boolean;
90
+ /** Overrides the project's default for THIS worktree only. */
91
+ dataMode?: BranchDataMode;
75
92
  }): Promise<WorktreeCreateResult> {
76
93
  const project = projectQueries.getById(input.projectId);
77
94
  if (!project) throw new Error('Project not found');
@@ -110,7 +127,23 @@ export async function createWorktree(input: {
110
127
  });
111
128
 
112
129
  debug.log('worktree', `Created worktree "${worktree.name}" (${clone.mode}) at ${targetPath}`);
113
- return { worktree, fileCount: clone.fileCount, carriedIgnoredFiles: clone.carriedIgnoredFiles };
130
+
131
+ // AFTER the clone, never before. The clone is the expensive step that
132
+ // genuinely fails — a missing project path, a full disk, an unreadable tree —
133
+ // and cutting a remote branch first would leak one at the provider on every
134
+ // failed create. `attach` never throws.
135
+ const branch = await worktreeBranching.attach(worktree, {
136
+ skip: input.skipBranch,
137
+ dataMode: input.dataMode
138
+ });
139
+
140
+ return {
141
+ worktree,
142
+ fileCount: clone.fileCount,
143
+ carriedIgnoredFiles: clone.carriedIgnoredFiles,
144
+ branch: branch.branch,
145
+ branchError: branch.error
146
+ };
114
147
  }
115
148
 
116
149
  /** Delete the worktree directory and its row. Sessions fall back to the main tree. */
@@ -118,6 +151,13 @@ export async function removeWorktree(worktreeId: string): Promise<void> {
118
151
  const worktree = worktreeQueries.getById(worktreeId);
119
152
  if (!worktree) return;
120
153
 
154
+ // BEFORE the directory and the row go, so the branch is still reachable
155
+ // through its own row. A failure here does not stop the deletion — it leaves
156
+ // the branch row behind as a reportable orphan instead, because the user has
157
+ // already said what they want and refusing to delete a worktree over a
158
+ // third-party outage would trap them.
159
+ await worktreeBranching.detach(worktree.id);
160
+
121
161
  // Shells and browser tabs live in the worktree's own scope; without this they
122
162
  // would outlive the directory they were opened in.
123
163
  releaseWorkspaceScope(worktree.project_id, worktree.id);
@@ -131,6 +171,13 @@ export async function removeWorktree(worktreeId: string): Promise<void> {
131
171
 
132
172
  /** Remove every worktree of a project — used when the project itself is deleted. */
133
173
  export async function removeProjectWorktrees(projectId: string): Promise<void> {
174
+ // Detached one at a time BEFORE the rows go, for the reason `removeWorktree`
175
+ // does it: once the worktree rows are deleted, `worktree_id` is null on every
176
+ // branch and they all read as orphans whether or not they were cleaned up.
177
+ for (const worktree of worktreeQueries.getByProjectId(projectId)) {
178
+ await worktreeBranching.detach(worktree.id);
179
+ }
180
+
134
181
  for (const worktree of worktreeQueries.deleteByProjectId(projectId)) {
135
182
  releaseWorkspaceScope(projectId, worktree.id);
136
183
  }