@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
@@ -4,32 +4,58 @@
4
4
  * Community detection and force layout both used to run on the read path — one
5
5
  * on the server inside `buildGraphView`, the other in the browser on every open —
6
6
  * and both produce the SAME answer for the same dataset. They were being
7
- * recomputed, not computed: opening the modal twice paid for the identical
8
- * arrangement twice, and every conversation that recorded a memory made every
9
- * connected client pay for it again.
10
- *
11
- * That is what made the modal's opening animation stutter once the graph got
12
- * large. The animation is two hundred milliseconds of one thread, and a few
13
- * hundred milliseconds of layout was landing inside it.
14
- *
15
- * So it happens HERE instead: once, in the background, written to `graph_layout`,
16
- * and read back as two numbers per node. Reading a laid-out graph is then a
17
- * table lookup whatever the graph costs to lay out, and the browser never runs a
18
- * force simulation for the whole store again.
19
- *
20
- * ── Warm, not cold ────────────────────────────────────────────────────────────
21
- * A pass starts from where the last one finished. That is not only cheaper, it is
22
- * the thing that makes the view stable to look at: a memory arriving must not
23
- * rearrange the map somebody has learned. New nodes are seeded at the centroid of
24
- * whatever they connect to and a short pass settles them into the gaps, exactly
25
- * as the client's incremental path used to do for a single session.
7
+ * recomputed, not computed. So they happen HERE instead: in the background,
8
+ * written to `graph_layout`, and read back as a position per node. Reading a
9
+ * laid-out graph is then a table lookup whatever the graph costs to lay out.
10
+ *
11
+ * ── Two kinds of pass ─────────────────────────────────────────────────────────
12
+ * A COLD pass arranges every live memory from nothing: communities, a force
13
+ * simulation per component, lobes pushed apart, components packed. It is the
14
+ * only thing that decides the map's shape, and it is the expensive half —
15
+ * seconds for a few thousand memories.
16
+ *
17
+ * A WARM pass places what arrived since, and moves NOTHING that was already
18
+ * placed. New memories are dropped next to what they connect to and relaxed
19
+ * into the gaps around them by a small solver whose cost is the arrivals times
20
+ * their neighbourhood, not the store. That is what keeps a map somebody has
21
+ * learned in place while a conversation writes into it.
22
+ *
23
+ * ── Why a warm pass may not re-settle the map ────────────────────────────────
24
+ * It used to, and the map grew without limit. A warm pass re-ran the simulation
25
+ * from the stored positions and then pushed the lobes apart again — but the
26
+ * stored positions were ALREADY pushed apart, and the simulation only pulls a
27
+ * part of that back. Measured on one unchanged store, every pass inflated the
28
+ * map by about 1.4×: 9.8k units, then 13.8k, 18.9k, 28.9k, 39.3k, 52.4k. Over
29
+ * weeks of passes that compounded to 10³⁸, where squaring a coordinate
30
+ * overflows to Infinity, Infinity / Infinity is NaN, and every pass after that
31
+ * failed on the NOT NULL constraint — so nothing written since was ever placed,
32
+ * and the overview binned five thousand memories into thirty-five marks because
33
+ * the extent it divided into a grid was astronomically wide.
34
+ *
35
+ * Re-settling has no fixed point to converge to, so it is not done at all. The
36
+ * map changes shape only on a cold pass, and a cold pass runs when the store has
37
+ * grown enough since the last one that the shape is worth revisiting (see
38
+ * `RECOLD_RATIO`) — or when the stored arrangement is unusable.
39
+ *
40
+ * ── A cold pass must not look like a new map ─────────────────────────────────
41
+ * Two things would make it one, and both are undone after the fact. Louvain
42
+ * numbers its communities arbitrarily, so colours would shuffle; the new
43
+ * communities are matched to the old ones by overlap and take their numbers.
44
+ * And a fresh simulation has no reason to face the same way as the last one; the
45
+ * result is rotated (or mirrored) and translated onto the previous arrangement —
46
+ * rigidly, never scaled, so the map cannot creep in size either way.
47
+ *
48
+ * ── The world ────────────────────────────────────────────────────────────────
49
+ * The view is served as tiles of a fixed square, the WORLD, which covers every
50
+ * placed row with a margin. It is part of the stored state together with an
51
+ * EPOCH that changes whenever the world does — a cold pass, or an arrival that
52
+ * lands outside it — because a client's cached tiles and camera are expressed in
53
+ * it and have to know when they no longer mean the same thing.
26
54
  *
27
55
  * ── Bounded on purpose ────────────────────────────────────────────────────────
28
- * `MAX_LAYOUT_NODES` caps the simulation. A force layout is superlinear and the
29
- * store grows without limit, so an uncapped pass would eventually take longer
30
- * than the interval between the writes that trigger it. What survives the cap is
31
- * what the view ranks highest anyway; anything below it is reachable by search
32
- * and by expanding a lobe, neither of which needs a position.
56
+ * `MAX_LAYOUT_NODES` caps the simulation. What survives the cap is what the view
57
+ * ranks highest; everything below it is placed by the same solver that places
58
+ * arrivals, next to what it connects to.
33
59
  */
34
60
 
35
61
  import Graph from 'graphology';
@@ -44,50 +70,92 @@ import { debug } from '$shared/utils/logger';
44
70
  * What produced the stored arrangement. BUMP IT whenever that changes — either
45
71
  * the edges this pass lays out, or how it places them.
46
72
  *
47
- * A pass is warm by default: every node is seeded at the position it already had
48
- * and only lightly re-settled, which is what stops one new memory rearranging a
49
- * map somebody has learned. That is exactly wrong after the pass itself changes,
50
- * because the arrangement it would preserve was computed by different rules —
51
- * when removing the code half took the store from 1,351 components to one, the
52
- * surviving memories stayed in the shell those nine thousand nodes had shaped.
53
- *
54
- * So the marker is stored alongside the arrangement, and a mismatch drops the
55
- * arrangement once. It costs one cold pass, which the store pays for anyway the
56
- * first time it is laid out.
73
+ * A mismatch drops the arrangement once and lays the store out cold. Version 7
74
+ * is the one that stopped warm passes re-settling the map; every arrangement
75
+ * written before it was inflated by them, and some of them to the point of being
76
+ * unreadable, so none of them is worth preserving.
57
77
  */
58
- const LAYOUT_VERSION = '6';
78
+ const LAYOUT_VERSION = '8';
59
79
  const LAYOUT_VERSION_KEY = 'memory_layout_version';
60
80
  /** The key this used before it covered placement as well as derivation. */
61
81
  const LEGACY_LAYOUT_KEY = 'memory_layout_derivation';
82
+ /** Where the world, the epoch and the cold-pass bookkeeping live. */
83
+ const LAYOUT_STATE_KEY = 'memory_layout_state';
62
84
 
63
85
  /**
64
86
  * Two caps, because the two halves of a pass scale differently.
65
87
  *
66
- * COMMUNITY DETECTION is roughly linear in the edges, and it is what the overview
67
- * groups by — a node left out of it has no lobe to belong to and would vanish
68
- * from the picture entirely, which is exactly the failure a cap is supposed to
69
- * prevent. So it runs over everything live, up to a ceiling far beyond any real
70
- * store.
88
+ * COMMUNITY DETECTION is roughly linear in the edges and colours every node, so
89
+ * it runs over everything live, up to a ceiling far beyond any real store.
71
90
  *
72
91
  * THE FORCE SIMULATION is superlinear and measurably so — around 15 ms per
73
92
  * iteration at 1,200 nodes and 90 ms at 5,000 — so it runs only over the
74
- * highest-ranked nodes. The rest keep their real community and get a position
75
- * near it, marked `placed = 0` so nothing downstream mistakes the guess for a
76
- * computed arrangement.
93
+ * highest-ranked nodes. The rest are placed by the arrival solver next to what
94
+ * they connect to.
77
95
  */
78
96
  const MAX_COMMUNITY_NODES = 50_000;
79
97
  const MAX_LAYOUT_NODES = 6_000;
80
98
 
99
+ /**
100
+ * How much the store may grow by warm placement before the shape is revisited.
101
+ *
102
+ * Arrivals are placed well, but locally: a subject that grows from three
103
+ * memories to three hundred still sits in the room its first three were given.
104
+ * Past a fifth of the store arriving since the last cold pass, the arrangement
105
+ * is describing a graph that no longer exists, and a cold pass is cheaper than
106
+ * the confusion. Low enough that small stores — where a cold pass is a few
107
+ * milliseconds — are re-arranged often.
108
+ */
109
+ const RECOLD_RATIO = 0.2;
110
+
111
+ /**
112
+ * Past this magnitude a coordinate is not an arrangement, it is a divergence.
113
+ *
114
+ * A healthy store spans thousands of units and a very large one tens of
115
+ * thousands; a stored row beyond this means some earlier pass went wrong, and
116
+ * the only sound response is to lay out from nothing.
117
+ */
118
+ const MAX_SANE_COORDINATE = 1e7;
119
+
120
+ /** Margin around the placed rows, as a fraction of the world's side. */
121
+ const WORLD_MARGIN = 0.08;
122
+
81
123
  /**
82
124
  * How long to wait after a write before laying out again.
83
125
  *
84
126
  * `notifyGraphChanged` already folds a turn's ingestion burst into one event at
85
- * 600 ms; this sits on top because a layout pass is far more expensive than a
86
- * broadcast and a user watching the graph does not need the new node to have
87
- * found its final place within the second — it appears immediately either way,
88
- * seeded next to what it connects to.
127
+ * 600 ms; this sits on top so a burst becomes one pass. Short, because a warm
128
+ * pass is cheap now — and until it runs a new memory has no position, so it is
129
+ * not on the map at all.
89
130
  */
