@myrialabs/clopen 0.4.48 → 0.4.50

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 (114) hide show
  1. package/backend/chat/background-wait.test.ts +28 -0
  2. package/backend/chat/message-pages.test.ts +180 -0
  3. package/backend/chat/message-pages.ts +237 -0
  4. package/backend/chat/stream-manager.ts +101 -18
  5. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  6. package/backend/database/migrations/088_create_messages_fts_map.ts +52 -0
  7. package/backend/database/migrations/089_add_memory_layout_tiles.ts +58 -0
  8. package/backend/database/migrations/index.ts +21 -0
  9. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  10. package/backend/database/queries/graph-queries.ts +392 -135
  11. package/backend/database/queries/index.ts +2 -0
  12. package/backend/database/queries/message-fts.test.ts +120 -0
  13. package/backend/database/queries/message-queries.ts +45 -9
  14. package/backend/database/queries/session-queries.ts +3 -2
  15. package/backend/database/queries/utils-queries.ts +3 -0
  16. package/backend/db-client/env/diff.ts +9 -33
  17. package/backend/db-client/env/env.test.ts +8 -8
  18. package/backend/db-client/env/service.ts +1 -1
  19. package/backend/engine/adapters/claude/environment.ts +4 -0
  20. package/backend/engine/adapters/claude/input-gate.test.ts +59 -0
  21. package/backend/engine/adapters/claude/input-gate.ts +74 -0
  22. package/backend/engine/adapters/claude/message-converter.test.ts +16 -0
  23. package/backend/engine/adapters/claude/message-converter.ts +8 -0
  24. package/backend/engine/adapters/claude/stream.ts +15 -0
  25. package/backend/files/file-watcher.ts +19 -0
  26. package/backend/git/contributors.test.ts +35 -0
  27. package/backend/git/contributors.ts +46 -0
  28. package/backend/git/identity/scope-config.test.ts +7 -4
  29. package/backend/http/static-assets.test.ts +78 -0
  30. package/backend/http/static-assets.ts +104 -0
  31. package/backend/index.ts +46 -17
  32. package/backend/memory/README.md +7 -4
  33. package/backend/memory/layout.test.ts +377 -0
  34. package/backend/memory/layout.ts +1029 -265
  35. package/backend/memory/view.ts +257 -386
  36. package/backend/preview/browser/browser-preview-service.ts +24 -6
  37. package/backend/project/status-manager.ts +4 -2
  38. package/backend/snapshot/blob-store.ts +9 -1
  39. package/backend/snapshot/helpers.ts +3 -10
  40. package/backend/snapshot/line-stats.test.ts +80 -0
  41. package/backend/snapshot/line-stats.ts +64 -0
  42. package/backend/snapshot/snapshot-service.ts +14 -27
  43. package/backend/snapshot/turn-changes.test.ts +10 -5
  44. package/backend/snapshot/turn-changes.ts +78 -40
  45. package/backend/terminal/ptykit.ts +6 -1
  46. package/backend/utils/ws-wire.test.ts +87 -0
  47. package/backend/utils/ws-wire.ts +189 -0
  48. package/backend/utils/ws.ts +40 -38
  49. package/backend/ws/chat/stream.ts +60 -20
  50. package/backend/ws/files/read.ts +30 -0
  51. package/backend/ws/git/log.ts +52 -0
  52. package/backend/ws/memory/crud.ts +118 -81
  53. package/backend/ws/messages/crud.ts +51 -0
  54. package/backend/ws/preview/index.ts +2 -0
  55. package/backend/ws/preview/watchers.ts +84 -0
  56. package/backend/ws/sessions/crud.ts +8 -12
  57. package/backend/ws/snapshot/changes.ts +5 -6
  58. package/backend/ws/terminal/tunnel.ts +2 -2
  59. package/bin/clopen.ts +37 -30
  60. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  61. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  62. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  63. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  64. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  65. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  66. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  67. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  68. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  69. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  70. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  71. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  72. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  73. package/dist/assets/{index-DJzwt-hq.js → index-By6KdSLT.js} +1 -1
  74. package/dist/assets/index-By6KdSLT.js.br +0 -0
  75. package/dist/assets/index-By6KdSLT.js.gz +0 -0
  76. package/dist/assets/{index-CONlwAXZ.js → index-DV4TiDn1.js} +1 -1
  77. package/dist/assets/index-DV4TiDn1.js.br +0 -0
  78. package/dist/assets/index-DV4TiDn1.js.gz +0 -0
  79. package/dist/assets/main-DIESTGTD.css +1 -0
  80. package/dist/assets/main-DIESTGTD.css.br +0 -0
  81. package/dist/assets/main-DIESTGTD.css.gz +0 -0
  82. package/dist/assets/{main-nBOb9YOA.js → main-Da3JKoua.js} +623 -623
  83. package/dist/assets/main-Da3JKoua.js.br +0 -0
  84. package/dist/assets/main-Da3JKoua.js.gz +0 -0
  85. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  86. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  87. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  88. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  89. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  90. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  91. package/dist/fonts/dm-sans.css.br +0 -0
  92. package/dist/fonts/dm-sans.css.gz +0 -0
  93. package/dist/index.html +2 -2
  94. package/dist/index.html.br +0 -0
  95. package/dist/index.html.gz +0 -0
  96. package/dist/sw.js.br +0 -0
  97. package/dist/sw.js.gz +0 -0
  98. package/package.json +3 -4
  99. package/shared/types/memory.ts +96 -73
  100. package/shared/types/unified/index.ts +1 -0
  101. package/shared/types/unified/stream.ts +33 -2
  102. package/shared/utils/diff-calculator.test.ts +178 -41
  103. package/shared/utils/diff-calculator.ts +383 -100
  104. package/shared/utils/process-supervisor.test.ts +242 -0
  105. package/shared/utils/process-supervisor.ts +356 -0
  106. package/shared/utils/process-tree.ts +99 -0
  107. package/shared/utils/ws-chunk.test.ts +33 -0
  108. package/shared/utils/ws-chunk.ts +73 -0
  109. package/shared/utils/ws-client-chunks.test.ts +45 -0
  110. package/shared/utils/ws-client.ts +43 -0
  111. package/shared/utils/ws-server.ts +17 -14
  112. package/backend/database/migrations/086_single_owner.test.ts +0 -170
  113. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +0 -1
  114. package/dist/assets/main-BUiUL3eZ.css +0 -1
