@myrialabs/clopen 0.4.29 → 0.4.31

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 (42) hide show
  1. package/backend/chat/stream-manager.ts +1 -1
  2. package/backend/database/migrations/067_add_memory_graph_layout.ts +91 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/graph-queries.ts +417 -32
  5. package/backend/db-client/drivers/mssql.ts +57 -22
  6. package/backend/db-client/drivers/mysql.ts +69 -48
  7. package/backend/db-client/drivers/postgres.ts +65 -53
  8. package/backend/engine/adapters/claude/stream.ts +81 -15
  9. package/backend/engine/adapters/codex/stream.ts +6 -3
  10. package/backend/engine/adapters/opencode/server.ts +13 -4
  11. package/backend/engine/bootstrap-default-engine.ts +67 -38
  12. package/backend/engine/docs/artifacts.md +1 -1
  13. package/backend/engine/docs/quick-reference.md +1 -1
  14. package/backend/engine/engine-cli.ts +313 -0
  15. package/backend/engine/engine-setup.ts +40 -3
  16. package/backend/engine/install-recipes.test.ts +99 -5
  17. package/backend/engine/install-recipes.ts +47 -11
  18. package/backend/engine/install-runner.ts +34 -16
  19. package/backend/engine/stack-project.ts +72 -0
  20. package/backend/index.ts +5 -0
  21. package/backend/memory/bootstrap.ts +9 -0
  22. package/backend/memory/layout.ts +985 -0
  23. package/backend/memory/notify.ts +33 -7
  24. package/backend/memory/view.ts +375 -69
  25. package/backend/permissions/index.ts +4 -2
  26. package/backend/permissions/resolve.ts +7 -5
  27. package/backend/utils/path-enrich.ts +2 -0
  28. package/backend/utils/process-warnings.ts +41 -0
  29. package/backend/ws/engine/claude/accounts.ts +9 -4
  30. package/backend/ws/engine/codex/accounts.ts +8 -5
  31. package/backend/ws/engine/codex/status.ts +10 -17
  32. package/backend/ws/memory/crud.ts +50 -2
  33. package/backend/ws/settings/crud.ts +1 -1
  34. package/backend/ws/stack/access.ts +5 -2
  35. package/dist/assets/{index-C7e5TWG3.js → index-DUc5T21e.js} +1 -1
  36. package/dist/assets/{index-Derlqeyy.js → index-DYwQ5bP8.js} +1 -1
  37. package/dist/assets/main-VgdjTBLR.css +1 -0
  38. package/dist/assets/{main-OGhsRKU1.js → main-r0iv2PDz.js} +393 -386
  39. package/dist/index.html +2 -2
  40. package/package.json +1 -1
  41. package/shared/types/memory.ts +70 -0
  42. package/dist/assets/main-CqzaPnux.css +0 -1
@@ -126,6 +126,18 @@ export class MssqlAdapter implements DbClientDriverAdapter {
126
126
  return this.pool;
127
127
  }
128
128
 