90
- const DEBOUNCE_MS = 4_000;
131
+ const DEBOUNCE_MS = 1_500;
132
+
133
+ /** The arrangement's bookkeeping, persisted next to it. */
134
+ export interface LayoutState {
135
+ /** Changes whenever the world does, so clients know their tiles are stale. */
136
+ epoch: number;
137
+ /**
138
+ * Changes whenever a pass writes anything — a new memory placed, an edge laid
139
+ * out. What a client compares to decide whether the tiles it holds still say
140
+ * the same thing; reinforcement rings the change doorbell constantly and moves
141
+ * none of this.
142
+ */
143
+ stamp: number;
144
+ /** The square every tile is cut from, or null before anything is placed. */
145
+ world: { minX: number; minY: number; size: number } | null;
146
+ /**
147
+ * The median distance from a live memory to its nearest neighbour — how much
148
+ * room a memory has on this map. The view sizes nodes from it, so a dot never
149
+ * outgrows the space around it at any zoom or store size.
150
+ */
151
+ spacing: number;
152
+ /** Live memories the last cold pass arranged. */
153
+ coldNodes: number;
154
+ /** Memories the arrival solver has placed since then. */
155
+ arrivals: number;
156
+ }
157
+
158
+ const EMPTY_STATE: LayoutState = { epoch: 0, stamp: 0, world: null, spacing: 0, coldNodes: 0, arrivals: 0 };
91
159
 
92
160
  let timer: ReturnType<typeof setTimeout> | null = null;
93
161
  let running = false;
@@ -95,24 +163,58 @@ let running = false;
95
163
  let rerunRequested = false;
96
164
 
97
165
  /**
98
- * What the last pass laid out.
166
+ * What the last pass was computed from.
99
167
  *
100
168
  * Reinforcement bumps `weight` and `updated_at` on every recall, so the change
101
- * notification fires constantly without the SET of nodes moving at all. Laying
102
- * out an unchanged set produces an unchanged answer, so this skips it.
169
+ * notification fires constantly without the set of nodes or edges moving at
170
+ * all. Laying out an unchanged graph produces an unchanged answer, so this
171
+ * skips it.
103
172
  */
104
- let lastMembership = '';
173
+ let lastFingerprint = '';
174
+
175
+ /** The state as last read or written, so the read path does not parse JSON per fetch. */
176
+ let cachedState: LayoutState | null = null;
105
177
 
106
178
  /** Cheap order-sensitive fingerprint of an id list. */
