@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
@@ -157,6 +157,54 @@ export const ADMIN_ONLY_ROUTES = new Set([
157
157
  'integrations:disconnect',
158
158
  'integrations:health',
159
159
  'integrations:secrets-health',
160
+ // Account-backed database connections. Linking reads a credential belonging
161
+ // to the install rather than to the caller, and projects a connection every
162
+ // admin sees — the same reason the rest of the integrations surface is
163
+ // admin-only. The ordinary db-client routes stay open: a member still
164
+ // manages their own hand-typed connections exactly as before.
165
+ 'db-client:providers',
166
+ 'db-client:remote-databases',
167
+ 'db-client:create-options',
168
+ // Provisions real infrastructure against the account's quota, which is as
169
+ // outward-facing as anything on this surface gets. Creating an organisation
170
+ // creates a BILLING entity, which is more so.
171
+ 'db-client:create-group',
172
+ 'db-client:create-database',
173
+ // Renames a database everyone at the provider sees.
174
+ 'db-client:rename-database',
175
+ // Destroys a database and everything in it.
176
+ 'db-client:delete-database',
177
+ 'db-client:link',
178
+ 'db-client:update-link',
179
+ 'db-client:unlink',
180
+ // Applying a migration changes a schema everyone shares, and writing types
181
+ // writes a file into the repository. The Supabase READS are not listed, so
182
+ // anyone who can use the connection can look.
183
+ 'db-client:supabase-apply-migration',
184
+ 'db-client:supabase-write-types',
185
+ // Worktree database branching. Pointing a project at a parent database
186
+ // commits an account's quota to it, and deleting a branch destroys a real
187
+ // database — both spend a credential that belongs to the install rather than
188
+ // to the caller, the same reason `db-client:link` is gated.
189
+ //
190
+ // `worktrees:branching-state` and `worktrees:branch-rewrite-env` are
191
+ // deliberately NOT listed: a member has to be able to see whether their own
192
+ // worktree got a branch, and to retry the dotenv write when it was refused.
193
+ //
194
+ // NEITHER ARE `worktrees:branch-parents` AND `worktrees:branching-save`, and
195
+ // that is a change rather than an oversight. They used to be here because a
196
+ // binding could only point at an integration account, and committing the
197
+ // install's quota is an admin decision. A binding can now point at a DB
198
+ // Client connection instead — a database the member themselves saved — and
199
+ // refusing that would make "give this worktree its own database" an
200
+ // admin-only feature for no reason that survives being stated. The account
201
+ // half keeps the old rule: `listBranchSources` shows accounts to admins
202
+ // only, and `requireSource` refuses anything the caller cannot see.
203
+ 'worktrees:branching-clear',
204
+ 'worktrees:branch-orphans',
205
+ 'worktrees:branch-delete',
206
+ 'worktrees:branch-forget',
207
+ 'worktrees:branch-delete-remote',
160
208
  // Memory Graph — the graph is instance-global and is injected into every
161
209
  // future turn on every engine, so editing it changes what every agent is told.
162
210
  // Mutations only: the read surface (memory:graph / :node / :search / :stats /
@@ -1338,7 +1338,7 @@ class StreamManager extends EventEmitter {
1338
1338
  return null;
1339
1339
  })
1340
1340
  .then(delta => {
1341
- void ingestTurn({
1341
+ ingestTurn({
1342
1342
  projectId,
1343
1343
  projectPath,
1344
1344
  sessionId: chatSessionId,
@@ -27,7 +27,15 @@ export const SECRET_COLUMNS: Record<string, readonly string[]> = {
27
27
  db_client_connections: ['password', 'ssh_password', 'ssh_private_key', 'ssh_passphrase'],
28
28
  ssh_connections: ['password', 'private_key', 'passphrase'],
29
29
  engine_accounts: ['credential'],
30
- integration_accounts: ['credentials']
30
+ integration_accounts: ['credentials'],
31
+ // The secret a linked remote database needs, which is NOT always the same as
32
+ // the account's credential — a Supabase Management API token cannot read
33
+ // back the Postgres password, so the password lives here and nowhere else.
34
+ integration_db_links: ['secrets'],
35
+ // A worktree's branch database answers on a connection string that carries
36
+ // its own password — generated by the provider and never typed by anyone, so
37
+ // this row is the only place it exists.
38
+ worktree_branches: ['connection_json']
31
39
  } as const;
32
40
 
33
41
  /** Column names of one table, or an empty list when the table holds no secrets. */
@@ -0,0 +1,54 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create deploy_bindings for the Deployments surface';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating deploy_bindings table...');
8
+
9
+ // Which remote project a Clopen project deploys to, through one account.
10
+ //
11
+ // Belongs to the SURFACE, not to the account layer, for the same reason
12
+ // `work_bindings` does: an account is one Vercel token, while "which Vercel
13
+ // project is this" is per project, and two projects sharing one token is the
14
+ // normal case.
15
+ //
16
+ // This is a sibling of `work_bindings` rather than a generalisation of it.
17
+ // The columns differ where it matters: `display_name` exists because a
18
+ // deployment locator is an opaque `prj_8Qc…` that means nothing to a reader,
19
+ // unlike an `owner/repo` that describes itself, and `team_id` exists because
20
+ // one token reaches several teams and the team is a property of which
21
+ // project you picked — not of the credential.
22
+ //
23
+ // Nothing about a deployment itself is stored. The provider is the truthful
24
+ // answer for state, logs and URLs, all three go stale within seconds, and
25
+ // there is no local artifact (no worktree, no branch) that would survive the
26
+ // remote record — so unlike the Issues surface there is not even a link
27
+ // table here.
28
+ db.exec(`
29
+ CREATE TABLE IF NOT EXISTS deploy_bindings (
30
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
31
+ account_id TEXT NOT NULL REFERENCES integration_accounts(id) ON DELETE CASCADE,
32
+ locator TEXT NOT NULL,
33
+ display_name TEXT NOT NULL DEFAULT '',
34
+ team_id TEXT,
35
+ detected INTEGER NOT NULL DEFAULT 0,
36
+ config_json TEXT NOT NULL DEFAULT '{}',
37
+ created_at TEXT NOT NULL,
38
+ updated_at TEXT NOT NULL,
39
+ PRIMARY KEY (project_id, account_id)
40
+ )
41
+ `);
42
+
43
+ db.exec(`
44
+ CREATE INDEX IF NOT EXISTS idx_deploy_bindings_account
45
+ ON deploy_bindings(account_id)
46
+ `);
47
+
48
+ debug.log('migration', 'Deploy bindings table created');
49
+ };
50
+
51
+ export const down = (db: DatabaseConnection): void => {
52
+ debug.log('migration', 'Dropping deploy_bindings table...');
53
+ db.exec('DROP TABLE IF EXISTS deploy_bindings');
54
+ };
@@ -0,0 +1,229 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description =
5
+ 'Remove the structural half of the Memory Graph and keep a memory\'s file paths as an attribute';
6
+
7
+ /**
8
+ * The code half of the graph is removed, and the paths it existed to anchor
9
+ * become an attribute of the memory itself.
10
+ *
11
+ * Migration 066 stored the codebase as nodes — a node per file, per directory
12
+ * and up to twenty-five per file's symbols — on the argument that a question
13
+ * about code could then travel to the decisions made around it. Measured on a
14
+ * real store, that half was 81% of the nodes (9,053 of 11,159) and 88% of the
15
+ * edges, and it was paying for almost none of what it cost:
16
+ *
17
+ * - IT NEVER REACHED THE AGENT. `context.ts` drops structural hits before
18
+ * building the injected block, deliberately: the agent can read the
19
+ * repository, so spending recall budget to tell it a file exists is worse
20
+ * than saying nothing.
21
+ * - IT CROWDED OUT THE MEMORIES. Structural nodes carry no vector (they are
22
+ * names and paths; embedding them produces a bag of fragments), so they
23
+ * competed only in BM25 — where they won, because there were four times as
24
+ * many of them and they match exactly whenever a turn mentions a path.
25
+ * `RETRIEVAL_DEPTH` had been raised from 18 to 60 purely to leave room for
26
+ * the episodic hits underneath them.
27
+ * - MOST OF IT WAS UNREFERENCED. Of 1,920 `about` edges, 1,903 pointed at a
28
+ * file and 17 at a module. NONE pointed at a symbol — so 4,458 symbol nodes
29
+ * and their 4,458 `defines` edges were never once the reason a memory was
30
+ * found.
31
+ *
32
+ * What the half genuinely did was answer one question: WHICH FILES DOES THIS
33
+ * MEMORY CLAIM SOMETHING ABOUT. Structural invalidation needs it (age the
34
+ * memories standing on code that just changed) and so does anchor seeding (a
35
+ * turn that says only "continue" still reaches the memories attached to the file
36
+ * in front of it). That question needs a path, not a node.
37
+ *
38
+ * So paths are demoted from nodes to an attribute, exactly as migration 066
39
+ * already did for entities after canonical entity nodes became half the graph.
40
+ * The lookups get cheaper rather than poorer: invalidation and anchoring are now
41
+ * one index seek into `graph_node_paths` instead of a path → file-node → `about`
42
+ * edge hop, and nothing has to be kept in sync with a parallel node population.
43
+ *
44
+ * `kind` stays on `graph_nodes` as a constant `'episodic'`. It is part of the
45
+ * unique digest index and of the FTS mirror's schema, and rebuilding both across
46
+ * a live memory store to reclaim one constant column would be real risk for no
47
+ * benefit. The application no longer has the concept at all.
48
+ *
49
+ * EVERY STEP HERE IS RE-RUNNABLE, and that is a correctness requirement rather
50
+ * than tidiness. The runner records a migration only after `up` RETURNS, and it
51
+ * wraps nothing in a transaction — so an interrupted run leaves the schema
52
+ * partly changed and the migration still pending. The second run then hits its
53
+ * own output: the backfill reads `graph_nodes.path`, which the first run had
54
+ * already dropped, and the failure is not soft. `initializeDatabase` refuses to
55
+ * start, so the app will not boot again until someone edits the database by
56
+ * hand. Deletes keyed on `kind = 'structural'` are naturally idempotent; the two
57
+ * steps that are not are guarded on whether the old column is still there.
58
+ *
59
+ * There is deliberately NO `VACUUM`. Deleting four fifths of the graph leaves
60
+ * free pages worth reclaiming, but on a real 2.7 GB store the vacuum took around
61
+ * ninety seconds — with the server not yet listening and nothing on screen to
62
+ * explain the wait. A user who gives up and restarts then has two processes
63
+ * racing on one file. The pages are reused as the database grows; reclaiming
64
+ * them is not worth owning that window.
65
+ */
66
+ /**
67
+ * Whether a table exists, so this migration can run against a database holding
68
+ * only the graph. The memory tests build one from 066 and this file alone, and
69
+ * both `graph_layout` (067) and `settings` are outside that pair.
70
+ */
71
+ function hasTable(db: DatabaseConnection, name: string): boolean {
72
+ const row = db
73
+ .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`)
74
+ .get(name) as { name: string } | null;
75
+ return row !== null && row !== undefined;
76
+ }
77
+
78
+ /** Whether a column is still present — the test for "has this already run". */
79
+ function hasColumn(db: DatabaseConnection, table: string, column: string): boolean {
80
+ const rows = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];
81
+ return rows.some(row => row.name === column);
82
+ }
83
+
84
+ export const up = (db: DatabaseConnection): void => {
85
+ debug.log('migration', 'Removing the structural half of the memory graph...');
86
+
87
+ // ── the paths a memory is about ──────────────────────────────────────────
88
+ // Shaped like `graph_node_entities`: keyed by node, replaced wholesale when
89
+ // extraction re-reads a memory, cascading away with it. `path` is indexed on
90
+ // its own because the hot direction is the reverse one — "these files just
91
+ // changed, which memories claimed something about them".
92
+ db.exec(`
93
+ CREATE TABLE IF NOT EXISTS graph_node_paths (
94
+ node_id TEXT NOT NULL REFERENCES graph_nodes(id) ON DELETE CASCADE,
95
+ path TEXT NOT NULL,
96
+ PRIMARY KEY (node_id, path)
97
+ )
98
+ `);
99
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_node_paths_path ON graph_node_paths (path)`);
100
+
101
+ // Carry the existing attributions over BEFORE anything is deleted: an `about`
102
+ // edge already records precisely this, it is simply pointing at a node instead
103
+ // of naming a string.
104
+ //
105
+ // Skipped when `path` is already gone, which means an earlier run of this
106
+ // migration got at least this far. Reading it unconditionally is what turned an
107
+ // interrupted run into a database that would not open.
108
+ if (hasColumn(db, 'graph_nodes', 'path')) {
109
+ db.exec(`
110
+ INSERT OR IGNORE INTO graph_node_paths (node_id, path)
111
+ SELECT e.src_id, d.path
112
+ FROM graph_edges e
113
+ INNER JOIN graph_nodes d ON d.id = e.dst_id
114
+ WHERE e.rel = 'about' AND d.kind = 'structural' AND d.path IS NOT NULL AND d.path <> ''
115
+ `);
116
+ }
117
+
118
+ const carried = (
119
+ db.prepare(`SELECT COUNT(*) AS c FROM graph_node_paths`).get() as { c: number }
120
+ ).c;
121
+
122
+ // ── remove the code nodes ────────────────────────────────────────────────
123
+ // The lexical mirror goes first and goes through `fts_rowid`, the way every
124
+ // other delete in this feature does: `graph_nodes_fts.node_id` is UNINDEXED,
125
+ // so matching on it is a full scan of a table that only grows.
126
+ db.exec(`
127
+ DELETE FROM graph_nodes_fts
128
+ WHERE rowid IN (
129
+ SELECT fts_rowid FROM graph_nodes WHERE kind = 'structural' AND fts_rowid IS NOT NULL
130
+ )
131
+ `);
132
+ // Then anything the rowid could not reach — a mirror row whose node was hard
133
+ // deleted at some point without its `fts_rowid` being cleared.
134
+ db.exec(`DELETE FROM graph_nodes_fts WHERE kind = 'structural'`);
135
+
136
+ // A memory pointing at a code node as its current belief would be left
137
+ // superseded by something that no longer exists, which hides it from retrieval
138
+ // forever with nothing to explain why. Supersession never crossed the two
139
+ // halves, so this should find nothing — it costs one indexed update to be sure.
140
+ db.exec(`
141
+ UPDATE graph_nodes SET superseded_by = NULL
142
+ WHERE superseded_by IN (SELECT id FROM graph_nodes WHERE kind = 'structural')
143
+ `);
144
+
145
+ // Dependent rows are deleted explicitly rather than left to ON DELETE CASCADE.
146
+ // Foreign keys are a per-connection pragma and this codebase does not rely on
147
+ // them being on anywhere else either (see `graphLayoutQueries.pruneOrphans`).
148
+ db.exec(`
149
+ DELETE FROM graph_edges
150
+ WHERE src_id IN (SELECT id FROM graph_nodes WHERE kind = 'structural')
151
+ OR dst_id IN (SELECT id FROM graph_nodes WHERE kind = 'structural')
152
+ `);
153
+ db.exec(
154
+ `DELETE FROM graph_vectors WHERE node_id IN (SELECT id FROM graph_nodes WHERE kind = 'structural')`
155
+ );
156
+ db.exec(
157
+ `DELETE FROM graph_node_entities WHERE node_id IN (SELECT id FROM graph_nodes WHERE kind = 'structural')`
158
+ );
159
+ // `graph_layout` arrived in a later migration (067) and is derived data that is
160
+ // documented as safe to drop wholesale, so its absence is not an error here.
161
+ if (hasTable(db, 'graph_layout')) {
162
+ db.exec(
163
+ `DELETE FROM graph_layout WHERE node_id IN (SELECT id FROM graph_nodes WHERE kind = 'structural')`
164
+ );
165
+ }
166
+
167
+ const removed = (
168
+ db.prepare(`SELECT COUNT(*) AS c FROM graph_nodes WHERE kind = 'structural'`).get() as {
169
+ c: number;
170
+ }
171
+ ).c;
172
+ db.exec(`DELETE FROM graph_nodes WHERE kind = 'structural'`);
173
+
174
+ // ── drop what only the code half used ────────────────────────────────────
175
+ // The indexes go before the columns: SQLite refuses to drop a column that any
176
+ // index, view or trigger still mentions.
177
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_path`);
178
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_structural_path`);
179
+
180
+ // `path`, `symbol` and `language` were only ever written for structural nodes,
181
+ // so every surviving row holds three NULLs. Best-effort: DROP COLUMN needs
182
+ // SQLite 3.35, and a column left behind is dead weight rather than a fault.
183
+ for (const column of ['path', 'symbol', 'language']) {
184
+ if (!hasColumn(db, 'graph_nodes', column)) continue;
185
+ try {
186
+ db.exec(`ALTER TABLE graph_nodes DROP COLUMN ${column}`);
187
+ } catch (error) {
188
+ debug.warn('migration', `Could not drop graph_nodes.${column} (harmless)`, error);
189
+ }
190
+ }
191
+
192
+ // "Map the code" is no longer a thing memory can be asked to do.
193
+ if (hasTable(db, 'settings')) {
194
+ db.exec(`DELETE FROM settings WHERE key = 'memory_record_code'`);
195
+ }
196
+
197
+ debug.log(
198
+ 'migration',
199
+ `Memory graph: ${removed} code node(s) removed, ${carried} path attribution(s) carried over`
200
+ );
201
+ };
202
+
203
+ /**
204
+ * Down restores the SHAPE, not the data.
205
+ *
206
+ * The code half was derived from the disk in the first place — re-running a turn
207
+ * re-observes whatever it described — so there is nothing here worth trying to
208
+ * reconstruct. The columns and indexes come back so an older build can write to
209
+ * the table again; the path attributions stay, because they are the one thing
210
+ * that was not derivable.
211
+ */
212
+ export const down = (db: DatabaseConnection): void => {
213
+ debug.log('migration', 'Restoring the structural columns on the memory graph...');
214
+
215
+ for (const column of ['path TEXT', 'symbol TEXT', 'language TEXT']) {
216
+ try {
217
+ db.exec(`ALTER TABLE graph_nodes ADD COLUMN ${column}`);
218
+ } catch (error) {
219
+ debug.warn('migration', `Could not restore graph_nodes.${column} (harmless)`, error);
220
+ }
221
+ }
222
+
223
+ db.exec(
224
+ `CREATE INDEX IF NOT EXISTS idx_graph_nodes_path ON graph_nodes (COALESCE(project_id, ''), path)`
225
+ );
226
+ db.exec(
227
+ `CREATE INDEX IF NOT EXISTS idx_graph_nodes_structural_path ON graph_nodes (project_id, kind, path)`
228
+ );
229
+ };
@@ -0,0 +1,150 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create integration_db_links and widen integration_projections to many rows per capability';
5
+
6
+ /**
7
+ * One account, many derived rows.
8
+ *
9
+ * `integration_projections` was keyed `(account_id, capability, target_kind)`,
10
+ * which encoded an assumption that only held for the first capability shipped:
11
+ * an account with agent tools owns exactly one `mcp_servers` row. A database
12
+ * account does not work that way. One Supabase personal access token reaches
13
+ * every project in every organisation the user belongs to, so "which database"
14
+ * is not a property of the credential — it is a choice the user makes, possibly
15
+ * several times.
16
+ *
17
+ * The alternative was one account per remote database, and it is the same
18
+ * mistake `Task 3` refused for Vercel teams: it would make a user with a
19
+ * production and a staging project paste the same token twice and rotate it in
20
+ * two places. So the key gains `target_id`, and the choices themselves get a
21
+ * table.
22
+ */
23
+ export const up = (db: DatabaseConnection): void => {
24
+ debug.log('migration', 'Widening integration_projections primary key...');
25
+
26
+ // SQLite cannot alter a primary key, so the table is rebuilt. It is small
27
+ // (one row per projected surface row) and the copy is a straight SELECT —
28
+ // every column keeps its meaning, only the key widens.
29
+ db.exec('PRAGMA foreign_keys = OFF;');
30
+
31
+ db.exec(`
32
+ CREATE TABLE IF NOT EXISTS integration_projections_new (
33
+ account_id TEXT NOT NULL REFERENCES integration_accounts(id) ON DELETE CASCADE,
34
+ capability TEXT NOT NULL,
35
+ target_kind TEXT NOT NULL,
36
+ target_id TEXT NOT NULL,
37
+ adopted INTEGER NOT NULL DEFAULT 0,
38
+ restore_json TEXT,
39
+ created_at TEXT NOT NULL,
40
+ PRIMARY KEY (account_id, capability, target_kind, target_id)
41
+ )
42
+ `);
43
+
44
+ db.exec(`
45
+ INSERT INTO integration_projections_new (
46
+ account_id, capability, target_kind, target_id, adopted, restore_json, created_at
47
+ )
48
+ SELECT account_id, capability, target_kind, target_id, adopted, restore_json, created_at
49
+ FROM integration_projections;
50
+ `);
51
+
52
+ db.exec('DROP TABLE integration_projections;');
53
+ db.exec('ALTER TABLE integration_projections_new RENAME TO integration_projections;');
54
+
55
+ db.exec(`
56
+ CREATE INDEX IF NOT EXISTS idx_integration_projections_target
57
+ ON integration_projections(target_kind, target_id)
58
+ `);
59
+
60
+ db.exec('PRAGMA foreign_keys = ON;');
61
+
62
+ debug.log('migration', 'Creating integration_db_links table...');
63
+
64
+ // One row per remote database the user chose to bring into DB Client.
65
+ //
66
+ // `secrets` is a sealed JSON blob rather than a password column because the
67
+ // secret a database provider needs is not the same everywhere: Supabase
68
+ // needs the Postgres password (which its Management API deliberately cannot
69
+ // read back), Turso needs an auth token, and a later provider may need a
70
+ // client certificate. It lives HERE rather than only on the projected
71
+ // connection because a projection must be rebuildable from the account plus
72
+ // the link alone — a release followed by a re-project must not silently drop
73
+ // the password and leave a connection that can no longer log in.
74
+ //
75
+ // `remote_ref` is the provider's own identifier for the database (a Supabase
76
+ // project ref, a Neon project id). `(account_id, remote_ref)` is unique: two
77
+ // links to the same remote database from one account would project two
78
+ // connections to the same place.
79
+ db.exec(`
80
+ CREATE TABLE IF NOT EXISTS integration_db_links (
81
+ id TEXT PRIMARY KEY,
82
+ account_id TEXT NOT NULL REFERENCES integration_accounts(id) ON DELETE CASCADE,
83
+ remote_ref TEXT NOT NULL,
84
+ label TEXT NOT NULL,
85
+ driver TEXT NOT NULL,
86
+ mode TEXT NOT NULL DEFAULT 'pooler-session',
87
+ secrets TEXT NOT NULL DEFAULT '{}',
88
+ config_json TEXT NOT NULL DEFAULT '{}',
89
+ detected INTEGER NOT NULL DEFAULT 0,
90
+ created_at TEXT NOT NULL,
91
+ updated_at TEXT NOT NULL,
92
+ UNIQUE (account_id, remote_ref)
93
+ )
94
+ `);
95
+
96
+ db.exec(`
97
+ CREATE INDEX IF NOT EXISTS idx_integration_db_links_account
98
+ ON integration_db_links(account_id)
99
+ `);
100
+
101
+ debug.log('migration', 'integration_db_links created');
102
+ };
103
+
104
+ export const down = (db: DatabaseConnection): void => {
105
+ debug.log('migration', 'Dropping integration_db_links...');
106
+ db.exec('DROP INDEX IF EXISTS idx_integration_db_links_account');
107
+ db.exec('DROP TABLE IF EXISTS integration_db_links');
108
+
109
+ // Narrow the key back. A row that only exists because the wider key allowed
110
+ // it would collide, so the copy keeps the first row per narrow key — the
111
+ // projections it drops are exactly the ones the old schema could not hold,
112
+ // and the surface rows they point at are left where they are rather than
113
+ // being deleted by a rollback.
114
+ debug.log('migration', 'Narrowing integration_projections primary key...');
115
+ db.exec('PRAGMA foreign_keys = OFF;');
116
+
117
+ db.exec(`
118
+ CREATE TABLE IF NOT EXISTS integration_projections_old (
119
+ account_id TEXT NOT NULL REFERENCES integration_accounts(id) ON DELETE CASCADE,
120
+ capability TEXT NOT NULL,
121
+ target_kind TEXT NOT NULL,
122
+ target_id TEXT NOT NULL,
123
+ adopted INTEGER NOT NULL DEFAULT 0,
124
+ restore_json TEXT,
125
+ created_at TEXT NOT NULL,
126
+ PRIMARY KEY (account_id, capability, target_kind)
127
+ )
128
+ `);
129
+
130
+ db.exec(`
131
+ INSERT OR IGNORE INTO integration_projections_old (
132
+ account_id, capability, target_kind, target_id, adopted, restore_json, created_at
133
+ )
134
+ SELECT account_id, capability, target_kind, target_id, adopted, restore_json, created_at
135
+ FROM integration_projections
136
+ ORDER BY created_at ASC;
137
+ `);
138
+
139
+ db.exec('DROP TABLE integration_projections;');
140
+ db.exec('ALTER TABLE integration_projections_old RENAME TO integration_projections;');
141
+
142
+ db.exec(`
143
+ CREATE INDEX IF NOT EXISTS idx_integration_projections_target
144
+ ON integration_projections(target_kind, target_id)
145
+ `);
146
+
147
+ db.exec('PRAGMA foreign_keys = ON;');
148
+
149
+ debug.log('migration', 'integration_db_links migration rolled back');
150
+ };
@@ -0,0 +1,158 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create worktree_branch_bindings and worktree_branches for database branching';
5
+
6
+ /**
7
+ * Worktree database branching — the binding, and the branches it produced.
8
+ *
9
+ * Two tables, for the same reason the Issues surface has two: one records the
10
+ * decision ("give this project's worktrees their own database"), the other
11
+ * records what that decision actually created and therefore what has to be
12
+ * cleaned up.
13
+ *
14
+ * A SOURCE IS NOT ALWAYS AN ACCOUNT, which is why both tables carry
15
+ * `source_kind` and two nullable parent columns instead of a single
16
+ * `account_id`. Neon cuts a branch through its API and needs an integration
17
+ * account; a Postgres running on the user's laptop needs nothing but the DB
18
+ * Client connection that already reaches it. Tying the feature to accounts made
19
+ * it a Neon feature by accident — a database with no vendor behind it had no
20
+ * way in at all.
21
+ */
22
+ export const up = (db: DatabaseConnection): void => {
23
+ debug.log('migration', 'Creating worktree_branch_bindings table...');
24
+
25
+ // ONE BINDING PER PROJECT, which is why `project_id` is the whole primary
26
+ // key rather than half of it as in `work_bindings` and `deploy_bindings`.
27
+ //
28
+ // Those two are keyed per (project, account) because a project genuinely can
29
+ // track issues in two places or deploy to two targets. This one cannot: the
30
+ // binding's entire output is a single environment variable inside a single
31
+ // worktree, and two bindings would both claim it. Making the schema hold a
32
+ // state the feature cannot express would only produce a silent last-writer.
33
+ //
34
+ // `parent_name` is cached alongside the ref for the reason `deploy_bindings`
35
+ // caches `display_name`: a Neon project id is `winter-frost-12345678` and
36
+ // answers no question anyone asked.
37
+ //
38
+ // Exactly ONE of `account_id` and `connection_id` is set, and `source_kind`
39
+ // says which. Both cascade: a disconnected account or a deleted connection
40
+ // leaves a binding that points at nothing, and a binding that points at
41
+ // nothing would fail on every worktree create with a message about a thing
42
+ // the user already removed.
43
+ db.exec(`
44
+ CREATE TABLE IF NOT EXISTS worktree_branch_bindings (
45
+ project_id TEXT PRIMARY KEY REFERENCES projects(id) ON DELETE CASCADE,
46
+ source_kind TEXT NOT NULL DEFAULT 'account',
47
+ account_id TEXT REFERENCES integration_accounts(id) ON DELETE CASCADE,
48
+ connection_id TEXT REFERENCES db_client_connections(id) ON DELETE CASCADE,
49
+ parent_ref TEXT NOT NULL,
50
+ parent_name TEXT NOT NULL,
51
+ config_json TEXT NOT NULL DEFAULT '{}',
52
+ created_at TEXT NOT NULL,
53
+ updated_at TEXT NOT NULL
54
+ )
55
+ `);
56
+
57
+ db.exec(`
58
+ CREATE INDEX IF NOT EXISTS idx_worktree_branch_bindings_account
59
+ ON worktree_branch_bindings(account_id)
60
+ `);
61
+
62
+ db.exec(`
63
+ CREATE INDEX IF NOT EXISTS idx_worktree_branch_bindings_connection
64
+ ON worktree_branch_bindings(connection_id)
65
+ `);
66
+
67
+ debug.log('migration', 'Creating worktree_branches table...');
68
+
69
+ // `worktree_id` is NULLABLE and ON DELETE SET NULL — deliberately NOT a
70
+ // cascade, and this is the load-bearing decision in the whole table.
71
+ //
72
+ // Deleting a worktree deletes its branch at the provider. When that call
73
+ // FAILS — an expired token, a provider outage, a branch the account can no
74
+ // longer reach — the remote branch is still there, costing money and holding
75
+ // data. A cascade would delete the only record of it in the same breath, so
76
+ // the leak would be both silent and unrecoverable: nothing left would know
77
+ // the branch had ever belonged to anything.
78
+ //
79
+ // So the row survives its worktree. `worktree_id IS NULL` is precisely the
80
+ // definition of an orphan, and the orphan list is built from it.
81
+ //
82
+ // `connection_json` holds the branch's own connection string INCLUDING the
83
+ // password, so it is sealed — see `SECRET_COLUMNS`. It lives here rather than
84
+ // only on the projected connection because the projection must be
85
+ // rebuildable from the row alone; a release followed by a re-project would
86
+ // otherwise lose the password and leave a connection that cannot log in.
87
+ // `source_connection_id` deliberately carries NO foreign key, unlike its
88
+ // twin on the binding. The same reasoning as `worktree_id` above: this row
89
+ // is the only record of a real database that exists right now, and deleting
90
+ // the DB Client connection it was copied from must not erase the evidence of
91
+ // the copy. The orphan list is what the user has left to clean it up with.
92
+ db.exec(`
93
+ CREATE TABLE IF NOT EXISTS worktree_branches (
94
+ id TEXT PRIMARY KEY,
95
+ worktree_id TEXT REFERENCES worktrees(id) ON DELETE SET NULL,
96
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
97
+ source_kind TEXT NOT NULL DEFAULT 'account',
98
+ account_id TEXT REFERENCES integration_accounts(id) ON DELETE CASCADE,
99
+ source_connection_id TEXT,
100
+ parent_ref TEXT NOT NULL,
101
+ branch_ref TEXT NOT NULL,
102
+ branch_name TEXT NOT NULL,
103
+ connection_json TEXT,
104
+ connection_id TEXT,
105
+ env_var TEXT NOT NULL,
106
+ env_file TEXT NOT NULL,
107
+ env_status TEXT NOT NULL DEFAULT 'failed',
108
+ env_detail TEXT,
109
+ status TEXT NOT NULL DEFAULT 'active',
110
+ error TEXT,
111
+ strategy TEXT,
112
+ notice TEXT,
113
+ created_at TEXT NOT NULL,
114
+ updated_at TEXT NOT NULL
115
+ )
116
+ `);
117
+
118
+ db.exec(`
119
+ CREATE INDEX IF NOT EXISTS idx_worktree_branches_worktree
120
+ ON worktree_branches(worktree_id)
121
+ `);
122
+
123
+ db.exec(`
124
+ CREATE INDEX IF NOT EXISTS idx_worktree_branches_account
125
+ ON worktree_branches(account_id)
126
+ `);
127
+
128
+ // Identity is (source, parent, branch), and the source is whichever of the
129
+ // two columns is set. A table constraint cannot express that — SQLite treats
130
+ // every NULL as distinct, so `UNIQUE (account_id, …)` would stop enforcing
131
+ // anything the moment the source was a connection.
132
+ db.exec(`
133
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_worktree_branches_identity
134
+ ON worktree_branches(
135
+ source_kind,
136
+ COALESCE(account_id, source_connection_id, ''),
137
+ parent_ref,
138
+ branch_ref
139
+ )
140
+ `);
141
+
142
+ debug.log('migration', 'Worktree branching tables created');
143
+ };
144
+
145
+ export const down = (db: DatabaseConnection): void => {
146
+ debug.log('migration', 'Dropping worktree branching tables...');
147
+ db.exec('DROP INDEX IF EXISTS idx_worktree_branches_identity');
148
+ db.exec('DROP INDEX IF EXISTS idx_worktree_branches_account');
149
+ db.exec('DROP INDEX IF EXISTS idx_worktree_branches_worktree');
150
+ db.exec('DROP TABLE IF EXISTS worktree_branches');
151
+ db.exec('DROP INDEX IF EXISTS idx_worktree_branch_bindings_connection');
152
+ db.exec('DROP INDEX IF EXISTS idx_worktree_branch_bindings_account');
153
+ db.exec('DROP TABLE IF EXISTS worktree_branch_bindings');
154
+ // The remote branches themselves are deliberately left alone. A rollback is
155
+ // a schema operation, and destroying someone's databases from one would be
156
+ // the single worst thing this migration could do.
157
+ debug.log('migration', 'Worktree branching tables dropped — remote branches were left untouched');
158
+ };