129
+ /**
130
+ * The database a statement should run in.
131
+ *
132
+ * Most DDL here is three-part qualified and so needs no context, but the
133
+ * statements that cannot be (`sp_rename`, `CREATE VIEW`) must name one —
134
+ * falling back to the connection's configured database rather than trusting
135
+ * whichever database the pooled connection was last left in.
136
+ */
137
+ private scopeDb(opts?: SchemaOpts): string | undefined {
138
+ return opts?.database || this.conn?.database || undefined;
139
+ }
140
+
129
141
  async health(): Promise<DbClientHealth> {
130
142
  if (!this.pool) return notConnected();
131
143
  const start = performance.now();
@@ -218,9 +230,14 @@ export class MssqlAdapter implements DbClientDriverAdapter {
218
230
  async executeRead(q: string, params: unknown[] = [], opts?: { database?: string; limit?: number }): Promise<DbClientQueryResult> {
219
231
  const pool = this.requirePool();
220
232
  const start = performance.now();
221
- const needUse = opts?.database && opts.database.toLowerCase() !== this.conn?.database?.toLowerCase();
222
-
223
- if (needUse && isBatchSensitive(q)) {
233
+ // Always switch when a database is named — never skip because it matches
234
+ // the connection's configured one. `USE` is per-connection session state
235
+ // and the driver hands pooled connections back without resetting it, so a
236
+ // connection an earlier request left on another database would otherwise
237
+ // silently serve this one.
238
+ const database = opts?.database;
239
+
240
+ if (database && isBatchSensitive(q)) {
224
241
  // Batch-sensitive DDL (CREATE PROCEDURE, …) can't share a batch with
225
242
  // `USE`, so run the database switch as a separate request first, wrapped
226
243
  // in a transaction for atomicity.
@@ -228,7 +245,7 @@ export class MssqlAdapter implements DbClientDriverAdapter {
228
245
  await transaction.begin();
229
246
  try {
230
247
  const useRequest = new sql.Request(transaction);
231
- await useRequest.query(`USE ${Q(opts!.database as string)}`);
248
+ await useRequest.query(`USE ${Q(database)}`);
232
249
 
233
250
  const request = new sql.Request(transaction);
234
251
  this.bindParams(request, params);
@@ -247,7 +264,7 @@ export class MssqlAdapter implements DbClientDriverAdapter {
247
264
 
248
265
  const request = pool.request();
249
266
  this.bindParams(request, params);
250
- const finalQuery = needUse ? `USE ${Q(opts!.database as string)};\n${q}` : q;
267
+ const finalQuery = database ? `USE ${Q(database)};\n${q}` : q;
251
268
  const result = await request.query(finalQuery);
252
269
  return this.buildResult(result, q, Math.round(performance.now() - start));
253
270
  }
@@ -265,15 +282,19 @@ export class MssqlAdapter implements DbClientDriverAdapter {
265
282
  await transaction.begin();
266
283
 
267
284
  const txDb = opts?.database;
285
+ // The transaction owns one connection for its whole lifetime, so the
286
+ // database it was switched to holds until we switch it again — track it
287
+ // and skip the redundant `USE` on every statement of a batch.
288
+ let txCurrentDb: string | null = null;
268
289
 
269
290
  try {
270
291
  const txContext: DbClientTxContext = {
271
292
  executeRead: async (q, params, txOpts) => {
272
293
  const db = txOpts?.database || txDb;
273
- const needUse = db && db.toLowerCase() !== this.conn?.database?.toLowerCase();
274
- if (needUse) {
294
+ if (db && db !== txCurrentDb) {
275
295
  const useRequest = new sql.Request(transaction);
276
- await useRequest.query(`USE ${Q(db as string)}`);
296
+ await useRequest.query(`USE ${Q(db)}`);
297
+ txCurrentDb = db;
277
298
  }
278
299
  const request = new sql.Request(transaction);
279
300
  this.bindParams(request, params ?? []);
@@ -295,10 +316,10 @@ export class MssqlAdapter implements DbClientDriverAdapter {
295
316
  },
296
317
  executeWrite: async (q, params, txOpts) => {
297
318
  const db = txOpts?.database || txDb;
298
- const needUse = db && db.toLowerCase() !== this.conn?.database?.toLowerCase();
299
- if (needUse) {
319
+ if (db && db !== txCurrentDb) {
300
320
  const useRequest = new sql.Request(transaction);
301
- await useRequest.query(`USE ${Q(db as string)}`);
321
+ await useRequest.query(`USE ${Q(db)}`);
322
+ txCurrentDb = db;
302
323
  }
303
324
  const request = new sql.Request(transaction);
304
325
  this.bindParams(request, params ?? []);
@@ -347,15 +368,18 @@ export class MssqlAdapter implements DbClientDriverAdapter {
347
368
  `, [db]);
348
369
  const sizeBytes = Number(sizeRes.rows[0]?.size_bytes ?? 0);
349
370
 
350
- // Tables and views count
371
+ // Tables and views count. `sys.tables`/`sys.views` are per-database
372
+ // catalogs, so these have to run against the database being reported on —
373
+ // otherwise the panel shows the counts of whatever database the pooled
374
+ // connection happened to sit on (usually `master`).
351
375
  const tablesRes = await this.executeRead(`
352
376
  SELECT COUNT(*) AS tables_count
353
377
  FROM sys.tables
354
- `);
378
+ `, [], { database: db });
355
379
  const viewsRes = await this.executeRead(`
356
380
  SELECT COUNT(*) AS views_count
357
381
  FROM sys.views
358
- `);
382
+ `, [], { database: db });
359
383
 
360
384
  return {
361
385
  serverVersion: health.serverVersion,
@@ -561,17 +585,20 @@ export class MssqlAdapter implements DbClientDriverAdapter {
561
585
 
562
586
  // ── Structure ─────────────────────────────────────────────────────────
563
587
 
588
+ // Database-level DDL runs from `master`: SQL Server refuses to drop or rename
589
+ // a database the connection is sitting in, and a pooled connection may well
590
+ // be sitting in the one being changed.
564
591
  async createDatabase(name: string): Promise<string> {
565
592
  assertSafeIdentifier(name);
566
593
  const ddl = `CREATE DATABASE ${Q(name)}`;
567
- await this.executeWrite(ddl);
594
+ await this.executeWrite(ddl, [], { database: 'master' });
568
595
  return ddl;
569
596
  }
570
597
 
571
598
  async dropDatabase(name: string): Promise<string> {
572
599
  assertSafeIdentifier(name);
573
600
  const ddl = `DROP DATABASE ${Q(name)}`;
574
- await this.executeWrite(ddl);
601
+ await this.executeWrite(ddl, [], { database: 'master' });
575
602
  return ddl;
576
603
  }
577
604
 
@@ -579,7 +606,7 @@ export class MssqlAdapter implements DbClientDriverAdapter {
579
606
  assertSafeIdentifier(name);
580
607
  assertSafeIdentifier(newName);
581
608
  const ddl = `ALTER DATABASE ${Q(name)} MODIFY NAME = ${Q(newName)}`;
582
- await this.executeWrite(ddl);
609
+ await this.executeWrite(ddl, [], { database: 'master' });
583
610
  return ddl;
584
611
  }
585
612
 
@@ -616,7 +643,7 @@ export class MssqlAdapter implements DbClientDriverAdapter {
616
643
  }
617
644
 
618
645
  const fullQuery = ddls.join(';\n');
619
- await this.executeWrite(fullQuery);
646
+ await this.executeWrite(fullQuery, [], { database: this.scopeDb(opts) });
620
647
  return fullQuery;
621
648
  }
622
649
 
@@ -652,6 +679,9 @@ export class MssqlAdapter implements DbClientDriverAdapter {
652
679
  case 'rename-column':
653
680
  assertSafeIdentifier(op.name);
654
681
  assertSafeIdentifier(op.newName);
682
+ // sp_rename cannot cross databases — it resolves its argument in
683
+ // the connection's current database, which is why this batch is
684
+ // sent with the target database attached below.
655
685
  const objectPath = `${schema}.${name}.${op.name}`;
656
686
  ddls.push(`EXEC sp_rename '${objectPath}', '${op.newName}', 'COLUMN'`);
657
687
  break;
@@ -666,7 +696,7 @@ export class MssqlAdapter implements DbClientDriverAdapter {
666
696
  }
667
697
 
668
698
  const fullQuery = ddls.join(';\n');
669
- await this.executeWrite(fullQuery);
699
+ await this.executeWrite(fullQuery, [], { database: this.scopeDb(opts) });
670
700
  return fullQuery;
671
701
  }
672
702
 
@@ -694,8 +724,10 @@ export class MssqlAdapter implements DbClientDriverAdapter {
694
724
  assertSafeIdentifier(newName);
695
725
  const schema = opts?.schema || 'dbo';
696
726
  const objectPath = `${schema}.${name}`;
727
+ // sp_rename takes a two-part name and resolves it in the current database,
728
+ // so the target database has to be selected for the statement.
697
729
  const ddl = `EXEC sp_rename '${objectPath}', '${newName}'`;
698
- await this.executeWrite(ddl);
730
+ await this.executeWrite(ddl, [], { database: this.scopeDb(opts) });
699
731
  return ddl;
700
732
  }
701
733
 
@@ -753,9 +785,12 @@ export class MssqlAdapter implements DbClientDriverAdapter {
753
785
 
754
786
  async createView(name: string, query: string, opts?: SchemaOpts): Promise<string> {
755
787
  assertSafeIdentifier(name);
756
- const fqt = qualified(Q, [opts?.database, opts?.schema || 'dbo', name]);
788
+ // T-SQL rejects a database prefix on CREATE VIEW, and the statement must be
789
+ // alone in its batch — name it two-part and let the batch-sensitive path
790
+ // select the database in a separate request.
791
+ const fqt = qualified(Q, [opts?.schema || 'dbo', name]);
757
792
  const ddl = `CREATE VIEW ${fqt} AS ${query}`;
758
- await this.executeWrite(ddl);
793
+ await this.executeWrite(ddl, [], { database: this.scopeDb(opts) });
759
794
  return ddl;
760
795
  }
761
796
 
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import { SQL } from 'bun';
6
+ import type { ReservedSQL } from 'bun';
6
7
  import type {
7
8
  DbClientConnection,
8
9
  DbClientHealth,
@@ -45,13 +46,10 @@ export class MysqlAdapter implements DbClientDriverAdapter {
45
46
 
46
47
  private sql: SQL | null = null;
47
48
  private alive = false;
48
- // The session's currently-USEd database (mutated by ensureDatabase).
49
- private defaultDb: string | null = null;
50
49
  // The connection's configured database — immutable, used as the scope
51
50
  // fallback so a connection-level overview never resolves to the last-browsed
52
- // database that only the session happens to be sitting on.
51
+ // database, and as the state every pooled socket is restored to.
53
52
  private configuredDb: string | null = null;
54
- private ensureLock = Promise.resolve();
55
53
 
56
54
  async connect(conn: DbClientConnection, tunnelPort?: number): Promise<void> {
57
55
  const host = tunnelPort ? '127.0.0.1' : (conn.host ?? '127.0.0.1');
@@ -64,26 +62,16 @@ export class MysqlAdapter implements DbClientDriverAdapter {
64
62
  const url = `mysql://${auth}${host}:${port}${db}`;
65
63
  this.sql = new SQL(url, BUN_SQL_POOL_OPTIONS);
66
64
  await this.sql.connect();
67
- this.defaultDb = conn.database || null;
68
65
  this.configuredDb = conn.database || null;
69
66
  this.alive = true;
70
67
  }
71
68
 
72
69
  async close(): Promise<void> {
73
- let release: () => void;
74
- const prev = this.ensureLock;
75
- this.ensureLock = new Promise<void>((resolve) => { release = resolve; });
76
- await prev;
77
-
78
- try {
79
- this.alive = false;
80
- this.defaultDb = null;
81
- if (!this.sql) return;
82
- await this.sql.close().catch((err) => debug.warn('db-client', 'MySQL close error:', err));
83
- this.sql = null;
84
- } finally {
85
- release!();
86
- }
70
+ this.alive = false;
71
+ if (!this.sql) return;
72
+ const sql = this.sql;
73
+ this.sql = null;
74
+ await sql.close().catch((err) => debug.warn('db-client', 'MySQL close error:', err));
87
75
  }
88
76
 
89
77
  isAlive(): boolean {
@@ -123,32 +111,53 @@ export class MysqlAdapter implements DbClientDriverAdapter {
123
111
  return opts?.database || this.configuredDb || undefined;
124
112
  }
125
113
 
126
- private async ensureDatabase(database?: string): Promise<void> {
127
- if (!database) return;
128
- if (database === this.defaultDb) return;
129
-
130
- let release: () => void;
131
- const prev = this.ensureLock;
132
- this.ensureLock = new Promise<void>((resolve) => { release = resolve; });
133
- await prev;
134
-
114
+ /**
115
+ * Restore a socket to the connection's configured database.
116
+ *
117
+ * Every pooled socket is opened on the configured database (it is in the
118
+ * connection URL), so putting it back there before releasing keeps an idle
119
+ * socket's session state predictable for statements that carry their own
120
+ * qualification instead of naming a database.
121
+ */
122
+ private async restoreConfigured(sql: SQL, current: string): Promise<void> {
123
+ if (!this.configuredDb || this.configuredDb === current) return;
124
+ await sql
125
+ .unsafe(`USE ${quoteMysql(this.configuredDb)}`)
126
+ .catch((err) => debug.warn('db-client', 'MySQL restore database failed:', err));
127
+ }
128
+
129
+ /**
130
+ * Run `fn` on a socket pinned to `database`.
131
+ *
132
+ * `USE` is per-connection session state while the adapter holds a *pool*, so
133
+ * a `USE` sent on one pooled socket says nothing about the socket the next
134
+ * query lands on — that is why browsing a database other than the configured
135
+ * one intermittently failed with "Table 'configured_db.x' doesn't exist".
136
+ * Reserving a connection makes the switch and the query share one socket.
137
+ */
138
+ private async withDatabase<T>(
139
+ database: string | undefined,
140
+ fn: (sql: SQL | ReservedSQL) => Promise<T>
141
+ ): Promise<T> {
142
+ const sql = this.requireSql();
143
+ if (!database) return fn(sql);
144
+ assertSafeIdentifier(database);
145
+ const reserved = await sql.reserve();
135
146
  try {
136
- if (database === this.defaultDb) return;
137
- const sql = this.requireSql();
138
- assertSafeIdentifier(database);
139
- await sql.unsafe(`USE ${quoteMysql(database)}`);
140
- this.defaultDb = database;
147
+ await reserved.unsafe(`USE ${quoteMysql(database)}`);
148
+ return await fn(reserved);
141
149
  } finally {
142
- release!();
150
+ await this.restoreConfigured(reserved, database);
151
+ reserved.release();
143
152
  }
144
153
  }
145
154
 
146
155
  async executeRead(q: string, params: unknown[] = [], opts?: { database?: string }): Promise<DbClientQueryResult> {
147
- await this.ensureDatabase(opts?.database);
148
- const sql = this.requireSql();
149
- const start = performance.now();
150
- const raw = await sql.unsafe(q, params as never);
151
- return normalizeBunSqlResult(raw, Math.round(performance.now() - start));
156
+ return this.withDatabase(opts?.database, async (sql) => {
157
+ const start = performance.now();
158
+ const raw = await sql.unsafe(q, params as never);
159
+ return normalizeBunSqlResult(raw, Math.round(performance.now() - start));
160
+ });
152
161
  }
153
162
 
154
163
  async executeWrite(q: string, params: unknown[] = [], opts?: { database?: string }): Promise<DbClientQueryResult> {
@@ -160,22 +169,33 @@ export class MysqlAdapter implements DbClientDriverAdapter {
160
169
  }
161
170
 
162
171
  async withTransaction<T>(fn: (tx: DbClientTxContext) => Promise<T>, opts?: { database?: string }): Promise<T> {
163
- await this.ensureDatabase(opts?.database);
164
172
  const sql = this.requireSql();
165
- // Bun.sql reserves one connection for the `begin` block. Note: MySQL
173
+ const database = opts?.database;
174
+ if (database) assertSafeIdentifier(database);
175
+ // Bun.sql reserves one connection for the `begin` block, so the batch's
176
+ // database has to be selected inside it — a `USE` sent anywhere else
177
+ // belongs to a different socket. `USE` is not an implicit-commit
178
+ // statement, so it is safe within the transaction. Note: MySQL
166
179
  // implicitly commits on DDL (CREATE/ALTER/DROP/…), so a batch that
167
180
  // mixes DDL with later failures cannot fully roll back the DDL — a
168
181
  // server limitation, not an app one.
169
182
  return sql.begin(async (tx) => {
183
+ if (database) await tx.unsafe(`USE ${quoteMysql(database)}`);
170
184
  const run = async (q: string, params: unknown[] = []): Promise<DbClientQueryResult> => {
171
185
  const start = performance.now();
172
186
  const raw = await tx.unsafe(q, params as never);
173
187
  return normalizeBunSqlResult(raw, Math.round(performance.now() - start));
174
188
  };
175
- return fn({
176
- executeRead: (q, params) => run(q, params ?? []),
177
- executeWrite: (q, params) => run(q, params ?? [])
178
- });
189
+ try {
190
+ return await fn({
191
+ executeRead: (q, params) => run(q, params ?? []),
192
+ executeWrite: (q, params) => run(q, params ?? [])
193
+ });
194
+ } finally {
195
+ // The transaction's socket goes back to the pool once the block
196
+ // ends, and a rollback does not undo `USE`.
197
+ if (database) await this.restoreConfigured(tx, database);
198
+ }
179
199
  }) as Promise<T>;
180
200
  }
181
201
 
@@ -358,7 +378,8 @@ export class MysqlAdapter implements DbClientDriverAdapter {
358
378
  assertSafeIdentifier(name);
359
379
  const ddl = `DROP DATABASE ${Q(name)}`;
360
380
  await this.requireSql().unsafe(ddl);
361
- if (this.defaultDb === name) this.defaultDb = null;
381
+ // Nothing to fall back to or restore sockets into once it is gone.
382
+ if (this.configuredDb === name) this.configuredDb = null;
362
383
  return ddl;
363
384
  }
364
385
 
@@ -379,8 +400,8 @@ export class MysqlAdapter implements DbClientDriverAdapter {
379
400
  await sql.unsafe(`RENAME TABLE ${qualified(Q, [name, r.TABLE_NAME])} TO ${qualified(Q, [newName, r.TABLE_NAME])}`);
380
401
  }
381
402
  await sql.unsafe(`DROP DATABASE ${Q(name)}`);
382
- // Force a fresh `USE` on next access — the session's selected db is gone.
383
- if (this.defaultDb === name) this.defaultDb = null;
403
+ // The connection's scope database no longer exists under that name.
404
+ if (this.configuredDb === name) this.configuredDb = null;
384
405
  return `CREATE DATABASE ${Q(newName)}; RENAME TABLE …; DROP DATABASE ${Q(name)}`;
385
406
  }
386
407