107
179
  function membershipOf(ids: string[]): string {
108
- let hash = 2166136261;
109
- for (const id of ids) {
110
- for (let i = 0; i < id.length; i++) {
111
- hash ^= id.charCodeAt(i);
112
- hash = Math.imul(hash, 16777619);
180
+ return `${ids.length}:${hashOf(ids.join('\u0000')).toString(36)}`;
181
+ }
182
+
183
+ /**
184
+ * The stored world and epoch — what the view tiles against.
185
+ *
186
+ * Read through a cache because every tile request asks; written only by a pass.
187
+ */
188
+ export function getLayoutState(): LayoutState {
189
+ if (cachedState) return cachedState;
190
+ const raw = settingsQueries.get(LAYOUT_STATE_KEY)?.value;
191
+ let state = EMPTY_STATE;
192
+ if (raw) {
193
+ try {
194
+ const parsed = JSON.parse(raw) as Partial<LayoutState>;
195
+ const world = parsed.world;
196
+ state = {
197
+ epoch: Number.isFinite(parsed.epoch) ? (parsed.epoch as number) : 0,
198
+ stamp: Number.isFinite(parsed.stamp) ? (parsed.stamp as number) : 0,
199
+ world:
200
+ world && [world.minX, world.minY, world.size].every(Number.isFinite) && world.size > 0
201
+ ? { minX: world.minX, minY: world.minY, size: world.size }
202
+ : null,
203
+ spacing: Number.isFinite(parsed.spacing) ? (parsed.spacing as number) : 0,
204
+ coldNodes: Number.isFinite(parsed.coldNodes) ? (parsed.coldNodes as number) : 0,
205
+ arrivals: Number.isFinite(parsed.arrivals) ? (parsed.arrivals as number) : 0
206
+ };
207
+ } catch {
208
+ state = EMPTY_STATE;
113
209
  }
114
210
  }
115
- return `${ids.length}:${(hash >>> 0).toString(36)}`;
211
+ cachedState = state;
212
+ return state;
213
+ }
214
+
215
+ function saveLayoutState(state: LayoutState): void {
216
+ cachedState = state;
217
+ settingsQueries.set(LAYOUT_STATE_KEY, JSON.stringify(state));
116
218
  }
117
219
 
118
220
  /**
@@ -131,17 +233,17 @@ export function scheduleGraphLayout(): void {
131
233
  timer.unref?.();
132
234
  }
133
235
 
134
- /** Forget what was laid out, so the next pass rebuilds from nothing. */
236
+ /** Forget what was laid out, so the next pass rebuilds from what the database holds. */
135
237
  export function resetGraphLayoutState(): void {
136
- lastMembership = '';
238
+ lastFingerprint = '';
239
+ cachedState = null;
137
240
  }
138
241
 
139
242
  /**
140
- * Recompute communities and positions for the live graph.
243
+ * Bring the arrangement up to date with the live graph.
141
244
  *
142
- * Never throws: a missing arrangement costs the client a seeded layout of its
143
- * own, which is what it used to do for everything, so a failure here degrades to
144
- * the previous behaviour instead of breaking the view.
245
+ * Never throws: a failed pass leaves the previous arrangement in place, and the
246
+ * memories it would have placed simply wait for the next one.
145
247
  */
146
248
  export async function runGraphLayout(): Promise<void> {
147
249
  if (running) {
@@ -151,105 +253,100 @@ export async function runGraphLayout(): Promise<void> {
151
253
  running = true;
152
254
 
153
255
  try {
154
- // Rank-ordered, so "the first N" is also "the N the view would have shown".
155
- const ids = graphLayoutQueries.liveNodeIds(MAX_COMMUNITY_NODES);
156
- if (ids.length === 0) {
157
- graphLayoutQueries.clear();
158
- lastMembership = membershipOf(ids);
159
- return;
160
- }
161
-
162
256
  // Before anything reads the stored arrangement: if a different version of
163
257
  // this pass produced it, it is not an arrangement of this graph.
164
258
  if (settingsQueries.get(LAYOUT_VERSION_KEY)?.value !== LAYOUT_VERSION) {
165
259
  graphLayoutQueries.clear();
166
260
  settingsQueries.set(LAYOUT_VERSION_KEY, LAYOUT_VERSION);
167
261
  settingsQueries.delete(LEGACY_LAYOUT_KEY);
168
- lastMembership = '';
262
+ const previous = getLayoutState();
263
+ saveLayoutState({ ...EMPTY_STATE, epoch: previous.epoch + 1, stamp: previous.stamp + 1 });
264
+ lastFingerprint = '';
169
265
  debug.log('memory', 'Memory layout: the pass changed, arranging from scratch');
170
266
  }
171
267
 
172
- const membership = membershipOf(ids);
173
- // Same nodes as last time and nothing waiting to be placed: the answer is
174
- // the one already in the table.
175
- if (membership === lastMembership && !graphLayoutQueries.hasUnplaced()) return;
268
+ // Rank-ordered, so "the first N" is also "the N the view would have shown".
269
+ const ids = graphLayoutQueries.liveNodeIds(MAX_COMMUNITY_NODES);
270
+ const state = getLayoutState();
176
271
 
177
- const started = Date.now();
178
- const existing = graphLayoutQueries.read(ids);
179
- const graph = buildLayoutGraph(ids);
180
-
181
- // Louvain needs at least one edge; an edgeless graph leaves every node in
182
- // its own community, which is also the honest answer.
183
- let communities: Record<string, number> = {};
184
- if (graph.size > 0) {
185
- try {
186
- // `rng` is NOT optional here, whatever the signature suggests.
187
- // graphology-communities-louvain defaults to `Math.random` and walks the
188
- // graph in random order, so the same store produced different lobes on
189
- // every pass — and since everything downstream is seeded from the
190
- // community structure, that alone made the whole map move. A fixed seed
191
- // keeps the randomised traversal (which is what the algorithm wants)
192
- // while making the answer reproducible.
193
- communities = louvain(graph, { getEdgeWeight: 'weight', rng: seededRandom() });
194
- } catch (error) {
195
- debug.warn('memory', 'Community detection failed; laying out without lobes', error);
272
+ if (ids.length === 0) {
273
+ graphLayoutQueries.clear();
274
+ if (state.world) {
275
+ saveLayoutState({ ...EMPTY_STATE, epoch: state.epoch + 1, stamp: state.stamp + 1 });
276
+ broadcastGraphChanged('layout');
196
277
  }
278
+ lastFingerprint = '';
279
+ return;
197
280
  }
198
281
 
199
- const simulatedIds = ids.slice(0, MAX_LAYOUT_NODES);
200
- const simulated = simulatedIds.length === ids.length ? graph : restrictTo(graph, simulatedIds);
201
-
202
- const cold = existing.size === 0;
203
- const rows = await arrange(simulated, communities, existing, cold);
204
-
205
- // Everything below the simulation cap. It keeps its real community — so the
206
- // view counts it and groups it correctly — and sits near the members of that
207
- // community that WERE placed, spread by its own id so a lobe of ten thousand
208
- // does not become one dot. `placed: 0` tells the view this is a
209
- // neighbourhood rather than an arrangement.
210
- if (simulatedIds.length < ids.length) {
211
- const centroids = new Map<number, { x: number; y: number; count: number }>();
212
- for (const row of rows) {
213
- const centroid = centroids.get(row.community) ?? { x: 0, y: 0, count: 0 };
214
- centroid.x += row.x;
215
- centroid.y += row.y;
216
- centroid.count++;
217
- centroids.set(row.community, centroid);
218
- }
282
+ // Same nodes, same edges, and nothing waiting to be placed: the answer is the
283
+ // one already in the table.
284
+ const fingerprint = `${membershipOf(ids)}|${graphLayoutQueries.sourceFingerprint()}`;
285
+ if (fingerprint === lastFingerprint && !graphLayoutQueries.hasUnplaced()) return;
219
286
 
220
- for (let i = simulatedIds.length; i < ids.length; i++) {
221
- const id = ids[i];
222
- const community = communities[id] ?? 0;
223
- const centroid = centroids.get(community);
224
- const anchor = centroid
225
- ? { x: centroid.x / centroid.count, y: centroid.y / centroid.count }
226
- : { x: 0, y: 0 };
227
- const radius = centroid ? 40 + 8 * Math.sqrt(centroid.count) : 200;
228
- const jitter = jitterOf(id);
287
+ const started = Date.now();
288
+ const existing = graphLayoutQueries.read(ids);
289
+ const { graph, derived } = buildLayoutGraph(ids);
229
290
 
230
- rows.push({
231
- nodeId: id,
232
- community,
233
- x: anchor.x + jitter.x * radius,
234
- y: anchor.y + jitter.y * radius,
235
- placed: 0
236
- });
237
- }
291
+ const placed = new Map<string, GraphLayoutRow>();
292
+ for (const [id, row] of existing) {
293
+ if (row.placed === 1 && Number.isFinite(row.x) && Number.isFinite(row.y)) placed.set(id, row);
238
294
  }
239
295
 
240
- graphLayoutQueries.writeMany(rows);
296
+ const bounds = graphLayoutQueries.bounds();
297
+ const corrupt = bounds !== null && !(bounds.magnitude <= MAX_SANE_COORDINATE);
298
+ const arriving = ids.length - placed.size;
299
+ const reason = corrupt
300
+ ? 'the stored arrangement diverged'
301
+ : placed.size === 0 || state.world === null
302
+ ? 'nothing is placed yet'
303
+ : state.arrivals + arriving > RECOLD_RATIO * Math.max(1, state.coldNodes)
304
+ ? 'the store outgrew its arrangement'
305
+ : null;
306
+
307
+ const rows = reason
308
+ ? await coldPass(ids, graph, corrupt ? new Map() : placed)
309
+ : warmPass(ids, graph, placed);
310
+
311
+ // Retired memories are drawn by the "show archived" view, so they need a
312
+ // place too. A cold pass draws a new map and re-places every one of them; a
313
+ // warm pass only places those that have none yet, and leaves the rest where
314
+ // they were, which is still the same map.
315
+ const retired = placeRetired(rows, reason !== null);
316
+
317
+ const written = sanitise([...rows, ...retired]);
318
+ const liveIds = new Set(ids);
319
+ const world = worldFor(written, reason ? null : state.world);
320
+ const worldChanged =
321
+ !state.world ||
322
+ world.minX !== state.world.minX ||
323
+ world.minY !== state.world.minY ||
324
+ world.size !== state.world.size;
325
+
326
+ graphLayoutQueries.writeMany(written);
327
+ graphLayoutQueries.replaceDerivedEdges(derived);
241
328
  graphLayoutQueries.pruneOrphans();
242
- lastMembership = membership;
243
329
 
244
- // Tell open views, or they never learn. The arrangement changes several
245
- // seconds AFTER the write that triggered it — long after the doorbell for
246
- // that write has been answered — so without this a modal that was open the
247
- // whole time keeps drawing positions it computed for itself, and only a
248
- // close-and-reopen picks up the real ones.
330
+ saveLayoutState({
331
+ epoch: reason || worldChanged ? state.epoch + 1 : state.epoch,
332
+ stamp: state.stamp + 1,
333
+ world,
334
+ spacing: medianSpacing(written.filter(row => liveIds.has(row.nodeId))),
335
+ coldNodes: reason ? ids.length : state.coldNodes,
336
+ arrivals: reason ? 0 : state.arrivals + arriving
337
+ });
338
+ lastFingerprint = fingerprint;
339
+
340
+ // Tell open views, or they never learn. The arrangement changes a moment
341
+ // AFTER the write that triggered it — after the doorbell for that write has
342
+ // been answered — so without this a new memory would stay off the map until
343
+ // the modal was reopened.
249
344
  broadcastGraphChanged('layout');
250
345
  debug.log(
251
346
  'memory',
252
- `Laid out ${simulated.order} of ${rows.length} memory node(s) in ${Date.now() - started}ms`
347
+ reason
348
+ ? `Laid out ${ids.length} memory node(s) from scratch (${reason}) in ${Date.now() - started}ms`
349
+ : `Placed ${arriving} arriving memory node(s) in ${Date.now() - started}ms`
253
350
  );
254
351
  } catch (error) {
255
352
  debug.warn('memory', 'Memory graph layout failed (non-fatal)', error);
@@ -262,14 +359,640 @@ export async function runGraphLayout(): Promise<void> {
262
359
  }
263
360
  }
264
361
 
362
+ /**
363
+ * Arrange every live memory from nothing, then make it look like the map it
364
+ * replaces.
365
+ *
366
+ * `previous` is the last arrangement's placed rows, empty when there was none or
367
+ * it was unusable — in which case there is nothing to stay faithful to and the
368
+ * fresh arrangement stands as computed.
369
+ */
370
+ async function coldPass(
371
+ ids: string[],
372
+ graph: Graph,
373
+ previous: Map<string, GraphLayoutRow>
374
+ ): Promise<GraphLayoutRow[]> {
375
+ // Louvain needs at least one edge; an edgeless graph leaves every node in its
376
+ // own community, which is also the honest answer.
377
+ let communities: Record<string, number> = {};
378
+ if (graph.size > 0) {
379
+ try {
380
+ // `rng` is NOT optional here, whatever the signature suggests.
381
+ // graphology-communities-louvain defaults to `Math.random` and walks the
382
+ // graph in random order, so the same store produced different lobes on
383
+ // every pass. A fixed seed keeps the randomised traversal (which is what
384
+ // the algorithm wants) while making the answer reproducible.
385
+ communities = louvain(graph, { getEdgeWeight: 'weight', rng: seededRandom() });
386
+ } catch (error) {
387
+ debug.warn('memory', 'Community detection failed; laying out without lobes', error);
388
+ }
389
+ }
390
+ for (const id of ids) communities[id] ??= 0;
391
+ communities = keepCommunityNumbers(ids, communities, previous);
392
+
393
+ const simulatedIds = ids.slice(0, MAX_LAYOUT_NODES);
394
+ const simulated = simulatedIds.length === ids.length ? graph : restrictTo(graph, simulatedIds);
395
+ const arranged = await arrange(simulated, communities);
396
+
397
+ alignTo(arranged, previous);
398
+
399
+ // Everything below the simulation cap is placed the way an arrival is: next to
400
+ // what it connects to, among what the simulation already placed.
401
+ const positions = new Map<string, { x: number; y: number }>();
402
+ for (const row of arranged) positions.set(row.nodeId, { x: row.x, y: row.y });
403
+ const remaining = ids.slice(simulatedIds.length);
404
+ const solved = placeArrivals(remaining, graph, positions, communities);
405
+
406
+ return [
407
+ ...arranged.map(row => ({ ...row, degree: graph.degree(row.nodeId) })),
408
+ ...remaining.map(id => {
409
+ const at = solved.positions.get(id) as { x: number; y: number };
410
+ return { nodeId: id, community: communities[id], x: at.x, y: at.y, placed: 1, degree: graph.degree(id) };
411
+ })
412
+ ];
413
+ }
414
+
415
+ /**
416
+ * Place what arrived since the last pass, leaving everything else untouched.
417
+ *
418
+ * Every existing row is rewritten with its own position and community — only
419
+ * its degree moves, because a new memory changes how connected its neighbours
420
+ * are.
421
+ */
422
+ function warmPass(ids: string[], graph: Graph, placed: Map<string, GraphLayoutRow>): GraphLayoutRow[] {
423
+ const positions = new Map<string, { x: number; y: number }>();
424
+ const communities: Record<string, number> = {};
425
+ for (const [id, row] of placed) {
426
+ positions.set(id, { x: row.x, y: row.y });
427
+ communities[id] = row.community;
428
+ }
429
+
430
+ const arriving = ids.filter(id => !placed.has(id));
431
+ const solved = placeArrivals(arriving, graph, positions, communities);
432
+
433
+ return ids.map(id => {
434
+ const row = placed.get(id);
435
+ if (row) return { ...row, degree: graph.degree(id) };
436
+ const at = solved.positions.get(id) as { x: number; y: number };
437
+ return {
438
+ nodeId: id,
439
+ community: solved.communities[id] ?? 0,
440
+ x: at.x,
441
+ y: at.y,
442
+ placed: 1,
443
+ degree: graph.degree(id)
444
+ };
445
+ });
446
+ }
447
+
448
+ /**
449
+ * Place archived and superseded memories among the live ones.
450
+ *
451
+ * They are not part of the layout graph — the pass arranges what is live — so
452
+ * their neighbours are read from the stored edges, and one with no live
453
+ * neighbour is placed in the field like any lone memory. They never move a live
454
+ * memory: the live rows are the fixed half of the solve.
455
+ */
456
+ function placeRetired(live: GraphLayoutRow[], all: boolean): GraphLayoutRow[] {
457
+ const retired = graphLayoutQueries.retiredIds(all);
458
+ if (retired.length === 0) return [];
459
+
460
+ const positions = new Map<string, { x: number; y: number }>();
461
+ const communities: Record<string, number> = {};
462
+ for (const row of live) {
463
+ positions.set(row.nodeId, { x: row.x, y: row.y });
464
+ communities[row.nodeId] = row.community;
465
+ }
466
+
467
+ const graph = new Graph({ type: 'undirected', multi: false });
468
+ for (const row of live) graph.addNode(row.nodeId);
469
+ for (const id of retired) if (!graph.hasNode(id)) graph.addNode(id);
470
+ for (const edge of graphQueries.edgesWithin([...retired, ...live.map(row => row.nodeId)])) {
471
+ if (edge.srcId === edge.dstId || graph.hasEdge(edge.srcId, edge.dstId)) continue;
472
+ graph.addUndirectedEdge(edge.srcId, edge.dstId, { weight: edge.weight });
473
+ }
474
+
475
+ const solved = placeArrivals(retired, graph, positions, communities);
476
+ return retired.map(id => {
477
+ const at = solved.positions.get(id) as { x: number; y: number };
478
+ return {
479
+ nodeId: id,
480
+ community: solved.communities[id] ?? 0,
481
+ x: at.x,
482
+ y: at.y,
483
+ placed: 1,
484
+ degree: graph.degree(id)
485
+ };
486
+ });
487
+ }
488
+
489
+ /**
490
+ * Only finite rows are written — the last line of defence for the table.
491
+ *
492
+ * Nothing upstream should produce anything else, and that is exactly why this
493
+ * exists: the failure it replaces was a single NaN that made every subsequent
494
+ * pass throw on the NOT NULL constraint, permanently, with the store growing
495
+ * unplaced behind it. A row dropped here stays unplaced and is retried.
496
+ */
497
+ function sanitise(rows: GraphLayoutRow[]): GraphLayoutRow[] {
498
+ const kept = rows.filter(
499
+ row =>
500
+ Number.isFinite(row.x) &&
501
+ Number.isFinite(row.y) &&
502
+ Math.abs(row.x) <= MAX_SANE_COORDINATE &&
503
+ Math.abs(row.y) <= MAX_SANE_COORDINATE &&
504
+ Number.isFinite(row.community)
505
+ );
506
+ if (kept.length < rows.length) {
507
+ debug.warn('memory', `Memory layout: dropped ${rows.length - kept.length} unusable position(s)`);
508
+ }
509
+ return kept;
510
+ }
511
+
512
+ /**
513
+ * The median distance from a memory to its nearest neighbour.
514
+ *
515
+ * Found through a spatial hash whose cell is grown until most memories have a
516
+ * neighbour within reach, so the cost stays linear whatever the scale.
517
+ */
518
+ function medianSpacing(rows: { x: number; y: number }[]): number {
519
+ if (rows.length < 2) return 0;
520
+ let minX = Infinity;
521
+ let maxX = -Infinity;
522
+ let minY = Infinity;
523
+ let maxY = -Infinity;
524
+ for (const row of rows) {
525
+ minX = Math.min(minX, row.x);
526
+ maxX = Math.max(maxX, row.x);
527
+ minY = Math.min(minY, row.y);
528
+ maxY = Math.max(maxY, row.y);
529
+ }
530
+ // The spacing a uniform scatter would have: a starting cell, not the answer.
531
+ const cell = Math.max(1e-6, Math.sqrt(((maxX - minX) * (maxY - minY)) / rows.length) || 1);
532
+ const grid = new Map<string, { x: number; y: number }[]>();
533
+ for (const row of rows) {
534
+ const key = `${Math.floor(row.x / cell)}:${Math.floor(row.y / cell)}`;
535
+ const bucket = grid.get(key);
536
+ if (bucket) bucket.push(row);
537
+ else grid.set(key, [row]);
538
+ }
539
+
540
+ const nearest: number[] = [];
541
+ for (const row of rows) {
542
+ const cx = Math.floor(row.x / cell);
543
+ const cy = Math.floor(row.y / cell);
544
+ let best = Infinity;
545
+ // Ring by ring until something is found and no closer ring can beat it.
546
+ for (let ring = 1; ring <= 64; ring++) {
547
+ for (let gx = cx - ring; gx <= cx + ring; gx++) {
548
+ for (let gy = cy - ring; gy <= cy + ring; gy++) {
549
+ if (Math.max(Math.abs(gx - cx), Math.abs(gy - cy)) !== ring && ring > 1) continue;
550
+ for (const other of grid.get(`${gx}:${gy}`) ?? []) {
551
+ if (other === row) continue;
552
+ best = Math.min(best, Math.hypot(other.x - row.x, other.y - row.y));
553
+ }
554
+ }
555
+ }
556
+ if (best <= (ring - 1) * cell) break;
557
+ }
558
+ if (Number.isFinite(best)) nearest.push(best);
559
+ }
560
+ if (nearest.length === 0) return 0;
561
+ nearest.sort((a, b) => a - b);
562
+ return nearest[nearest.length >> 1];
563
+ }
564
+
565
+ /**
566
+ * The square the view tiles, covering every row with a margin.
567
+ *
568
+ * `current` is kept whenever everything still fits inside it, so a warm pass
569
+ * does not invalidate every client's tiles for a memory that landed in the
570
+ * middle of the map. When something lands outside, the world is recomputed with
571
+ * the margin restored — growing in steps rather than per arrival.
572
+ */
573
+ function worldFor(
574
+ rows: GraphLayoutRow[],
575
+ current: { minX: number; minY: number; size: number } | null
576
+ ): { minX: number; minY: number; size: number } {
577
+ let minX = Infinity;
578
+ let maxX = -Infinity;
579
+ let minY = Infinity;
580
+ let maxY = -Infinity;
581
+ for (const row of rows) {
582
+ minX = Math.min(minX, row.x);
583
+ maxX = Math.max(maxX, row.x);
584
+ minY = Math.min(minY, row.y);
585
+ maxY = Math.max(maxY, row.y);
586
+ }
587
+ if (!Number.isFinite(minX)) return current ?? { minX: -500, minY: -500, size: 1000 };
588
+
589
+ if (
590
+ current &&
591
+ minX >= current.minX &&
592
+ minY >= current.minY &&
593
+ maxX < current.minX + current.size &&
594
+ maxY < current.minY + current.size
595
+ ) {
596
+ return current;
597
+ }
598
+
599
+ const side = Math.max(maxX - minX, maxY - minY, 200);
600
+ const size = side * (1 + 2 * WORLD_MARGIN);
601
+ return {
602
+ minX: (minX + maxX) / 2 - size / 2,
603
+ minY: (minY + maxY) / 2 - size / 2,
604
+ size
605
+ };
606
+ }
607
+
608
+ /**
609
+ * Give the new communities the numbers the old ones had, wherever they overlap.
610
+ *
611
+ * Colour is derived from the community number, and Louvain's numbering is
612
+ * arbitrary: without this every cold pass would recolour the whole map even
613
+ * when the lobes were the same lobes. Largest communities choose first, each
614
+ * taking the old number most of its members carried; anything with no
615
+ * predecessor gets a number nothing has used.
616
+ */
617
+ function keepCommunityNumbers(
618
+ ids: string[],
619
+ communities: Record<string, number>,
620
+ previous: Map<string, GraphLayoutRow>
621
+ ): Record<string, number> {
622
+ if (previous.size === 0) return communities;
623
+
624
+ const members = new Map<number, string[]>();
625
+ for (const id of ids) {
626
+ const community = communities[id];
627
+ const list = members.get(community);
628
+ if (list) list.push(id);
629
+ else members.set(community, [id]);
630
+ }
631
+
632
+ let next = 0;
633
+ for (const row of previous.values()) next = Math.max(next, row.community + 1);
634
+ for (const community of members.keys()) next = Math.max(next, community + 1);
635
+
636
+ const taken = new Set<number>();
637
+ const renumber = new Map<number, number>();
638
+ const ordered = [...members.entries()].sort((a, b) => b[1].length - a[1].length || a[0] - b[0]);
639
+
640
+ for (const [community, list] of ordered) {
641
+ const votes = new Map<number, number>();
642
+ for (const id of list) {
643
+ const old = previous.get(id);
644
+ if (old) votes.set(old.community, (votes.get(old.community) ?? 0) + 1);
645
+ }
646
+ let best: number | null = null;
647
+ let bestVotes = 0;
648
+ for (const [old, count] of [...votes.entries()].sort((a, b) => a[0] - b[0])) {
649
+ if (taken.has(old) || count <= bestVotes) continue;
650
+ best = old;
651
+ bestVotes = count;
652
+ }
653
+ const assigned = best ?? next++;
654
+ taken.add(assigned);
655
+ renumber.set(community, assigned);
656
+ }
657
+
658
+ const result: Record<string, number> = {};
659
+ for (const id of ids) result[id] = renumber.get(communities[id]) ?? communities[id];
660
+ return result;
661
+ }
662
+
663
+ /**
664
+ * Turn a fresh arrangement to face the way the previous one did.
665
+ *
666
+ * Orthogonal Procrustes over the memories both arrangements placed: the
667
+ * rotation — or rotation with a mirror, whichever fits better — and translation
668
+ * that bring the new positions closest to the old. RIGID: no scaling, so the
669
+ * map's size is always the simulation's own and can never ratchet the way the
670
+ * old warm passes did.
671
+ *
672
+ * @internal Exported for tests.
673
+ */
674
+ export function alignTo(rows: GraphLayoutRow[], previous: Map<string, GraphLayoutRow>): void {
675
+ const pairs: { nx: number; ny: number; ox: number; oy: number }[] = [];
676
+ for (const row of rows) {
677
+ const old = previous.get(row.nodeId);
678
+ if (old) pairs.push({ nx: row.x, ny: row.y, ox: old.x, oy: old.y });
679
+ }
680
+ if (pairs.length < 3) return;
681
+
682
+ let ncx = 0;
683
+ let ncy = 0;
684
+ let ocx = 0;
685
+ let ocy = 0;
686
+ for (const pair of pairs) {
687
+ ncx += pair.nx;
688
+ ncy += pair.ny;
689
+ ocx += pair.ox;
690
+ ocy += pair.oy;
691
+ }
692
+ ncx /= pairs.length;
693
+ ncy /= pairs.length;
694
+ ocx /= pairs.length;
695
+ ocy /= pairs.length;
696
+
697
+ let sxx = 0;
698
+ let sxy = 0;
699
+ let syx = 0;
700
+ let syy = 0;
701
+ for (const pair of pairs) {
702
+ const ax = pair.nx - ncx;
703
+ const ay = pair.ny - ncy;
704
+ const bx = pair.ox - ocx;
705
+ const by = pair.oy - ocy;
706
+ sxx += ax * bx;
707
+ sxy += ax * by;
708
+ syx += ay * bx;
709
+ syy += ay * by;
710
+ }
711
+
712
+ // The best proper rotation maximises cos θ (Sxx + Syy) + sin θ (Sxy − Syx);
713
+ // mirroring the new arrangement in y first flips the signs of Syx and Syy.
714
+ const rotation = Math.hypot(sxx + syy, sxy - syx);
715
+ const mirrored = Math.hypot(sxx - syy, sxy + syx);
716
+ const mirror = mirrored > rotation;
717
+ const angle = mirror ? Math.atan2(sxy + syx, sxx - syy) : Math.atan2(sxy - syx, sxx + syy);
718
+ const cos = Math.cos(angle);
719
+ const sin = Math.sin(angle);
720
+
721
+ for (const row of rows) {
722
+ const ax = row.x - ncx;
723
+ const ay = mirror ? -(row.y - ncy) : row.y - ncy;
724
+ row.x = ocx + cos * ax - sin * ay;
725
+ row.y = ocy + sin * ax + cos * ay;
726
+ }
727
+ }
728
+
729
+ /**
730
+ * Place memories among an arrangement that does not move.
731
+ *
732
+ * Each is dropped at the centroid of whatever it connects to that already has a
733
+ * place — so a chain of arrivals resolves outward from whichever end touches the
734
+ * map — and one connected to nothing placed is dropped into the field the map
735
+ * already covers. Then a short relaxation moves ONLY the arrivals: pulled to an
736
+ * edge's natural length from their neighbours, pushed off anything closer than
737
+ * that. The natural length is measured from the arrangement itself, so the
738
+ * solver works at whatever scale the map is drawn at.
739
+ *
740
+ * Cost is the arrivals times their neighbourhood. Repulsion reads a spatial
741
+ * hash, never the whole store, which is what makes a warm pass milliseconds
742
+ * where re-running the simulation was seconds.
743
+ *
744
+ * Deterministic: ids are visited in sorted order and every scatter comes from
745
+ * `jitterOf`.
746
+ */
747
+ function placeArrivals(
748
+ arrivals: string[],
749
+ graph: Graph,
750
+ fixed: Map<string, { x: number; y: number }>,
751
+ knownCommunities: Record<string, number>
752
+ ): { positions: Map<string, { x: number; y: number }>; communities: Record<string, number> } {
753
+ const positions = new Map(fixed);
754
+ const communities: Record<string, number> = { ...knownCommunities };
755
+ if (arrivals.length === 0) return { positions, communities };
756
+
757
+ const neighboursOf = (id: string): string[] => (graph.hasNode(id) ? graph.neighbors(id) : []);
758
+ // Two scales, because a declumped map has two. Edges are long — they span a
759
+ // lobe — but neighbours sit only `spacing` apart, and a solver that kept an
760
+ // edge's length of clear space around each arrival found no room left inside
761
+ // a lobe and pushed newcomers out of it, sometimes nearer a different subject
762
+ // than their own. So arrivals are pulled to within a few spacings of what
763
+ // they connect to and keep only a neighbour's distance clear.
764
+ const spacing = medianSpacing([...fixed.values()]);
765
+ const length = spacing > 0 ? Math.min(naturalLength(graph, fixed), spacing * 1.5) : naturalLength(graph, fixed);
766
+ const personal = spacing > 0 ? spacing * 0.6 : length * 0.75;
767
+
768
+ let nextCommunity = 0;
769
+ for (const value of Object.values(communities)) nextCommunity = Math.max(nextCommunity, value + 1);
770
+
771
+ // The field: where the map already is, so a lone memory lands inside it rather
772
+ // than deciding how far it reaches.
773
+ let centreX = 0;
774
+ let centreY = 0;
775
+ for (const point of fixed.values()) {
776
+ centreX += point.x;
777
+ centreY += point.y;
778
+ }
779
+ if (fixed.size > 0) {
780
+ centreX /= fixed.size;
781
+ centreY /= fixed.size;
782
+ }
783
+ let reach = 0;
784
+ for (const point of fixed.values()) reach = Math.max(reach, Math.hypot(point.x - centreX, point.y - centreY));
785
+ if (reach === 0) reach = length * Math.sqrt(arrivals.length + 1) * 2;
786
+
787
+ const pending = [...arrivals].sort();
788
+ const waiting = new Set(pending);
789
+
790
+ while (waiting.size > 0) {
791
+ // Everything that touches the map, repeatedly, until nothing new does.
792
+ let progressed = true;
793
+ while (progressed) {
794
+ progressed = false;
795
+ for (const id of pending) {
796
+ if (!waiting.has(id)) continue;
797
+ let sumX = 0;
798
+ let sumY = 0;
799
+ let count = 0;
800
+ const votes = new Map<number, number>();
801
+ for (const neighbour of neighboursOf(id)) {
802
+ const at = positions.get(neighbour);
803
+ if (!at) continue;
804
+ sumX += at.x;
805
+ sumY += at.y;
806
+ count++;
807
+ const community = communities[neighbour];
808
+ if (community !== undefined) votes.set(community, (votes.get(community) ?? 0) + 1);
809
+ }
810
+ if (count === 0) continue;
811
+
812
+ const jitter = jitterOf(id);
813
+ positions.set(id, { x: sumX / count + jitter.x * length * 0.6, y: sumY / count + jitter.y * length * 0.6 });
814
+ if (communities[id] === undefined) {
815
+ let best = -1;
816
+ let bestVotes = 0;
817
+ for (const [community, votesFor] of [...votes.entries()].sort((a, b) => a[0] - b[0])) {
818
+ if (votesFor > bestVotes) {
819
+ best = community;
820
+ bestVotes = votesFor;
821
+ }
822
+ }
823
+ communities[id] = best >= 0 ? best : nextCommunity++;
824
+ }
825
+ waiting.delete(id);
826
+ progressed = true;
827
+ }
828
+ }
829
+
830
+ // One that connects to nothing placed seeds its own little group in the
831
+ // field; the loop above then grows the rest of that group around it.
832
+ const seed = pending.find(id => waiting.has(id));
833
+ if (seed === undefined) break;
834
+ const draw = jitterOf(seed);
835
+ const radius = reach * Math.sqrt((draw.x + 1) / 2);
836
+ positions.set(seed, {
837
+ x: centreX + Math.cos(draw.angle) * radius,
838
+ y: centreY + Math.sin(draw.angle) * radius
839
+ });
840
+ communities[seed] ??= nextCommunity++;
841
+ waiting.delete(seed);
842
+ }
843
+
844
+ relaxArrivals(pending, graph, fixed, positions, length, personal);
845
+ return { positions, communities };
846
+ }
847
+
848
+ /**
849
+ * The typical edge length of an arrangement — the scale the solver works at.
850
+ *
851
+ * The median over edges both of whose ends are placed, so a handful of long
852
+ * bridges between lobes does not inflate it. Falls back to the spacing a
853
+ * uniform scatter of the placed nodes would have, and to a constant when there
854
+ * is nothing placed at all.
855
+ */
856
+ function naturalLength(graph: Graph, fixed: Map<string, { x: number; y: number }>): number {
857
+ const lengths: number[] = [];
858
+ graph.forEachEdge((_edge, _attributes, source, target) => {
859
+ if (lengths.length >= 20_000) return;
860
+ const a = fixed.get(source);
861
+ const b = fixed.get(target);
862
+ if (!a || !b) return;
863
+ const distance = Math.hypot(a.x - b.x, a.y - b.y);
864
+ if (distance > 0 && Number.isFinite(distance)) lengths.push(distance);
865
+ });
866
+ if (lengths.length >= 8) {
867
+ lengths.sort((a, b) => a - b);
868
+ return lengths[lengths.length >> 1];
869
+ }
870
+
871
+ if (fixed.size >= 2) {
872
+ let minX = Infinity;
873
+ let maxX = -Infinity;
874
+ let minY = Infinity;
875
+ let maxY = -Infinity;
876
+ for (const point of fixed.values()) {
877
+ minX = Math.min(minX, point.x);
878
+ maxX = Math.max(maxX, point.x);
879
+ minY = Math.min(minY, point.y);
880
+ maxY = Math.max(maxY, point.y);
881
+ }
882
+ const area = Math.max(1, (maxX - minX) * (maxY - minY));
883
+ return Math.max(10, Math.sqrt(area / fixed.size));
884
+ }
885
+ return 40;
886
+ }
887
+
888
+ /**
889
+ * Settle the arrivals into the gaps, moving nothing else.
890
+ *
891
+ * Spring toward each neighbour to `length`, push off anything nearer than
892
+ * `personal`, and never move further than half of `length` in one step — the
893
+ * bound is what makes it impossible for this to diverge the way an unbounded
894
+ * force step can.
895
+ */
896
+ function relaxArrivals(
897
+ arrivals: string[],
898
+ graph: Graph,
899
+ fixed: Map<string, { x: number; y: number }>,
900
+ positions: Map<string, { x: number; y: number }>,
901
+ length: number,
902
+ personal: number
903
+ ): void {
904
+ const ITERATIONS = 40;
905
+ const cell = Math.max(1e-6, personal);
906
+ const key = (x: number, y: number): string => `${Math.floor(x / cell)}:${Math.floor(y / cell)}`;
907
+
908
+ const fixedGrid = new Map<string, { x: number; y: number }[]>();
909
+ for (const point of fixed.values()) {
910
+ const k = key(point.x, point.y);
911
+ const list = fixedGrid.get(k);
912
+ if (list) list.push(point);
913
+ else fixedGrid.set(k, [point]);
914
+ }
915
+
916
+ const moving = arrivals.filter(id => positions.has(id) && !fixed.has(id));
917
+ if (moving.length === 0) return;
918
+
919
+ for (let iteration = 0; iteration < ITERATIONS; iteration++) {
920
+ const cooling = 1 - iteration / ITERATIONS;
921
+
922
+ const arrivalGrid = new Map<string, string[]>();
923
+ for (const id of moving) {
924
+ const at = positions.get(id) as { x: number; y: number };
925
+ const k = key(at.x, at.y);
926
+ const list = arrivalGrid.get(k);
927
+ if (list) list.push(id);
928
+ else arrivalGrid.set(k, [id]);
929
+ }
930
+
931
+ for (const id of moving) {
932
+ const at = positions.get(id) as { x: number; y: number };
933
+ let dx = 0;
934
+ let dy = 0;
935
+
936
+ for (const neighbour of graph.hasNode(id) ? graph.neighbors(id) : []) {
937
+ const other = positions.get(neighbour);
938
+ if (!other) continue;
939
+ const ox = other.x - at.x;
940
+ const oy = other.y - at.y;
941
+ const distance = Math.hypot(ox, oy);
942
+ if (distance < 1e-9) continue;
943
+ const pull = ((distance - length) / distance) * 0.3;
944
+ dx += ox * pull;
945
+ dy += oy * pull;
946
+ }
947
+
948
+ const cx = Math.floor(at.x / cell);
949
+ const cy = Math.floor(at.y / cell);
950
+ for (let gx = cx - 1; gx <= cx + 1; gx++) {
951
+ for (let gy = cy - 1; gy <= cy + 1; gy++) {
952
+ const k = `${gx}:${gy}`;
953
+ const push = (other: { x: number; y: number }, salt: string): void => {
954
+ let ox = at.x - other.x;
955
+ let oy = at.y - other.y;
956
+ let distance = Math.hypot(ox, oy);
957
+ if (distance >= personal) return;
958
+ if (distance < 1e-9) {
959
+ const angle = jitterOf(id + salt).angle;
960
+ ox = Math.cos(angle);
961
+ oy = Math.sin(angle);
962
+ distance = 1;
963
+ }
964
+ const strength = ((personal - distance) / distance) * 0.5;
965
+ dx += ox * strength;
966
+ dy += oy * strength;
967
+ };
968
+ for (const point of fixedGrid.get(k) ?? []) push(point, `${point.x},${point.y}`);
969
+ for (const other of arrivalGrid.get(k) ?? []) {
970
+ if (other !== id) push(positions.get(other) as { x: number; y: number }, other);
971
+ }
972
+ }
973
+ }
974
+
975
+ const step = Math.hypot(dx, dy);
976
+ const limit = length * 0.5 * cooling;
977
+ if (!Number.isFinite(step) || step === 0) continue;
978
+ const scale = step > limit ? limit / step : 1;
979
+ positions.set(id, { x: at.x + dx * scale, y: at.y + dy * scale });
980
+ }
981
+ }
982
+ }
983
+
265
984
  /**
266
985
  * The graph the simulation runs on: stored edges plus the derived ones.
267
986
  *
268
987
  * Both are included because the derived edges are most of the structure the
269
988
  * episodic half has (see `graphQueries.derivedEdges`) — laying out without them
270
- * scatters memories that plainly belong together.
989
+ * scatters memories that plainly belong together. The derived set is returned as
990
+ * well, because the view draws exactly the edges the map was laid out on.
271
991
  */
272
- function buildLayoutGraph(ids: string[]): Graph {
992
+ function buildLayoutGraph(ids: string[]): {
993
+ graph: Graph;
994
+ derived: { srcId: string; dstId: string; weight: number }[];
995
+ } {
273
996
  const graph = new Graph({ type: 'undirected', multi: false });
274
997
  for (const id of ids) graph.addNode(id, { x: 0, y: 0, size: 1 });
275
998
 
@@ -281,14 +1004,15 @@ function buildLayoutGraph(ids: string[]): Graph {
281
1004
  };
282
1005
 
283
1006
  for (const edge of graphQueries.edgesWithin(ids)) link(edge.srcId, edge.dstId, edge.weight);
284
- for (const edge of graphQueries.derivedEdges(ids)) link(edge.srcId, edge.dstId, edge.weight);
1007
+ const derived = graphQueries.derivedEdges(ids);
1008
+ for (const edge of derived) link(edge.srcId, edge.dstId, edge.weight);
285
1009
 
286
1010
  // ForceAtlas2 reads mass from `size`; a hub that weighs more holds its
287
1011
  // neighbours' fan open instead of being dragged into the middle of it.
288
1012
  graph.forEachNode(id => {
289
1013
  graph.setNodeAttribute(id, 'size', 1 + Math.sqrt(graph.degree(id)));
290
1014
  });
291
- return graph;
1015
+ return { graph, derived };
292
1016
  }
293
1017
 
294
1018
  /** The induced subgraph over `ids` — the part the simulation will actually move. */
@@ -345,12 +1069,7 @@ function restrictTo(graph: Graph, ids: string[]): Graph {
345
1069
  * (Σnᵢ)². On the store measured above that is 1.0M against 3.2M — the shape is
346
1070
  * better AND the pass is a third of the work.
347
1071
  */
348
- async function arrange(
349
- simulated: Graph,
350
- communities: Record<string, number>,
351
- existing: Map<string, GraphLayoutRow>,
352
- cold: boolean
353
- ): Promise<GraphLayoutRow[]> {
1072
+ async function arrange(simulated: Graph, communities: Record<string, number>): Promise<GraphLayoutRow[]> {
354
1073
  const components = componentsOf(simulated);
355
1074
  const singletons: string[] = [];
356
1075
  const placed: PlacedComponent[] = [];
@@ -362,15 +1081,12 @@ async function arrange(
362
1081
  }
363
1082
 
364
1083
  const part = restrictTo(simulated, member);
365
- // A component that was already on the map keeps its place. Only its interior
366
- // is re-settled, so a memory arriving in one lobe cannot rearrange the
367
- // others — the map somebody has learned survives the pass.
368
- const anchor = existingCentroid(member, existing);
369
- seedComponent(part, communities, existing, anchor);
370
- await settle(part, cold || !anchor ? iterationsFor(part.order) : warmIterationsFor(part.order));
1084
+ seedComponent(part, communities);
1085
+ await settle(part, iterationsFor(part.order));
1086
+ declump(part, communities);
371
1087
  const lobes = spreadCommunities(part, communities);
372
1088
 
373
- placed.push(measure(part, anchor, lobes));
1089
+ placed.push(measure(part, lobes));
374
1090
  }
375
1091
 
376
1092
  packComponents(placed);
@@ -383,7 +1099,9 @@ async function arrange(
383
1099
  community: communities[component.ids[i]] ?? 0,
384
1100
  x: component.xs[i] + component.offsetX,
385
1101
  y: component.ys[i] + component.offsetY,
386
- placed: 1
1102
+ placed: 1,
1103
+ // Filled in by the caller, which holds the whole graph.
1104
+ degree: 0
387
1105
  });
388
1106
  }
389
1107
  }
@@ -398,10 +1116,106 @@ async function arrange(
398
1116
  }
399
1117
  }
400
1118
 
401
- for (const row of placeLoneNodes(singletons, field, communities, existing)) rows.push(row);
1119
+ for (const row of placeLoneNodes(singletons, field, communities)) rows.push(row);
402
1120
  return rows;
403
1121
  }
404
1122
 
1123
+ /**
1124
+ * Give every memory room of its own, at the scale the lobe was drawn at.
1125
+ *
1126
+ * ForceAtlas2 with mass-distributed attraction pulls a lobe's members onto its
1127
+ * hubs, so a settled lobe is a dense core with a thin rim. Measured on a real
1128
+ * store, the median distance to the nearest neighbour was 46 units against a
1129
+ * median edge of 416 — at the zoom that shows the whole map that is under two
1130
+ * pixels, so the cores drew as solid blobs and nothing inside them could be
1131
+ * told apart, hovered or clicked.
1132
+ *
1133
+ * So members closer than `MIN_SPACING` of the lobe's own typical edge are pushed
1134
+ * apart, pairwise, until none are — which grows the dense cores and leaves the
1135
+ * already-spacious rims where they were. Measured against the component's
1136
+ * INTRA-lobe edges, so the spacing follows the scale this layout happened to
1137
+ * settle at rather than a constant that is right for one store.
1138
+ *
1139
+ * Neighbours are found through a spatial hash, so a pass is linear in the
1140
+ * members; deterministic, because every tie is broken by id.
1141
+ */
1142
+ function declump(part: Graph, communities: Record<string, number>): void {
1143
+ /** Clear space between two members, as a fraction of the lobe's median edge. */
1144
+ const MIN_SPACING = 0.8;
1145
+ /**
1146
+ * A ceiling, not a count: the loop stops the moment nothing overlaps. Dense
1147
+ * cores need many — each pass only resolves the overlaps it sees, and pushing
1148
+ * one pair apart presses both into their other neighbours.
1149
+ */
1150
+ const PASSES = 400;
1151
+
1152
+ const lengths: number[] = [];
1153
+ part.forEachUndirectedEdge((_edge, _attributes, source, target) => {
1154
+ if ((communities[source] ?? 0) !== (communities[target] ?? 0)) return;
1155
+ const a = part.getNodeAttributes(source) as { x: number; y: number };
1156
+ const b = part.getNodeAttributes(target) as { x: number; y: number };
1157
+ const length = Math.hypot(a.x - b.x, a.y - b.y);
1158
+ if (length > 0 && Number.isFinite(length)) lengths.push(length);
1159
+ });
1160
+ if (lengths.length === 0) return;
1161
+ lengths.sort((a, b) => a - b);
1162
+ const spacing = lengths[lengths.length >> 1] * MIN_SPACING;
1163
+ if (!(spacing > 0)) return;
1164
+
1165
+ const ids = part.nodes().sort();
1166
+ const xs = new Float64Array(ids.length);
1167
+ const ys = new Float64Array(ids.length);
1168
+ for (let i = 0; i < ids.length; i++) {
1169
+ xs[i] = part.getNodeAttribute(ids[i], 'x') as number;
1170
+ ys[i] = part.getNodeAttribute(ids[i], 'y') as number;
1171
+ }
1172
+
1173
+ for (let pass = 0; pass < PASSES; pass++) {
1174
+ const grid = new Map<string, number[]>();
1175
+ for (let i = 0; i < ids.length; i++) {
1176
+ const key = `${Math.floor(xs[i] / spacing)}:${Math.floor(ys[i] / spacing)}`;
1177
+ const bucket = grid.get(key);
1178
+ if (bucket) bucket.push(i);
1179
+ else grid.set(key, [i]);
1180
+ }
1181
+
1182
+ let moved = false;
1183
+ for (let i = 0; i < ids.length; i++) {
1184
+ const cx = Math.floor(xs[i] / spacing);
1185
+ const cy = Math.floor(ys[i] / spacing);
1186
+ for (let gx = cx - 1; gx <= cx + 1; gx++) {
1187
+ for (let gy = cy - 1; gy <= cy + 1; gy++) {
1188
+ for (const j of grid.get(`${gx}:${gy}`) ?? []) {
1189
+ if (j <= i) continue;
1190
+ let dx = xs[j] - xs[i];
1191
+ let dy = ys[j] - ys[i];
1192
+ let distance = Math.hypot(dx, dy);
1193
+ if (distance >= spacing) continue;
1194
+ if (distance < 1e-9) {
1195
+ const angle = jitterOf(ids[i] + ids[j]).angle;
1196
+ dx = Math.cos(angle);
1197
+ dy = Math.sin(angle);
1198
+ distance = 1;
1199
+ }
1200
+ const push = (spacing - distance) / distance / 2;
1201
+ xs[i] -= dx * push;
1202
+ ys[i] -= dy * push;
1203
+ xs[j] += dx * push;
1204
+ ys[j] += dy * push;
1205
+ moved = true;
1206
+ }
1207
+ }
1208
+ }
1209
+ }
1210
+ if (!moved) break;
1211
+ }
1212
+
1213
+ for (let i = 0; i < ids.length; i++) {
1214
+ part.setNodeAttribute(ids[i], 'x', xs[i]);
1215
+ part.setNodeAttribute(ids[i], 'y', ys[i]);
1216
+ }
1217
+ }
1218
+
405
1219
  /**
406
1220
  * Push the lobes apart from each other, leaving each one's interior alone.
407
1221
  *
@@ -444,8 +1258,10 @@ function spreadCommunities(part: Graph, communities: Record<string, number>): Di
444
1258
  * uses 0.15 between whole components; lobes want far more, because unlike
445
1259
  * components they are joined by edges that read as bridges.
446
1260
  */
447
- const GAP = 0.9;
1261
+ const GAP = 0.35;
448
1262
  const PASSES = 240;
1263
+ /** Share of the distance to the centre a lobe moves per compaction pass. */
1264
+ const COMPACT_PULL = 0.06;
449
1265
  /**
450
1266
  * The percentile of member distances taken as a lobe's radius.
451
1267
  *
@@ -493,11 +1309,12 @@ function spreadCommunities(part: Graph, communities: Record<string, number>): Di
493
1309
  // One lobe has nothing to be spread away from, but it is still the field.
494
1310
  if (lobes.length < 2) return lobes.map(lobe => ({ x: lobe.x, y: lobe.y, radius: lobe.radius }));
495
1311
 
496
- for (let pass = 0; pass < PASSES; pass++) {
1312
+ const separate = (limit: number): void => {
1313
+ for (let pass = 0; pass < limit; pass++) {
497
1314
  // Over-relaxed early and settling toward an exact correction, for the same
498
1315
  // reason `packComponents` does it: separating one pair nudges both into
499
1316
  // their other neighbours.
500
- const relax = 1.4 - 0.4 * (pass / PASSES);
1317
+ const relax = 1.4 - 0.4 * (pass / limit);
501
1318
  let collided = false;
502
1319
 
503
1320
  for (let i = 0; i < lobes.length; i++) {
@@ -531,6 +1348,38 @@ function spreadCommunities(part: Graph, communities: Record<string, number>): Di
531
1348
 
532
1349
  if (!collided) break;
533
1350
  }
1351
+ };
1352
+
1353
+ separate(PASSES);
1354
+
1355
+ // Then close the gaps. Separation only ever pushes apart, so lobes stayed as
1356
+ // far apart as the simulation left them — and once `declump` had grown their
1357
+ // interiors, that was most of the map: measured, the lobes covered a sixth of
1358
+ // the world, the rest was empty, and every edge between two lobes crossed it
1359
+ // as a long line. Drawing the lobes toward their common centre while the
1360
+ // separation keeps them from overlapping packs them like circles: the same
1361
+ // neighbours, a fraction of the empty space, and shorter bridges.
1362
+ const COMPACT_PASSES = 160;
1363
+ for (let pass = 0; pass < COMPACT_PASSES; pass++) {
1364
+ let weight = 0;
1365
+ let centreX = 0;
1366
+ let centreY = 0;
1367
+ for (const lobe of lobes) {
1368
+ const area = lobe.radius * lobe.radius;
1369
+ centreX += lobe.x * area;
1370
+ centreY += lobe.y * area;
1371
+ weight += area;
1372
+ }
1373
+ centreX /= weight;
1374
+ centreY /= weight;
1375
+ for (const lobe of lobes) {
1376
+ lobe.x += (centreX - lobe.x) * COMPACT_PULL;
1377
+ lobe.y += (centreY - lobe.y) * COMPACT_PULL;
1378
+ }
1379
+ separate(8);
1380
+ }
1381
+ // Whatever the last pull left touching is pulled apart for good.
1382
+ separate(PASSES);
534
1383
 
535
1384
  for (const lobe of lobes) {
536
1385
  const shiftX = lobe.x - lobe.originX;
@@ -561,7 +1410,7 @@ interface PlacedComponent {
561
1410
  radius: number;
562
1411
  offsetX: number;
563
1412
  offsetY: number;
564
- /** Where it already sat, when it was on the map before this pass. */
1413
+ /** Held still by the packing — the largest component, which holds the origin. */
565
1414
  anchored: boolean;
566
1415
  /** Its lobes, in the same local space as `xs`/`ys`. See `placeLoneNodes`. */
567
1416
  lobes: Disc[];
@@ -601,24 +1450,6 @@ function componentsOf(graph: Graph): string[][] {
601
1450
  return components;
602
1451
  }
603
1452
 
604
- /** The centroid this component occupied before the pass, if it was on the map. */
605
- function existingCentroid(
606
- member: string[],
607
- existing: Map<string, GraphLayoutRow>
608
- ): { x: number; y: number } | null {
609
- let sumX = 0;
610
- let sumY = 0;
611
- let count = 0;
612
- for (const id of member) {
613
- const previous = existing.get(id);
614
- if (!previous || previous.placed !== 1) continue;
615
- sumX += previous.x;
616
- sumY += previous.y;
617
- count++;
618
- }
619
- return count > 0 ? { x: sumX / count, y: sumY / count } : null;
620
- }
621
-
622
1453
  /**
623
1454
  * Where a component's nodes start, in LOCAL space.
624
1455
  *
@@ -627,49 +1458,14 @@ function existingCentroid(
627
1458
  * passes every component would have crept into one pile — the disc again, arrived
628
1459
  * at slowly instead of immediately.
629
1460
  *
630
- * Nodes that already had a position keep it, translated into local space, which
631
- * is what makes successive passes refinements of one arrangement rather than a
632
- * new arrangement each time.
1461
+ * Every node starts inside its community's region, scattered by its own id, so
1462
+ * the same store always starts — and therefore settles — the same way.
633
1463
  */
634
- function seedComponent(
635
- part: Graph,
636
- communities: Record<string, number>,
637
- existing: Map<string, GraphLayoutRow>,
638
- anchor: { x: number; y: number } | null
639
- ): void {
1464
+ function seedComponent(part: Graph, communities: Record<string, number>): void {
640
1465
  const meta = communityMetaSeed(part, communities);
641
- const placedIds = new Set<string>();
642
1466
 
643
1467
  part.forEachNode(id => {
644
- const previous = existing.get(id);
645
- if (!previous || previous.placed !== 1 || !anchor) return;
646
- part.setNodeAttribute(id, 'x', previous.x - anchor.x);
647
- part.setNodeAttribute(id, 'y', previous.y - anchor.y);
648
- placedIds.add(id);
649
- });
650
-
651
- part.forEachNode(id => {
652
- if (placedIds.has(id)) return;
653
-
654
- // Near whatever it connects to that is already placed — an arriving memory
655
- // belongs next to its subject, not wherever its community happens to sit.
656
- let sumX = 0;
657
- let sumY = 0;
658
- let count = 0;
659
- part.forEachNeighbor(id, neighbour => {
660
- if (!placedIds.has(neighbour)) return;
661
- sumX += part.getNodeAttribute(neighbour, 'x') as number;
662
- sumY += part.getNodeAttribute(neighbour, 'y') as number;
663
- count++;
664
- });
665
-
666
1468
  const jitter = jitterOf(id);
667
- if (count > 0) {
668
- part.setNodeAttribute(id, 'x', sumX / count + jitter.x * 12);
669
- part.setNodeAttribute(id, 'y', sumY / count + jitter.y * 12);
670
- return;
671
- }
672
-
673
1469
  const region = meta.get(communities[id] ?? 0);
674
1470
  part.setNodeAttribute(id, 'x', (region?.x ?? 0) + jitter.x * (region?.radius ?? 120));
675
1471
  part.setNodeAttribute(id, 'y', (region?.y ?? 0) + jitter.y * (region?.radius ?? 120));
@@ -761,7 +1557,7 @@ function communityMetaSeed(
761
1557
  }
762
1558
 
763
1559
  /** Centre a settled component on its own centroid and measure what it needs. */
764
- function measure(part: Graph, anchor: { x: number; y: number } | null, lobes: Disc[]): PlacedComponent {
1560
+ function measure(part: Graph, lobes: Disc[]): PlacedComponent {
765
1561
  const ids = part.nodes();
766
1562
  const xs = new Float64Array(ids.length);
767
1563
  const ys = new Float64Array(ids.length);
@@ -792,16 +1588,15 @@ function measure(part: Graph, anchor: { x: number; y: number } | null, lobes: Di
792
1588
  // actually are once the component is given a place.
793
1589
  lobes: lobes.map(lobe => ({ x: lobe.x - centreX, y: lobe.y - centreY, radius: lobe.radius })),
794
1590
  radius: Math.max(radius, 20),
795
- // An anchored component keeps its old centroid; the drift the settle
796
- // introduced is absorbed by re-centring rather than accumulating.
797
- offsetX: anchor ? anchor.x + centreX : 0,
798
- offsetY: anchor ? anchor.y + centreY : 0,
799
- anchored: anchor !== null
1591
+ // Given a place by `packComponents`.
1592
+ offsetX: 0,
1593
+ offsetY: 0,
1594
+ anchored: false
800
1595
  };
801
1596
  }
802
1597
 
803
1598
  /**
804
- * Give every unanchored component a place, and separate any that overlap.
1599
+ * Give every component a place, and separate any that overlap.
805
1600
  *
806
1601
  * A store this feature has been running in for any length of time is ONE mass
807
1602
  * and a handful of stragglers, so the placement is built around that rather than
@@ -810,7 +1605,8 @@ function measure(part: Graph, anchor: { x: number; y: number } | null, lobes: Di
810
1605
  * whatever still collides. The silhouette is then decided by how big the mass is
811
1606
  * and how many stragglers there are, both of which are properties of the data.
812
1607
  *
813
- * Anchored components do not move: they are where the user last saw them.
1608
+ * The largest component is held still once it is given the origin; everything
1609
+ * else moves around it.
814
1610
  */
815
1611
  function packComponents(placed: PlacedComponent[]): void {
816
1612
  if (placed.length === 0) return;
@@ -931,38 +1727,12 @@ function packComponents(placed: PlacedComponent[]): void {
931
1727
  function placeLoneNodes(
932
1728
  singletons: string[],
933
1729
  field: Disc[],
934
- communities: Record<string, number>,
935
- existing: Map<string, GraphLayoutRow>
1730
+ communities: Record<string, number>
936
1731
  ): GraphLayoutRow[] {
937
1732
  if (singletons.length === 0) return [];
938
1733
 
939
1734
  const rows: GraphLayoutRow[] = [];
940
-
941
- /**
942
- * One that was already on the map stays exactly where it was.
943
- *
944
- * Anchoring these matters more than anchoring components, and measurement is
945
- * what showed it: the old free-cell grid was derived from where the components
946
- * ended up, so a single memory arriving anywhere reassigned EVERY lone node. A
947
- * warm pass moved a hundred of them clear across the map — the one thing a
948
- * background pass must never do to a view somebody is reading.
949
- */
950
- const ordered: string[] = [];
951
- for (const id of [...singletons].sort()) {
952
- const previous = existing.get(id);
953
- if (previous && previous.placed === 1) {
954
- rows.push({
955
- nodeId: id,
956
- community: communities[id] ?? 0,
957
- x: previous.x,
958
- y: previous.y,
959
- placed: 1
960
- });
961
- continue;
962
- }
963
- ordered.push(id);
964
- }
965
- if (ordered.length === 0) return rows;
1735
+ const ordered = [...singletons].sort();
966
1736
 
967
1737
  // Nothing else on the map — a field of their own, which is the only case where
968
1738
  // they set the scale, because there is nothing else to set it.
@@ -976,7 +1746,8 @@ function placeLoneNodes(
976
1746
  community: communities[id] ?? 0,
977
1747
  x: Math.cos(draw.angle) * radius,
978
1748
  y: Math.sin(draw.angle) * radius,
979
- placed: 1
1749
+ placed: 1,
1750
+ degree: 0
980
1751
  });
981
1752
  }
982
1753
  return rows;
@@ -1030,7 +1801,7 @@ function placeLoneNodes(
1030
1801
  y = hit.y + (dy / distance) * target;
1031
1802
  }
1032
1803
 
1033
- rows.push({ nodeId: id, community: communities[id] ?? 0, x, y, placed: 1 });
1804
+ rows.push({ nodeId: id, community: communities[id] ?? 0, x, y, placed: 1, degree: 0 });
1034
1805
  }
1035
1806
 
1036
1807
  return rows;
@@ -1080,13 +1851,6 @@ function iterationsFor(order: number): number {
1080
1851
  return 600;
1081
1852
  }
1082
1853
 
1083
- /** A warm pass only has to absorb what arrived since the last one. */
1084
- function warmIterationsFor(order: number): number {
1085
- if (order > 3_000) return 40;
1086
- if (order > 1_500) return 60;
1087
- return 90;
1088
- }
1089
-
1090
1854
  /**
1091
1855
  * Run the simulation, yielding between chunks.
1092
1856
  *