@myrialabs/clopen 0.4.28 → 0.4.30

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 (62) hide show
  1. package/backend/auth/auth-service.ts +45 -25
  2. package/backend/auth/onboarding.test.ts +106 -0
  3. package/backend/auth/permissions.ts +1 -1
  4. package/backend/database/migrations/067_add_memory_graph_layout.ts +91 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/database/queries/graph-queries.ts +417 -32
  7. package/backend/database/utils/connection.ts +7 -31
  8. package/backend/db-client/drivers/mssql.ts +57 -22
  9. package/backend/db-client/drivers/mysql.ts +69 -48
  10. package/backend/db-client/drivers/postgres.ts +65 -53
  11. package/backend/engine/README.md +8 -3
  12. package/backend/engine/adapters/claude/message-converter.ts +51 -0
  13. package/backend/engine/adapters/claude/stream.ts +81 -15
  14. package/backend/engine/adapters/codex/message-converter.ts +8 -2
  15. package/backend/engine/adapters/codex/models.ts +85 -98
  16. package/backend/engine/adapters/codex/stream.ts +5 -7
  17. package/backend/engine/adapters/codex/usage-rollout.ts +7 -0
  18. package/backend/engine/adapters/copilot/stream.ts +24 -0
  19. package/backend/engine/docs/artifacts.md +1 -1
  20. package/backend/engine/docs/lessons-learned.md +78 -1
  21. package/backend/engine/docs/quick-reference.md +1 -1
  22. package/backend/engine/docs/stack.md +8 -0
  23. package/backend/engine/install-recipes.ts +19 -2
  24. package/backend/files/file-size-limit.ts +5 -14
  25. package/backend/files/file-watcher.test.ts +160 -0
  26. package/backend/files/file-watcher.ts +276 -58
  27. package/backend/git/git-executor.ts +8 -0
  28. package/backend/git/git-service.test.ts +136 -0
  29. package/backend/git/git-service.ts +113 -17
  30. package/backend/index.ts +16 -4
  31. package/backend/mcp/internal/remote-server.test.ts +8 -3
  32. package/backend/mcp/internal/remote-server.ts +1 -1
  33. package/backend/memory/bootstrap.ts +9 -0
  34. package/backend/memory/layout.ts +985 -0
  35. package/backend/memory/notify.ts +33 -7
  36. package/backend/memory/view.ts +375 -69
  37. package/backend/permissions/index.ts +4 -2
  38. package/backend/permissions/resolve.ts +7 -5
  39. package/backend/settings/system-settings.ts +97 -0
  40. package/backend/tunnel/public-origin.ts +5 -13
  41. package/backend/utils/env.ts +29 -0
  42. package/backend/utils/paths.ts +9 -3
  43. package/backend/utils/process-warnings.ts +41 -0
  44. package/backend/ws/auth/login.test.ts +8 -1
  45. package/backend/ws/auth/login.ts +22 -15
  46. package/backend/ws/auth/status.ts +24 -1
  47. package/backend/ws/chat/stream.ts +1 -0
  48. package/backend/ws/files/watch.ts +9 -0
  49. package/backend/ws/memory/crud.ts +50 -2
  50. package/backend/ws/settings/crud.ts +14 -22
  51. package/dist/assets/{index-BujQYGBm.js → index-DUc5T21e.js} +1 -1
  52. package/dist/assets/{index-DRMOgS9y.js → index-DYwQ5bP8.js} +1 -1
  53. package/dist/assets/main-VgdjTBLR.css +1 -0
  54. package/dist/assets/main-r0iv2PDz.js +1044 -0
  55. package/dist/index.html +2 -2
  56. package/package.json +14 -14
  57. package/shared/constants/engines.ts +1 -0
  58. package/shared/types/memory.ts +70 -0
  59. package/shared/types/stores/settings.ts +11 -1
  60. package/shared/types/unified/stream.ts +10 -4
  61. package/dist/assets/main-BrYtWn-4.js +0 -1036
  62. package/dist/assets/main-BrqMMMRX.css +0 -1