@@ -1544,36 +1544,6 @@ export const graphQueries = {
1544
1544
  return rows.map(toNode);
1545
1545
  },
1546
1546
 
1547
- /**
1548
- * The same listing, narrowed to a rectangle of the persisted layout.
1549
- *
1550
- * This is what opening a bin reads, and it is why the view can be complete
1551
- * without being unbounded: zooming into part of the map costs that part. The
1552
- * bounds come from the layout's own coordinate space, which the client already
1553
- * holds — every mark it drew carries the cell it stands for.
1554
- */
1555
- listInRegion(
1556
- filter: GraphListFilter & { limit?: number },
1557
- region: { minX: number; maxX: number; minY: number; maxY: number }
1558
- ): GraphNode[] {
1559
- const { where, params } = buildNodeFilter(filter);
1560
- where.push(
1561
- `id IN (SELECT node_id FROM graph_layout
1562
- WHERE x >= ? AND x <= ? AND y >= ? AND y <= ?)`
1563
- );
1564
- params.push(region.minX, region.maxX, region.minY, region.maxY);
1565
- params.push(filter.limit ?? 2000);
1566
-
1567
- const rows = getDatabase()
1568
- .prepare(
1569
- `SELECT * FROM graph_nodes WHERE ${where.join(' AND ')}
1570
- ORDER BY pinned DESC, weight DESC, updated_at DESC
1571
- LIMIT ?`
1572
- )
1573
- .all(...params) as GraphNodeRow[];
1574
- return rows.map(toNode);
1575
- },
1576
-
1577
1547
  /**
1578
1548
  * Whether the graph holds any live memory at all.
1579
1549
  *
@@ -1906,11 +1876,14 @@ export interface GraphLayoutRow {
1906
1876
  x: number;
1907
1877
  y: number;
1908
1878
  /**
1909
- * 1 when the force simulation computed this position, 0 when it is a guess
1910
- * from the community's neighbourhood. See migration 067 for why the two must
1911
- * stay distinguishable.
1879
+ * 1 when the position is a real one — computed by the simulation or by the
1880
+ * arrival solver — and 0 when it is not usable. See migration 067 for why the
1881
+ * two must stay distinguishable; the pass no longer writes 0, but rows from
1882
+ * before it may still hold it, and those are treated as unplaced.
1912
1883
  */
1913
1884
  placed: number;
1885
+ /** Connections in the graph the pass laid out, stored and derived. Sizes the node. */
1886
+ degree: number;
1914
1887
  }
1915
1888
 
1916
1889
  /** How many nodes match a filter, and the rectangle their layout occupies. */
@@ -1924,51 +1897,91 @@ export interface GraphLayoutExtent {
1924
1897
  maxY: number;
1925
1898
  }
1926
1899
 