@@ -269,57 +269,89 @@ export interface GraphListFilter {
269
269
  * Kept in one place because the three drifting apart is how a node ends up
270
270
  * counted but not shown, or shown in the graph after being forgotten.
271
271
  */
272
- function appendProjectFilter(filter: GraphListFilter, where: string[], params: unknown[]): void {
272
+ /**
273
+ * An id set as ONE bound parameter instead of one placeholder per id.
274
+ *
275
+ * The graph view hands these queries up to three thousand ids at a time, and
276
+ * `IN (?, ?, … ×3000)` builds a different SQL string for every distinct length —
277
+ * so the statement cache never hits and SQLite recompiles the query on each
278
+ * call. `edgesWithin` was the worst of them, repeating the set twice for six
279
+ * thousand bound parameters. `json_each` takes the whole set as a single JSON
280
+ * argument, which makes the SQL text constant and the statement cacheable.
281
+ */
282
+ const ID_SET = '(SELECT value FROM json_each(?))';
283
+
284
+ const idSet = (ids: string[]): string => JSON.stringify(ids);
285
+
286
+ function appendProjectFilter(
287
+ filter: GraphListFilter,
288
+ where: string[],
289
+ params: unknown[],
290
+ as: string = ''
291
+ ): void {
273
292
  if (filter.projectIds !== undefined) {
274
293
  // Nothing selected is "global only", not "everything": the user has narrowed
275
294
  // away every repository, and what remains is what was never a repository's.
276
- if (filter.projectIds.length === 0) where.push(`project_id IS NULL`);
295
+ if (filter.projectIds.length === 0) where.push(`${as}project_id IS NULL`);
277
296
  else {
278
- where.push(`(project_id IN (${filter.projectIds.map(() => '?').join(',')}) OR project_id IS NULL)`);
297
+ where.push(
298
+ `(${as}project_id IN (${filter.projectIds.map(() => '?').join(',')}) OR ${as}project_id IS NULL)`
299
+ );
279
300
  params.push(...filter.projectIds);
280
301
  }
281
302
  return;
282
303
  }
283
304
  if (filter.projectId === undefined) return;
284
305
  if (filter.projectId === null) {
285
- where.push(`project_id IS NULL`);
306
+ where.push(`${as}project_id IS NULL`);
286
307
  return;
287
308
  }
288
309
  // A project view also shows the global memories that apply to it —
289
310
  // conventions and preferences are part of that project's context.
290
- where.push(`(project_id = ? OR project_id IS NULL)`);
311
+ where.push(`(${as}project_id = ? OR ${as}project_id IS NULL)`);
291
312
  params.push(filter.projectId);
292
313
  }
293
314
 
294
- function buildNodeFilter(filter: GraphListFilter): { where: string[]; params: unknown[] } {
315
+ /**
316
+ * The graph view's WHERE clause, optionally qualified by a table alias.
317
+ *
318
+ * The alias exists for the queries that join `graph_nodes` to itself through an
319
+ * edge — the cluster-adjacency rollup has to apply the SAME narrowing to both
320
+ * ends of every edge, and unqualified column names are ambiguous there. Callers
321
+ * pass `'n.'`; everything else keeps the bare form it always had.
322
+ */
323
+ function buildNodeFilter(
324
+ filter: GraphListFilter,
325
+ as: string = ''
326
+ ): { where: string[]; params: unknown[] } {
295
327
  const where: string[] = [];
296
328
  const params: unknown[] = [];
297
329
 
298
- appendProjectFilter(filter, where, params);
330
+ appendProjectFilter(filter, where, params, as);
299
331
  if (filter.kinds?.length) {
300
- where.push(`kind IN (${filter.kinds.map(() => '?').join(',')})`);
332
+ where.push(`${as}kind IN (${filter.kinds.map(() => '?').join(',')})`);
301
333
  params.push(...filter.kinds);
302
334
  }
303
335
  if (filter.subkinds?.length) {
304
- where.push(`subkind IN (${filter.subkinds.map(() => '?').join(',')})`);
336
+ where.push(`${as}subkind IN (${filter.subkinds.map(() => '?').join(',')})`);
305
337
  params.push(...filter.subkinds);
306
338
  }
307
339
  if (filter.scopes?.length) {
308
- where.push(`scope IN (${filter.scopes.map(() => '?').join(',')})`);
340
+ where.push(`${as}scope IN (${filter.scopes.map(() => '?').join(',')})`);
309
341
  params.push(...filter.scopes);
310
342
  }
311
343
  if (filter.sources?.length) {
312
- where.push(`source IN (${filter.sources.map(() => '?').join(',')})`);
344
+ where.push(`${as}source IN (${filter.sources.map(() => '?').join(',')})`);
313
345
  params.push(...filter.sources);
314
346
  }
315
347
 
316
- if (filter.archivedOnly) where.push(`archived_at IS NOT NULL`);
317
- else if (!filter.includeArchived) where.push(`archived_at IS NULL`);
348
+ if (filter.archivedOnly) where.push(`${as}archived_at IS NOT NULL`);
349
+ else if (!filter.includeArchived) where.push(`${as}archived_at IS NULL`);
318
350
 
319
351
  // The graph view shows current beliefs. Superseded ones stay reachable by
320
352
  // walking a `supersedes` edge from the node that replaced them, which is where
321
353
  // that history belongs.
322
- if (!filter.includeSuperseded) where.push(`superseded_by IS NULL`);
354
+ if (!filter.includeSuperseded) where.push(`${as}superseded_by IS NULL`);
323
355
 
324
356
  return { where, params };
325
357
  }
@@ -437,10 +469,9 @@ export const graphQueries = {
437
469
 
438
470
  getByIds(ids: string[]): GraphNode[] {
439
471
  if (ids.length === 0) return [];
440
- const placeholders = ids.map(() => '?').join(',');
441
472
  const rows = getDatabase()
442
- .prepare(`SELECT * FROM graph_nodes WHERE id IN (${placeholders})`)
443
- .all(...ids) as GraphNodeRow[];
473
+ .prepare(`SELECT * FROM graph_nodes WHERE id IN ${ID_SET}`)
474
+ .all(idSet(ids)) as GraphNodeRow[];
444
475
  return rows.map(toNode);
445
476
  },
446
477
 
@@ -767,11 +798,13 @@ export const graphQueries = {
767
798
  if (nodeIds.length === 0) return byNode;
768
799
  const rows = getDatabase()
769
800
  .prepare(
770
- `SELECT node_id, name FROM graph_node_entities WHERE node_id IN (${nodeIds.map(() => '?').join(',')})`
801
+ `SELECT node_id, name FROM graph_node_entities WHERE node_id IN ${ID_SET}`
771
802
  )
772
- .all(...nodeIds) as { node_id: string; name: string }[];
803
+ .all(idSet(nodeIds)) as { node_id: string; name: string }[];
773
804
  for (const row of rows) {
774
- byNode.set(row.node_id, [...(byNode.get(row.node_id) ?? []), row.name]);
805
+ const names = byNode.get(row.node_id);
806
+ if (names) names.push(row.name);
807
+ else byNode.set(row.node_id, [row.name]);
775
808
  }
776
809
  return byNode;
777
810
  },
@@ -813,7 +846,7 @@ export const graphQueries = {
813
846
  /** Links each memory draws per group, toward the heaviest members. */
814
847
  const LINKS_PER_MEMBER = 4;
815
848
 
816
- const placeholders = nodeIds.map(() => '?').join(',');
849
+ const set = idSet(nodeIds);
817
850
  const edges: { srcId: string; dstId: string; weight: number; via: 'subject' | 'project' }[] = [];
818
851
  const seen = new Set<string>();
819
852
 
@@ -837,12 +870,21 @@ export const graphQueries = {
837
870
  `SELECT e.entity_key AS groupKey, e.node_id AS nodeId
838
871
  FROM graph_node_entities e
839
872
  INNER JOIN graph_nodes n ON n.id = e.node_id
840
- WHERE e.node_id IN (${placeholders})
873
+ WHERE e.node_id IN ${ID_SET}
841
874
  ORDER BY e.entity_key, n.weight DESC, n.updated_at DESC`
842
875
  )
843
- .all(...nodeIds) as { groupKey: string; nodeId: string }[];
876
+ .all(set) as { groupKey: string; nodeId: string }[];
877
+ // Appended, not rebuilt. Spreading the existing array on every row made this
878
+ // quadratic in the size of a group — invisible for the subject groups, which
879
+ // are capped at two dozen, and the dominant cost of the whole call for the
880
+ // project groups, which routinely run to hundreds before the size check
881
+ // below discards them.
844
882
  const bySubject = new Map<string, string[]>();
845
- for (const row of rows) bySubject.set(row.groupKey, [...(bySubject.get(row.groupKey) ?? []), row.nodeId]);
883
+ for (const row of rows) {
884
+ const members = bySubject.get(row.groupKey);
885
+ if (members) members.push(row.nodeId);
886
+ else bySubject.set(row.groupKey, [row.nodeId]);
887
+ }
846
888
  // `members` is heaviest-first, so linking forward attaches the tail of a
847
889
  // subject to its most reinforced memories rather than to whichever happened
848
890
  // to be written first.
@@ -861,12 +903,16 @@ export const graphQueries = {
861
903
  const projectRows = getDatabase()
862
904
  .prepare(
863
905
  `SELECT project_id AS groupKey, id AS nodeId FROM graph_nodes
864
- WHERE id IN (${placeholders}) AND project_id IS NOT NULL AND kind = 'episodic'
906
+ WHERE id IN ${ID_SET} AND project_id IS NOT NULL AND kind = 'episodic'
865
907
  ORDER BY project_id, weight DESC, updated_at DESC`
866
908
  )
867
- .all(...nodeIds) as { groupKey: string; nodeId: string }[];
909
+ .all(set) as { groupKey: string; nodeId: string }[];
868
910
  const byProject = new Map<string, string[]>();
869
- for (const row of projectRows) byProject.set(row.groupKey, [...(byProject.get(row.groupKey) ?? []), row.nodeId]);
911
+ for (const row of projectRows) {
912
+ const members = byProject.get(row.groupKey);
913
+ if (members) members.push(row.nodeId);
914
+ else byProject.set(row.groupKey, [row.nodeId]);
915
+ }
870
916
  for (const members of byProject.values()) connect(members, 0.4, 'project');
871
917
 
872
918
  return edges;
@@ -1250,14 +1296,30 @@ export const graphQueries = {
1250
1296
  /** Every edge with both ends inside the given set — the induced subgraph. */
1251
1297
  edgesWithin(nodeIds: string[]): GraphEdge[] {
1252
1298
  if (nodeIds.length === 0) return [];
1253
- const placeholders = nodeIds.map(() => '?').join(',');
1299
+
1300
+ /**
1301
+ * Driven from the index, with the second end checked in JS.
1302
+ *
1303
+ * `WHERE src_id IN (…) AND dst_id IN (…)` reads naturally and is 200× slower,
1304
+ * measured: SQLite scans `graph_edges` and tests each row against a set of up
1305
+ * to three thousand values twice over, using neither of the indexes on the
1306
+ * columns being tested. 220 ms for 1,789 edges. Joining the id set to
1307
+ * `idx_graph_edges_src` turns it into one seek per id — 1 ms for the same
1308
+ * data — and the surviving rows are few enough that filtering the far end
1309
+ * against a `Set` here costs nothing.
1310
+ *
1311
+ * The placeholder form this replaced was no better; the cost was never the
1312
+ * binding, it was the plan.
1313
+ */
1314
+ const wanted = new Set(nodeIds);
1254
1315
  const rows = getDatabase()
1255
1316
  .prepare(
1256
- `SELECT * FROM graph_edges
1257
- WHERE src_id IN (${placeholders}) AND dst_id IN (${placeholders})`
1317
+ `SELECT e.* FROM json_each(?) ids
1318
+ INNER JOIN graph_edges e ON e.src_id = ids.value`
1258
1319
  )
1259
- .all(...nodeIds, ...nodeIds) as GraphEdgeRow[];
1260
- return rows.map(toEdge);
1320
+ .all(idSet(nodeIds)) as GraphEdgeRow[];
1321
+
1322
+ return rows.filter(row => wanted.has(row.dst_id)).map(toEdge);
1261
1323
  },
1262
1324
 
1263
1325
  /**
@@ -1355,6 +1417,36 @@ export const graphQueries = {
1355
1417
  return rows.map(toNode);
1356
1418
  },
1357
1419
 
1420
+ /**
1421
+ * The same listing, narrowed to a rectangle of the persisted layout.
1422
+ *
1423
+ * This is what opening a bin reads, and it is why the view can be complete
1424
+ * without being unbounded: zooming into part of the map costs that part. The
1425
+ * bounds come from the layout's own coordinate space, which the client already
1426
+ * holds — every mark it drew carries the cell it stands for.
1427
+ */
1428
+ listInRegion(
1429
+ filter: GraphListFilter & { limit?: number },
1430
+ region: { minX: number; maxX: number; minY: number; maxY: number }
1431
+ ): GraphNode[] {
1432
+ const { where, params } = buildNodeFilter(filter);
1433
+ where.push(
1434
+ `id IN (SELECT node_id FROM graph_layout
1435
+ WHERE x >= ? AND x <= ? AND y >= ? AND y <= ?)`
1436
+ );
1437
+ params.push(region.minX, region.maxX, region.minY, region.maxY);
1438
+ params.push(filter.limit ?? 2000);
1439
+
1440
+ const rows = getDatabase()
1441
+ .prepare(
1442
+ `SELECT * FROM graph_nodes WHERE ${where.join(' AND ')}
1443
+ ORDER BY pinned DESC, weight DESC, updated_at DESC
1444
+ LIMIT ?`
1445
+ )
1446
+ .all(...params) as GraphNodeRow[];
1447
+ return rows.map(toNode);
1448
+ },
1449
+
1358
1450
  /**
1359
1451
  * Whether the graph holds any live memory at all.
1360
1452
  *
@@ -1762,3 +1854,296 @@ export const graphQueries = {
1762
1854
  return Number(result.changes ?? 0);
1763
1855
  }
1764
1856
  };
1857
+
1858
+ /** One node's place in the persisted arrangement. */
1859
+ export interface GraphLayoutRow {
1860
+ nodeId: string;
1861
+ community: number;
1862
+ x: number;
1863
+ y: number;
1864
+ /**
1865
+ * 1 when the force simulation computed this position, 0 when it is a guess
1866
+ * from the community's neighbourhood. See migration 067 for why the two must
1867
+ * stay distinguishable.
1868
+ */
1869
+ placed: number;
1870
+ }
1871
+
1872
+ /** How many nodes match a filter, and the rectangle their layout occupies. */
1873
+ export interface GraphLayoutExtent {
1874
+ total: number;
1875
+ /** Matching nodes with no position yet — counted, but outside the bounds. */
1876
+ unplaced: number;
1877
+ minX: number;
1878
+ maxX: number;
1879
+ minY: number;
1880
+ maxY: number;
1881
+ }
1882
+
1883
+ /** The grid a binned view is rolled up to, in layout coordinates. */
1884
+ export interface GraphBinGrid {
1885
+ originX: number;
1886
+ originY: number;
1887
+ cellWidth: number;
1888
+ cellHeight: number;
1889
+ }
1890
+
1891
+ /** One occupied cell: how many it holds, where they average, and which speaks for it. */
1892
+ export interface GraphBinRow {
1893
+ cellX: number;
1894
+ cellY: number;
1895
+ members: number;
1896
+ x: number;
1897
+ y: number;
1898
+ /** The most reinforced member — the mark itself when `members` is 1. */
1899
+ id: string;
1900
+ label: string;
1901
+ community: number;
1902
+ }
1903
+
1904
+ export interface GraphBinEdgeRow {
1905
+ srcX: number;
1906
+ srcY: number;
1907
+ dstX: number;
1908
+ dstY: number;
1909
+ weight: number;
1910
+ }
1911
+
1912
+ /**
1913
+ * Reading and writing the persisted arrangement (see migration 067).
1914
+ *
1915
+ * Kept apart from `graphQueries` because it answers a different question:
1916
+ * `graphQueries` is about what is remembered, this is about how it is drawn.
1917
+ * Every row here is derived and disposable — deleting the table costs one
1918
+ * background pass and no memory.
1919
+ */
1920
+ export const graphLayoutQueries = {
1921
+ /** Positions and communities for a set of nodes. */
1922
+ read(nodeIds: string[]): Map<string, GraphLayoutRow> {
1923
+ const result = new Map<string, GraphLayoutRow>();
1924
+ if (nodeIds.length === 0) return result;
1925
+ const rows = getDatabase()
1926
+ .prepare(
1927
+ `SELECT node_id AS nodeId, community, x, y, placed FROM graph_layout
1928
+ WHERE node_id IN ${ID_SET}`
1929
+ )
1930
+ .all(idSet(nodeIds)) as GraphLayoutRow[];
1931
+ for (const row of rows) result.set(row.nodeId, row);
1932
+ return result;
1933
+ },
1934
+
1935
+ /** Replace the arrangement for the nodes given, in one transaction. */
1936
+ writeMany(rows: GraphLayoutRow[]): number {
1937
+ if (rows.length === 0) return 0;
1938
+ return graphQueries.transaction(() => {
1939
+ const statement = getDatabase().prepare(
1940
+ `INSERT INTO graph_layout (node_id, community, x, y, placed, updated_at)
1941
+ VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
1942
+ ON CONFLICT(node_id) DO UPDATE SET
1943
+ community = excluded.community, x = excluded.x, y = excluded.y,
1944
+ placed = excluded.placed, updated_at = CURRENT_TIMESTAMP`
1945
+ );
1946
+ for (const row of rows) {
1947
+ statement.run(row.nodeId, row.community, row.x, row.y, row.placed);
1948
+ }
1949
+ return rows.length;
1950
+ });
1951
+ },
1952
+
1953
+ /**
1954
+ * Live nodes in the order the view itself ranks them, for the layout pass.
1955
+ *
1956
+ * Capped, because a force layout over an unbounded set is unbounded work. What
1957
+ * survives the cap is what the view would have shown anyway — pinned, then
1958
+ * most reinforced, then most recent — so anything left unplaced is also the
1959
+ * least likely to be looked at.
1960
+ */
1961
+ liveNodeIds(limit: number): string[] {
1962
+ const rows = getDatabase()
1963
+ .prepare(
1964
+ // `id` is the tiebreak, and it is load-bearing rather than tidy. Most
1965
+ // live nodes share a weight and a timestamp, so without it SQLite is
1966
+ // free to return ties in any order — and this order decides the order
1967
+ // the layout graph is built in, which ForceAtlas2 is sensitive to. The
1968
+ // same store laid out to a different map on every pass.
1969
+ `SELECT id FROM graph_nodes
1970
+ WHERE archived_at IS NULL AND superseded_by IS NULL
1971
+ ORDER BY pinned DESC, weight DESC, updated_at DESC, id ASC
1972
+ LIMIT ?`
1973
+ )
1974
+ .all(limit) as { id: string }[];
1975
+ return rows.map(row => row.id);
1976
+ },
1977
+
1978
+ /** Whether any live node is still waiting to be placed. */
1979
+ hasUnplaced(): boolean {
1980
+ const row = getDatabase()
1981
+ .prepare(
1982
+ `SELECT 1 AS present FROM graph_nodes n
1983
+ LEFT JOIN graph_layout l ON l.node_id = n.id
1984
+ WHERE n.archived_at IS NULL AND n.superseded_by IS NULL AND l.node_id IS NULL
1985
+ LIMIT 1`
1986
+ )
1987
+ .get() as { present: number } | null;
1988
+ return row !== null && row !== undefined;
1989
+ },
1990
+
1991
+ /** Rows whose node no longer exists. Foreign keys are not always enforced. */
1992
+ pruneOrphans(): number {
1993
+ const result = getDatabase()
1994
+ .prepare(`DELETE FROM graph_layout WHERE node_id NOT IN (SELECT id FROM graph_nodes)`)
1995
+ .run() as { changes?: number };
1996
+ return Number(result.changes ?? 0);
1997
+ },
1998
+
1999
+ /** Drop the whole arrangement — used when the graph is purged. */
2000
+ clear(): void {
2001
+ getDatabase().prepare(`DELETE FROM graph_layout`).run();
2002
+ },
2003
+
2004
+ /**
2005
+ * How many nodes match, and the rectangle their arrangement occupies.
2006
+ *
2007
+ * One pass answering both, because the two are always wanted together: the
2008
+ * count decides whether the view has to bin at all, and the extent is what the
2009
+ * grid is laid over. `MIN`/`MAX` skip NULLs, so a node still waiting to be
2010
+ * placed is counted without dragging the bounds toward the origin.
2011
+ */
2012
+ extent(filter: GraphListFilter): GraphLayoutExtent {
2013
+ const { where, params } = buildNodeFilter(filter, 'n.');
2014
+ const clause = where.length ? `WHERE ${where.join(' AND ')}` : '';
2015
+
2016
+ const row = getDatabase()
2017
+ .prepare(
2018
+ `SELECT COUNT(*) AS total,
2019
+ SUM(CASE WHEN l.node_id IS NULL THEN 1 ELSE 0 END) AS unplaced,
2020
+ MIN(l.x) AS minX, MAX(l.x) AS maxX,
2021
+ MIN(l.y) AS minY, MAX(l.y) AS maxY
2022
+ FROM graph_nodes n
2023
+ LEFT JOIN graph_layout l ON l.node_id = n.id
2024
+ ${clause}`
2025
+ )
2026
+ .get(...params) as {
2027
+ total: number;
2028
+ unplaced: number | null;
2029
+ minX: number | null;
2030
+ maxX: number | null;
2031
+ minY: number | null;
2032
+ maxY: number | null;
2033
+ };
2034
+
2035
+ return {
2036
+ total: row.total ?? 0,
2037
+ unplaced: row.unplaced ?? 0,
2038
+ minX: row.minX ?? 0,
2039
+ maxX: row.maxX ?? 0,
2040
+ minY: row.minY ?? 0,
2041
+ maxY: row.maxY ?? 0
2042
+ };
2043
+ },
2044
+
2045
+ /**
2046
+ * One row per occupied cell of the grid: its size, its centroid, and its most
2047
+ * reinforced member.
2048
+ *
2049
+ * The count of rows is bounded by the grid, not by the store — that is the
2050
+ * whole point. A cell holding one memory comes back with `members = 1` and
2051
+ * that memory's id, so the caller can return the memory ITSELF rather than a
2052
+ * bin standing for it; below the render budget that is every cell, and the
2053
+ * view is bit-for-bit the flat one.
2054
+ *
2055
+ * `CAST(... AS INTEGER)` truncates toward zero, which would fold the cells on
2056
+ * either side of the origin into one — the grid is therefore anchored at the
2057
+ * arrangement's minimum, so every offset it sees is positive.
2058
+ */
2059
+ binnedNodes(filter: GraphListFilter, grid: GraphBinGrid): GraphBinRow[] {
2060
+ const { where, params } = buildNodeFilter(filter, 'n.');
2061
+ const clause = where.length ? `WHERE ${where.join(' AND ')}` : '';
2062
+
2063
+ return getDatabase()
2064
+ .prepare(
2065
+ `SELECT cellX, cellY, members, cx AS x, cy AS y, id, label, community
2066
+ FROM (
2067
+ SELECT cellX, cellY, id, label, community,
2068
+ COUNT(*) OVER (PARTITION BY cellX, cellY) AS members,
2069
+ AVG(x) OVER (PARTITION BY cellX, cellY) AS cx,
2070
+ AVG(y) OVER (PARTITION BY cellX, cellY) AS cy,
2071
+ ROW_NUMBER() OVER (
2072
+ PARTITION BY cellX, cellY
2073
+ ORDER BY pinned DESC, weight DESC, updated_at DESC
2074
+ ) AS rn
2075
+ FROM (
2076
+ SELECT CAST((l.x - ?) / ? AS INTEGER) AS cellX,
2077
+ CAST((l.y - ?) / ? AS INTEGER) AS cellY,
2078
+ l.x AS x, l.y AS y, l.community AS community,
2079
+ n.id AS id, n.label AS label,
2080
+ n.pinned AS pinned, n.weight AS weight, n.updated_at AS updated_at
2081
+ FROM graph_nodes n
2082
+ INNER JOIN graph_layout l ON l.node_id = n.id
2083
+ ${clause}
2084
+ )
2085
+ )
2086
+ WHERE rn = 1`
2087
+ )
2088
+ .all(
2089
+ grid.originX,
2090
+ grid.cellWidth,
2091
+ grid.originY,
2092
+ grid.cellHeight,
2093
+ ...params
2094
+ ) as GraphBinRow[];
2095
+ },
2096
+
2097
+ /**
2098
+ * Edges rolled up to the same grid, so the binned picture keeps its structure.
2099
+ *
2100
+ * Stored edges only. The derived ones (see `derivedEdges`) exist to hold a
2101
+ * subject's memories together, and the layout pass already consumed them —
2102
+ * their effect is in the POSITIONS, which is where it belongs at this
2103
+ * resolution. Recomputing them here would mean handing this query the id of
2104
+ * every matching node, which is the unbounded thing the grid exists to avoid.
2105
+ *
2106
+ * Edges inside a single cell are dropped: both ends are the same mark.
2107
+ */
2108
+ binnedEdges(filter: GraphListFilter, grid: GraphBinGrid, limit: number): GraphBinEdgeRow[] {
2109
+ const src = buildNodeFilter(filter, 'na.');
2110
+ const dst = buildNodeFilter(filter, 'nb.');
2111
+ const conditions = [...src.where, ...dst.where];
2112
+ const clause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
2113
+
2114
+ return getDatabase()
2115
+ .prepare(
2116
+ `SELECT srcX, srcY, dstX, dstY, SUM(weight) AS weight
2117
+ FROM (
2118
+ SELECT CAST((la.x - ?) / ? AS INTEGER) AS srcX,
2119
+ CAST((la.y - ?) / ? AS INTEGER) AS srcY,
2120
+ CAST((lb.x - ?) / ? AS INTEGER) AS dstX,
2121
+ CAST((lb.y - ?) / ? AS INTEGER) AS dstY,
2122
+ e.weight AS weight
2123
+ FROM graph_edges e
2124
+ INNER JOIN graph_layout la ON la.node_id = e.src_id
2125
+ INNER JOIN graph_layout lb ON lb.node_id = e.dst_id
2126
+ INNER JOIN graph_nodes na ON na.id = e.src_id
2127
+ INNER JOIN graph_nodes nb ON nb.id = e.dst_id
2128
+ ${clause}
2129
+ )
2130
+ WHERE NOT (srcX = dstX AND srcY = dstY)
2131
+ GROUP BY 1, 2, 3, 4
2132
+ ORDER BY weight DESC
2133
+ LIMIT ?`
2134
+ )
2135
+ .all(
2136
+ grid.originX,
2137
+ grid.cellWidth,
2138
+ grid.originY,
2139
+ grid.cellHeight,
2140
+ grid.originX,
2141
+ grid.cellWidth,
2142
+ grid.originY,
2143
+ grid.cellHeight,
2144
+ ...src.params,
2145
+ ...dst.params,
2146
+ limit
2147
+ ) as GraphBinEdgeRow[];
2148
+ }
2149
+ };
@@ -1,4 +1,5 @@
1
1
  import { join } from 'path';
2
+ import { mkdirSync } from 'fs';
2
3
  import { Database } from 'bun:sqlite';
3
4
  import type { DatabaseConnection } from '$shared/types/database/connection';
4
5
 
@@ -29,37 +30,12 @@ export class DatabaseManager {
29
30
  debug.log('database', '🔗 Connecting to database...');
30
31
 
31
32
  try {
32
- // Create clopen directory if it doesn't exist
33
- const clopenDir = getClopenDir();
34
- const dirFile = Bun.file(clopenDir);
35
-
36
- // Check if directory exists, if not create it
37
- try {
38
- await dirFile.stat();
39
- } catch {
40
- // Directory doesn't exist, create using Bun.write workaround
41
- const tempFile = join(clopenDir, '.init');
42
- await Bun.write(tempFile, '');
43
- // Remove the temp file
44
- try {
45
- const tempFileHandle = Bun.file(tempFile);
46
- if (await tempFileHandle.exists()) {
47
- if (process.platform === 'win32') {
48
- await Bun.spawn(['cmd', '/c', 'del', '/f', '/q', tempFile.replace(/\//g, '\\')], {
49
- stdout: 'ignore',
50
- stderr: 'ignore'
51
- }).exited;
52
- } else {
53
- await Bun.spawn(['rm', '-f', tempFile], {
54
- stdout: 'ignore',
55
- stderr: 'ignore'
56
- }).exited;
57
- }
58
- }
59
- } catch {
60
- // Ignore cleanup errors
61
- }
62
- }
33
+ // Ensure the data directory exists before SQLite touches the path.
34
+ // This has to be reliable: on a first run the directory is missing, and
35
+ // opening a database inside a missing directory fails in ways that
36
+ // surface much later as "no such table". `mkdirSync` is atomic, creates
37
+ // parents, and no-ops when the directory is already there.
38
+ mkdirSync(getClopenDir(), { recursive: true });
63
39
 
64
40
  // Use Bun's native SQLite exclusively
65
41
  this.db = new Database(this.dbPath);