1927
- /** The grid a binned view is rolled up to, in layout coordinates. */
1928
- export interface GraphBinGrid {
1900
+ /** A rectangle of layout space, half-open: `[minX, maxX) × [minY, maxY)`. */
1901
+ export interface GraphLayoutRect {
1902
+ minX: number;
1903
+ maxX: number;
1904
+ minY: number;
1905
+ maxY: number;
1906
+ }
1907
+
1908
+ /** A square grid laid over layout space — tiles at one zoom level, or cells inside them. */
1909
+ export interface GraphLayoutGrid {
1929
1910
  originX: number;
1930
1911
  originY: number;
1931
- cellWidth: number;
1932
- cellHeight: number;
1912
+ size: number;
1933
1913
  }
1934
1914
 
1935
- /** One occupied cell: how many it holds, where they average, and which speaks for it. */
1936
- export interface GraphBinRow {
1937
- cellX: number;
1938
- cellY: number;
1939
- members: number;
1940
- x: number;
1941
- y: number;
1942
- /** The most reinforced member — the mark itself when `members` is 1. */
1915
+ /** A memory as a tile carries it: enough to draw and hover, nothing to inspect. */
1916
+ export interface GraphTileNodeRow {
1943
1917
  id: string;
1944
1918
  label: string;
1945
1919
  community: number;
1920
+ degree: number;
1921
+ x: number;
1922
+ y: number;
1923
+ }
1924
+
1925
+ /** One occupied cell of a crowded tile, with the member that speaks for it. */
1926
+ export interface GraphTileCellRow extends GraphTileNodeRow {
1927
+ cellX: number;
1928
+ cellY: number;
1929
+ members: number;
1930
+ }
1931
+
1932
+ /** An edge leaving a tile's memory, with where its far end sits. */
1933
+ export interface GraphTileEdgeRow {
1934
+ source: string;
1935
+ target: string;
1936
+ weight: number;
1937
+ targetX: number;
1938
+ targetY: number;
1946
1939
  }
1947
1940
 
1948
- export interface GraphBinEdgeRow {
1949
- srcX: number;
1950
- srcY: number;
1951
- dstX: number;
1952
- dstY: number;
1941
+ /** Edges between the cells of a crowded tile and the cells they reach. */
1942
+ export interface GraphTileCellEdgeRow {
1943
+ sourceCellX: number;
1944
+ sourceCellY: number;
1945
+ targetCellX: number;
1946
+ targetCellY: number;
1953
1947
  weight: number;
1954
1948
  }
1955
1949
 
1950
+ /** Longest caption a tile carries; the full text belongs to the inspector. */
1951
+ const TILE_LABEL_MAX = 80;
1952
+
1953
+ /**
1954
+ * Every edge touching a set of nodes, from both of the places edges live, and
1955
+ * oriented so `s` is always the member of the set.
1956
+ *
1957
+ * Stored edges come from `graph_edges` directly rather than from the layout
1958
+ * pass, so a connection a model records is drawn on the next fetch instead of
1959
+ * after the next pass. Derived ones come from `graph_layout_edges`, which the
1960
+ * pass keeps (see migration 089). Both are read through their own indexes, one
1961
+ * lookup per id per column.
1962
+ */
1963
+ const PAIRS_OF = (set: string): string => `
1964
+ SELECT e.src_id AS s, e.dst_id AS t, e.weight AS w FROM ${set} ids JOIN graph_edges e ON e.src_id = ids.id
1965
+ UNION ALL SELECT e.dst_id, e.src_id, e.weight FROM ${set} ids JOIN graph_edges e ON e.dst_id = ids.id
1966
+ UNION ALL SELECT d.src_id, d.dst_id, d.weight FROM ${set} ids JOIN graph_layout_edges d ON d.src_id = ids.id
1967
+ UNION ALL SELECT d.dst_id, d.src_id, d.weight FROM ${set} ids JOIN graph_layout_edges d ON d.dst_id = ids.id`;
1968
+
1956
1969
  /**
1957
- * Reading and writing the persisted arrangement (see migration 067).
1970
+ * Reading and writing the persisted arrangement (see migrations 067 and 089).
1958
1971
  *
1959
1972
  * Kept apart from `graphQueries` because it answers a different question:
1960
1973
  * `graphQueries` is about what is remembered, this is about how it is drawn.
1961
- * Every row here is derived and disposable — deleting the table costs one
1974
+ * Every row here is derived and disposable — deleting the tables costs one
1962
1975
  * background pass and no memory.
1963
1976
  */
1964
1977
  export const graphLayoutQueries = {
1965
- /** Positions and communities for a set of nodes. */
1978
+ /** Positions, communities and degrees for a set of nodes. */
1966
1979
  read(nodeIds: string[]): Map<string, GraphLayoutRow> {
1967
1980
  const result = new Map<string, GraphLayoutRow>();
1968
1981
  if (nodeIds.length === 0) return result;
1969
1982
  const rows = getDatabase()
1970
1983
  .prepare(
1971
- `SELECT node_id AS nodeId, community, x, y, placed FROM graph_layout
1984
+ `SELECT node_id AS nodeId, community, x, y, placed, degree FROM graph_layout
1972
1985
  WHERE node_id IN ${ID_SET}`
1973
1986
  )
1974
1987
  .all(idSet(nodeIds)) as GraphLayoutRow[];
@@ -1976,24 +1989,69 @@ export const graphLayoutQueries = {
1976
1989
  return result;
1977
1990
  },
1978
1991
 
1992
+ /**
1993
+ * Memories that are no longer live — archived or superseded — for the pass
1994
+ * to place.
1995
+ *
1996
+ * The pass arranges live memories, but "show archived" draws these too, and a
1997
+ * memory with no position cannot be drawn. `all` asks for every one of them,
1998
+ * which a cold pass needs because it draws a new map; otherwise only those
1999
+ * with no usable position yet. Capped, most recent first, because the
2000
+ * forgotten pile is allowed to grow far beyond anything worth drawing.
2001
+ */
2002
+ retiredIds(all: boolean, limit = 20_000): string[] {
2003
+ const rows = getDatabase()
2004
+ .prepare(
2005
+ `SELECT n.id AS id FROM graph_nodes n
2006
+ LEFT JOIN graph_layout l ON l.node_id = n.id
2007
+ WHERE (n.archived_at IS NOT NULL OR n.superseded_by IS NOT NULL)
2008
+ AND (? = 1 OR l.node_id IS NULL OR l.placed = 0)
2009
+ ORDER BY n.updated_at DESC, n.id ASC
2010
+ LIMIT ?`
2011
+ )
2012
+ .all(all ? 1 : 0, limit) as { id: string }[];
2013
+ return rows.map(row => row.id).sort();
2014
+ },
2015
+
1979
2016
  /** Replace the arrangement for the nodes given, in one transaction. */
1980
2017
  writeMany(rows: GraphLayoutRow[]): number {
1981
2018
  if (rows.length === 0) return 0;
1982
2019
  return graphQueries.transaction(() => {
1983
2020
  const statement = getDatabase().prepare(
1984
- `INSERT INTO graph_layout (node_id, community, x, y, placed, updated_at)
1985
- VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
2021
+ `INSERT INTO graph_layout (node_id, community, x, y, placed, degree, updated_at)
2022
+ VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
1986
2023
  ON CONFLICT(node_id) DO UPDATE SET
1987
2024
  community = excluded.community, x = excluded.x, y = excluded.y,
1988
- placed = excluded.placed, updated_at = CURRENT_TIMESTAMP`
2025
+ placed = excluded.placed, degree = excluded.degree, updated_at = CURRENT_TIMESTAMP`
1989
2026
  );
1990
2027
  for (const row of rows) {
1991
- statement.run(row.nodeId, row.community, row.x, row.y, row.placed);
2028
+ statement.run(row.nodeId, row.community, row.x, row.y, row.placed, row.degree);
1992
2029
  }
1993
2030
  return rows.length;
1994
2031
  });
1995
2032
  },
1996
2033
 
2034
+ /**
2035
+ * Replace every derived edge with the set the pass just laid out on.
2036
+ *
2037
+ * Wholesale rather than diffed: the set is a function of the whole graph — one
2038
+ * memory joining a subject re-chains that subject's members — so there is no
2039
+ * cheaper correct answer than the new set itself.
2040
+ */
2041
+ replaceDerivedEdges(edges: { srcId: string; dstId: string; weight: number }[]): void {
2042
+ graphQueries.transaction(() => {
2043
+ const db = getDatabase();
2044
+ db.prepare(`DELETE FROM graph_layout_edges`).run();
2045
+ const statement = db.prepare(
2046
+ `INSERT OR REPLACE INTO graph_layout_edges (src_id, dst_id, weight) VALUES (?, ?, ?)`
2047
+ );
2048
+ for (const edge of edges) {
2049
+ const [a, b] = edge.srcId < edge.dstId ? [edge.srcId, edge.dstId] : [edge.dstId, edge.srcId];
2050
+ statement.run(a, b, edge.weight);
2051
+ }
2052
+ });
2053
+ },
2054
+
1997
2055
  /**
1998
2056
  * Live nodes in the order the view itself ranks them, for the layout pass.
1999
2057
  *
@@ -2019,39 +2077,102 @@ export const graphLayoutQueries = {
2019
2077
  return rows.map(row => row.id);
2020
2078
  },
2021
2079
 
2080
+ /**
2081
+ * A cheap fingerprint of everything the edges of the layout graph come from.
2082
+ *
2083
+ * Reinforcement rings the change doorbell on every recall without moving a
2084
+ * node or an edge, so the pass compares this before doing any work. Counts and
2085
+ * the highest id are enough: rows are inserted and deleted, never rewritten in
2086
+ * place in a way that changes what they connect.
2087
+ */
2088
+ sourceFingerprint(): string {
2089
+ const row = getDatabase()
2090
+ .prepare(
2091
+ `SELECT (SELECT COUNT(*) FROM graph_edges) AS edges,
2092
+ (SELECT COALESCE(MAX(id), 0) FROM graph_edges) AS lastEdge,
2093
+ (SELECT COUNT(*) FROM graph_node_entities) AS entities,
2094
+ (SELECT COUNT(*) FROM graph_node_paths) AS paths`
2095
+ )
2096
+ .get() as { edges: number; lastEdge: number; entities: number; paths: number };
2097
+ return `${row.edges}:${row.lastEdge}:${row.entities}:${row.paths}`;
2098
+ },
2099
+
2022
2100
  /** Whether any live node is still waiting to be placed. */
2023
2101
  hasUnplaced(): boolean {
2024
2102
  const row = getDatabase()
2025
2103
  .prepare(
2026
2104
  `SELECT 1 AS present FROM graph_nodes n
2027
2105
  LEFT JOIN graph_layout l ON l.node_id = n.id
2028
- WHERE n.archived_at IS NULL AND n.superseded_by IS NULL AND l.node_id IS NULL
2106
+ WHERE n.archived_at IS NULL AND n.superseded_by IS NULL
2107
+ AND (l.node_id IS NULL OR l.placed = 0)
2029
2108
  LIMIT 1`
2030
2109
  )
2031
2110
  .get() as { present: number } | null;
2032
2111
  return row !== null && row !== undefined;
2033
2112
  },
2034
2113
 
2114
+ /**
2115
+ * The rectangle every placed row occupies — live or not — and the largest
2116
+ * coordinate magnitude in it.
2117
+ *
2118
+ * The magnitude is what catches a corrupted arrangement: a healthy one spans
2119
+ * thousands of units, and anything near the float range means a pass diverged.
2120
+ */
2121
+ bounds(): (GraphLayoutRect & { count: number; magnitude: number }) | null {
2122
+ const row = getDatabase()
2123
+ .prepare(
2124
+ `SELECT COUNT(*) AS count, MIN(x) AS minX, MAX(x) AS maxX, MIN(y) AS minY, MAX(y) AS maxY,
2125
+ MAX(MAX(ABS(x)), MAX(ABS(y))) AS magnitude
2126
+ FROM graph_layout WHERE placed = 1`
2127
+ )
2128
+ .get() as {
2129
+ count: number;
2130
+ minX: number | null;
2131
+ maxX: number | null;
2132
+ minY: number | null;
2133
+ maxY: number | null;
2134
+ magnitude: number | null;
2135
+ };
2136
+ if (!row || row.count === 0 || row.minX === null || row.maxX === null || row.minY === null || row.maxY === null) {
2137
+ return null;
2138
+ }
2139
+ return {
2140
+ count: row.count,
2141
+ minX: row.minX,
2142
+ maxX: row.maxX,
2143
+ minY: row.minY,
2144
+ maxY: row.maxY,
2145
+ magnitude: row.magnitude ?? 0
2146
+ };
2147
+ },
2148
+
2035
2149
  /** Rows whose node no longer exists. Foreign keys are not always enforced. */
2036
2150
  pruneOrphans(): number {
2037
- const result = getDatabase()
2151
+ const db = getDatabase();
2152
+ db.prepare(
2153
+ `DELETE FROM graph_layout_edges
2154
+ WHERE src_id NOT IN (SELECT id FROM graph_nodes) OR dst_id NOT IN (SELECT id FROM graph_nodes)`
2155
+ ).run();
2156
+ const result = db
2038
2157
  .prepare(`DELETE FROM graph_layout WHERE node_id NOT IN (SELECT id FROM graph_nodes)`)
2039
2158
  .run() as { changes?: number };
2040
2159
  return Number(result.changes ?? 0);
2041
2160
  },
2042
2161
 
2043
- /** Drop the whole arrangement — used when the graph is purged. */
2162
+ /** Drop the whole arrangement — used when the graph is purged or the pass changes. */
2044
2163
  clear(): void {
2045
- getDatabase().prepare(`DELETE FROM graph_layout`).run();
2164
+ const db = getDatabase();
2165
+ db.prepare(`DELETE FROM graph_layout_edges`).run();
2166
+ db.prepare(`DELETE FROM graph_layout`).run();
2046
2167
  },
2047
2168
 
2048
2169
  /**
2049
2170
  * How many nodes match, and the rectangle their arrangement occupies.
2050
2171
  *
2051
- * One pass answering both, because the two are always wanted together: the
2052
- * count decides whether the view has to bin at all, and the extent is what the
2053
- * grid is laid over. `MIN`/`MAX` skip NULLs, so a node still waiting to be
2054
- * placed is counted without dragging the bounds toward the origin.
2172
+ * The count is what the header reports and the rectangle is what "Fit" frames
2173
+ * — the filtered part of the map rather than the whole of it. `MIN`/`MAX` skip
2174
+ * NULLs, so a node still waiting to be placed is counted without dragging the
2175
+ * bounds toward the origin.
2055
2176
  */
2056
2177
  extent(filter: GraphListFilter): GraphLayoutExtent {
2057
2178
  const { where, params } = buildNodeFilter(filter, 'n.');
@@ -2060,9 +2181,11 @@ export const graphLayoutQueries = {
2060
2181
  const row = getDatabase()
2061
2182
  .prepare(
2062
2183
  `SELECT COUNT(*) AS total,
2063
- SUM(CASE WHEN l.node_id IS NULL THEN 1 ELSE 0 END) AS unplaced,
2064
- MIN(l.x) AS minX, MAX(l.x) AS maxX,
2065
- MIN(l.y) AS minY, MAX(l.y) AS maxY
2184
+ SUM(CASE WHEN l.node_id IS NULL OR l.placed = 0 THEN 1 ELSE 0 END) AS unplaced,
2185
+ MIN(CASE WHEN l.placed = 1 THEN l.x END) AS minX,
2186
+ MAX(CASE WHEN l.placed = 1 THEN l.x END) AS maxX,
2187
+ MIN(CASE WHEN l.placed = 1 THEN l.y END) AS minY,
2188
+ MAX(CASE WHEN l.placed = 1 THEN l.y END) AS maxY
2066
2189
  FROM graph_nodes n
2067
2190
  LEFT JOIN graph_layout l ON l.node_id = n.id
2068
2191
  ${clause}`
@@ -2087,107 +2210,241 @@ export const graphLayoutQueries = {
2087
2210
  },
2088
2211
 
2089
2212
  /**
2090
- * One row per occupied cell of the grid: its size, its centroid, and its most
2091
- * reinforced member.
2213
+ * How many matching memories fall in each tile of `grid` inside `rect`.
2092
2214
  *
2093
- * The count of rows is bounded by the grid, not by the store — that is the
2094
- * whole point. A cell holding one memory comes back with `members = 1` and
2095
- * that memory's id, so the caller can return the memory ITSELF rather than a
2096
- * bin standing for it; below the render budget that is every cell, and the
2097
- * view is bit-for-bit the flat one.
2098
- *
2099
- * `CAST(... AS INTEGER)` truncates toward zero, which would fold the cells on
2100
- * either side of the origin into one — the grid is therefore anchored at the
2101
- * arrangement's minimum, so every offset it sees is positive.
2215
+ * Asked once per request over the union of the tiles wanted, so the caller can
2216
+ * decide per tile whether it fits its budget before reading a single label.
2217
+ * `CAST` truncates toward zero, which is only a floor for non-negative input —
2218
+ * the world box is anchored below every placed row, so it always is.
2102
2219
  */
2103
- binnedNodes(filter: GraphListFilter, grid: GraphBinGrid): GraphBinRow[] {
2220
+ tileCounts(filter: GraphListFilter, grid: GraphLayoutGrid, rect: GraphLayoutRect): { tileX: number; tileY: number; count: number }[] {
2104
2221
  const { where, params } = buildNodeFilter(filter, 'n.');
2105
- const clause = where.length ? `WHERE ${where.join(' AND ')}` : '';
2222
+ const clause = where.length ? `AND ${where.join(' AND ')}` : '';
2223
+ return getDatabase()
2224
+ .prepare(
2225
+ `SELECT CAST((l.x - ?) / ? AS INTEGER) AS tileX,
2226
+ CAST((l.y - ?) / ? AS INTEGER) AS tileY,
2227
+ COUNT(*) AS count
2228
+ FROM graph_layout l
2229
+ INNER JOIN graph_nodes n ON n.id = l.node_id
2230
+ WHERE l.placed = 1 AND l.x >= ? AND l.x < ? AND l.y >= ? AND l.y < ? ${clause}
2231
+ GROUP BY 1, 2`
2232
+ )
2233
+ .all(
2234
+ grid.originX,
2235
+ grid.size,
2236
+ grid.originY,
2237
+ grid.size,
2238
+ rect.minX,
2239
+ rect.maxX,
2240
+ rect.minY,
2241
+ rect.maxY,
2242
+ ...params
2243
+ ) as { tileX: number; tileY: number; count: number }[];
2244
+ },
2106
2245
 
2246
+ /** Every matching memory inside a rectangle, drawn individually. */
2247
+ tileNodes(filter: GraphListFilter, rect: GraphLayoutRect, limit: number): GraphTileNodeRow[] {
2248
+ const { where, params } = buildNodeFilter(filter, 'n.');
2249
+ const clause = where.length ? `AND ${where.join(' AND ')}` : '';
2107
2250
  return getDatabase()
2108
2251
  .prepare(
2109
- `SELECT cellX, cellY, members, cx AS x, cy AS y, id, label, community
2252
+ `SELECT n.id AS id, substr(n.label, 1, ?) AS label, l.community AS community,
2253
+ l.degree AS degree, l.x AS x, l.y AS y
2254
+ FROM graph_layout l
2255
+ INNER JOIN graph_nodes n ON n.id = l.node_id
2256
+ WHERE l.placed = 1 AND l.x >= ? AND l.x < ? AND l.y >= ? AND l.y < ? ${clause}
2257
+ ORDER BY n.pinned DESC, n.weight DESC, n.updated_at DESC, n.id ASC
2258
+ LIMIT ?`
2259
+ )
2260
+ .all(TILE_LABEL_MAX, rect.minX, rect.maxX, rect.minY, rect.maxY, ...params, limit) as GraphTileNodeRow[];
2261
+ },
2262
+
2263
+ /**
2264
+ * A crowded tile folded into the cells of `cells`: one row per occupied cell,
2265
+ * with its size, its centroid and its most reinforced member.
2266
+ *
2267
+ * Cell coordinates are GLOBAL — counted from the world origin, not the tile —
2268
+ * so an edge from any tile can name the cell it lands in without knowing which
2269
+ * tile that cell belongs to.
2270
+ */
2271
+ tileCells(filter: GraphListFilter, rect: GraphLayoutRect, cells: GraphLayoutGrid): GraphTileCellRow[] {
2272
+ const { where, params } = buildNodeFilter(filter, 'n.');
2273
+ const clause = where.length ? `AND ${where.join(' AND ')}` : '';
2274
+ return getDatabase()
2275
+ .prepare(
2276
+ `SELECT cellX, cellY, members, cx AS x, cy AS y, id, label, community, degree
2110
2277
  FROM (
2111
- SELECT cellX, cellY, id, label, community,
2112
- COUNT(*) OVER (PARTITION BY cellX, cellY) AS members,
2113
- AVG(x) OVER (PARTITION BY cellX, cellY) AS cx,
2114
- AVG(y) OVER (PARTITION BY cellX, cellY) AS cy,
2278
+ SELECT cellX, cellY, id, label, community, degree,
2279
+ COUNT(*) OVER cell AS members,
2280
+ AVG(x) OVER cell AS cx,
2281
+ AVG(y) OVER cell AS cy,
2115
2282
  ROW_NUMBER() OVER (
2116
2283
  PARTITION BY cellX, cellY
2117
- ORDER BY pinned DESC, weight DESC, updated_at DESC
2284
+ ORDER BY pinned DESC, weight DESC, updated_at DESC, id ASC
2118
2285
  ) AS rn
2119
2286
  FROM (
2120
2287
  SELECT CAST((l.x - ?) / ? AS INTEGER) AS cellX,
2121
2288
  CAST((l.y - ?) / ? AS INTEGER) AS cellY,
2122
- l.x AS x, l.y AS y, l.community AS community,
2123
- n.id AS id, n.label AS label,
2289
+ l.x AS x, l.y AS y, l.community AS community, l.degree AS degree,
2290
+ n.id AS id, substr(n.label, 1, ?) AS label,
2124
2291
  n.pinned AS pinned, n.weight AS weight, n.updated_at AS updated_at
2125
- FROM graph_nodes n
2126
- INNER JOIN graph_layout l ON l.node_id = n.id
2127
- ${clause}
2292
+ FROM graph_layout l
2293
+ INNER JOIN graph_nodes n ON n.id = l.node_id
2294
+ WHERE l.placed = 1 AND l.x >= ? AND l.x < ? AND l.y >= ? AND l.y < ? ${clause}
2128
2295
  )
2296
+ WINDOW cell AS (PARTITION BY cellX, cellY)
2129
2297
  )
2130
2298
  WHERE rn = 1`
2131
2299
  )
2132
2300
  .all(
2133
- grid.originX,
2134
- grid.cellWidth,
2135
- grid.originY,
2136
- grid.cellHeight,
2301
+ cells.originX,
2302
+ cells.size,
2303
+ cells.originY,
2304
+ cells.size,
2305
+ TILE_LABEL_MAX,
2306
+ rect.minX,
2307
+ rect.maxX,
2308
+ rect.minY,
2309
+ rect.maxY,
2137
2310
  ...params
2138
- ) as GraphBinRow[];
2311
+ ) as GraphTileCellRow[];
2139
2312
  },
2140
2313
 
2141
2314
  /**
2142
- * Edges rolled up to the same grid, so the binned picture keeps its structure.
2315
+ * Edges touching a set of memories, each with where its far end sits.
2143
2316
  *
2144
- * Stored edges only. The derived ones (see `derivedEdges`) exist to hold a
2145
- * subject's memories together, and the layout pass already consumed them —
2146
- * their effect is in the POSITIONS, which is where it belongs at this
2147
- * resolution. Recomputing them here would mean handing this query the id of
2148
- * every matching node, which is the unbounded thing the grid exists to avoid.
2149
- *
2150
- * Edges inside a single cell are dropped: both ends are the same mark.
2317
+ * The far end is filtered exactly like the near one, so an edge never leads
2318
+ * into a memory the current filter hides — and it must have a position, or
2319
+ * there is nowhere to draw it to.
2151
2320
  */
2152
- binnedEdges(filter: GraphListFilter, grid: GraphBinGrid, limit: number): GraphBinEdgeRow[] {
2153
- const src = buildNodeFilter(filter, 'na.');
2154
- const dst = buildNodeFilter(filter, 'nb.');
2155
- const conditions = [...src.where, ...dst.where];
2156
- const clause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
2321
+ edgesTouching(filter: GraphListFilter, nodeIds: string[], limit: number): GraphTileEdgeRow[] {
2322
+ if (nodeIds.length === 0) return [];
2323
+ const { where, params } = buildNodeFilter(filter, 'nb.');
2324
+ const clause = where.length ? `AND ${where.join(' AND ')}` : '';
2325
+ return getDatabase()
2326
+ .prepare(
2327
+ `WITH wanted(id) AS (SELECT value FROM json_each(?)),
2328
+ pairs(s, t, w) AS (${PAIRS_OF('wanted')})
2329
+ SELECT p.s AS source, p.t AS target, MAX(p.w) AS weight, l.x AS targetX, l.y AS targetY
2330
+ FROM pairs p
2331
+ INNER JOIN graph_layout l ON l.node_id = p.t
2332
+ INNER JOIN graph_nodes nb ON nb.id = p.t
2333
+ WHERE p.s != p.t AND l.placed = 1 ${clause}
2334
+ GROUP BY p.s, p.t
2335
+ ORDER BY weight DESC
2336
+ LIMIT ?`
2337
+ )
2338
+ .all(idSet(nodeIds), ...params, limit) as GraphTileEdgeRow[];
2339
+ },
2157
2340
 
2341
+ /**
2342
+ * Edges leaving a crowded tile, rolled up to the cells at both ends.
2343
+ *
2344
+ * Same sources and the same filtering as `edgesTouching`, aggregated so a tile
2345
+ * of ten thousand memories costs a few hundred lines rather than ten thousand.
2346
+ * Edges that stay inside one cell are dropped: both ends are the same mark.
2347
+ */
2348
+ cellEdges(filter: GraphListFilter, rect: GraphLayoutRect, cells: GraphLayoutGrid, limit: number): GraphTileCellEdgeRow[] {
2349
+ const near = buildNodeFilter(filter, 'n.');
2350
+ const far = buildNodeFilter(filter, 'nb.');
2351
+ const nearClause = near.where.length ? `AND ${near.where.join(' AND ')}` : '';
2352
+ const farClause = far.where.length ? `AND ${far.where.join(' AND ')}` : '';
2158
2353
  return getDatabase()
2159
2354
  .prepare(
2160
- `SELECT srcX, srcY, dstX, dstY, SUM(weight) AS weight
2355
+ `WITH inside(id) AS (
2356
+ SELECT n.id FROM graph_layout l
2357
+ INNER JOIN graph_nodes n ON n.id = l.node_id
2358
+ WHERE l.placed = 1 AND l.x >= ? AND l.x < ? AND l.y >= ? AND l.y < ? ${nearClause}
2359
+ ),
2360
+ pairs(s, t, w) AS (${PAIRS_OF('inside')})
2361
+ SELECT sourceCellX, sourceCellY, targetCellX, targetCellY, SUM(w) AS weight
2161
2362
  FROM (
2162
- SELECT CAST((la.x - ?) / ? AS INTEGER) AS srcX,
2163
- CAST((la.y - ?) / ? AS INTEGER) AS srcY,
2164
- CAST((lb.x - ?) / ? AS INTEGER) AS dstX,
2165
- CAST((lb.y - ?) / ? AS INTEGER) AS dstY,
2166
- e.weight AS weight
2167
- FROM graph_edges e
2168
- INNER JOIN graph_layout la ON la.node_id = e.src_id
2169
- INNER JOIN graph_layout lb ON lb.node_id = e.dst_id
2170
- INNER JOIN graph_nodes na ON na.id = e.src_id
2171
- INNER JOIN graph_nodes nb ON nb.id = e.dst_id
2172
- ${clause}
2363
+ SELECT CAST((la.x - ?) / ? AS INTEGER) AS sourceCellX,
2364
+ CAST((la.y - ?) / ? AS INTEGER) AS sourceCellY,
2365
+ CAST((lb.x - ?) / ? AS INTEGER) AS targetCellX,
2366
+ CAST((lb.y - ?) / ? AS INTEGER) AS targetCellY,
2367
+ p.w AS w
2368
+ FROM pairs p
2369
+ INNER JOIN graph_layout la ON la.node_id = p.s
2370
+ INNER JOIN graph_layout lb ON lb.node_id = p.t
2371
+ INNER JOIN graph_nodes nb ON nb.id = p.t
2372
+ WHERE p.s != p.t AND lb.placed = 1 ${farClause}
2173
2373
  )
2174
- WHERE NOT (srcX = dstX AND srcY = dstY)
2374
+ WHERE NOT (sourceCellX = targetCellX AND sourceCellY = targetCellY)
2175
2375
  GROUP BY 1, 2, 3, 4
2176
2376
  ORDER BY weight DESC
2177
2377
  LIMIT ?`
2178
2378
  )
2179
2379
  .all(
2180
- grid.originX,
2181
- grid.cellWidth,
2182
- grid.originY,
2183
- grid.cellHeight,
2184
- grid.originX,
2185
- grid.cellWidth,
2186
- grid.originY,
2187
- grid.cellHeight,
2188
- ...src.params,
2189
- ...dst.params,
2380
+ rect.minX,
2381
+ rect.maxX,
2382
+ rect.minY,
2383
+ rect.maxY,
2384
+ ...near.params,
2385
+ cells.originX,
2386
+ cells.size,
2387
+ cells.originY,
2388
+ cells.size,
2389
+ cells.originX,
2390
+ cells.size,
2391
+ cells.originY,
2392
+ cells.size,
2393
+ ...far.params,
2190
2394
  limit
2191
- ) as GraphBinEdgeRow[];
2395
+ ) as GraphTileCellEdgeRow[];
2396
+ },
2397
+
2398
+ /**
2399
+ * Where particular memories are, whatever is loaded around them.
2400
+ *
2401
+ * What lets the view go TO something it has not drawn — a search result, a
2402
+ * connection in the inspector, a step back through history. Unfiltered on
2403
+ * purpose: the caller already decided these ids are worth showing.
2404
+ */
2405
+ locate(nodeIds: string[]): GraphTileNodeRow[] {
2406
+ if (nodeIds.length === 0) return [];
2407
+ return getDatabase()
2408
+ .prepare(
2409
+ `SELECT n.id AS id, substr(n.label, 1, ?) AS label, l.community AS community,
2410
+ l.degree AS degree, l.x AS x, l.y AS y
2411
+ FROM json_each(?) ids
2412
+ INNER JOIN graph_nodes n ON n.id = ids.value
2413
+ INNER JOIN graph_layout l ON l.node_id = n.id
2414
+ WHERE l.placed = 1`
2415
+ )
2416
+ .all(TILE_LABEL_MAX, idSet(nodeIds)) as GraphTileNodeRow[];
2417
+ },
2418
+
2419
+ /**
2420
+ * The degree that counts as "fully connected" for sizing, over what matches.
2421
+ *
2422
+ * The 95th percentile rather than the maximum — one hub with a hundred edges
2423
+ * would otherwise flatten every ordinary node to the floor. Computed over the
2424
+ * whole filtered set, never over a tile, or a memory would change size as the
2425
+ * tiles around it loaded.
2426
+ */
2427
+ degreeScale(filter: GraphListFilter): number {
2428
+ const { where, params } = buildNodeFilter(filter, 'n.');
2429
+ const clause = where.length ? `AND ${where.join(' AND ')}` : '';
2430
+ const db = getDatabase();
2431
+ const count = (
2432
+ db
2433
+ .prepare(
2434
+ `SELECT COUNT(*) AS c FROM graph_layout l INNER JOIN graph_nodes n ON n.id = l.node_id
2435
+ WHERE l.placed = 1 ${clause}`
2436
+ )
2437
+ .get(...params) as { c: number }
2438
+ ).c;
2439
+ if (count === 0) return 1;
2440
+ const row = db
2441
+ .prepare(
2442
+ `SELECT l.degree AS degree FROM graph_layout l INNER JOIN graph_nodes n ON n.id = l.node_id
2443
+ WHERE l.placed = 1 ${clause}
2444
+ ORDER BY l.degree ASC
2445
+ LIMIT 1 OFFSET ?`
2446
+ )
2447
+ .get(...params, Math.min(count - 1, Math.floor(count * 0.95))) as { degree: number } | null;
2448
+ return Math.max(1, row?.degree ?? 1);
2192
2449
  }
2193
2450
  };